language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 168 | 2.0625 | 2 | [] | no_license | package com.ipl.dao;
import com.ipl.model.User;
public interface UserDao {
public void addUser(User user) ;
public User authUser(String email,String password);
}
|
JavaScript | UTF-8 | 4,384 | 2.75 | 3 | [] | no_license | /**
* @module Ink.Dom.Loaded_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Dom.Loaded', 1, [], function() {
'use strict';
/**
* The Loaded class provides a method that allows developers to queue functions to run when
* the page is loaded (document is ready).
*
* @class Ink.Dom.Loaded
* @version 1
* @static
*/
var Loaded = {
/**
* Functions queue.
*
* @property _cbQueue
* @type {Array}
* @private
* @static
* @readOnly
*/
_cbQueue: [], // Callbacks' queue
/**
* Adds a new function that will be invoked once the document is ready
*
* @method run
* @param {Object} [win] Window object to attach/add the event
* @param {Function} fn Callback function to be run after the page is loaded
* @public
* @example
* Ink.requireModules(['Ink.Dom.Loaded_1'],function(Loaded){
* Loaded.run(function(){
* console.log('This will run when the page/document is ready/loaded');
* });
* });
*/
run: function(win, fn) {
if (!fn) {
fn = win;
win = window;
}
this._win = win;
this._doc = win.document;
this._root = this._doc.documentElement;
this._done = false;
this._top = true;
this._handlers = {
checkState: Ink.bindEvent(this._checkState, this),
poll: Ink.bind(this._poll, this)
};
var ael = this._doc.addEventListener;
this._add = ael ? 'addEventListener' : 'attachEvent';
this._rem = ael ? 'removeEventListener' : 'detachEvent';
this._pre = ael ? '' : 'on';
this._det = ael ? 'DOMContentLoaded' : 'onreadystatechange';
this._wet = this._pre + 'load';
var csf = this._handlers.checkState;
if (this._doc.readyState === 'complete'){
fn.call(this._win, 'lazy');
}
else {
this._cbQueue.push(fn);
this._doc[this._add]( this._det , csf );
this._win[this._add]( this._wet , csf );
var frameElement = 1;
try{
frameElement = this._win.frameElement;
} catch(e) {}
if ( !ael && this._root.doScroll ) { // IE HACK
try {
this._top = !frameElement;
} catch(e) { }
if (this._top) {
this._poll();
}
}
}
},
/**
* Function that will be running the callbacks after the page is loaded
*
* @method _checkState
* @param {Event} event Triggered event
* @private
*/
_checkState: function(event) {
if ( !event || (event.type === 'readystatechange' && this._doc.readyState !== 'complete')) {
return;
}
var where = (event.type === 'load') ? this._win : this._doc;
where[this._rem](this._pre+event.type, this._handlers.checkState, false);
this._ready();
},
/**
* Polls the load progress of the page to see if it has already loaded or not
*
* @method _poll
* @private
*/
/**
*
* function _poll
*/
_poll: function() {
try {
this._root.doScroll('left');
} catch(e) {
return setTimeout(this._handlers.poll, 50);
}
this._ready();
},
/**
* Function that runs the callbacks from the queue when the document is ready.
*
* @method _ready
* @private
*/
_ready: function() {
if (!this._done) {
this._done = true;
for (var i = 0; i < this._cbQueue.length; ++i) {
this._cbQueue[i].call(this._win);
}
this._cbQueue = [];
}
}
};
return Loaded;
});
|
C | UTF-8 | 2,306 | 3.6875 | 4 | [] | no_license | #include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MAX 100
typedef struct{
char nome[50];
int id;
} tipoDados;
typedef struct{
tipoDados vet[MAX];
int nelem;
} tipoLista;
void iniciar_lista(tipoLista *L){
(*L).nelem = 0; //ou L->nelem
}
void inserir_lista(tipoLista *L){
register int i;
i = L->nelem;
if(i>=MAX){
printf("\nLista cheia!!");
}
printf("\nInsira o nome: ");
scanf("%s", L->vet[i].nome);
printf("\nInsira a idade: ");
scanf("%d", &L->vet[i].id);
L->nelem = L->nelem + 1;
printf("\n\n");
}
void mostrar_lista(tipoLista *L){
register int x, i;
x = L->nelem;
for(i=0; i<=x; i++){
if(L->vet[i].nome[0] != '\0'){
printf("\n%s", L->vet[i].nome);
printf("\n%d", L->vet[i].id);
}
}
printf("\n\n");
}
void deletar_lista(tipoLista *L){
register int t, x;
char aux[20];
t = L->nelem;
int cont=0;
printf("\nInsira um nome: ");
scanf("%s", aux);
for(x=0; x<=t; x++){
if(strcmp(L->vet[x].nome, aux)==0){
L->vet[x].nome[0] = '\0';
L->nelem = L->nelem - 1;
cont ++;
}
}
if(cont!=0){
printf("\n(%d)Elemento(os) removidos com sucesso!!!\n", cont);
}
else{
printf("\nNão há registros com esse nome!!!\n");
}
}
void ordenar_lista(tipoLista *L){
int i, j, menor;
int exchange = 0;
char *aux;
tipoLista *LL;
tipoDados D;
LL = L;
for(i=0; i<LL->nelem-1; i++){
aux = LL->vet[i].nome;
menor = i;
for(j=i+1; j<LL->nelem; j++){
if(strcmp(LL->vet[j].nome, aux)<0){
menor = j;
exchange = 1;
}
}
if(exchange == 1){
D = L->vet[i];
L->vet[i] = L->vet[menor];
L->vet[menor] = D;
}
}
}
int menu(){
int escolha;
printf("\n\n>>>PROGRAMA DE CADASTRO DE NOMES<<<");
printf("\n(1) Inserir");
printf("\n(2) Deletar");
printf("\n(3) Mostrar");
printf("\n(4) Ordenar");
printf("\n(5) Sair");
printf("\ndigite o numero da sua opção: ");
scanf("%d", &escolha);
return escolha;
}
int main(){
tipoLista L;
int escolha;
iniciar_lista(&L);
for ( ; ; )
{
escolha = menu();
switch(escolha)
{
case 1:
inserir_lista(&L);
break;
case 2:
deletar_lista(&L);
break;
case 3:
mostrar_lista(&L);
break;
case 4:
ordenar_lista(&L);
break;
case 5:
exit(0);
}
}
return 0;
}
|
C++ | UTF-8 | 804 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include <conio.h>
#define pi 3.14
using namespace std;
class area{
float areas;
public:
void area_51(int a , int b);
void area_51(double l, double c);
void area_51(double r);
};
void area :: area_51(int a, int b)
{
areas=a*b;
cout<<"area of rectangle="<<areas<<endl;
}
void area :: area_51(double l, double c)
{
areas=(l*c)/2;
cout<<"area of triangle="<<areas<<endl;
}
void area :: area_51(double r)
{
areas=pi*r*r;
cout<<"area of circle="<<areas<<endl;
}
main()
{
int a,b;
double l,c,r;
area obj;
cout<<"enter the lenght and breath of rectangle"<<endl;
cin>>a>>b;
obj.area_51(a,b);
cout<<"enter the lenght and height of triangle"<<endl;
cin>>l>>c;
obj.area_51(l,c);
cout<<"eneter the radius of circle"<<endl;
cin>>r;
obj.area_51(r);
}
|
Python | UTF-8 | 6,136 | 2.921875 | 3 | [
"MIT"
] | permissive | from ground.base import (Context,
Relation)
from ground.hints import Point
from prioq.base import PriorityQueue
from reprit.base import generate_repr
from .event import Event
class EventsQueueKey:
__slots__ = 'event',
def __init__(self, event: Event) -> None:
self.event = event
__repr__ = generate_repr(__init__)
def __lt__(self, other: 'EventsQueueKey') -> bool:
"""
Checks if the event should be processed before the other.
"""
event, other_event = self.event, other.event
start_x, start_y = event.start.x, event.start.y
other_start_x, other_start_y = other_event.start.x, other_event.start.y
if start_x != other_start_x:
# different x-coordinate,
# the event with lower x-coordinate is processed first
return start_x < other_start_x
elif start_y != other_start_y:
# different starts, but same x-coordinate,
# the event with lower y-coordinate is processed first
return start_y < other_start_y
elif event.is_left_endpoint is not other_event.is_left_endpoint:
# same start, but one is a left endpoint
# and the other is a right endpoint,
# the right endpoint is processed first
return not event.is_left_endpoint
else:
# same start,
# both events are left endpoints or both are right endpoints
return event.end < other_event.end
class EventsQueue:
__slots__ = 'context', '_queue'
def __init__(self, context: Context) -> None:
self.context = context
self._queue = PriorityQueue(key=EventsQueueKey)
__repr__ = generate_repr(__init__)
def __bool__(self) -> bool:
return bool(self._queue)
def detect_intersection(self, below_event: Event, event: Event) -> None:
relation = self.context.segments_relation(
below_event.start, below_event.end, event.start, event.end)
if relation is Relation.TOUCH or relation is Relation.CROSS:
# segments touch or cross
point = self.context.segments_intersection(
below_event.start, below_event.end, event.start, event.end)
if point != below_event.start and point != below_event.end:
self._divide_segment(below_event, point)
if point != event.start and point != event.end:
self._divide_segment(event, point)
event.set_both_relations(max(event.relation, relation))
below_event.set_both_relations(max(below_event.relation, relation))
elif relation is not Relation.DISJOINT:
# segments overlap
starts_equal = event.start == below_event.start
start_min, start_max = (
(None, None)
if starts_equal
else ((event, below_event)
if EventsQueueKey(event) < EventsQueueKey(below_event)
else (below_event, event)))
ends_equal = event.end == below_event.end
end_min, end_max = (
(None, None)
if ends_equal
else ((event.complement, below_event.complement)
if (EventsQueueKey(event.complement)
< EventsQueueKey(below_event.complement))
else (below_event.complement, event.complement)))
if starts_equal:
if ends_equal:
# segments are equal
event.set_both_relations(relation)
below_event.set_both_relations(relation)
else:
# segments share the left endpoint
end_min.set_both_relations(relation)
end_max.complement.relation = relation
self._divide_segment(end_max.complement, end_min.start)
elif ends_equal:
# segments share the right endpoint
start_max.set_both_relations(relation)
start_min.complement.relation = relation
self._divide_segment(start_min, start_max.start)
elif start_min is end_max.complement:
# one line segment includes the other one
start_max.set_both_relations(relation)
start_min_original_relationship = start_min.relation
start_min.relation = relation
self._divide_segment(start_min, end_min.start)
start_min.relation = start_min_original_relationship
start_min.complement.relation = relation
self._divide_segment(start_min, start_max.start)
else:
# no line segment includes the other one
start_max.relation = relation
self._divide_segment(start_max, end_min.start)
start_min.complement.relation = relation
self._divide_segment(start_min, start_max.start)
def peek(self) -> Event:
return self._queue.peek()
def pop(self) -> Event:
return self._queue.pop()
def push(self, event: Event) -> None:
if event.start == event.end:
raise ValueError('Degenerate segment found '
'with both endpoints being: {}.'
.format(event.start))
self._queue.push(event)
def _divide_segment(self, event: Event, break_point: Point) -> None:
left_event = event.complement.complement = Event(
start=break_point,
complement=event.complement,
is_left_endpoint=True,
relation=event.complement.relation,
segments_ids=event.segments_ids)
right_event = event.complement = Event(
start=break_point,
complement=event,
is_left_endpoint=False,
relation=event.relation,
segments_ids=event.complement.segments_ids)
self.push(left_event)
self.push(right_event)
|
C# | UTF-8 | 5,524 | 2.90625 | 3 | [] | no_license | using System.Collections.Generic;
using System.Text;
using DataCreator.Utility;
using DataCreator.Shared;
using DataCreator.Enemies;
namespace DataCreator.Encounters
{
/// <summary>
/// An object for a single encounter. Contains related tactics and media files.
/// </summary>
public class Encounter : BaseType
{
/// <summary>
/// Copies this tactic to fitting enemy tactics. This is needed to share boss tactics between encounters and the boss's page.
/// </summary>
public void CopyToEnemyTactics(List<Enemy> enemies)
{
var enemiesToUpdate = LinkGenerator.GetEnemiesFromLinks(Name, Paths, enemies);
var nameWithoutLinks = LinkGenerator.RemoveLinks(Name);
foreach (var enemy in enemiesToUpdate)
{
// Longer the encounter name, less valid its tactics are.
var tacticValidity = (double)enemy.Name.Length / nameWithoutLinks.Length;
if (enemy.TacticValidity < tacticValidity)
{
enemy.TacticValidity = tacticValidity;
enemy.Tactics = Helper.CloneJson(Tactics);
}
}
}
/// <summary>
/// Returns HTML representation for this encounter.
/// </summary>
public string ToHtml(int orderNumber, IEnumerable<Encounter> encounters, int fractalScale, string mapFile)
{
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<table class=\"encounter\"><tr>");
htmlBuilder.Append(GenerateLeftSide(orderNumber, encounters));
htmlBuilder.Append(GenerateContent(orderNumber, fractalScale, mapFile));
htmlBuilder.Append("<td class=\"encounter-right\">").Append(Constants.LineEnding);
htmlBuilder.Append("</td>");
htmlBuilder.Append("</tr></table>").Append(Constants.LineEnding).Append("<br/>").Append(Constants.LineEnding);
return htmlBuilder.ToString();
}
/// <summary>
/// Generates left side for the encounter. Left side is used for media thumbnails but also for the table of contents.
/// </summary>
private StringBuilder GenerateLeftSide(int orderNumber, IEnumerable<Encounter> encounters)
{
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<td class=\"encounter-left\">").Append(Constants.LineEnding);
if (orderNumber == 0)
htmlBuilder.Append(GenerateTableOfContents(encounters));
foreach (var media in Medias)
{
htmlBuilder.Append("<div>").Append(Constants.LineEnding);
htmlBuilder.Append(media.GetThumbnailHTML()).Append(Constants.LineEnding);
htmlBuilder.Append("</div>").Append(Constants.LineEnding);
htmlBuilder.Append(Constants.LineEnding);
}
htmlBuilder.Append("</td>");
return htmlBuilder;
}
/// <summary>
/// Generates a table of contents from given encounters.
/// </summary>
private StringBuilder GenerateTableOfContents(IEnumerable<Encounter> encounters)
{
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<div>").Append(Constants.LineEnding);
htmlBuilder.Append("<ul class=\"table-of-contents\">").Append(Constants.LineEnding);
htmlBuilder.Append("<li><h3>Table of contents</h3></li>");
var tableCounter = 0;
foreach (var encounter in encounters)
{
// Ignpre the dungeon name because it's often long and doesn't add any information or functionality.
if (tableCounter > 0)
{
htmlBuilder.Append("<li><a href=\"#").Append(tableCounter).Append("\">");
htmlBuilder.Append(Helper.ConvertSpecial(LinkGenerator.RemoveLinks(encounter.Name))).Append("</a></li>");
}
tableCounter++;
}
htmlBuilder.Append("</ul>").Append(Constants.LineEnding);
htmlBuilder.Append("</div>").Append(Constants.LineEnding);
htmlBuilder.Append(Constants.LineEnding);
return htmlBuilder;
}
/// <summary>
/// Generates HTML for the encounters.
/// </summary>
private StringBuilder GenerateContent(int orderNumber, int fractalScale, string mapFile)
{
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<td id=\"").Append(orderNumber).Append("\" class=\"encounter-main\">");
// Add relevant information to start of the encounter so it can be easily found by the website.
// TODO: Not sure are these truly needed anymore.
htmlBuilder.Append("<div data-name=\"").Append(DataName).Append("\" ");
htmlBuilder.Append("data-path=\"").Append(Helper.Simplify(string.Join("|", Paths))).Append("\">").Append(Constants.LineEnding);
htmlBuilder.Append(Gw2Helper.AddTab(1)).Append("<div class=\"in-line\">");
htmlBuilder.Append(Gw2Helper.AddTab(2)).Append(orderNumber == 0 ? "<h1>" : "<h2>");
// Because of the index file, links have to be added this late to the encounter name.
htmlBuilder.Append(Helper.ConvertSpecial(Name));
htmlBuilder.Append(orderNumber == 0 ? "</h1>" : "</h2>");
if (mapFile.Length > 0)
htmlBuilder.Append(Constants.Space).Append(Constants.Space).Append("<a class=\"overlay-link\" href=\"").Append(mapFile).Append("\"><span class=\"glyphicon glyphicon-picture\"></span></a>");
htmlBuilder.Append(Constants.LineEnding);
htmlBuilder.Append(Gw2Helper.AddTab(1)).Append("</div>");
htmlBuilder.Append(Tactics.ToHtml(Index, 1, fractalScale));
htmlBuilder.Append("</div></td>");
return htmlBuilder;
}
}
}
|
Java | UTF-8 | 1,288 | 2.390625 | 2 | [] | no_license | package admin;
import entities.User;
import qualifiers.Users;
import javax.inject.Inject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
@WebServlet("/EditUsersServlet")
public class EditUsersServlet extends HttpServlet {
@Inject @Users
HashSet<User> users;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String usernameToEdit = req.getParameter("user");
User userToEdit = users.stream().filter(u -> u.getUsername().equals(usernameToEdit)).findFirst().orElse(null);
String newName = req.getParameter("name");
String newUsername = req.getParameter("username");
if(userToEdit != null) {
userToEdit.setName(newName);
userToEdit.setUsername(newUsername);
}
req.setAttribute("usersEdited", users);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/AdminServlet");
requestDispatcher.forward(req, resp);
}
}
|
Java | UTF-8 | 2,765 | 2.359375 | 2 | [] | no_license | package it.polito.tdp.spellchecker;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
//import java.util.Dictionary;
import java.util.ResourceBundle;
import it.polito.tdp.spellchecker.model.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
public class FXMLController {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private ComboBox<String> boxLanguage;
private ObservableList<String> lingue = FXCollections.observableArrayList("Italian", "English");
@FXML
private TextArea txtInput;
@FXML
private Button btnSpellCheck;
@FXML
private TextArea txtWrongWords;
@FXML
private Label txtErrors;
@FXML
private Button btnClearText;
@FXML
private Label txtTime;
@FXML
void doClearText(ActionEvent event) {
txtInput.clear();
txtWrongWords.clear();
}
@FXML
void doSpellCheck(ActionEvent event) {
Dictionary d = new Dictionary();
d.loadDictionary(boxLanguage.getValue());
d.setLanguage(boxLanguage.getValue());
List<String> testoInput = getInput();
d.spellCheckTextDichotomic(testoInput);
txtWrongWords.setText(d.getWrongWords());
txtErrors.setText("Ci sono " + d.getErrors() + " errori");
}
private List<String> getInput () {
List<String> stemp = new LinkedList<String>();
for (String s : txtInput.getText().split(" ")) {
stemp.add(s);
}
return stemp;
}
@FXML
void initialize() {
assert boxLanguage != null : "fx:id=\"boxLanguage\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtInput != null : "fx:id=\"txtInput\" was not injected: check your FXML file 'Scene.fxml'.";
assert btnSpellCheck != null : "fx:id=\"btnSpellCheck\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtWrongWords != null : "fx:id=\"txtWrongWords\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtErrors != null : "fx:id=\"txtErrors\" was not injected: check your FXML file 'Scene.fxml'.";
assert btnClearText != null : "fx:id=\"btnClearText\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtTime != null : "fx:id=\"txtTime\" was not injected: check your FXML file 'Scene.fxml'.";
boxLanguage.setItems(lingue);
}
}
|
Java | UTF-8 | 733 | 2.453125 | 2 | [] | no_license | package flickster.com.flickster.model;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProvider;
import android.support.annotation.NonNull;
import flickster.com.flickster.database.MovieDatabase;
public class AddMovieViewModelFactory extends ViewModelProvider.NewInstanceFactory{
private final MovieDatabase movieDatabase;
private final int movieId;
public AddMovieViewModelFactory(MovieDatabase movieDatabase, int movieId) {
this.movieDatabase = movieDatabase;
this.movieId = movieId;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new AddMovieViewModel(movieDatabase, movieId);
}
}
|
Python | UTF-8 | 380 | 3.390625 | 3 | [] | no_license | # Link: https://uva.onlinejudge.org/external/15/1584.pdf
import re
def get_smallest_lex_dna(dna):
for nucleotide in 'ACGT':
all_indices = [m.start() for m in re.finditer(nucleotide, dna)]
if all_indices:
return sorted([dna[index:] + dna[:index] for index in all_indices])[0]
for _ in range(int(input())):
print(get_smallest_lex_dna(input()))
|
SQL | UTF-8 | 969 | 2.9375 | 3 | [] | no_license | CREATE TABLE sa.table_part_class (
objid NUMBER,
"NAME" VARCHAR2(40 BYTE),
description VARCHAR2(255 BYTE),
dev NUMBER,
x_model_number VARCHAR2(30 BYTE),
x_psms_inquiry VARCHAR2(150 BYTE)
);
ALTER TABLE sa.table_part_class ADD SUPPLEMENTAL LOG GROUP dmtsora577323333_0 (description, dev, "NAME", objid, x_model_number, x_psms_inquiry) ALWAYS;
COMMENT ON TABLE sa.table_part_class IS 'Defines logical groups of parts (generic parts) for DE purposes';
COMMENT ON COLUMN sa.table_part_class.objid IS 'Internal record number';
COMMENT ON COLUMN sa.table_part_class."NAME" IS 'A unique name for the part class';
COMMENT ON COLUMN sa.table_part_class.description IS 'A brief description for the part class';
COMMENT ON COLUMN sa.table_part_class.dev IS 'Row version number for mobile distribution purposes';
COMMENT ON COLUMN sa.table_part_class.x_model_number IS 'TBD';
COMMENT ON COLUMN sa.table_part_class.x_psms_inquiry IS 'PSMS Inquiry String'; |
Java | UTF-8 | 1,997 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | package xworker.javafx.control.cell;
import javafx.scene.control.cell.ComboBoxTreeTableCell;
import javafx.util.StringConverter;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.javafx.control.TableCellActions;
import xworker.javafx.control.TreeTableCellActions;
import xworker.javafx.util.JavaFXUtils;
import java.util.Iterator;
public class ComboBoxTreeTableCellActions {
public static void init(ComboBoxTreeTableCell<Object, Object> node, Thing thing, ActionContext actionContext){
TreeTableCellActions.init(node, thing, actionContext);
if(thing.valueExists("converter")){
StringConverter<Object> converter = JavaFXUtils.getObject(thing, "converter", actionContext);
if(converter != null) {
node.setConverter(converter);
}
}
if(thing.valueExists("items")){
Iterable<Object> items = JavaFXUtils.getObject(thing, "items", actionContext);
if(items != null) {
Iterator<Object> iter = items.iterator();
while(iter.hasNext()){
node.getItems().add(iter.next());
}
}
}
if(thing.valueExists("comboBoxEditable")){
node.setComboBoxEditable(thing.getBoolean("comboBoxEditable"));
}
}
public static ComboBoxTreeTableCell<Object, Object> create(ActionContext actionContext){
Thing self = actionContext.getObject("self");
ComboBoxTreeTableCell<Object, Object> node = new ComboBoxTreeTableCell<>();
init(node, self, actionContext);
actionContext.g().put(self.getMetadata().getName(), node);
actionContext.peek().put("parent", node);
for(Thing child : self.getChilds()){
Object obj = child.doAction("create", actionContext);
if(obj instanceof StringConverter){
node.setConverter((StringConverter) obj);
}
}
return node;
}
}
|
C | UTF-8 | 5,504 | 3.125 | 3 | [
"MIT"
] | permissive | #ifndef _KS_TREESET_H_
#define _KS_TREESET_H_
/* ---------------------
* ks_treeset_new():
* Creates a new empty ks_treeset.
*
* Inputs:
* void
*
* Returns:
* ks_treeset* ts - an empty ks_treeset.
*/
ks_treeset* ks_treeset_new();
/* ----------------------
* ks_treeset_delete():
* Deletes a ks_treeset and all of its contents.
*
* Inputs:
* ks_treeset* ts - the ks_treeset to be deleted.
*
* Returns:
* void
*/
void ks_treeset_delete(ks_treeset* ts);
/* -----------------------
* ks_treeset_copy():
* Creates a copy of a ks_treeset and all of its contents.
*
* Inputs:
* ks_treeset* ts - the ks_treeset to be copied.
*
* Returns:
* ks_treesetnode - a copy of the treesetnode.
*/
ks_treeset* ks_treeset_copy(const ks_treeset* ts);
/* ----------------------
* ks_treeset_add():
* Adds a ks_datacont to a ks_treeset.
*
* Inputs:
* ks_treeset* ts - the ks_treeset being added to.
* ks_datacont* dc - the ks_datacont being added to the ks_treeset.
*
* Returns:
* int result - (-1) if either param is NULL, or if 'dc' is not comparable to the other
* ks_dataconts in the ks_treeset (e.g. if 'dc' is of type CHAR and the others are INT).
* - (0) 'dc' was successfully added to 'ts'.
* - (1) 'dc' is already present in the ks_treeset and was not added.
*
* Notes:
* If 'dc' is successfully stored into the set, 'dc' should not be deleted by the user code,
* as it will be directly stored into the tree. Otherwise a seg fault is likely to occur.
* In the event that a value matching 'dc' is already present in the ks_treeset, 'dc' will not
* be stored, and 'dc' must be deleted by the user code.
*/
int ks_treeset_add(ks_treeset* ts, const ks_datacont* dc);
/* ------------------------------
* ks_treeset_remove_by():
* Remove a ks_datacont from a ks_treeset that contains a value matching the value of the 'dc'
* argument.
*
* Inputs:
* ks_treeset* ts - the ks_treeset being removed from.
* ks_datacont* dc - the ks_datacont value to remove from the ks_treeset.
*
* Returns:
* int result - (-1) if either param is NULL, or if 'dc' could not be found.
* - (0) on success.
*/
int ks_treeset_remove_by(ks_treeset* ts, const ks_datacont* dc);
/* ----------------------------
* ks_treeset_remove_at():
* Remove a ks_datacont from a ks_treeset at a specified index.
*
* Inputs:
* ks_treeset* ts - the ks_treeset being removed from.
* int index - the index of the ks_datacont to be removed.
*
* Returns:
* int result - (-1) if 'index' is OOB or if 'ts' is NULL.
* - >= (0) on success.
*/
int ks_treeset_remove_at(ks_treeset* ts, const int index);
/* ---------------------------
* ks_treeset_index():
* Returns the index of a given ks_datacont value.
*
* Inputs:
* ks_treeset* ts - the ks_treeset being searched.
* ks_datacont* dc - the ks_datacont to search for within 'ts'.
*
* Returns:
* int index - (-1) if 'dc' could not be found, or if either param is NULL.
* - >= (0) the index of 'dc'. Negative values will wrap around.
*
* Notes:
* This function should not be used to determine if a ks_datacont is present within
* a ks_treeset*. Instead ks_treeset_contains() should be used as it is a much faster
* operation than ks_treeset_index().
*/
int ks_treeset_index(const ks_treeset* ts, const ks_datacont* dc);
/* -----------------------------
* ks_treeset_contains():
* Searches for a specified ks_datacont value within a ks_treeset.
*
* Inputs:
* ks_treeset* ts - the ks_treeset being searched.
* ks_datacont* dc - the ks_datacont to search for within 'ts'.
*
* Returns:
* unsigned int result - (0) if 'dc' could not be found, or if either param is NULL.
* - (1) if 'dc' was found.
*/
unsigned int ks_treeset_contains(const ks_treeset* ts, const ks_datacont* dc);
/* ---------------------------
* ks_treeset_get():
* Returns a ks_datacont located at a specified index within a ks_treeset.
*
* Inputs:
* ks_treeset* ts - the ks_treeset* being operated on.
* int index - the index of the ks_datacont to being retrieved. Negative values
* will wrap around.
*
* Returns:
* ks_datacont* dc - (NULL) if 'index' is OOB, or if 'tsn' is NULL.
* - the ks_datacont located at 'index'.
*
* Notes:
* The ks_datacont returned by this function is a pointer to the original contained within the ks_treeset,
* so it should not be deleted or modified by client code.
*/
ks_datacont* ks_treeset_get(const ks_treeset* tsn, const int index);
/* -------------------------
* ks_treeset_count():
* Returns the number of ks_dataconts stored in a ks_treeset.
*
* Inputs:
* ks_treeset* ts - the ks_treeset being operated on.
*
* Returns:
* unsigned int count - >= (0) the number of nodes in 'ts', (0) when 'ts' is NULL.
*/
unsigned int ks_treeset_count(const ks_treeset* ts);
/* --------------------------
* ks_treeset_height():
* Calculates the height of the ks_treeset and all connected nodes.
*
* Inputs:
* ks_treeset* ts - the ks_treeset being operated on.
*
* Returns:
* unsigned int height - >= (0) the height of the ks_treeset, (0) when 'ts' is NULL.
*/
unsigned int ks_treeset_height(const ks_treeset* ts);
/* --------------------------
* ks_treeset_balance():
* Balances a ks_treeset tree to ensure optimal performance.
*
* Inputs:
* ks_treeset* tsn - the ks_treeset being balanced.
*
* Returns:
* void
*/
void ks_treeset_balance(ks_treeset* ts);
#endif
|
Python | UTF-8 | 2,912 | 3.765625 | 4 | [] | no_license | #1st Dictionary Exercise. I went ahead and modified it to do the Phonebook App exercise too.
import pickle
phonebook_dict = {
'Alice': '703-493-1834',
'Bob': '857-384-1234',
'Elizabeth': '484-584-2923'
}
def retrieveNum():
nameNum = input("Whose number? (Enter Name) ")
print("Found entry for {}: {}".format(nameNum, phonebook_dict[nameNum]))
def addNum():
newName = input("Name? ")
newPhone = input("Phone number? ")
newEntry = {newName: newPhone}
phonebook_dict.update(newEntry)
print("Entry stored for {}".format(newEntry))
def delNum():
killPhone = input("Who should I delete? ")
del phonebook_dict[killPhone]
print("Deleted entry for {}.".format(killPhone))
def changNum():
oldNum = input("Whose number should I change? (Enter Name) ")
newNum = input("What's the new phone number? ")
phonebook_dict[oldNum] = newNum
print("All set! {}: {}".format(oldNum, phonebook_dict[oldNum]))
def showAll():
print(phonebook_dict)
selectDict = input("""Please make a selection from 1 - 5:
1. Print a phone number/Look up an entry.
2. Set an entry.
3. Delete an entry.
4. Change a phone number.
5. Display all phone entries.
6. Save entries.
7. Load saved entries.
8. Quit\n""")
selection = True
while selection:
if selectDict == '1':
retrieveNum()
selectDict = input("Make another selection. ")
elif selectDict == '2':
addNum()
selectDict = input("Make another selection. ")
elif selectDict == '3':
delNum()
selectDict = input("Make another selection. ")
elif selectDict == '4':
changNum()
selectDict = input("Make another selection. ")
elif selectDict == '5':
showAll()
selectDict = input("Make another selection. ")
elif selectDict == '6':
myfile = open('phonebook_dict.pickle', 'wb')
pickle.dump(phonebook_dict, myfile)
myfile.close()
selectDict = input("Make another selection. ")
elif selectDict == '7':
myfile = open('phonebook_dict.pickle', 'rb')
phonebook_dict = pickle.load(myfile)
print(phonebook_dict)
selectDict = input("Make another selection. ")
elif selectDict == '8':
print("Closing the phonebook.")
selection = False
else:
print("Invalid selection. Closing the phonebook.")
selection = False
# #2nd Dictionary Exercise
# ramit = {
# 'name': 'Ramit',
# 'email': 'ramit@gmail.com',
# 'interests': ['movies', 'tennis'],
# 'friends': [
# {
# 'name': 'Jasmine',
# 'email': 'jasmine@yahoo.com',
# 'interests': ['photography', 'tennis']
# },
# {
# 'name': 'Jan',
# 'email': 'jan@hotmail.com',
# 'interests': ['movies', 'tv']
# }
# ]
# }
# print(ramit['email'])
# print(ramit['interests'][0])
# print(ramit['friends'][0]['email'])
# print(ramit['friends'][1]['interests'][1])
|
C# | UTF-8 | 705 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | namespace CrypTool.Plugins.ChaCha.ViewModel.Components
{
internal interface IActionTag
{
/// <summary>
/// Saves action indices under a "tag" for later retrieval.
/// This implements "action tagging". We can mark actions with a string
/// and then retrieve their action index using that string.
/// One must use this function during action creation and call
/// it with the index of the action we want to tag.
/// </summary>
void TagAction(string tag, int actionIndex);
/// <summary>
/// Return the action index of the given action tag.
/// </summary>
int GetTaggedActionIndex(string tag);
}
} |
C# | UTF-8 | 1,803 | 2.59375 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DiceScript : MonoBehaviour {
public GameObject Plane;
public GameObject TextGB;
private GameObject Dice1;
private GameObject Dice2;
private GameObject Dice3;
private GameObject Dice4;
private GameObject Dice5;
private GameObject Dice6;
private bool isStill;
private Rigidbody rb;
private Text text;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody> ();
text = TextGB.GetComponent<Text>();
Dice1 = GameObject.Find ("Dice1");
Dice2 = GameObject.Find ("Dice2");
Dice3 = GameObject.Find ("Dice3");
Dice4 = GameObject.Find ("Dice4");
Dice5 = GameObject.Find ("Dice5");
Dice6 = GameObject.Find ("Dice6");
// Random rotation on start
this.transform.rotation = Random.rotation;
isStill = false;
}
// Update is called once per frame
void Update () {
string diceValue = "";
if (!isStill && rb.velocity.x == 0 && rb.velocity.y == 0 && rb.velocity.z == 0) {
if (Dice1.transform.eulerAngles.x == Plane.transform.eulerAngles.x + 90) {
diceValue = "1";
}
if (Dice2.transform.eulerAngles.x == Plane.transform.eulerAngles.x + 90) {
diceValue = "2";
}
if (Dice3.transform.eulerAngles.x == Plane.transform.eulerAngles.x + 90) {
diceValue = "3";
}
if (Dice4.transform.eulerAngles.x == Plane.transform.eulerAngles.x + 90) {
diceValue = "4";
}
if (Dice5.transform.eulerAngles.x == Plane.transform.eulerAngles.x + 90) {
diceValue = "5";
}
if (Dice6.transform.eulerAngles.x == Plane.transform.eulerAngles.x + 90) {
diceValue = "6";
}
if (diceValue != "") {
isStill = true;
}
Debug.Log ("Dice " +diceValue);
text.text = "You got a " +diceValue +"!";
}
}
}
|
Java | UTF-8 | 580 | 2.375 | 2 | [] | no_license | /**
*
*/
package net.skyebook.padloader.test;
import java.io.File;
import java.io.IOException;
import java.util.List;
import net.skyebook.padloader.read.BBLReader;
import net.skyebook.padloader.record.Record;
/**
* @author Skye Book
*
*/
public class TestBBLReader {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File file = new File("/Users/skyebook/Downloads/pad10d/bobabbl.txt");
List<Record> records = new BBLReader().readRecords(file);
System.out.println(records.size() + " records read");
}
}
|
C++ | UTF-8 | 1,148 | 2.921875 | 3 | [
"MIT"
] | permissive | #pragma once
namespace Playground {
namespace Com {
template <typename T>
struct Box {
T* ptr_ = nullptr;
Box() = default;
Box(Box const&) = delete;
Box& operator=(Box const&) = delete;
Box(Box&& other)
{
ptr_ = other.ptr_;
other.ptr_ = nullptr;
}
Box& operator=(Box&& other)
{
Release();
ptr_ = other.ptr_;
other.ptr_ = nullptr;
return *this;
}
~Box()
{
Release();
}
void Release()
{
if (ptr_) {
ptr_->Release();
ptr_ = nullptr;
}
}
T** InitAddress()
{
return &ptr_;
}
T* operator->()
{
return ptr_;
}
T* Get()
{
return ptr_;
}
T* operator*()
{
return Get();
}
T* Get() const
{
return ptr_;
}
T* operator*() const
{
return Get();
}
};
}
} |
C++ | UTF-8 | 1,066 | 2.59375 | 3 | [] | no_license | #include<Wire.h>
#include<LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F,16,2); //first parameter address , and 16 x 2 lcd
#include "DHT.h"
#define DHTTYPE DHT11
#define dht_pin 0
DHT dht(dht_pin , DHTTYPE);
//----------------------------------------------------------------------------------------
void setup() {
// put your setup code here, to run once:
dht.begin();
Serial.begin(9600);
Serial.print("Humidity and Temperature :- \n\n");
lcd.init(); //initial
lcd.backlight();
delay(700);
}
//----------------------------------------------------------------------------------------
void loop() {
// put your main code here, to run repeatedly:
float h = dht.readHumidity();
float t = dht.readTemperature();
Serial.print("\nCurrent Humidity = ");
Serial.print(h);
Serial.print("% ");
Serial.print("Temperature = ");
Serial.print(t);
Serial.print("C");
lcd.setCursor(0,0);
lcd.print("Temp = ");
lcd.print(t);
lcd.print(" C");
lcd.setCursor(0,1);
lcd.print("HUMID = ");
lcd.print(h);
lcd.print("% ");
delay(800);
}
|
Markdown | UTF-8 | 1,322 | 3.203125 | 3 | [] | no_license | ## Ruby Refresher
#### A series of rspec tests to pass. This challenge was set on week 7 at Makers Academy. We had spent the previous two weeks on Javascript so this refresher challenge was set before we revisited Ruby.
- [x] Questions 1-10 complete
- [x] Questions 11-20 complete
- [x] Questions 21-30 complete
- [ ] Questions 31-40 complete
- [ ] Question 40 + complete
###The Objective
Here we're going to revisit the basics of Ruby. There are 41 questions - you don't have to do every single one (although if you can, that's great). You should be able to do at least 50% of them. They vary in level from quite easy to fairly hard. Work through them and check if they're correct by running the specs.
You should be able to answer most questions with a couple of lines of code, and just a few methods. If you're writing a long, complex solution, there's probably a better way.
### Rules
* Try and get the RSpec tests to pass (but not by cheating - i.e. hardcoding the expected value)
* You shouldn't need any extra libraries or gems
* The cleaner your code the better!
* Googling is fine as usual
### How To Use
To run the specs, just run
~~~
$ rspec questions_spec.rb
~~~
**Quick tip**: to run a single example, change `it` to `fit` on that example, then run
~~~
$ rspec questions_spec.rb --tag focus
~~~
|
TypeScript | UTF-8 | 1,353 | 2.6875 | 3 | [] | no_license | import { AllianceFleet } from "../domain/AllianceFleet";
import { Satellite } from "../domain/Satellite";
import { IRepository } from "../repository/IRepository";
export class TopSecretController {
private repository: IRepository
constructor(repository: IRepository) {
this.repository = repository;
}
async postTopSecret(params) {
let satellites = [];
for (const s of params) {
let sat = await this.repository.getSatelliteByName(s.name);
sat.receiveMessage(s.distance, s.message);
satellites.push(sat);
}
return this.getEnemyData(satellites);
}
async postTopSecretSplit(satelliteName: any, distance: any, message: any) {
await this.repository.saveMessage(satelliteName, distance, message);
}
async getTopSecretSplit() {
const satellites = await this.repository.getAllSatellitesWithLastMsg();
return this.getEnemyData(satellites);
}
private getEnemyData(satellites: Satellite[]) {
const fleet = new AllianceFleet(satellites);
const location = fleet.findEnemyLocation();
const message = fleet.decodeEnemyMsg();
return {
position: {
x: location[0],
y: location[1]
},
message: message
}
}
} |
Java | UTF-8 | 23,809 | 3.265625 | 3 | [] | no_license | package IC.Visitors;
import java.util.*;
import IC.AST.*;
import IC.SymbolTable.*;
import IC.TypeTable.*;
/**
* Visitor for building all Symbol tables (Global, class, method and block), and check:
* - illegal symbol redefinitions
* - illegal shadowing
* - illegal methods overriding
* - existence and uniqueness of "main" method
*/
public class SymbolTableBuilder implements IC.AST.Visitor{
private String icFileName;
private boolean hasMain = false;
/**
* constructor
* @param icFileName
*/
public SymbolTableBuilder(String icFilePath){
String[] path = icFilePath.split("\\\\");
this.icFileName = path[path.length-1];
TypeTable.initTypeTable(icFileName);
}
/**
* getter for the ic program file name
* @return
*/
public String getFileName(){
return this.icFileName;
}
/**
* returns true iff the given method is the main method
*/
private static boolean isMainMethod(MethodSymbol ms, Method m){
if (!ms.isStatic()) return false; // method is not static
if (ms.getName().compareTo("main") != 0) return false; // method name is not "main"
IC.TypeTable.MethodType mt = (IC.TypeTable.MethodType) ms.getType();
try{
if (!mt.getReturnType().subtypeOf(TypeTable.getType("void"))) return false; // return type is not void
Iterator<IC.TypeTable.Type> paramTypesIter = mt.getParamTypes().iterator();
if (!paramTypesIter.hasNext()) return false; // no parameters
IC.TypeTable.Type t = paramTypesIter.next();
if (!t.subtypeOf(TypeTable.arrayType(TypeTable.getType("string")))) return false; // param is not of type string[]
if (paramTypesIter.hasNext()) return false; // too many parameters
}catch(SemanticError se){System.err.println("*** BUG: DefTypeCheckingVisitor, Literal visitor");} // will never get here
//if (m.getFormals().get(0).getName().compareTo("args") != 0) return false;
return true;
}
/**
* Program visitor:
* - creates GlobalSymbolTable
* - adds classes and updates the type table
* - recursive calls to class visitor for building ClassSymbolTable
* - adds class symbol tables to global
* Program is the only node with a NULL enclosingScope
* returns GlobalSymbolTable, or null if encountered an error
*/
public Object visit(Program program){
// create a new global symbol table, to be returned at the end of construction
GlobalSymbolTable global = new GlobalSymbolTable(icFileName);
// add classes to global and updates the type table
for (ICClass c: program.getClasses()){
try{
global.addClass(c);
} catch (SemanticError se){
// class is previously defined or super class is not defined
se.setLine(c.getLine());
System.err.println(se);
return null; // run will be killed in the compiler in this case
}
}
// recursive class symbol tables build
for (ICClass c: program.getClasses()){
// set enclosing scope
c.setEnclosingScope(global);
ClassSymbolTable cst = (ClassSymbolTable) c.accept(this);
if (cst == null) return null; // If anywhere in the recursion an error has been encountered, the run will terminate.
else {
if(c.hasSuperClass()){
global.getClassSymbolTableRec(c.getSuperClassName()).addClassSymbolTable(cst);
} else {
global.addClassSymbolTable(cst);
}
}
}
// check if has main method
if (!hasMain){
System.err.println(new SemanticError("Program has no main method",0,""));
return null;
}
return global;
}
/**
* Class visitor:
* - creates ClassSymbolTable
* - adds fields and methods to the symbol table, while checking semantic rules
* - recursive calls to method visitor for building MethodSymbolTable
* - adds method symbol tables to this class symbol table
* returns ClassSymbolTable, or null if encountered an error
*/
public Object visit(ICClass icClass) {
ClassSymbolTable cst;
GlobalSymbolTable global = (GlobalSymbolTable) icClass.getEnclosingScope();
// create suitable class symbol table
if (icClass.hasSuperClass()) {
cst = new ClassSymbolTable(icClass.getName(),
global.getClassSymbolTableRec(icClass.getSuperClassName()),
global);
} else { // no superclass
cst = new ClassSymbolTable(icClass.getName(),global);
}
// recursively fill class symbol table
// fields:
for (Field f: icClass.getFields()){
// set enclosing scope
f.setEnclosingScope(cst);
// check if previously defined
try{
cst.getFieldSymbolRec(f.getName());
// if got till here, field is previously defined as field, print error
System.err.println(new SemanticError("field is previously defined",f.getLine(),f.getName()));
return null;
} catch (SemanticError se){
try{
cst.getMethodSymbolRec(f.getName());
// if got till here, field is previously defined as method, print error
System.err.println(new SemanticError("field is previously defined",f.getLine(),f.getName()));
return null;
} catch (SemanticError se2){ // field is not previously defined
try{
cst.addFieldSymbol(f.getName(), f.getType().getFullName());
} catch (SemanticError se3){
// the field's type is undefined
se3.setLine(f.getLine());
System.err.println(se3);
return null;
}
}
}
// recursively call visitor
if (f.accept(this) == null) return null;
}
// methods:
for (Method m: icClass.getMethods()){
// set enclosing scope
m.setEnclosingScope(cst);
// create MethodSymbol
MethodSymbol ms;
try{
ms = new MethodSymbol(m);
// check if this method is "main" and check uniqueness
if (isMainMethod(ms, m)){
if (hasMain){
// already have "main" method, throw error
System.err.println(new SemanticError("Program already has main method",
m.getLine(),
ms.getName()));
return null;
} else {
hasMain = true;
}
}
} catch (SemanticError se){
// semantic error while creating the method symbol (some semantic type error)
se.setLine(m.getLine());
System.err.println(se);
return null;
}
// check if previously defined as field or method
// if method is previously defined in this class scope or in a super class with
// a different signature (including if it's static or not), error. else, add a new MethodSymbol to the Symbol Table.
try{
cst.getFieldSymbolRec(m.getName());
// if got here, method is previously defined as field, print error
System.err.println(new SemanticError("method is previously defined",m.getLine(),m.getName()));
return null;
} catch (SemanticError e){ // e will not be handled
try{
cst.getMethodSymbol(m.getName());
// if got here, method is previously defined in this class, print error
System.err.println(new SemanticError("method is previously defined",m.getLine(),m.getName()));
return null;
} catch (SemanticError e2){ // e2 will not be handled
try{
MethodSymbol prevMS = cst.getMethodSymbolRec(m.getName());
if (!prevMS.getType().equals(ms.getType()) || (prevMS.isStatic() != ms.isStatic())){
// if got here, method is previously defined in super-class with a different signature, print error
System.err.println(new SemanticError(
"method is previously defined, overloading not allowed",
m.getLine(),
m.getName()));
return null;
} else { // overriding method
cst.addMethodSymbol(m.getName(), ms);
}
}catch(SemanticError se){
// method is not previously defined
cst.addMethodSymbol(m.getName(), ms);
}
}
}
}
// recursive method symbol table build
for (Method m: icClass.getMethods()){
MethodSymbolTable mst = (MethodSymbolTable) m.accept(this);
if (mst == null) return null;
else cst.addMethodSymbolTable(mst);
}
return cst;
}
/**
* Method visit helper:
* - creates MethodSymbolTable for all method types (static, virtual and library methods)
* - adds returned type symbol and parameters symbols to the symbol table, while checking semantic rules
* - recursive calls to all other statements, in which local variables and block symbol tables will be
* added to this method's symbol table
* returns MethodSymbolTable, or null if encountered an error
*/
public MethodSymbolTable methodVisit(Method method){
// create method symbol table
MethodSymbolTable mst = new MethodSymbolTable(method.getName(),
(ClassSymbolTable)method.getEnclosingScope());
// add return type symbol
// set enclosing scope for return type
method.getType().setEnclosingScope(mst);
try{
mst.setReturnVarSymbol(method.getType().getFullName());
} catch (SemanticError se){
// semantic error while creating the return type symbol (some semantic type error)
se.setLine(method.getLine());
System.err.println(se);
return null;
}
// fill method symbol table with parameters (formals)
for (Formal f: method.getFormals()){
// set enclosing scope
f.setEnclosingScope(mst);
try{
mst.getVarParamSymbol(f.getName());
// if got here, parameter is previously defined in this method
System.err.println(new SemanticError("parameter is previously defined in method "+method.getName(),
f.getLine(),
f.getName()));
return null;
} catch (SemanticError e){ // e will not be handled
// parameter is undefined, insert its symbol to this method symbol table
try{
mst.addParamSymbol(f.getName(), f.getType().getFullName());
} catch (SemanticError se){
// semantic error while creating the parameter type symbol (some semantic type error)
se.setLine(f.getLine());
System.err.println(se);
return null;
}
}
// recursive call to visitor
if (f.accept(this) == null) return null;
}
// recursive call to visitor
for (Statement s: method.getStatements()){
// set enclosing scope
s.setEnclosingScope(mst);
if (s.accept(this) == null) return null;
}
return mst;
}
/**
* StaticMethod visitor: see methodVisit documentation
*/
public Object visit(StaticMethod method) {
MethodSymbolTable mst = methodVisit(method);
if (mst == null) return null;
else return mst;
}
/**
* VirtualMethod visitor: see methodVisit documentation
*/
public Object visit(VirtualMethod method) {
MethodSymbolTable mst = methodVisit(method);
if (mst == null) return null;
else return mst;
}
/**
* LibraryMethod visitor: see methodVisit documentation
*/
public Object visit(LibraryMethod method) {
MethodSymbolTable mst = methodVisit(method);
if (mst == null) return null;
else return mst;
}
/**
* StatementsBlock visitor:
* - creates BlockSymbolTable
* - updates its father (method / block) to include this block symbol table in its bst list
* - recursive calls to all statements in this block, in which local variables will be added
* to this block symbol table
* returns BlockSymbolTable, or null if encountered an error
*/
public Object visit(StatementsBlock statementsBlock) {
BlockSymbolTable bst = new BlockSymbolTable(statementsBlock.getEnclosingScope());
// get this bst's father (block / method symbol table)
BlockSymbolTable bst_father = (BlockSymbolTable) statementsBlock.getEnclosingScope();
// recursive call to visitor
for (Statement s: statementsBlock.getStatements()){
// set enclosing scope
s.setEnclosingScope(bst);
if (s.accept(this) == null) return null;
}
// add this block symbol table to its father's (method/block symbol table) bst list
bst_father.addBlockSymbolTable(bst);
return bst;
}
/**
* LocalVariable visitor:
* - creates symbol for this local variable and updates its father's symbol table (method / block)
* - updates enclosing scope for initValue and type, and calls their visitors recursively
* returns true, or null if encountered an error
*/
public Object visit(LocalVariable localVariable) {
BlockSymbolTable bst = (BlockSymbolTable)localVariable.getEnclosingScope();
try{
bst.getVarSymbol(localVariable.getName());
// if got here, local variable is previously defined in this method / block
System.err.println(new SemanticError("variable is previously defined",
localVariable.getLine(),
localVariable.getName()));
return null;
} catch (SemanticError e){ // e will not be handled
// local variable is undefined, insert its symbol to block/method symbol table
try{
bst.addVarSymbol(localVariable.getName(), localVariable.getType().getFullName());
} catch (SemanticError se){
// semantic error while creating the local variable type symbol (some semantic type error)
se.setLine(localVariable.getLine());
System.err.println(se);
return null;
}
}
// recursive call to visitor
if (localVariable.hasInitValue()){
localVariable.getInitValue().setEnclosingScope(localVariable.getEnclosingScope());
if (localVariable.getInitValue().accept(this) == null) return null;
}
localVariable.getType().setEnclosingScope(localVariable.getEnclosingScope());
if (localVariable.getType().accept(this) == null) return null;
return true;
}
/**
* Assignment visitor:
* - updates enclosing scope for location and value, and calls their visitors recursively
* returns true, or null if encountered an error
*/
public Object visit(Assignment assignment) {
// recursive call to visitor
assignment.getVariable().setEnclosingScope(assignment.getEnclosingScope());
if (assignment.getVariable().accept(this) == null) return null;
assignment.getAssignment().setEnclosingScope(assignment.getEnclosingScope());
if (assignment.getAssignment().accept(this) == null) return null;
return true;
}
/**
* Break visitor: does nothing, returns true
*/
public Object visit(Break breakStatement) {
return true;
}
/**
* CallStatement visitor:
* - updates enclosing scope for call, and calls its visitor recursively
* returns true, or null if encountered an error
*/
public Object visit(CallStatement callStatement) {
callStatement.getCall().setEnclosingScope(callStatement.getEnclosingScope());
if (callStatement.getCall().accept(this) == null) return null;
return true;
}
/**
* Continue visitor: does nothing, returns true
*/
public Object visit(Continue continueStatement) {
return true;
}
/**
* If visitor:
* - updates enclosing scope for condition, operation and else-operation, and calls their visitors recursively
* - if operation or else-operation are a LocalVariable statement, creates new block symbol table (for each)
* returns true, or null if encountered an error
*/
public Object visit(If ifStatement) {
ifStatement.getCondition().setEnclosingScope(ifStatement.getEnclosingScope());
if (ifStatement.getCondition().accept(this) == null) return null;
// in case of a LocalVariable statement, create new BlockSymbolTable
Statement operation = ifStatement.getOperation();
if (operation instanceof LocalVariable){
BlockSymbolTable bst = new BlockSymbolTable(ifStatement.getEnclosingScope());
((BlockSymbolTable)ifStatement.getEnclosingScope()).addBlockSymbolTable(bst);
operation.setEnclosingScope(bst);
} else operation.setEnclosingScope(ifStatement.getEnclosingScope());
if (operation.accept(this) == null) return null;
if (ifStatement.hasElse()){
// in case of a LocalVariable statement, create new BlockSymbolTable
Statement elseOperation = ifStatement.getElseOperation();
if (elseOperation instanceof LocalVariable){
BlockSymbolTable bst = new BlockSymbolTable(ifStatement.getEnclosingScope());
((BlockSymbolTable)ifStatement.getEnclosingScope()).addBlockSymbolTable(bst);
elseOperation.setEnclosingScope(bst);
} else elseOperation.setEnclosingScope(ifStatement.getEnclosingScope());
if (elseOperation.accept(this) == null) return null;
}
return true;
}
/**
* Return visitor:
* - updates enclosing scope for value, and calls its visitor recursively
* returns true, or null if encountered an error
*/
public Object visit(Return returnStatement) {
if (returnStatement.hasValue()){
returnStatement.getValue().setEnclosingScope(returnStatement.getEnclosingScope());
if (returnStatement.getValue().accept(this) == null) return null;
}
return true;
}
/**
* While visitor:
* - updates enclosing scope for condition and operation, and calls their visitors recursively
* - if operation is a LocalVariable statement, creates new block symbol table
* returns true, or null if encountered an error
*/
public Object visit(While whileStatement) {
whileStatement.getCondition().setEnclosingScope(whileStatement.getEnclosingScope());
if (whileStatement.getCondition().accept(this) == null) return null;
// in case of a LocalVariable statement, create new BlockSymbolTable
Statement operation = whileStatement.getOperation();
if (operation instanceof LocalVariable){
BlockSymbolTable bst = new BlockSymbolTable(whileStatement.getEnclosingScope());
((BlockSymbolTable)whileStatement.getEnclosingScope()).addBlockSymbolTable(bst);
operation.setEnclosingScope(bst);
} else operation.setEnclosingScope(whileStatement.getEnclosingScope());
if (operation.accept(this) == null) return null;
return true;
}
/**
* ArrayLocation visitor:
* - updates enclosing scope for array and index, and calls their visitors recursively
* returns true, or null if encountered an error
*/
public Object visit(ArrayLocation location) {
location.getArray().setEnclosingScope(location.getEnclosingScope());
if (location.getArray().accept(this) == null) return null;
location.getIndex().setEnclosingScope(location.getEnclosingScope());
if (location.getIndex().accept(this) == null) return null;
return true;
}
/**
* ExpressionBlock visitor:
* - updates enclosing scope for expression, and calls its visitor recursively
* returns true, or null if encountered an error
*/
public Object visit(ExpressionBlock expressionBlock) {
expressionBlock.getExpression().setEnclosingScope(expressionBlock.getEnclosingScope());
if (expressionBlock.getExpression().accept(this) == null) return null;
return true;
}
/**
* Field visitor:
* - updates enclosing scope for type, and calls its visitor recursively
* adding field to class symbol table is handled in the class's visitor
* returns true, or null if encountered an error
*/
public Object visit(Field field) {
field.getType().setEnclosingScope(field.getEnclosingScope());
if (field.getType().accept(this) == null) return null;
return true;
}
/**
* Formal visitor:
* - updates enclosing scope for type, and calls its visitor recursively
* adding formal (parameter) to method symbol table is handled in the method's visitor
* returns true, or null if encountered an error
*/
public Object visit(Formal formal) {
formal.getType().setEnclosingScope(formal.getEnclosingScope());
if (formal.getType().accept(this) == null) return null;
return true;
}
/**
* Length visitor:
* - updates enclosing scope for array, and calls its visitor recursively
* returns true, or null if encountered an error
*/
public Object visit(Length length) {
length.getArray().setEnclosingScope(length.getEnclosingScope());
if (length.getArray().accept(this) == null) return null;
return true;
}
/**
* Literal visitor: does nothing, returns true
*/
public Object visit(Literal literal) {
return true;
}
/**
* BinaryOp visit helper:
* - updates enclosing scope for operand1 and operand2, and calls their visitors recursively
* used for LogicalBinaryOp and MathBinaryOp
* returns true, or null if encountered an error
*/
public Object binaryOpVisit(BinaryOp binaryOp){
binaryOp.getFirstOperand().setEnclosingScope(binaryOp.getEnclosingScope());
if (binaryOp.getFirstOperand().accept(this) == null) return null;
binaryOp.getSecondOperand().setEnclosingScope(binaryOp.getEnclosingScope());
if (binaryOp.getSecondOperand().accept(this) == null) return null;
return true;
}
/**
* LogicalBinaryOp visitor: see binaryOpVisit documentation
*/
public Object visit(LogicalBinaryOp binaryOp) {
return binaryOpVisit(binaryOp);
}
/**
* MathBinaryOp visitor: see binaryOpVisit documentation
*/
public Object visit(MathBinaryOp binaryOp) {
return binaryOpVisit(binaryOp);
}
/**
* UnaryOp visit helper:
* - updates enclosing scope for operand, and calls its visitor recursively
* used for LogicalUnaryOp and MathUnaryOp
* returns true, or null if encountered an error
*/
public Object unaryOpVisit(UnaryOp unaryOp){
unaryOp.getOperand().setEnclosingScope(unaryOp.getEnclosingScope());
if (unaryOp.getOperand().accept(this) == null) return null;
return true;
}
/**
* LogicalUnaryOp visitor: see unaryOpVisit documentation
*/
public Object visit(LogicalUnaryOp unaryOp) {
return unaryOpVisit(unaryOp);
}
/**
* MathUnaryOp visitor: see unaryOpVisit documentation
*/
public Object visit(MathUnaryOp unaryOp) {
return unaryOpVisit(unaryOp);
}
/**
* NewArray visitor:
* - updates enclosing scope for type and size, and calls their visitors recursively
* returns true, or null if encountered an error
*/
public Object visit(NewArray newArray) {
newArray.getType().setEnclosingScope(newArray.getEnclosingScope());
if (newArray.getType().accept(this) == null) return null;
newArray.getSize().setEnclosingScope(newArray.getEnclosingScope());
if (newArray.getSize().accept(this) == null) return null;
return true;
}
/**
* NewClass visitor: does nothing, returns true
*/
public Object visit(NewClass newClass) {
return true;
}
/**
* PrimitiveType visitor: does nothing, returns true
*/
public Object visit(PrimitiveType type) {
return true;
}
/**
* This visitor: does nothing, returns true
*/
public Object visit(This thisExpression) {
return true;
}
/**
* UserType visitor: does nothing, returns true
*/
public Object visit(UserType type) {
return true;
}
/**
* VariableLocation visitor:
* - updates enclosing scope for location, and calls its visitor recursively
* returns true, or null if encountered an error
*/
public Object visit(VariableLocation location) {
if (location.isExternal()){ // field location is not null
location.getLocation().setEnclosingScope(location.getEnclosingScope());
if (location.getLocation().accept(this) == null) return null;
}else try{
// check that the location is a previously defined variable
((BlockSymbolTable) location.getEnclosingScope()).getVarSymbolRec(location.getName());
} catch (SemanticError se){
se.setLine(location.getLine());
System.err.println(se);
return null;
}
return true;
}
/**
* StaticCall visitor:
* - updates enclosing scope for arguments, and calls their visitors recursively
* returns true, or null if encountered an error
*/
public Object visit(StaticCall call) {
for (Expression e: call.getArguments()){
e.setEnclosingScope(call.getEnclosingScope());
if (e.accept(this) == null) return null;
}
return true;
}
/**
* VirtualCall visitor:
* - updates enclosing scope for location and arguments, and calls their visitors recursively
* returns true, or null if encountered an error
*/
public Object visit(VirtualCall call) {
if (call.isExternal()) { // field location is not null
call.getLocation().setEnclosingScope(call.getEnclosingScope());
if (call.getLocation().accept(this) == null) return null;
}
for (Expression e: call.getArguments()){
e.setEnclosingScope(call.getEnclosingScope());
if (e.accept(this) == null) return null;
}
return true;
}
}
|
Python | UTF-8 | 331 | 4.3125 | 4 | [] | no_license | #Name: Dante Rivera
#Date: August 27th, 2018
#This program draws an octagon using the turtle module when run
#Importing turtle module
import turtle
#Creating a turtle and naming it
dat_t = turtle.Turtle()
# Move turtle 5 times forward 150 units, and 144deg to the right
for i in range(5):
dat_t.forward(150)
dat_t.right(144)
|
C# | UTF-8 | 944 | 2.8125 | 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 PruebaSuma
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPulsar_Click(object sender, EventArgs e)
{
try
{
int num1 = Convert.ToInt16(txtN1.Text);
int num2 = Convert.ToInt16(txtN2.Text);
int suma = num1 + num2;
txtResultado.Text = suma.ToString();
}
catch (FormatException err)
{
MessageBox.Show("Lo siento ocurrió un error(s) : "+err.Message+"!!");
}
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
|
Java | UTF-8 | 2,116 | 3.40625 | 3 | [] | no_license | package com.nexusy.algorithms.string;
/**
* @author lanhuidong
* @since 2019-04-02
*/
public class Msd {
private static final int radix = 256;
private static final int m = 15;
private static String[] aux;
private static int charAt(String s, int d) {
return d < s.length() ? s.charAt(d) : -1;
}
public static void sort(String[] a) {
int n = a.length;
aux = new String[n];
sort(a, 0, n - 1, 0);
}
private static void insertionSort(String[] a, int lo, int hi, int d) {
for (int i = lo; i <= hi; i++) {
for (int j = i; j > lo && less(a[j], a[j - 1], d); j--) {
String tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
}
}
}
private static boolean less(String v, String w, int d) {
return v.substring(d).compareTo(w.substring(d)) < 0;
}
private static void sort(String[] a, int lo, int hi, int d) {
if (lo + m >= hi) { //小数组采用插入排序,避免初始化count数组的开销
insertionSort(a, lo, hi, d);
return;
}
int[] count = new int[radix + 2];
for (int i = lo; i <= hi; i++) { //计算频率
count[charAt(a[i], d) + 2]++;
}
for (int r = 0; r < radix + 1; r++) { //转换成索引
count[r + 1] += count[r];
}
for (int i = lo; i <= hi; i++) { //在辅助数组中排序
aux[count[charAt(a[i], d) + 1]++] = a[i];
}
for (int i = lo; i <= hi; i++) { //拷贝回原数组
a[i] = aux[i - lo];
}
for (int r = 0; r < radix; r++) {
sort(a, lo + count[r], lo + count[r + 1] - 1, d + 1);
}
}
public static void main(String[] args) {
String[] a = {"she", "sells", "seashells", "by", "the", "sea", "shore", "the", "shells", "she", "sells", "are", "surely", "seashells"};
sort(a);
for (String s : a) {
System.out.print(s);
System.out.print(" ");
}
System.out.println();
}
}
|
Python | UTF-8 | 612 | 3.109375 | 3 | [] | no_license | # coding : utf-8
from selenium import webdriver # 导入 webdriver ,相当于加载了 webdriver 里面所有的方法
import time # 导入 time 包
driver = webdriver.Chrome() # 创建 chrome 对象
driver.get("https://www.csdn.net/")
time.sleep(3) # 网页打开后等待停止3秒
driver.set_window_size(800,600) # 固定大小显示
driver.get_screenshot_as_file(".\\jieping.png")
driver.refresh() # 刷新页面
time.sleep(5) # 目的是为了查看效果
driver.quit() # 关闭 chrome 对象
|
Java | UTF-8 | 6,043 | 2.5625 | 3 | [] | no_license | package paneles;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.SystemColor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ModificarClientes extends JPanel {
private JTextField txtId;
private JTextField txtCalle;
private JTextField txtPoblacion;
private JTextField txtProvincia;
private JTextField txtCP;
private JTextField txtTelefono;
private JTextField txtDniCliente;
private JTextField txtApellidos;
private JTextField txtNombre;
/**
* Create the panel.
*/
public ModificarClientes() {
setBackground(Color.WHITE);
setLayout(null);
JLabel lblIndiqueElId = new JLabel("Indique el id Cliente a modificar:");
lblIndiqueElId.setForeground(SystemColor.textHighlight);
lblIndiqueElId.setFont(new Font("Tahoma", Font.BOLD, 22));
lblIndiqueElId.setBounds(48, 232, 378, 40);
add(lblIndiqueElId);
txtId = new JTextField();
txtId.setFont(new Font("Tahoma", Font.BOLD, 18));
txtId.setBounds(436, 245, 96, 26);
add(txtId);
txtId.setColumns(10);
txtCalle = new JTextField();
txtCalle.setColumns(10);
txtCalle.setBackground(SystemColor.inactiveCaption);
txtCalle.setBounds(758, 424, 123, 20);
add(txtCalle);
txtPoblacion = new JTextField();
txtPoblacion.setColumns(10);
txtPoblacion.setBackground(SystemColor.inactiveCaption);
txtPoblacion.setBounds(758, 390, 123, 20);
add(txtPoblacion);
txtProvincia = new JTextField();
txtProvincia.setColumns(10);
txtProvincia.setBackground(SystemColor.inactiveCaption);
txtProvincia.setBounds(758, 356, 123, 20);
add(txtProvincia);
txtCP = new JTextField();
txtCP.setColumns(10);
txtCP.setBackground(SystemColor.inactiveCaption);
txtCP.setBounds(758, 315, 123, 20);
add(txtCP);
txtTelefono = new JTextField();
txtTelefono.setColumns(10);
txtTelefono.setBackground(SystemColor.inactiveCaption);
txtTelefono.setBounds(760, 276, 123, 20);
add(txtTelefono);
txtDniCliente = new JTextField();
txtDniCliente.setColumns(10);
txtDniCliente.setBackground(SystemColor.inactiveCaption);
txtDniCliente.setBounds(760, 235, 123, 20);
add(txtDniCliente);
txtApellidos = new JTextField();
txtApellidos.setColumns(10);
txtApellidos.setBackground(SystemColor.inactiveCaption);
txtApellidos.setBounds(760, 203, 121, 20);
add(txtApellidos);
txtNombre = new JTextField();
txtNombre.setColumns(10);
txtNombre.setBackground(SystemColor.inactiveCaption);
txtNombre.setBounds(760, 174, 121, 20);
add(txtNombre);
JLabel lblNombre = new JLabel("Nombre Cliente:");
lblNombre.setForeground(SystemColor.textHighlight);
lblNombre.setFont(new Font("Arial", Font.BOLD, 16));
lblNombre.setBounds(614, 164, 149, 35);
add(lblNombre);
JLabel lblApellidos = new JLabel("Apellidos Cliente:");
lblApellidos.setForeground(SystemColor.textHighlight);
lblApellidos.setFont(new Font("Arial", Font.BOLD, 16));
lblApellidos.setBounds(614, 193, 149, 35);
add(lblApellidos);
JLabel lblDni = new JLabel("DNI Cliente: ");
lblDni.setForeground(SystemColor.textHighlight);
lblDni.setFont(new Font("Arial", Font.BOLD, 16));
lblDni.setBounds(647, 235, 108, 15);
add(lblDni);
JLabel lblTelefono = new JLabel("Telefono:");
lblTelefono.setForeground(SystemColor.textHighlight);
lblTelefono.setFont(new Font("Arial", Font.BOLD, 16));
lblTelefono.setBounds(666, 276, 91, 14);
add(lblTelefono);
JLabel lblCP = new JLabel("CP:");
lblCP.setForeground(SystemColor.textHighlight);
lblCP.setFont(new Font("Arial", Font.BOLD, 16));
lblCP.setBounds(709, 315, 39, 14);
add(lblCP);
JLabel lblProvincia = new JLabel("Provincia:");
lblProvincia.setForeground(SystemColor.textHighlight);
lblProvincia.setFont(new Font("Arial", Font.BOLD, 16));
lblProvincia.setBounds(666, 356, 91, 14);
add(lblProvincia);
JLabel lblPoblacion = new JLabel("Poblaci\u00F3n:");
lblPoblacion.setForeground(SystemColor.textHighlight);
lblPoblacion.setFont(new Font("Arial", Font.BOLD, 16));
lblPoblacion.setBounds(655, 383, 108, 28);
add(lblPoblacion);
JLabel lblCalle = new JLabel("Calle:");
lblCalle.setForeground(SystemColor.textHighlight);
lblCalle.setFont(new Font("Arial", Font.BOLD, 16));
lblCalle.setBounds(695, 421, 66, 20);
add(lblCalle);
JButton btnModificarCliente = new JButton("Modificar Cliente");
btnModificarCliente.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
modificarCliente();
}
});
btnModificarCliente.setForeground(Color.WHITE);
btnModificarCliente.setFont(new Font("Arial", Font.BOLD, 18));
btnModificarCliente.setBackground(Color.BLUE);
btnModificarCliente.setBounds(555, 565, 209, 35);
add(btnModificarCliente);
}
public void modificarCliente() {
try {
int id=Integer.parseInt(txtId.getText());
String nombre = txtNombre.getText();
String apellidos = txtApellidos.getText();
int telefono = Integer.parseInt(txtTelefono.getText());
String dni = txtDniCliente.getText();
int cp = Integer.parseInt(txtCP.getText());
String provincia = txtProvincia.getText();
String poblacion = txtPoblacion.getText();
String calle = txtCalle.getText();
String agregar = "update Clientes set nombre='"+nombre+"', apellidos='"+ apellidos+"', telefono='"+telefono+"', "
+ "DNI='"+dni+"', CP='"+cp+"', Provincia='"+provincia+"', Poblacion='"+poblacion+"', Calle='"+calle+"' where ID="+id;
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/SotecarsBBDD", "TRABAJO",
"TRABAJO");
Statement consulta = conexion.createStatement();
consulta.executeUpdate(agregar);
JOptionPane.showMessageDialog(null, "Cliente Modificado");
conexion.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
JavaScript | UTF-8 | 9,096 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | var SamsungRemote = require('samsung-remote');
var inherits = require('util').inherits;
var Service, Characteristic, VolumeCharacteristic, ChannelCharacteristic, KeyCharacteristic;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
// we can only do this after we receive the homebridge API object
makeChannelCharacteristic();
makeKeyCharacteristic();
homebridge.registerAccessory("homebridge-samsungtv", "SamsungTV", SamsungTvAccessory);
};
//
// SoundTouch Accessory
//
function SamsungTvAccessory(log, config) {
this.log = log;
this.config = config;
this.name = config["name"];
this.ip_address = config["ip_address"] || '0.0.0.0';
this.send_delay = config["send_delay"] || 400;
this.host = config["host"] || null;
this.volume = config["defaultVolume"] || 50;
this.volume = Math.min(Math.max(this.volume, 100), 0);
if (this.ip_address == '0.0.0.0') this.log('Auto discover TV with UPnP');
this.remote = new SamsungRemote({
ip: this.ip_address, // required: IP address of your Samsung Smart TV
host: { ip: "127.0.0.1", mac: "11:00:AA:EE:BB:22", name: "HomeBridge" }
});
this.isSendingSequence = false;
// The channel value can not be accessed on the tv
// if the normal remote is used to change the channel
// the value will not be updated therefore
this.channel = 1;
this.service = new Service.Switch(this.name);
this.service
.getCharacteristic(Characteristic.On)
.on('get', this._getOn.bind(this))
.on('set', this._setOn.bind(this));
this.service
.addCharacteristic(Characteristic.Volume)
.on('set', this._setVolume.bind(this))
.updateValue(this.volume);
this.service
.addCharacteristic(ChannelCharacteristic)
.on('get', this._getChannel.bind(this))
.on('set', this._setChannel.bind(this));
this.service
.addCharacteristic(KeyCharacteristic)
.on('get', this._getKey.bind(this))
.on('set', this._setKey.bind(this));
if(this.remote.availability) {
var that = this;
this.remote.availability.on('change', function(available) {
that.service.getCharacteristic(Characteristic.On).updateValue(available ? 1 : 0)
});
}
}
SamsungTvAccessory.prototype.getInformationService = function() {
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Name, this.name)
.setCharacteristic(Characteristic.Manufacturer, 'Samsung TV')
.setCharacteristic(Characteristic.Model, '1.0.0')
.setCharacteristic(Characteristic.SerialNumber, this.ip_address);
return informationService;
};
SamsungTvAccessory.prototype.getServices = function() {
return [this.service, this.getInformationService()];
};
SamsungTvAccessory.prototype._getOn = function(callback) {
var accessory = this;
this.remote.isAlive(function(err) {
if (err) {
accessory.log.debug('TV is offline: %s', err);
callback(null, false);
} else {
accessory.log.debug('TV is alive.');
callback(null, true);
}
});
};
SamsungTvAccessory.prototype._setOn = function(on, callback) {
var accessory = this;
if (on) {
//callback(new Error('Could not turn on TV'));
this.remote.send('KEY_POWERON', function(err) {
if (err) {
accessory.log.debug('Could not turn TV on: %s', err);
callback(new Error(err));
} else {
accessory.log.debug('TV successfully turnen on');
callback(null);
}
});
} else {
this.remote.send('KEY_POWEROFF', function(err) {
if (err && accessory.remote.isAvailable) {
accessory.log.debug('Could not turn TV off: %s', err);
callback(new Error(err));
} else {
accessory.log.debug('TV successfully turned off');
callback(null);
}
});
}
};
SamsungTvAccessory.prototype._setVolume = function(volume, callback) {
var accessory = this;
// Dismiss the request when another key sequence sending
if (this.isSendingSequence) {
callback(null);
this.log.debug('Cannot send volume change by %s while sending other key sequence.', volume);
return;
}
this.isSendingSequence = true;
// When volume is 0, mute will be toggled
if (volume === 0) {
accessory.remote.send('KEY_MUTE', function(err) {
if (err) {
accessory.isSendingSequence = false;
callback(new Error(err));
accessory.log.error('Could not send mute key: %s', err);
return;
}
accessory.log.debug('Finished sending mute key.');
accessory.isSendingSequence = false;
callback(null);
});
return;
}
this.log.debug('Changing volume to %s. Current is %s', volume, accessory.volume);
var volumeKey = volume > accessory.volume ? 'KEY_VOLUP' : 'KEY_VOLDOWN';
var absVolume = Math.abs(volume-accessory.volume);
function sendKey(index) {
if (index > 0) {
accessory.remote.send(volumeKey, function(err) {
if (err) {
accessory.isSendingSequence = false;
callback(new Error(err));
accessory.log.error('Could not send volume key %s: %s', volumeKey, err);
return;
}
// Send the next key after the specified delay
setTimeout(function() {
sendKey(--index)
}, accessory.send_delay);
});
return;
}
accessory.log.debug('Finished changing volume to %s.', volume);
accessory.volume = volume;
accessory.isSendingSequence = false;
callback(null);
}
sendKey(absVolume);
};
SamsungTvAccessory.prototype._getChannel = function(callback) {
var accessory = this;
callback(null, accessory.channel);
};
SamsungTvAccessory.prototype._setChannel = function(channel, callback) {
var accessory = this;
// Dismiss the request when another key sequence sending
if (this.isSendingSequence) {
callback(null);
this.log.debug('Cannot send channel %s while sending other key sequence.', channel);
return;
}
this.isSendingSequence = true;
this.log.debug('Sending channel %s.', channel);
var channelInt = parseInt(channel, 10);
if (isNaN(channelInt) || channelInt < 1 || channelInt > 9999) {
callback(new Error('Invalid channel "' + channel + '"'));
this.log.error('Invalid channel "%s".', channel);
return;
}
var chStr = channelInt.toString(),
keys = [];
for (var i = 0, j = chStr.length; i < j; ++i) {
keys.push('KEY_' + chStr[i]);
}
// Add the enter key to the end
keys.push('KEY_ENTER');
function sendKey(index) {
if (index < keys.length) {
accessory.log.debug('Sending channel key %s.', keys[index]);
accessory.remote.send(keys[index], function(err) {
if (err) {
accessory.isSendingSequence = false;
callback(new Error(err));
accessory.log.error('Could not send channel key %s: %s', keys[index], err);
return;
}
// Send the next key after the specified delay
setTimeout(function() {
sendKey(++index)
}, accessory.send_delay);
});
return;
}
accessory.log.debug('Finished sending channel %s.', channel);
accessory.isSendingSequence = false;
accessory.channel = channel;
callback(null);
}
sendKey(0)
};
SamsungTvAccessory.prototype._getKey = function(callback) {
var accessory = this;
callback(null, accessory.key);
};
SamsungTvAccessory.prototype._setKey = function(key, callback) {
var accessory = this;
// Dismiss the request when a key sequence is sending
if (this.isSendingSequence) {
callback(null);
this.log.debug('Cannot send key %s while sending a key sequence.', key);
return;
}
this.isSendingSequence = true;
this.log.debug('Sending key %s.', key);
accessory.remote.send('KEY_' + key.toUpperCase(), function(err) {
if (err) {
accessory.isSendingSequence = false;
callback(new Error(err));
accessory.log.error('Could not send key %s: %s', key, err);
return;
}
accessory.log.debug('Finished sending key %s.', key);
accessory.isSendingSequence = false;
accessory.key = key;
callback(null);
});
};
/**
* Custom characteristic for channel
*
* @return {Characteristic} The channel characteristic
*/
function makeChannelCharacteristic() {
ChannelCharacteristic = function () {
Characteristic.call(this, 'Channel', '212131F4-2E14-4FF4-AE13-C97C3232499D');
this.setProps({
format: Characteristic.Formats.STRING,
unit: Characteristic.Units.NONE,
//maxValue: 9999,
//minValue: 1,
//minStep: 1,
perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
});
//this.value = this.getDefaultValue();
this.value = "1";
};
inherits(ChannelCharacteristic, Characteristic);
}
/**
* Custom characteristic for any key
* @see(https://github.com/natalan/samsung-remote) The key can be any remote key without the KEY_ at the beginning (e.g. MENU)
*
* @return {Characteristic} The key characteristic
*/
function makeKeyCharacteristic() {
KeyCharacteristic = function() {
Characteristic.call(this, 'Key', '2A6FD4DE-8103-4E58-BDAC-25835CD006BD');
this.setProps({
format: Characteristic.Formats.STRING,
unit: Characteristic.Units.NONE,
//maxValue: 10,
//minValue: -10,
//minStep: 1,
perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
});
//this.value = this.getDefaultValue();
this.value = "TV";
};
inherits(KeyCharacteristic, Characteristic);
}
|
Swift | UTF-8 | 7,552 | 2.703125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //
// SweetHMAC.swift
// SweetHMAC
//
// Copyright (c) 2014 Jan Cassio. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/*
Special thanks to jernejstrasner to provide the gist that inspired this approach
URL: https://gist.github.com/jernejstrasner/1d5fa5e2fabda2e729d1
*/
import Foundation
import CommonCrypto
public extension String {
/**
Proved a string for some HMAC algorithm and secret string.
- parameter algorithm: Some HMAC algorithm. Supported types are:
- MD5
- SHA1
- SHA224
- SHA256
- SHA384
- SHA512
- parameter secret: A secret message to authenticate the encrypted message.
- returns: A encryped string based on HMAC algorithm and secret string.
*/
func HMAC(algorithm: HMACAlgorithm, secret: String) -> String {
return SweetHMAC(message: self, secret: secret).HMAC(algorithm: algorithm)
}
func MD5() -> String {
return SweetHMAC.MD5(input: self)
}
func SHA1() -> String {
return SweetHMAC.SHA1(input: self)
}
func SHA224() -> String {
return SweetHMAC.SHA224(input: self)
}
func SHA256() -> String {
return SweetHMAC.SHA256(input: self)
}
func SHA384() -> String {
return SweetHMAC.SHA384(input: self)
}
func SHA512() -> String {
return SweetHMAC.SHA512(input: self)
}
}
/**
HMACAlgoriths enumerates all HMAC algorithms types supported by iOS (not verified in Mac OS X environment yet)
Supported iOS HMAC algorithms:
- MD5
- SHA1
- SHA224
- SHA256
- SHA348
- SHA512
*/
public enum HMACAlgorithm {
case md5, sha1, sha224, sha256, sha384, sha512
/**
Give the native value for HMACAlgorithm value
- returns: The system `CCHmacAlgorithm` native value.
*/
func toNative() -> CCHmacAlgorithm {
switch self {
case .md5:
return CCHmacAlgorithm(kCCHmacAlgMD5)
case .sha1:
return CCHmacAlgorithm(kCCHmacAlgSHA1)
case .sha224:
return CCHmacAlgorithm(kCCHmacAlgSHA224)
case .sha256:
return CCHmacAlgorithm(kCCHmacAlgSHA256)
case .sha384:
return CCHmacAlgorithm(kCCHmacAlgSHA384)
case .sha512:
return CCHmacAlgorithm(kCCHmacAlgSHA512)
}
}
func digestLength() -> Int {
switch self {
case .md5:
return Int(CC_MD5_DIGEST_LENGTH)
case .sha1:
return Int(CC_SHA1_DIGEST_LENGTH)
case .sha224:
return Int(CC_SHA224_DIGEST_LENGTH)
case .sha256:
return Int(CC_SHA256_DIGEST_LENGTH)
case .sha384:
return Int(CC_SHA384_DIGEST_LENGTH)
case .sha512:
return Int(CC_SHA512_DIGEST_LENGTH)
}
}
}
/// A simple class to encrypt strings using HMAC algorithms.
public class SweetHMAC {
struct UTF8EncodedString {
var data: [CChar]
var length: Int
public init(string: String) {
data = string.cString(using: String.Encoding.utf8)!
length = string.lengthOfBytes(using: String.Encoding.utf8)
}
}
/// Message to be encrypted
fileprivate var message = ""
/// Secret message to authenticate the encrypted message.
fileprivate var secret = ""
/**
Create a new SweetHMAC instance with given message and secret strings.
- parameter message: The message to be encrypted.
- parameter secret: The secret message to authenticate encrypted message.
*/
public init(message: String, secret: String) {
self.message = message
self.secret = secret
}
/**
Generate HMAC string with given algorithm.
- parameter algorithm: Algorithm to encrypt message.
- returns: A encrypted string.
*/
public func HMAC(algorithm: HMACAlgorithm) -> String {
let seed = UTF8EncodedString(string: message)
let key = UTF8EncodedString(string: secret)
let digestLength = algorithm.digestLength()
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLength)
CCHmac(algorithm.toNative(), key.data, key.length, seed.data, seed.length, result)
let hash = NSMutableString()
for i in 0..<digestLength {
hash.appendFormat("%02x", result[i])
}
// result.deinitialize()
return String(hash)
}
/**
Generate MD5 hash from the input string provided.
- parameter input: The string to be encrypted.
- returns: A encrypted string.
*/
public class func MD5(input: String) -> String {
return digest(algorithm: .md5, input: input)
}
/**
Generate SHA1 hash from the input string provided.
- parameter input: The string to be encrypted.
- returns: A encrypted string.
*/
public class func SHA1(input: String) -> String {
return digest(algorithm: .sha1, input: input)
}
/**
Generate SHA224 hash from the input string provided.
- parameter input: The string to be encrypted.
- returns: A encrypted string.
*/
public class func SHA224(input: String) -> String {
return digest(algorithm: .sha224, input: input)
}
/**
Generate SHA256 hash from the input string provided.
- parameter input: The string to be encrypted.
- returns: A encrypted string.
*/
public class func SHA256(input: String) -> String {
return digest(algorithm: .sha256, input: input)
}
/**
Generate SHA384 hash from the input string provided.
- parameter input: The string to be encrypted.
- returns: A encrypted string.
*/
public class func SHA384(input: String) -> String {
return digest(algorithm: .sha384, input: input)
}
/**
Generate SHA512 hash from the input string provided.
- parameter input: The string to be encrypted.
- returns: A encrypted string.
*/
public class func SHA512(input: String) -> String {
return digest(algorithm: .sha512, input: input)
}
/**
Generate abstraction for static methods
- parameter algorithm: Algorithm to encrypt message.
- parameter input: The string to be encrypted.
- returns: A encrypted string.
*/
public class func digest(algorithm: HMACAlgorithm, input: String) -> String {
let seed = UTF8EncodedString(string: input)
let digestLength = algorithm.digestLength()
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: digestLength)
switch algorithm {
case .md5:
CC_MD5(seed.data, CC_LONG(seed.length), result)
case .sha1:
CC_SHA1(seed.data, CC_LONG(seed.length), result)
case .sha224:
CC_SHA224(seed.data, CC_LONG(seed.length), result)
case .sha256:
CC_SHA256(seed.data, CC_LONG(seed.length), result)
case .sha384:
CC_SHA384(seed.data, CC_LONG(seed.length), result)
case .sha512:
CC_SHA512(seed.data, CC_LONG(seed.length), result)
}
let hash = NSMutableString()
for i in 0..<digestLength {
hash.appendFormat("%02x", result[i])
}
// result.deinitialize()
return String(hash)
}
}
|
PHP | UTF-8 | 378 | 2.78125 | 3 | [] | no_license | <?php
$wage = (10);
$regular_hours = (40);
$overtime = (2);
$overtime = (2);
$pay += ($overtime * $wage * 1.5);
$pay += ($regular_hours + $overtime) * $wage;
echo "hours worked: " . $regular_hours . "<br>";
echo "pay rate: $" . number_format($wage, 2) . "<br>";
echo "overtime hours: " . $overtime . "<br>";
echo "paycheck is: $" . number_format($pay, 2) . "<br>";
?>
|
Java | UTF-8 | 3,248 | 1.851563 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package io.jenkins.plugins.opentelemetry.job;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.Run;
import io.jenkins.plugins.opentelemetry.JenkinsOpenTelemetryPluginConfiguration;
import io.jenkins.plugins.opentelemetry.semconv.OTelEnvironmentVariablesConventions;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import io.opentelemetry.context.propagation.TextMapSetter;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Inject OpenTelemetry environment variables in shell steps: {@code TRACEPARENT}, {@code OTEL_EXPORTER_OTLP_ENDPOINT}...
*
* @see org.jenkinsci.plugins.workflow.steps.StepEnvironmentContributor
* @see hudson.model.EnvironmentContributor
*/
@Extension
public class OtelEnvironmentContributorService {
private final static Logger LOGGER = Logger.getLogger(OtelEnvironmentContributorService.class.getName());
private JenkinsOpenTelemetryPluginConfiguration jenkinsOpenTelemetryPluginConfiguration;
public void addEnvironmentVariables(@Nonnull Run run, @Nonnull EnvVars envs, @Nonnull Span span) {
String spanId = span.getSpanContext().getSpanId();
String traceId = span.getSpanContext().getTraceId();
try (Scope ignored = span.makeCurrent()) {
envs.putIfAbsent(OTelEnvironmentVariablesConventions.TRACE_ID, traceId);
envs.put(OTelEnvironmentVariablesConventions.SPAN_ID, spanId);
TextMapSetter<EnvVars> setter = (carrier, key, value) -> carrier.put(key.toUpperCase(), value);
W3CTraceContextPropagator.getInstance().inject(Context.current(), envs, setter);
}
MonitoringAction action = new MonitoringAction(traceId, spanId);
action.onAttached(run);
for (MonitoringAction.ObservabilityBackendLink link : action.getLinks()) {
// Default backend link got an empty environment variable.
if (link.getEnvironmentVariableName() != null) {
envs.put(link.getEnvironmentVariableName(), link.getUrl());
}
}
if (this.jenkinsOpenTelemetryPluginConfiguration.isExportOtelConfigurationAsEnvironmentVariables()) {
Map<String, String> otelConfiguration = jenkinsOpenTelemetryPluginConfiguration.getOtelConfigurationAsEnvironmentVariables();
for (Map.Entry<String, String> otelEnvironmentVariable : otelConfiguration.entrySet()) {
String previousValue = envs.put(otelEnvironmentVariable.getKey(), otelEnvironmentVariable.getValue());
if (previousValue != null) {
LOGGER.log(Level.FINE, "Overwrite environment variable '" + otelEnvironmentVariable.getKey() + "'");
}
}
} else {
// skip
}
}
@Inject
public void setJenkinsOpenTelemetryPluginConfiguration(JenkinsOpenTelemetryPluginConfiguration jenkinsOpenTelemetryPluginConfiguration) {
this.jenkinsOpenTelemetryPluginConfiguration = jenkinsOpenTelemetryPluginConfiguration;
}
}
|
Markdown | UTF-8 | 3,646 | 2.921875 | 3 | [] | no_license | #0x00. AirBnB clone - The console#
Welcome to the AirBnB clone project! (The Holberton B&B)
In this project we are going to create the first part of the Airbnb clone, for this you want to create a console where you can manage Airbnb objects or instances.
#CONSOLE FUNCTIONALITIES#
Create a new object (ex: a new User or a new Place)
Retrieve an object from a file, a database etc…
Do operations on objects (count, compute stats, etc…)
Update attributes of an object
Destroy an object
#INSTALLATION#
git clone https://github.com/ch-canaza/AirBnB_clone.git
cd AirBnB_clone
#USABILITY#
INTERACTIVE MODE
$ ./console.py
(hbnb) help
Documented commands (type help <topic>):
========================================
EOF help quit
(hbnb)
(hbnb)
(hbnb) quit
$
NON-INTERACTIVE
$ echo "help" | ./console.py
(hbnb)
Documented commands (type help <topic>):
========================================
EOF help quit
(hbnb)
$
$ cat test_help
help
$
$ cat test_help | ./console.py
(hbnb)
Documented commands (type help <topic>):
========================================
EOF help quit
(hbnb)
$
#UNITTEST#
All the commands were tested and reviewed with unittest to ensure their
functionality and minimize the probability of errors.
#DEPLOYMENT#
Your team must be Ubuntu or use a virtual machine with this operating system.
To install on your computer you must download the project folders from the git described above.
Enter the project folder.
Run the ./console.py code
Enjoy
#BUILT WITH#
Python3
#EXAMPLES#
#EXAMPLE FOR help#
./console.py
Help
Help create
This is the output
Creates a new instance of BaseModel,
saves it (to the JSON file) and prints the id.
Ex: $ create BaseModel
help destroy
This is the output
Deletes an instance based on the class name and id
#Example for all, create, show#
Prints all string representation of all instances based or not on the class name. Ex: $ all BaseModel or $ all.
./console.py
(hbnb) all MyModel
** class doesn't exist **
(hbnb) show BaseModel
** instance id missing **
(hbnb) show BaseModel Holberton
** no instance found **
(hbnb) create BaseModel
49faff9a-6318-451f-87b6-910505c55907
(hbnb) all BaseModel
["[BaseModel] (49faff9a-6318-451f-87b6-910505c55907) {'created_at': datetime.datetime(2017, 10, 2, 3, 10, 25, 903293), 'id': '49faff9a-6318-451f-87b6-910505c55907', 'updated_at': datetime.datetime(2017, 10, 2, 3, 10, 25, 903300)}"]
(hbnb) show BaseModel 49faff9a-6318-451f-87b6-910505c55907
[BaseModel] (49faff9a-6318-451f-87b6-910505c55907) {'created_at': datetime.datetime(2017, 10, 2, 3, 10, 25, 903293), 'id': '49faff9a-6318-451f-87b6-910505c55907', 'updated_at': datetime.datetime(2017, 10, 2, 3, 10, 25, 903300)}
#EXAMPLE TO DESTROY#
destroy: Deletes an instance based on the class name
and id (save the change into the JSON file). Ex: $
destroy BaseModel 1234-1234-1234.
(hbnb) destroy BaseModel 49faff9a-6318-451f-87b6-910505c55907
(hbnb) show BaseModel 49faff9a-6318-451f-87b6-910505c55907
** no instance found **
(hbnb)
#EXAMPLE TO UPDATE#
update: Updates an instance based on the class name
and id by adding or updating attribute (save the change
into the JSON file). Ex: $ update BaseModel 1234-1234-1234
email "aibnb@holbertonschool.com".
(hbnb) update BaseModel 49faff9a-6318-451f-87b6-910505c55907 first_name "Betty"
(hbnb) show BaseModel 49faff9a-6318-451f-87b6-910505c55907
[BaseModel] (49faff9a-6318-451f-87b6-910505c55907) {'first_name': 'Betty', 'id': '49faff9a-6318-451f-87b6-910505c55907', 'created_at': datetime.datetime(2017, 10, 2, 3, 10, 25, 903293), 'updated_at': datetime.datetime(2017, 10, 2, 3, 11, 3, 49401)}
|
Shell | UTF-8 | 1,805 | 3.890625 | 4 | [] | no_license | #!/bin/sh
#
# Music Box boot script
#
# (c) 2021 Yoichi Tanibayashi
#
MYNAME=`basename $0`
MUSICBOX_CMD=$HOME/bin/MusicBox
ENV_FILE=$HOME/musicbox-env
. $ENV_FILE
LOGDIR=$MUSICBOX_LOG_DIR
BOOT_FLAG=1
DEBUG_FLAG=
#
# functions
#
echo_do() {
_TS=`date +'%F %T'`
echo "$_TS $*"
eval "$*"
return $?
}
usage() {
echo
echo " Music Box boot script"
echo
echo " Usage: $MYNAME [-h] [-k] [-d]"
echo
echo " -k kill only"
echo " -d debug flag"
echo " -h show this usage"
echo
}
get_musicbox_pid() {
echo `ps x | grep python | sed -n '/musicbox/s/ *//p' | cut -d ' ' -f 1`
}
#
# main
#
while getopts hkd OPT; do
case $OPT in
h) usage; exit 0;;
k) BOOT_FLAG=0;;
d) DEBUG_FLAG="-d";;
*) usage; exit 1;;
esac
shift
done
#
# kill
#
echo_do "sudo pkill pigpiod"
sleep 1
PIDS=`get_musicbox_pid`
while [ ! -z "$PIDS" ]; do
echo_do "kill $PIDS"
sleep 1
PIDS=`get_musicbox_pid`
done
sleep 2
if [ $BOOT_FLAG -eq 0 ]; then
# don't boot, kill only
exit 0
fi
#
# boot
#
echo_do "sudo pigpiod"
sleep 1
echo_do "${MUSICBOX_CMD} webapp $DEBUG_FLAG >> $LOGDIR/webapp.log 2>&1 &"
sleep 1
echo_do "${MUSICBOX_CMD} server -w 0 -p 8880 $DEBUG_FLAG >> $LOGDIR/server0.log 2>&1 &"
sleep 2
echo_do "${MUSICBOX_CMD} server -w 1 -p 8881 $DEBUG_FLAG >> $LOGDIR/server1.log 2>&1 &"
sleep 2
echo_do "${MUSICBOX_CMD} server -w 2 -p 8882 $DEBUG_FLAG >> $LOGDIR/server2.log 2>&1 &"
sleep 2
echo_do "${MUSICBOX_CMD} server -w 3 -p 8883 $DEBUG_FLAG >> $LOGDIR/server3.log 2>&1 &"
sleep 5
echo_do "${MUSICBOX_CMD} send -p 8882 single_play 69"
echo_do "${MUSICBOX_CMD} send -p 8882 single_play 73"
echo_do "${MUSICBOX_CMD} send -p 8882 single_play 76"
echo_do "${MUSICBOX_CMD} send -p 8882 single_play 69 73 76"
|
Java | UTF-8 | 2,262 | 2.890625 | 3 | [] | no_license | package com.example.spinnercalculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText et1,et2;
private Spinner sp_options;
private TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText)findViewById(R.id.txt_value1);
et2 = (EditText)findViewById(R.id.txt_value2);
tv1 = (TextView)findViewById(R.id.tv_result);
sp_options = (Spinner)findViewById(R.id.spinner);
String [] options = {"Add", "Subtract", "Multiply", "Divide"};
ArrayAdapter <String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item_config, options);
sp_options.setAdapter(adapter);
}
public void calculate(View view){
String value1_string = et1.getText().toString();
String value2_string = et2.getText().toString();
int value1 = Integer.parseInt(value1_string);
int value2 = Integer.parseInt(value2_string);
String selection = sp_options.getSelectedItem().toString();
if (selection.equals("Add")) {
int add = value1 + value2;
String result = String.valueOf(add);
tv1.setText(result);
} else if (selection.equals("Subtract")){
int sub = value1 - value2;
String result = String.valueOf(sub);
tv1.setText(result);
} else if (selection.equals("Multiply")){
int mul = value1 * value2;
String result = String.valueOf(mul);
tv1.setText(result);
} else if (selection.equals("Divide")){
if (value2 != 0){
int div = value1 / value2;
String result = String.valueOf(div);
tv1.setText(result);
} else {
Toast.makeText(this, "You can't divide a number by 0", Toast.LENGTH_LONG).show();
}
}
}
} |
C++ | UTF-8 | 1,417 | 3.25 | 3 | [] | no_license | #pragma once
#include "SFML\Graphics.hpp"
#include <iostream>
#include <vector>
using namespace std;
class Tooltip
{
public:
Tooltip(sf::Vector2f pos, std::string message, float zoom)
{
arialFont.loadFromFile("Textures/Fonts/arial.ttf");
string.setString(message);
string.setCharacterSize(20 * zoom);
string.setFont(arialFont);
string.setPosition(pos);
string.setFillColor(sf::Color::Black);
int currentNoOfCharacter = 0;
for (size_t i = 0; i < message.length(); i++)
{
currentNoOfCharacter++;
if (message[i] == '\n')
{
numberOfLines++;
if (currentNoOfCharacter > longestLine)
{
longestLine = currentNoOfCharacter;
//cout << "Longest line: " << longestLine << endl;
}
currentNoOfCharacter = 0;
}
}
if (currentNoOfCharacter > longestLine)
{
longestLine = currentNoOfCharacter;
}
//cout << "Longest line: " << longestLine << endl;
//cout << "Number of lines: " << numberOfLines << endl;
rect.setPosition(pos);
rect.setFillColor(sf::Color::White);
rect.setOutlineThickness(2.0f * zoom);
rect.setOutlineColor(sf::Color::Black);
rect.setSize(sf::Vector2f(3 + (9 * longestLine * zoom) + 6, 3 + (22 * numberOfLines * zoom) + 3));
};
void Draw(sf::RenderWindow &w)
{
w.draw(rect);
w.draw(string);
}
private:
sf::Font arialFont;
sf::Text string;
sf::RectangleShape rect;
int numberOfLines = 1;
int longestLine = 0;
};
|
Markdown | UTF-8 | 1,977 | 2.59375 | 3 | [] | no_license | # Bug de Hadoop sous Windows
L'utilisation de Hadoop sous Windows entraîne la levée d'une exception de type IOException (Failed to set permissions of path:
```diff
-\tmp\hadoop-user\mapred\staging\user722309568\.staging to 0700).
```
C'est un bug connu de Hadoop (cf. https://issues.apache.org/jira/browse/HADOOP-7682), qu'il est possible de résoudre de la manière suivante :
1. Télécharger le jar suivant https://github.com/congainc/patch-hadoop_7682-1.0.x-win/downloads
2. Déplacer le jar dans TP_HMIN122M-hadoop/lib-dev
3. Ajouter le .jar au build path
4. Dans le package explorer, clic droit sur le projet /Build Path/Configure Build Path/Librairies/Add external jars
5. Ajouter le .jar précédemment téléchargé
6. Changer une valeur de la configuration du job avec la méthode suivante
```java
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("fs.file.impl", "com.conga.services.hadoop.patch.HADOOP_7682.WinLocalFileSystem");
...
```
# Problème sur les nouveaux postes informatique
L'exception levée sur les nouveaux postes informatiques est dûe au nouveau mécanisme d'authentification de l'UM, où votre nom utilisateur correspond à votre adresse e-mail ; Kerberos, le protocole d'authentification utilisé par Hadoop utilise des règles différentes pour les adresses email.
La solution est de modifier votre nom utilisateur lors de l'exécution du programme.
Pour ce faire il suffit d'ajouter la variable d'environnement HADOOP_USER_NAME avant l'exécution du programme.
Le plus simple est de l'ajouter directement via Eclipse où l'on va modifier la configuration à l'exécution.
1. Faites un click droit sur la racine de votre projet, situé dans l'onglet à droite, suivez "Run as/Run Configurations"
2. Onglet "Environment"
3. New...
4. Name: HADOOP_USER_NAME, Value: user
Exécutez le programme WordCount et vérifiez que tout fonctionne. |
Java | UTF-8 | 5,627 | 2.484375 | 2 | [] | no_license | package com.whut.util;
import java.io.File;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
public class SelectImage {
//上下文
private Context context;
//从本机选取图片
private final int SELECT_FROM_GALLERY = 0;
//拍照选取
private final int SELECT_FROM_CAPTURE = 1;
//裁剪图片
private final int CROP_IMAGE = 2;
//拍照图片存储路径
//private String path = Environment.getExternalStorageDirectory().toString()+"/seller/image/temp.png";
//图片文件
public File imageFile ;
//拍照图片Uri
public Uri imageUri ;
public SelectImage(Context context){
this.context = context;
// if(!imageFile.getParentFile().getParentFile().exists()){
// imageFile.getParentFile().getParentFile().mkdir();
// }
// if(!imageFile.getParentFile().exists()){
// imageFile.getParentFile().mkdir();
// }
imageFile = new File(Environment.getExternalStorageDirectory(),String.valueOf(System.currentTimeMillis())+".jpg");
try {
if(imageFile.exists()){
imageFile.delete();
}
imageFile.createNewFile();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
imageUri = Uri.fromFile(imageFile);
}
/**
* 选择获取图片方式
*/
public void selectWay(){
String[] items = {"本机","相机"};
new AlertDialog.Builder(context).setTitle("选择图片来源")
.setItems(items, new OnClickListener() {
Intent intent;
@Override
public void onClick(DialogInterface dialog, int which) {
switch(which){
case SELECT_FROM_GALLERY:
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity)context).startActivityForResult(intent, SELECT_FROM_GALLERY); //获取图片后返回本页
break;
case SELECT_FROM_CAPTURE:
intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//输出路径
System.out.println("imageUri.toString()=" + imageUri.toString());
//intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
((Activity)context).startActivityForResult(intent, SELECT_FROM_CAPTURE);
break;
default:
break;
}
}
}).create().show();
}
/**
* 获取选择图片
* @param requestCode 请求码
* @param resultCode 结果码
* @param data 图片数据
* @param isCrop 是否裁剪
* @return bitmap结果
*/
public Bitmap getImage(int requestCode, int resultCode, Intent data,boolean isCrop){
Bitmap bitmap = null;
if(resultCode==-1){//RESULT_OK = -1
switch(requestCode){
//本机照片
case SELECT_FROM_GALLERY:
Uri uri = data.getData();
if(isCrop){
System.out.println("需要裁剪");
crop(uri);
}else{
System.out.println("不需要裁剪");
bitmap = getBitmapFromFile(uri);
}
break;
//拍照选取
case SELECT_FROM_CAPTURE:
if(isCrop){
try{
crop(imageUri);
}catch (Exception e) {
Toast.makeText(context, "保存图片失败!", Toast.LENGTH_SHORT).show();
}
}else{
bitmap = getBitmapFromFile(imageUri);
}
break;
case CROP_IMAGE:
bitmap = getBitmapFromFile(imageUri);
break;
default:
break;
}
}else{//RESULT_CANCELED = 0
System.out.println("resultCode="+resultCode);
Toast.makeText(context, "选择图片错误!", Toast.LENGTH_SHORT).show();
}
return bitmap;
}
/**
* 从文件获取图片
*/
private Bitmap getBitmapFromFile(Uri uri){
System.out.println("uri.toString()=" + uri.toString());
Bitmap bitmap = null;
ContentResolver resolver = context.getContentResolver();
try {
bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri));
} catch (FileNotFoundException e) {
Toast.makeText(context, "选取图片失败!", Toast.LENGTH_SHORT).show();
}
return bitmap;
}
/**
* 裁剪图片
*/
private void crop(Uri uri){
//裁剪意图
System.out.println("uri = "+ uri.toString());
Intent intent = new Intent("com.android.camera.action.CROP");
//输入路径uri不能和输入路径imageUri相同!要不然会出错
intent.setDataAndType(uri, "image/*");
intent.putExtra("scale", true);
//输出路径
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
// Intent intent = new Intent("com.android.camera.action.CROP");
// intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
//裁剪框比例
intent.putExtra("aspectX", 3);
intent.putExtra("aspectY", 2);
//裁剪后输出图片尺寸大小
// intent.putExtra("outputX", 900);
// intent.putExtra("outputY", 600);
intent.putExtra("outputFormat", "PNG");//图片格式
intent.putExtra("noFaceDetection", true);//取消人脸识别
// intent.putExtra("scale", true);
intent.putExtra("return-data", false);//取消返回
System.out.println("裁剪中");
((Activity)context).startActivityForResult(intent, CROP_IMAGE);
}
}
|
C | UTF-8 | 995 | 3.5625 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
typedef struct{} Key;
typedef struct {
int number;
Key k;
}Element;
typedef struct Node{
int e;
struct Node* next;
}Node;
typedef struct{
Node* head;
Node* tail;
int size;
}SeqList;
SeqList newList(); // creates an empty list
SeqList insertInOrder(SeqList sl, int e); // add e to sl in order of key assuming sl is ordered; return the modified list
SeqList insertAtFront(SeqList sl, int e); // add e at the front of the list; return the modified list
SeqList insertAtEnd(SeqList sl, int e); // add e at the end of the list; return the modified list
SeqList delete(SeqList sl, int e); // delete e from sl; return the modified list
SeqList deleteAtFront(SeqList sl); // delete the first element from sl; return the modified list
Element find(SeqList sl, Key k);
SeqList merge(SeqList sl1, SeqList sl2);//merges two sorted lists
SeqList insertionSort(SeqList sl);//sorts an unsorted list and returns the sorted list;
void printList(SeqList sl);
|
Python | UTF-8 | 361 | 2.828125 | 3 | [] | no_license | file = open("core_java1.txt")
flag = True
lines = file.readlines()
f = ""
for line in lines:
f = f + line
file.close()
ending = f.find("}")
while(ending != -1):
starting = f[:ending].rfind("{")
if ending - starting > 50:
print ending - starting
print f[starting: ending]
f = f[:starting] + f[ending + 1:]
# print f
ending = f.find("}")
# print f
|
JavaScript | UTF-8 | 347 | 2.515625 | 3 | [] | no_license | class Menu extends Phaser.Scene {
constructor() {
super("start_menu");
}
create() {
this.add.text(300, 300, "Press SPACE to start");
gameStartButton = this.input.keyboard.addKey('SPACE');
}
update() {
if (gameStartButton.isDown) {
this.scene.start("main_game");
}
}
}
|
Markdown | UTF-8 | 1,269 | 2.890625 | 3 | [] | no_license | # 发起GET/POST/PUT/DELETE请求 #
## 注意 ##
- GET方法参数通过Query传递
- POST方法参数通过Body传递
- PUT方法参数通过Body传递
- DELETE方法参数通过Query传递
- 能够携带自定义Header
- (path中的query会被合并到Query或者Body里)
## 发起请求 ##
准备一些自定义Header信息
$headers = array(
'X_API_TEST1' => 'A',
'X_API_TEST2' => 'B'
);
通过category获取AppleStore产品列表 (GET请求) 利用path进行分 /api/path
$params = array(
'category' =>'mac'
);
$r = $client->get('/apple_store/get_list', $params, $headers);
通过category获取AppleStore产品列表 (POST请求) 利用请求参数进行分发 method
$params = array(
'method' =>'get_list',
'category' =>'mac'
);
$r = $client->post('/apple_store', $params, $headers);
## CURL和Socket连接
为了提高兼容性我们提供了方法来让用户选择使用哪一种HTTP/HTTPS请求方式(在CURL开启的情况下会自动优先启用CURL连接) :
$client->setRequester('socket');
$client->setRequester('curl');
## 可以携带Oauth的Access Token
$client->access_token = 'c4t6q5rh6fysu5v5ww5xenv4';
[返回](index.md) |
Python | UTF-8 | 8,400 | 2.546875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import os
import sys
import json
import pandas as pd
import numpy as np
from category.categoryManager import categoryManager
from spider.common.dealRecordModel import *
# NOTE:取值是 “历史成交”
global_name = '华宝证券'
# 0. 定义预期数据。所有 suppose 开头的变量都是需要验证的内容。当与预期不符时,程序应该报错并终止 #
# 预期文件的全部列名(第一次是从 xlsx 中复制过来的)
suppose_all_file_columns = ['成交日期', '成交时间', '股东代码', '证券代码', '证券名称', '委托类别', '成交价格', '成交数量', '发生金额', '剩余金额', '佣金', '印花税', '过户费', '成交费', '成交编号', '委托编号']
# 我们实际需要的列名
suppose_needed_columns=['成交编号', '成交日期', '证券代码', '证券名称', '委托类别', '成交价格', '成交数量', '发生金额', '佣金', '印花税', '过户费', '成交费']
# 证券代码取值范围
suppose_codes = {'name': '证券代码', 'value': ['799999', '162411', '515180', '159920', '513520', '160416', '512580', '512980','510500','501018']}
# 证券名称取值范围
suppose_names = {'name': '证券名称', 'value': ['登记指定', '华宝油气', '100红利', '恒生ETF', '日经ETF', '石油基金', '环保ETF', '传媒ETF','500ETF','南方原油']}
# 委托类别取值范围
suppose_operates = {'name': '委托类别', 'value': ['指定', '买入', '卖出', '基金申购','托管转入']}
# 需要校验的列集合
suppose_justify_columns = [suppose_codes, suppose_names, suppose_operates]
class huabaoSpider:
def __init__(self):
# 当前目录
self.folder = os.path.abspath(os.path.dirname(__file__))
self.owner = u'康力泉'
self.categoryManager = categoryManager()
# TEST 显示列名,列唯一值
# df = pd.read_excel(os.path.join(self.folder, 'input', global_name + u'.xlsx'))
# file_columns = df.columns
# # 列名
# print(list(file_columns))
# # 列唯一值
# for cate in df.columns:
# print("{" + "'name': '{0}', 'value': [{1}]".format(cate, ', '.join(["'{0}'".format(x) for x in df[cate].unique()])) + "}")
# exit(1)
# 1. 读取文件并校验目标文件的列名是否符合预期 #
df = pd.read_excel(os.path.join(self.folder, 'input', global_name + u'.xlsx'))
# 验证数据
df = self.verifyDataFrame(df)
# 调整列
self.needed_df = self.modifyDataFrame(df)
def verifyDataFrame(self, needed_df):
# 1. 读取文件并校验目标文件的列名是否符合预期 #
needed_df = pd.read_excel(os.path.join(self.folder, 'input', global_name + u'.xlsx'))
file_columns = needed_df.columns
is_columns_equals = file_columns == suppose_all_file_columns
for x in range(0,len(is_columns_equals)):
if is_columns_equals[x] == False:
print(global_name + '原始数据列名有误:{0} 预期:{1} vs 实际:{2}'.format(x, suppose_all_file_columns[x], file_columns[x]))
exit(1)
break
print('列名 校验通过')
# 2. 取目标列 #
needed_df = pd.DataFrame(needed_df, columns=suppose_needed_columns)
# 3. 校验特殊列的合法性 #
for columnDict in suppose_justify_columns:
target_column_values = needed_df[columnDict['name']].unique()
for value in target_column_values:
if str(value) not in columnDict['value']:
print(global_name + '原始数据列值有误,目标值:{0} 不在列:{1} 的预期值之中。'.format(value, columnDict['name']))
exit(1)
print('{0} 校验通过'.format(columnDict['name']))
return needed_df
def modifyDataFrame(self, needed_df):
# 4. 调整(增删改查) dataframe 数据列 #
needed_df['nav_acc'] = needed_df['成交价格']
needed_df['fee'] = needed_df['佣金'] + needed_df['印花税'] + needed_df['过户费'] + needed_df['成交费']
needed_df.drop(columns=['佣金', '印花税','过户费','成交费'])
needed_df['occurMoney'] = needed_df['发生金额']
needed_df['category1'] = '无'
needed_df['category2'] = '无'
needed_df['category3'] = '无'
needed_df['categoryId'] = 1
needed_df['note'] = '无'
needed_df['account'] = global_name
# 5. 生成 json 对象
# 按 model key 值顺序重组 dataframe
reindex_columns=['成交编号', '成交日期', '证券代码', '证券名称', '委托类别', '成交价格', 'nav_acc', '成交数量', '发生金额', 'fee','occurMoney','account', 'category1', 'category2', 'category3', 'categoryId', 'note']
needed_df = needed_df.reindex(columns=reindex_columns)
# print(needed_df)
return needed_df
def get(self):
# 模型字段数组
all_model_keys = dealRecordModelKeys()
records = []
others = []
for x in self.needed_df.values:
item = dict(zip(all_model_keys, list(x)))
# 最后一次修改
item['date'] = '{0}-{1}-{2}'.format(str(item['date'])[0:4],str(item['date'])[4:6],str(item['date'])[6:8])
item['code'] = str(item['code'])
# 托管转入是 0 手续费的转换操作,当成买入
if item['dealType'] == '基金申购' or item['dealType'] == '托管转入':
item['dealType'] = '买入'
if item['dealType'] == '买入':
item['occurMoney'] = item['dealMoney'] + item['fee']
elif item['dealType'] == '卖出':
item['occurMoney'] = item['dealMoney'] - item['fee']
item['occurMoney'] = round(float(item['occurMoney']), 2)
if item['dealType'] in ['买入','卖出']:
categoryInfo = self.categoryManager.getCategoryByCode(item['code'])
if categoryInfo != {}:
item['category1'] = categoryInfo['category1']
item['category2'] = categoryInfo['category2']
item['category3'] = categoryInfo['category3']
item['categoryId'] = categoryInfo['categoryId']
records.append(item)
else:
others.append(item)
# print(item)
# 5. 命中 & 过滤分别保存到不同文件。可以通过浏览过滤文件确保没有漏掉有用信息 #
records.sort(key=lambda x: x['date'])
for i in range(1, len(records) + 1):
records[i-1]['id'] = i
others.sort(key=lambda x: x['date'])
for i in range(1, len(others) + 1):
others[i-1]['id'] = i
with open(os.path.join(self.folder, 'output', u'康力泉' + u'_record.json'), 'w+', encoding='utf-8') as f:
f.write(json.dumps(records,ensure_ascii=False, indent=4))
with open(os.path.join(self.folder, 'output', u'康力泉' + u'_other.json'), 'w+', encoding='utf-8') as f:
f.write(json.dumps(others,ensure_ascii=False, indent=4))
return records
def increment(self):
return self.get()
# 获取所有记录中的唯一代码
def uniqueCodes(self):
output_path = os.path.join(self.folder, 'output', '{0}_record.json'.format(self.owner))
with open(output_path, 'r', encoding='utf-8') as f:
datalist = json.loads(f.read())
names = []
codes = []
for x in datalist:
names.append(x['name'])
codes.append(x['code'])
df = pd.DataFrame()
df['name'] = names
df['code'] = codes
df = df.drop_duplicates(['code'])
df = df.sort_values(by='code' , ascending=True)
df = df.reset_index(drop=True)
df.to_csv(os.path.join(self.folder, 'output', '{0}-huabao-unique-codes.csv'.format(self.owner)), sep='\t')
return df
def load(self):
output_path = os.path.join(self.folder, 'output', '{0}_record.json'.format(self.owner))
with open(output_path, 'r', encoding='utf-8') as f:
return json.loads(f.read())
if __name__ == "__main__":
spider = huabaoSpider()
spider.get() |
Python | UTF-8 | 98 | 3.578125 | 4 | [] | no_license | # 常用函数
numbers = [100,200,300]
print(len(numbers))
print(max(numbers))
print(min(numbers)) |
C++ | UTF-8 | 1,326 | 3.109375 | 3 | [] | no_license | const int pin = 2; // 开关引脚
const int pin2 = 13; // 电路部分正向电压引脚
const float V_all = 5.0; // 最大电压
int flag = 1; // 控制系统开关
void setup()
{
Serial.begin(9600);
pinMode(pin, INPUT_PULLUP); //设置引脚为内部上拉输入模式
pinMode(pin2, OUTPUT); // 控制电压
}
void loop()
{
/* 开关部分,控制开关 */
float time= pulseIn(pin, LOW,60000000)/1000; // 计算按下时间
if(time > 1000) // 长按进入系统开关控制部分
{
if(flag == 1) // 打开
{
flag = 0;
digitalWrite(pin2, HIGH);
Serial.println("System Open\n");
}
else // 关闭
{
flag = 1;
digitalWrite(pin2, LOW);
Serial.println("System Close");
}
}
/* 系统打开期间,计算各部分电压 */
else if(digitalRead(pin2) == HIGH)
{
/* 串口输出按下开关的时间 */
Serial.print("Pressing time = ");
Serial.print(time);
Serial.println("ms");
/* 输出定值电阻两端电压U1 */
float V1 = analogRead(A0);
float vol = V1*(5.0 / 1023.0);
Serial.print("U1 = ");
Serial.print(vol);
Serial.println(" V");
/* 输出编组去接入部分两端电压 */
Serial.print("U2 = ");
Serial.print(V_all - vol);
Serial.println(" V\n");
}
}
|
Java | UTF-8 | 1,612 | 2.8125 | 3 | [] | no_license | package tyu.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TyuObjectSerilizer {
static Object tmpValue = new Object();
/**
* @param aObj
* @param filename
* @return
*/
static public boolean writeObject(Object aObj,String filename) {
boolean res = false;
synchronized (tmpValue) {
try {
File file = new File(filename);
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(aObj);
oos.flush();
oos.close();
res = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return res;
}
static public Object readObject(String fileName) {
Object res = null;
synchronized (tmpValue) {
try {
File file = new File(fileName);
if (file.exists()) {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(file));
res = ois.readObject();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
res = null;
}
}
return res;
}
static public Object readObject(File file) {
Object res = null;
synchronized (tmpValue) {
try {
if (file.exists()) {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(file));
res = ois.readObject();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
res = null;
}
}
return res;
}
}
|
Java | UTF-8 | 432 | 2.75 | 3 | [] | no_license | package service.validator.impl;
import model.User;
import service.validator.Validator;
public class UsernameValidator implements Validator<User> {
private static final int MIN_LENGTH = 5;
@Override
public void validate(User user) {
if(user.getUsername().length() < MIN_LENGTH)
throw new IllegalArgumentException("The username must have a minimum length of " + MIN_LENGTH + " characters.");
}
}
|
Markdown | UTF-8 | 29,086 | 2.90625 | 3 | [] | no_license | 请求和响应 Requests and Responses
======================
Scrapy 使用 `Request` 和 `Response` 对象来爬取网页。
Typically, :class:`Request` objects are generated in the spiders and pass
across the system until they reach the Downloader, which executes the request
and returns a :class:`Response` object which travels back to the spider that
issued the request.
Both :class:`Request` and :class:`Response` classes have subclasses which add
functionality not required in the base classes. These are described
below in :ref:`topics-request-response-ref-request-subclasses` and
:ref:`topics-request-response-ref-response-subclasses`.
Request objects
===============
### Request(url[, callback, method='GET', headers, body, cookies, meta, encoding='utf-8', priority=0, dont_filter=False, errback, flags])
A :class:`Request` object represents an HTTP request, which is usually
generated in the Spider and executed by the Downloader, and thus generating
a :class:`Response`.
:param url: the URL of this request
:type url: string
:param callback: the function that will be called with the response of this
request (once its downloaded) as its first parameter. For more information
see :ref:`topics-request-response-ref-request-callback-arguments` below.
If a Request doesn't specify a callback, the spider's
:meth:`~scrapy.spiders.Spider.parse` method will be used.
Note that if exceptions are raised during processing, errback is called instead.
:type callback: callable
:param method: the HTTP method of this request. Defaults to ``'GET'``.
:type method: string
:param meta: the initial values for the :attr:`Request.meta` attribute. If
given, the dict passed in this parameter will be shallow copied.
:type meta: dict
:param body: the request body. If a ``unicode`` is passed, then it's encoded to
``str`` using the `encoding` passed (which defaults to ``utf-8``). If
``body`` is not given, an empty string is stored. Regardless of the
type of this argument, the final value stored will be a ``str`` (never
``unicode`` or ``None``).
:type body: str or unicode
:param headers: the headers of this request. The dict values can be strings
(for single valued headers) or lists (for multi-valued headers). If
``None`` is passed as value, the HTTP header will not be sent at all.
:type headers: dict
:param cookies: the request cookies. These can be sent in two forms.
1. Using a dict::
request_with_cookies = Request(url="http://www.example.com",
cookies={'currency': 'USD', 'country': 'UY'})
2. Using a list of dicts::
request_with_cookies = Request(url="http://www.example.com",
cookies=[{'name': 'currency',
'value': 'USD',
'domain': 'example.com',
'path': '/currency'}])
The latter form allows for customizing the ``domain`` and ``path``
attributes of the cookie. This is only useful if the cookies are saved
for later requests.
When some site returns cookies (in a response) those are stored in the
cookies for that domain and will be sent again in future requests. That's
the typical behaviour of any regular web browser. However, if, for some
reason, you want to avoid merging with existing cookies you can instruct
Scrapy to do so by setting the ``dont_merge_cookies`` key to True in the
:attr:`Request.meta`.
Example of request without merging cookies::
request_with_cookies = Request(url="http://www.example.com",
cookies={'currency': 'USD', 'country': 'UY'},
meta={'dont_merge_cookies': True})
For more info see :ref:`cookies-mw`.
:type cookies: dict or list
:param encoding: the encoding of this request (defaults to ``'utf-8'``).
This encoding will be used to percent-encode the URL and to convert the
body to ``str`` (if given as ``unicode``).
:type encoding: string
:param priority: the priority of this request (defaults to ``0``).
The priority is used by the scheduler to define the order used to process
requests. Requests with a higher priority value will execute earlier.
Negative values are allowed in order to indicate relatively low-priority.
:type priority: int
:param dont_filter: indicates that this request should not be filtered by
the scheduler. This is used when you want to perform an identical
request multiple times, to ignore the duplicates filter. Use it with
care, or you will get into crawling loops. Default to ``False``.
:type dont_filter: boolean
:param errback: a function that will be called if any exception was
raised while processing the request. This includes pages that failed
with 404 HTTP errors and such. It receives a `Twisted Failure`_ instance
as first parameter.
For more information,
see :ref:`topics-request-response-ref-errbacks` below.
:type errback: callable
:param flags: Flags sent to the request, can be used for logging or similar purposes.
:type flags: list
.. attribute:: Request.url
A string containing the URL of this request. Keep in mind that this
attribute contains the escaped URL, so it can differ from the URL passed in
the constructor.
This attribute is read-only. To change the URL of a Request use
:meth:`replace`.
.. attribute:: Request.method
A string representing the HTTP method in the request. This is guaranteed to
be uppercase. Example: ``"GET"``, ``"POST"``, ``"PUT"``, etc
.. attribute:: Request.headers
A dictionary-like object which contains the request headers.
.. attribute:: Request.body
A str that contains the request body.
This attribute is read-only. To change the body of a Request use
:meth:`replace`.
.. attribute:: Request.meta
A dict that contains arbitrary metadata for this request. This dict is
empty for new Requests, and is usually populated by different Scrapy
components (extensions, middlewares, etc). So the data contained in this
dict depends on the extensions you have enabled.
See :ref:`topics-request-meta` for a list of special meta keys
recognized by Scrapy.
This dict is `shallow copied`_ when the request is cloned using the
``copy()`` or ``replace()`` methods, and can also be accessed, in your
spider, from the ``response.meta`` attribute.
.. _shallow copied: https://docs.python.org/2/library/copy.html
.. method:: Request.copy()
Return a new Request which is a copy of this Request. See also:
:ref:`topics-request-response-ref-request-callback-arguments`.
.. method:: Request.replace([url, method, headers, body, cookies, meta, encoding, dont_filter, callback, errback])
Return a Request object with the same members, except for those members
given new values by whichever keyword arguments are specified. The
attribute :attr:`Request.meta` is copied by default (unless a new value
is given in the ``meta`` argument). See also
:ref:`topics-request-response-ref-request-callback-arguments`.
给回调函数传递额外的数据
---------------------------------------------
The callback of a request is a function that will be called when the response
of that request is downloaded. The callback function will be called with the
downloaded :class:`Response` object as its first argument.
Example::
def parse_page1(self, response):
return scrapy.Request("http://www.example.com/some_page.html",
callback=self.parse_page2)
def parse_page2(self, response):
# this would log http://www.example.com/some_page.html
self.logger.info("Visited %s", response.url)
In some cases you may be interested in passing arguments to those callback
functions so you can receive the arguments later, in the second callback. You
can use the :attr:`Request.meta` attribute for that.
Here's an example of how to pass an item using this mechanism, to populate
different fields from different pages::
def parse_page1(self, response):
item = MyItem()
item['main_url'] = response.url
request = scrapy.Request("http://www.example.com/some_page.html",
callback=self.parse_page2)
request.meta['item'] = item
yield request
def parse_page2(self, response):
item = response.meta['item']
item['other_url'] = response.url
yield item
使用errback在请求处理中捕获异常
--------------------------------------------------------
The errback of a request is a function that will be called when an exception
is raise while processing it.
It receives a `Twisted Failure`_ instance as first parameter and can be
used to track connection establishment timeouts, DNS errors etc.
Here's an example spider logging all errors and catching some specific
errors if needed::
import scrapy
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError
class ErrbackSpider(scrapy.Spider):
name = "errback_example"
start_urls = [
"http://www.httpbin.org/", # HTTP 200 expected
"http://www.httpbin.org/status/404", # Not found error
"http://www.httpbin.org/status/500", # server issue
"http://www.httpbin.org:12345/", # non-responding host, timeout expected
"http://www.httphttpbinbin.org/", # DNS error expected
]
def start_requests(self):
for u in self.start_urls:
yield scrapy.Request(u, callback=self.parse_httpbin,
errback=self.errback_httpbin,
dont_filter=True)
def parse_httpbin(self, response):
self.logger.info('Got successful response from {}'.format(response.url))
# do something useful here...
def errback_httpbin(self, failure):
# log all failures
self.logger.error(repr(failure))
# in case you want to do something special for some errors,
# you may need the failure's type:
if failure.check(HttpError):
# these exceptions come from HttpError spider middleware
# you can get the non-200 response
response = failure.value.response
self.logger.error('HttpError on %s', response.url)
elif failure.check(DNSLookupError):
# this is the original request
request = failure.request
self.logger.error('DNSLookupError on %s', request.url)
elif failure.check(TimeoutError, TCPTimedOutError):
request = failure.request
self.logger.error('TimeoutError on %s', request.url)
Request.meta special keys
=========================
The :attr:`Request.meta` attribute can contain any arbitrary data, but there
are some special keys recognized by Scrapy and its built-in extensions.
Those are:
* :reqmeta:`dont_redirect`
* :reqmeta:`dont_retry`
* :reqmeta:`handle_httpstatus_list`
* :reqmeta:`handle_httpstatus_all`
* ``dont_merge_cookies`` (see ``cookies`` parameter of :class:`Request` constructor)
* :reqmeta:`cookiejar`
* :reqmeta:`dont_cache`
* :reqmeta:`redirect_urls`
* :reqmeta:`bindaddress`
* :reqmeta:`dont_obey_robotstxt`
* :reqmeta:`download_timeout`
* :reqmeta:`download_maxsize`
* :reqmeta:`download_latency`
* :reqmeta:`download_fail_on_dataloss`
* :reqmeta:`proxy`
* ``ftp_user`` (See :setting:`FTP_USER` for more info)
* ``ftp_password`` (See :setting:`FTP_PASSWORD` for more info)
* :reqmeta:`referrer_policy`
* :reqmeta:`max_retry_times`
.. reqmeta:: bindaddress
bindaddress
-----------
The IP of the outgoing IP address to use for the performing the request.
.. reqmeta:: download_timeout
download_timeout
----------------
The amount of time (in secs) that the downloader will wait before timing out.
See also: :setting:`DOWNLOAD_TIMEOUT`.
.. reqmeta:: download_latency
download_latency
----------------
The amount of time spent to fetch the response, since the request has been
started, i.e. HTTP message sent over the network. This meta key only becomes
available when the response has been downloaded. While most other meta keys are
used to control Scrapy behavior, this one is supposed to be read-only.
.. reqmeta:: download_fail_on_dataloss
download_fail_on_dataloss
-------------------------
Whether or not to fail on broken responses. See:
:setting:`DOWNLOAD_FAIL_ON_DATALOSS`.
.. reqmeta:: max_retry_times
max_retry_times
---------------
The meta key is used set retry times per request. When initialized, the
:reqmeta:`max_retry_times` meta key takes higher precedence over the
:setting:`RETRY_TIMES` setting.
.. _topics-request-response-ref-request-subclasses:
Request 子类
==================
Here is the list of built-in :class:`Request` subclasses. You can also subclass
it to implement your own custom functionality.
FormRequest objects
-------------------
The FormRequest class extends the base :class:`Request` with functionality for
dealing with HTML forms. It uses `lxml.html forms`_ to pre-populate form
fields with form data from :class:`Response` objects.
.. _lxml.html forms: http://lxml.de/lxmlhtml.html#forms
.. class:: FormRequest(url, [formdata, ...])
The :class:`FormRequest` class adds a new argument to the constructor. The
remaining arguments are the same as for the :class:`Request` class and are
not documented here.
:param formdata: is a dictionary (or iterable of (key, value) tuples)
containing HTML Form data which will be url-encoded and assigned to the
body of the request.
:type formdata: dict or iterable of tuples
The :class:`FormRequest` objects support the following class method in
addition to the standard :class:`Request` methods:
.. classmethod:: FormRequest.from_response(response, [formname=None, formid=None, formnumber=0, formdata=None, formxpath=None, formcss=None, clickdata=None, dont_click=False, ...])
Returns a new :class:`FormRequest` object with its form field values
pre-populated with those found in the HTML ``<form>`` element contained
in the given response. For an example see
:ref:`topics-request-response-ref-request-userlogin`.
The policy is to automatically simulate a click, by default, on any form
control that looks clickable, like a ``<input type="submit">``. Even
though this is quite convenient, and often the desired behaviour,
sometimes it can cause problems which could be hard to debug. For
example, when working with forms that are filled and/or submitted using
javascript, the default :meth:`from_response` behaviour may not be the
most appropriate. To disable this behaviour you can set the
``dont_click`` argument to ``True``. Also, if you want to change the
control clicked (instead of disabling it) you can also use the
``clickdata`` argument.
.. caution:: Using this method with select elements which have leading
or trailing whitespace in the option values will not work due to a
`bug in lxml`_, which should be fixed in lxml 3.8 and above.
:param response: the response containing a HTML form which will be used
to pre-populate the form fields
:type response: :class:`Response` object
:param formname: if given, the form with name attribute set to this value will be used.
:type formname: string
:param formid: if given, the form with id attribute set to this value will be used.
:type formid: string
:param formxpath: if given, the first form that matches the xpath will be used.
:type formxpath: string
:param formcss: if given, the first form that matches the css selector will be used.
:type formcss: string
:param formnumber: the number of form to use, when the response contains
multiple forms. The first one (and also the default) is ``0``.
:type formnumber: integer
:param formdata: fields to override in the form data. If a field was
already present in the response ``<form>`` element, its value is
overridden by the one passed in this parameter. If a value passed in
this parameter is ``None``, the field will not be included in the
request, even if it was present in the response ``<form>`` element.
:type formdata: dict
:param clickdata: attributes to lookup the control clicked. If it's not
given, the form data will be submitted simulating a click on the
first clickable element. In addition to html attributes, the control
can be identified by its zero-based index relative to other
submittable inputs inside the form, via the ``nr`` attribute.
:type clickdata: dict
:param dont_click: If True, the form data will be submitted without
clicking in any element.
:type dont_click: boolean
The other parameters of this class method are passed directly to the
:class:`FormRequest` constructor.
.. versionadded:: 0.10.3
The ``formname`` parameter.
.. versionadded:: 0.17
The ``formxpath`` parameter.
.. versionadded:: 1.1.0
The ``formcss`` parameter.
.. versionadded:: 1.1.0
The ``formid`` parameter.
Request usage examples
----------------------
Using FormRequest to send data via HTTP POST
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want to simulate a HTML Form POST in your spider and send a couple of
key-value fields, you can return a :class:`FormRequest` object (from your
spider) like this::
return [FormRequest(url="http://www.example.com/post/action",
formdata={'name': 'John Doe', 'age': '27'},
callback=self.after_post)]
.. _topics-request-response-ref-request-userlogin:
Using FormRequest.from_response() to simulate a user login
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is usual for web sites to provide pre-populated form fields through ``<input
type="hidden">`` elements, such as session related data or authentication
tokens (for login pages). When scraping, you'll want these fields to be
automatically pre-populated and only override a couple of them, such as the
user name and password. You can use the :meth:`FormRequest.from_response`
method for this job. Here's an example spider which uses it::
import scrapy
class LoginSpider(scrapy.Spider):
name = 'example.com'
start_urls = ['http://www.example.com/users/login.php']
def parse(self, response):
return scrapy.FormRequest.from_response(
response,
formdata={'username': 'john', 'password': 'secret'},
callback=self.after_login
)
def after_login(self, response):
# check login succeed before going on
if "authentication failed" in response.body:
self.logger.error("Login failed")
return
# continue scraping with authenticated session...
Response objects
================
.. class:: Response(url, [status=200, headers=None, body=b'', flags=None, request=None])
A :class:`Response` object represents an HTTP response, which is usually
downloaded (by the Downloader) and fed to the Spiders for processing.
:param url: the URL of this response
:type url: string
:param status: the HTTP status of the response. Defaults to ``200``.
:type status: integer
:param headers: the headers of this response. The dict values can be strings
(for single valued headers) or lists (for multi-valued headers).
:type headers: dict
:param body: the response body. It must be str, not unicode, unless you're
using a encoding-aware :ref:`Response subclass
<topics-request-response-ref-response-subclasses>`, such as
:class:`TextResponse`.
:type body: str
:param flags: is a list containing the initial values for the
:attr:`Response.flags` attribute. If given, the list will be shallow
copied.
:type flags: list
:param request: the initial value of the :attr:`Response.request` attribute.
This represents the :class:`Request` that generated this response.
:type request: :class:`Request` object
.. attribute:: Response.url
A string containing the URL of the response.
This attribute is read-only. To change the URL of a Response use
:meth:`replace`.
.. attribute:: Response.status
An integer representing the HTTP status of the response. Example: ``200``,
``404``.
.. attribute:: Response.headers
A dictionary-like object which contains the response headers. Values can
be accessed using :meth:`get` to return the first header value with the
specified name or :meth:`getlist` to return all header values with the
specified name. For example, this call will give you all cookies in the
headers::
response.headers.getlist('Set-Cookie')
.. attribute:: Response.body
The body of this Response. Keep in mind that Response.body
is always a bytes object. If you want the unicode version use
:attr:`TextResponse.text` (only available in :class:`TextResponse`
and subclasses).
This attribute is read-only. To change the body of a Response use
:meth:`replace`.
.. attribute:: Response.request
The :class:`Request` object that generated this response. This attribute is
assigned in the Scrapy engine, after the response and the request have passed
through all :ref:`Downloader Middlewares <topics-downloader-middleware>`.
In particular, this means that:
- HTTP redirections will cause the original request (to the URL before
redirection) to be assigned to the redirected response (with the final
URL after redirection).
- Response.request.url doesn't always equal Response.url
- This attribute is only available in the spider code, and in the
:ref:`Spider Middlewares <topics-spider-middleware>`, but not in
Downloader Middlewares (although you have the Request available there by
other means) and handlers of the :signal:`response_downloaded` signal.
.. attribute:: Response.meta
A shortcut to the :attr:`Request.meta` attribute of the
:attr:`Response.request` object (ie. ``self.request.meta``).
Unlike the :attr:`Response.request` attribute, the :attr:`Response.meta`
attribute is propagated along redirects and retries, so you will get
the original :attr:`Request.meta` sent from your spider.
.. seealso:: :attr:`Request.meta` attribute
.. attribute:: Response.flags
A list that contains flags for this response. Flags are labels used for
tagging Responses. For example: `'cached'`, `'redirected`', etc. And
they're shown on the string representation of the Response (`__str__`
method) which is used by the engine for logging.
.. method:: Response.copy()
Returns a new Response which is a copy of this Response.
.. method:: Response.replace([url, status, headers, body, request, flags, cls])
Returns a Response object with the same members, except for those members
given new values by whichever keyword arguments are specified. The
attribute :attr:`Response.meta` is copied by default.
.. method:: Response.urljoin(url)
Constructs an absolute url by combining the Response's :attr:`url` with
a possible relative url.
This is a wrapper over `urlparse.urljoin`_, it's merely an alias for
making this call::
urlparse.urljoin(response.url, url)
.. automethod:: Response.follow
.. _urlparse.urljoin: https://docs.python.org/2/library/urlparse.html#urlparse.urljoin
.. _topics-request-response-ref-response-subclasses:
Response 子类
===================
Here is the list of available built-in Response subclasses. You can also
subclass the Response class to implement your own functionality.
TextResponse objects
--------------------
.. class:: TextResponse(url, [encoding[, ...]])
:class:`TextResponse` objects adds encoding capabilities to the base
:class:`Response` class, which is meant to be used only for binary data,
such as images, sounds or any media file.
:class:`TextResponse` objects support a new constructor argument, in
addition to the base :class:`Response` objects. The remaining functionality
is the same as for the :class:`Response` class and is not documented here.
:param encoding: is a string which contains the encoding to use for this
response. If you create a :class:`TextResponse` object with a unicode
body, it will be encoded using this encoding (remember the body attribute
is always a string). If ``encoding`` is ``None`` (default value), the
encoding will be looked up in the response headers and body instead.
:type encoding: string
:class:`TextResponse` objects support the following attributes in addition
to the standard :class:`Response` ones:
.. attribute:: TextResponse.text
Response body, as unicode.
The same as ``response.body.decode(response.encoding)``, but the
result is cached after the first call, so you can access
``response.text`` multiple times without extra overhead.
.. note::
``unicode(response.body)`` is not a correct way to convert response
body to unicode: you would be using the system default encoding
(typically `ascii`) instead of the response encoding.
.. attribute:: TextResponse.encoding
A string with the encoding of this response. The encoding is resolved by
trying the following mechanisms, in order:
1. the encoding passed in the constructor `encoding` argument
2. the encoding declared in the Content-Type HTTP header. If this
encoding is not valid (ie. unknown), it is ignored and the next
resolution mechanism is tried.
3. the encoding declared in the response body. The TextResponse class
doesn't provide any special functionality for this. However, the
:class:`HtmlResponse` and :class:`XmlResponse` classes do.
4. the encoding inferred by looking at the response body. This is the more
fragile method but also the last one tried.
.. attribute:: TextResponse.selector
A :class:`~scrapy.selector.Selector` instance using the response as
target. The selector is lazily instantiated on first access.
:class:`TextResponse` objects support the following methods in addition to
the standard :class:`Response` ones:
.. method:: TextResponse.xpath(query)
A shortcut to ``TextResponse.selector.xpath(query)``::
response.xpath('//p')
.. method:: TextResponse.css(query)
A shortcut to ``TextResponse.selector.css(query)``::
response.css('p')
.. automethod:: TextResponse.follow
.. method:: TextResponse.body_as_unicode()
The same as :attr:`text`, but available as a method. This method is
kept for backwards compatibility; please prefer ``response.text``.
HtmlResponse objects
--------------------
### HtmlResponse(url[, ...])
The :class:`HtmlResponse` class is a subclass of :class:`TextResponse`
which adds encoding auto-discovering support by looking into the HTML `meta
http-equiv`_ attribute. See :attr:`TextResponse.encoding`.
.. _meta http-equiv: http://www.w3schools.com/TAGS/att_meta_http_equiv.asp
XmlResponse objects
-------------------
### XmlResponse(url[, ...])
The :class:`XmlResponse` class is a subclass of :class:`TextResponse` which
adds encoding auto-discovering support by looking into the XML declaration
line. See :attr:`TextResponse.encoding`.
* Twisted Failure: https://twistedmatrix.com/documents/current/api/twisted.python.failure.Failure.html
* bug in lxml: https://bugs.launchpad.net/lxml/+bug/1665241
|
C# | UTF-8 | 1,455 | 2.546875 | 3 | [
"WTFPL"
] | permissive | using System.Collections.Generic;
using System.Threading.Tasks;
using SharpExchange.Api.V22.Types;
namespace SharpExchange.Api.V22.Endpoints
{
public static class Posts
{
/// <summary>
/// Gets all posts on a site.
/// </summary>
public static Task<Result<Post[]>> GetAllAsync(QueryOptions options = null)
{
options = options.GetDefaultIfNull();
var endpoint = $"{Constants.BaseApiUrl}/posts";
return ApiRequestScheduler.ScheduleRequestAsync<Post[]>(endpoint, options);
}
/// <summary>
/// Gets posts identified by a set of ids.
/// </summary>
public static Task<Result<Post[]>> GetByIdsAsync(IEnumerable<int> ids, QueryOptions options = null)
{
ids.ThrowIfNullOrEmpty(nameof(ids));
options = options.GetDefaultIfNull();
var idsStr = ids.ToDelimitedList();
var endpoint = $"{Constants.BaseApiUrl}/posts/{idsStr}";
return ApiRequestScheduler.ScheduleRequestAsync<Post[]>(endpoint, options);
}
/// <summary>
/// Gets all posts owned by the users identified by a set of ids.
/// </summary>
public static Task<Result<Post[]>> GetByUserIdsAsync(IEnumerable<int> userIds, QueryOptions options = null)
{
userIds.ThrowIfNullOrEmpty(nameof(userIds));
options = options.GetDefaultIfNull();
var idsStr = userIds.ToDelimitedList();
var endpoint = $"{Constants.BaseApiUrl}/users/{idsStr}/posts";
return ApiRequestScheduler.ScheduleRequestAsync<Post[]>(endpoint, options);
}
}
}
|
Python | UTF-8 | 1,049 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | from sklearn.metrics import confusion_matrix
def cohen_kappa_score(y1, y2, labels=None, weights=None):
confusion = confusion_matrix(y1, y2, labels=labels)
n_classes = confusion.shape[0]
sum0 = np.sum(confusion, axis=0)
sum1 = np.sum(confusion, axis=1)
expected = np.outer(sum0, sum1).astype(np.double) / np.sum(sum0) # type changed to double for consistency
if weights is None:
w_mat = np.ones([n_classes, n_classes], dtype=np.int)
w_mat.flat[:: n_classes + 1] = 0
elif weights == "linear" or weights == "quadratic":
w_mat = np.zeros([n_classes, n_classes], dtype=np.int)
w_mat += np.arange(n_classes)
if weights == "linear":
w_mat = np.abs(w_mat - w_mat.T)
else:
w_mat = (w_mat - w_mat.T) ** 2
else:
raise ValueError("Unknown kappa weighting type.")
k = np.sum(w_mat * confusion) / np.sum(w_mat * expected)
return 1 - k
def cohen_kappa_score_function(y_true, y_pred):
return cohen_kappa_score(y_pred, y_true)
|
Java | UTF-8 | 819 | 3.40625 | 3 | [] | no_license | package LeetCode_728;
import java.util.LinkedList;
import java.util.List;
public class Solution {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> result = new LinkedList<>();
for (int i = left; i <= right; i++) {
if (isDiviedNum(i)) {
result.add(i);
}
}
return result;
}
public boolean isDiviedNum(int n) {
String num = String.valueOf(n);
int length = num.length();
int[] record = new int[length];
for (int i = 0; i < length; i++) {
record[i] = num.charAt(i) - '0';
}
for (int i = 0; i < length; i++) {
if (record[i] == 0 || n % record[i] != 0) {
return false;
}
}
return true;
}
}
|
Markdown | UTF-8 | 2,384 | 2.8125 | 3 | [] | no_license | # Article R6323-1
I.-Pour les salariés dont la durée de travail à temps plein est fixée en application d'un accord d'entreprise ou de branche,
le nombre d'heures de travail de référence pour le calcul de l'alimentation du compte personnel de formation est égal à la
durée conventionnelle de travail.
II.-Pour les salariés dont la durée de travail à temps plein n'est pas fixée en application d'un accord d'entreprise ou de
branche, le nombre d'heures de travail de référence pour le calcul de l'alimentation du compte personnel de formation est
égal à 1 607 heures.
III.-Lorsque le salarié a effectué une durée de travail inférieure à la durée de travail mentionnée au I ou à 1 607 heures
sur l'ensemble de l'année, l'alimentation du compte est calculée au prorata du rapport entre le nombre d'heures effectuées et
la durée conventionnelle mentionnée au I ou 1 607 heures. Lorsque le calcul ainsi effectué aboutit à un nombre d'heures de
formation comportant une décimale, ce chiffre est arrondi au nombre entier immédiatement supérieur.
IV.-Pour les salariés dont la durée de travail est déterminée par une convention de forfait en jours, le nombre d'heures de
travail de référence pour le calcul de l'alimentation du compte personnel de formation est fixé à 1 607 heures.
V.-Pour les salariés dont la rémunération n'est pas établie en fonction d'un horaire de travail, le montant de référence pour
le calcul de l'alimentation du compte personnel de formation est fixé à 2 080 fois le montant du salaire minimum horaire de
croissance.
L'alimentation du compte de ces salariés est calculée au prorata du rapport entre la rémunération effectivement perçue et le
montant de référence mentionné à l'alinéa précédent. Lorsque le calcul ainsi effectué aboutit à un nombre d'heures de
formation comportant une décimale, ce chiffre est arrondi au nombre entier immédiatement supérieur.
VI.-En vue d'assurer l'alimentation des comptes personnels de formation des salariés mentionnés aux I et III, les entreprises
concernées informent l'organisme paritaire collecteur agréé dont elles relèvent, avant le 1er mars de chaque année, de la
durée de travail à temps plein applicable à ces salariés.
**Liens relatifs à cet article**
**Créé par**:
- Décret n°2014-1120 du 2 octobre 2014 - art. 1
|
JavaScript | UTF-8 | 2,041 | 3.734375 | 4 | [] | no_license | //******************************************************************
// almanzas.js
//******************************************************************
var counter = 1;
var driveup = 1;
setTimeout(counterOrder, 1000);//Counter customer at second 1
setTimeout(counterOrder, 2000);//Counter customer at second 2
setTimeout(driveupOrder, 3000);//Driveup customer at second 3
setTimeout(counterOrder, 4000);//Counter customer at second 4
setTimeout(counterOrder, 5000);//Counter customer at second 5
setTimeout(driveupOrder, 6000);//Driveup customer at second 6
setTimeout(driveupOrder, 7000);//Driveup customer at second 7
setTimeout(counterOrder, 8000);//Counter customer at second 8
//******************************************************************
//server(task)
//
//The server takes the orders from the customers and gives them
//to the kitchen, as well as delivering orders from the kitchen
//******************************************************************
function server(customer)
{
console.log("Take order " + customer);
kitchen(deliver);
function deliver()
{
console.log("Deliver " + customer + " food order");
}
}
//******************************************************************
//kitchen(callback)
//
//The kitchen takes tasks and completes them at a random time
//between 1 and 5 seconds
//******************************************************************
function kitchen(callback)
{
var delay = 1000 + Math.round(Math.random() * 4000);
setTimeout(callback, delay);
}
//******************************************************************
//counterOrder()
//
//Give order to server
//******************************************************************
function counterOrder()
{
server("C" + counter);
counter++;
}
//******************************************************************
//driveupOrder()
//
//Give order to server
//******************************************************************
function driveupOrder()
{
server("A" + driveup);
driveup++;
}
|
Python | UTF-8 | 586 | 2.515625 | 3 | [] | no_license | from pynput import keyboard, mouse
from pynput.keyboard import Key
import time
keyboard = keyboard.Controller()
mouse = mouse.Controller()
wait = 0.1
keyboard.press(Key.cmd)
keyboard.press(Key.space)
keyboard.release(Key.cmd)
keyboard.release(Key.space)
time.sleep(wait)
keyboard.type("terminal")
time.sleep(wait)
keyboard.press(Key.enter)
time.sleep(wait)
keyboard.type("cd ~/Desktop/Python\ for\ fun~/fun/")
time.sleep(wait)
keyboard.press(Key.enter)
time.sleep(wait)
keyboard.type("Python MouseTesting.py")
time.sleep(wait)
keyboard.press(Key.enter)
keyboard.release(Key.enter)
|
Python | UTF-8 | 553 | 3.078125 | 3 | [] | no_license | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class CheckBalance:
def __init__(self):
self.res = True
def check(self, root):
t = self.getHeight(root, 1)
return self.res
def getHeight(self, root, level=1):
if not root:
return level
left = self.getHeight(root.left, level+1)
right = self.getHeight(root.right, level+1)
if abs(left-right)>1:
self.res = False
return max(left,right)+1
|
Java | UTF-8 | 691 | 2.828125 | 3 | [] | no_license | package pass;
import java.util.Arrays;
import pass.TreeNode;
public class lc108 {
public TreeNode sortedArrayToBST(int[] nums) {
int length = nums.length;
if (length == 0) return null;
if (length == 1) return new TreeNode(nums[0]);
int start = 0;
int end = length - 1;
int mid = start + ((length - start) >> 1);
int num = nums[mid];
TreeNode head = new TreeNode(num);
int[] left = Arrays.copyOfRange(nums, start, mid);
int[] right = Arrays.copyOfRange(nums, mid + 1, end + 1);
head.left = sortedArrayToBST(left);
head.right = sortedArrayToBST(right);
return head;
}
}
|
Markdown | UTF-8 | 6,938 | 2.84375 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: Ställ en fråga data kan svara
titleSuffix: ML Studio (classic) - Azure
description: Lär dig att formulera en skarp datavetenskap fråga i Data Science för nybörjare video 3. Inkluderar en jämförelse av klassificerings- och regressionsfrågor.
services: machine-learning
ms.service: machine-learning
ms.subservice: studio
ms.topic: conceptual
author: sdgilley
ms.author: sgilley
ms.date: 03/22/2019
ms.openlocfilehash: 26837337b49d79a26404fd6709b036f6907720f8
ms.sourcegitcommit: 2ec4b3d0bad7dc0071400c2a2264399e4fe34897
ms.translationtype: MT
ms.contentlocale: sv-SE
ms.lasthandoff: 03/27/2020
ms.locfileid: "73838843"
---
# <a name="ask-a-question-you-can-answer-with-data"></a>Ställ en fråga som du kan svara på med data
## <a name="video-3-data-science-for-beginners-series"></a>Video 3: Data Science för nybörjare serien
Lär dig hur du formulerar ett datavetenskapsproblem i en fråga i datavetenskap för nybörjare video 3. Den här videon innehåller en jämförelse av frågor för klassificerings- och regressionsalgoritmer.
För att få ut det mesta av serien, titta på dem alla. [Gå till listan med videoklipp](#other-videos-in-this-series)
<br>
> [!VIDEO https://channel9.msdn.com/Blogs/Azure/Data-science-for-beginners-Ask-a-question-you-can-answer-with-data/player]
>
>
## <a name="other-videos-in-this-series"></a>Andra videor i denna serie
*Data Science for Beginners* är en snabb introduktion till datavetenskap i fem korta videor.
* Video 1: [De 5 frågorna datavetenskap svar](data-science-for-beginners-the-5-questions-data-science-answers.md) *(5 min 14 sek)*
* Video 2: [Är dina data redo för datavetenskap?](data-science-for-beginners-is-your-data-ready-for-data-science.md) *(4 min 56 sek)*
* Video 3: Ställ en fråga som du kan besvara med data
* Video 4: [Förutsäg ett svar med en enkel modell](data-science-for-beginners-predict-an-answer-with-a-simple-model.md) *(7 min 42 sek)*
* Video 5: [Kopiera andras arbete för att göra datavetenskap](data-science-for-beginners-copy-other-peoples-work-to-do-data-science.md) *(3 min 18 sek)*
## <a name="transcript-ask-a-question-you-can-answer-with-data"></a>Avskrift: Ställ en fråga som du kan besvara med data
Välkommen till den tredje videon i serien "Data Science for Beginners".
I den här får du några tips om hur du formulerar en fråga som du kan besvara med data.
Du kan få ut mer av den här videon, om du först tittar på de två tidigare videorna i den här serien: "De 5 frågorna som datavetenskap kan svara på" och "Är dina data redo för datavetenskap?"
## <a name="ask-a-sharp-question"></a>Ställ en skarp fråga
Vi har talat om hur datavetenskap är processen att använda namn (även kallade kategorier eller etiketter) och siffror för att förutsäga ett svar på en fråga. Men det kan inte vara vilken fråga som helst; Det måste vara en *skarp fråga.*
En fråga behöver inte besvaras med ett namn eller ett nummer. En skarp fråga måste.
Föreställ dig att du hittat en magisk lampa med en ande som sanningsenligt kommer att svara på alla frågor du ställer. Men det är en busig ande, som kommer att försöka göra sitt svar så vagt och förvirrande som de kan komma undan med. Du vill sätta dit dem med en fråga så lufttät att de inte kan låta bli att berätta vad du vill veta.
Om du skulle ställa en fråga, som Vad kommer att hända med mitt lager?, kan anden svara, Priset kommer att förändras. Det är ett sanningsenligt svar, men det är inte till stor hjälp.
Men om du skulle ställa en skarp fråga, som "Vad kommer mitt lager försäljningspris vara nästa vecka?", anden kan inte låta bli att ge dig ett specifikt svar och förutsäga ett försäljningspris.
## <a name="examples-of-your-answer-target-data"></a>Exempel på ditt svar: Måldata
När du har formulerat din fråga kontrollerar du om du har exempel på svaret i dina data.
Om vår fråga är "Vad kommer mina aktier försäljningspris vara nästa vecka?" då måste vi se till att våra data innehåller aktiekurshistoriken.
Om vår fråga är "Vilken bil i min flotta kommer att misslyckas först?" då måste vi se till att våra data innehåller information om tidigare fel.

Dessa exempel på svar kallas ett mål. Ett mål är vad vi försöker förutsäga om framtida datapunkter, oavsett om det är en kategori eller ett tal.
Om du inte har några måldata måste du skaffa några. Du kommer inte att kunna svara på din fråga utan den.
## <a name="reformulate-your-question"></a>Omformulera din fråga
Ibland kan du omformulera din fråga för att få ett mer användbart svar.
Frågan "Är detta datapunkt A eller B?" förutsäger kategori (eller namn eller etikett) för något. För att besvara det använder vi en *klassificeringsalgoritm*.
Frågan "Hur mycket?" eller "Hur många?" förutspår ett belopp. För att besvara det använder vi en *regressionsalgoritm*.
För att se hur vi kan förändra dessa, låt oss titta på frågan, "Vilken nyhet är den mest intressanta för denna läsare?" Det ber om en förutsägelse av ett enda val från många möjligheter - med andra ord "Är detta A eller B eller C eller D?" - och skulle använda en klassificeringsalgoritm.
Men kan denna fråga vara lättare att svara på om du omformulera det som "Hur intressant är varje berättelse på denna lista till denna läsare?" Nu kan du ge varje artikel en numerisk poäng, och sedan är det lätt att identifiera den högst poäng artikeln. Detta är en omformning av klassificeringen frågan i en regression fråga eller Hur mycket?

Hur du ställer en fråga är en ledtråd till vilken algoritm som kan ge dig ett svar.
Du kommer att upptäcka att vissa familjer av algoritmer - som de i vår nyhet exempel - är nära besläktade. Du kan omformulera din fråga för att använda den algoritm som ger dig det mest användbara svaret.
Men, viktigast av allt, ställa den skarpa frågan - den fråga som du kan svara med data. Och se till att du har rätt data för att svara på den.
Vi har talat om några grundläggande principer för att ställa en fråga som du kan svara på med data.
Var noga med att kolla in de andra videorna i "Data Science for Beginners" från Microsoft Azure Machine Learning Studio (klassisk).
## <a name="next-steps"></a>Nästa steg
* [Prova ett första datavetenskapsexperiment med Machine Learning Studio (klassiskt)](create-experiment.md)
* [Få en introduktion till Maskininlärning på Microsoft Azure](/azure/machine-learning/preview/overview-what-is-azure-ml)
|
C# | UTF-8 | 12,267 | 2.84375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace YiTui.DAL
{
/// <summary>
/// 貌似这玩意不好用??排不出结果???
/// </summary>
class scoreComparer : IComparer<double>
{
public int Compare(double x, double y)
{
return x < y ? 1 : (x == y ? 0 : -1);
}
}
public class objectSimilarity{
public objectSimilarity(int objectId,double similarity){this.objectId=objectId;this.similarity=similarity;}
public int objectId{get;set;}
public double similarity{get;set;}
}
public class RecommDAL
{
public RecommDAL()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// 返回关于1和2的基于距离的相似度评价
/// </summary>
/// <param name="person1Dic"></param>
/// <param name="person2Dic"></param>
/// <returns></returns>
private static double simDistance(Dictionary<int,double>person1Dic,Dictionary<int,double>person2Dic)
{
//如果两人没有消费过相同的条目,则相似度为0
bool simTag = false;
foreach (int item in person1Dic.Keys)
{
if (person2Dic.Keys.Contains(item))
{
simTag = true;
break;
}
}
if (!simTag) return 0;
double ret=0;
int sum=0;
foreach (int item in person1Dic.Keys)
if(person2Dic.Keys.Contains(item))
sum+=Convert.ToInt32(Math.Pow(Convert.ToDouble(person1Dic[item]-person2Dic[item]),Convert.ToDouble(2)));
ret = 1 / (1 + Math.Sqrt(sum));
return ret;
}
/// <summary>
/// 获取指定字典
/// </summary>
/// <param name="mainKeyName"></param>
/// <param name="subKeyName"></param>
/// <param name="valueName"></param>
/// <returns></returns>
private static Dictionary<int, Dictionary<int, double>>
getDic(string mainKeyName,string subKeyName,string valueName)
{
Dictionary<int, Dictionary<int, double>> ret = new Dictionary<int, Dictionary<int, double>>();
DataTable tmpDT = YiTui.DAL.Execute.ExecuteProcDataTable("sp_Query_User_Item_Rate");
int lastId = 0;//记录上一次获取的结果,如果不相同,则需新建dic
foreach (DataRow item in tmpDT.Rows)
{
//如果ret中没有该用户,向ret添加该用户,以及其对应的字典
//如果ret中有,则向该用户的字典中添加数据项
int mainId = Convert.ToInt32(item["mainKeyName"].ToString());
if (mainId != lastId)
ret.Add(mainId, new Dictionary<int, double>());
ret[mainId].Add(Convert.ToInt32(item["subKeyName"].ToString()),
Convert.ToSingle(item["valueName"].ToString()));
lastId = mainId;
}
return ret;
}
/// <summary>
/// 获取相似的条目/用户
/// </summary>
/// <param name="Dic"></param>
/// <param name="item"></param>
/// <param name="n"></param>
/// <returns></returns>
private static List<objectSimilarity> getSimObject
(Dictionary<int, Dictionary<int, double>> Dic, int item, int n = 3)
{
List<objectSimilarity> ls = new List<objectSimilarity>();
foreach (int other in Dic.Keys)
{
if (other != item)
{
double similarity = simDistance(Dic[item], Dic[other]);
if (similarity != 0)
ls.Add(new objectSimilarity(other, similarity));
}
}
ls.OrderBy(x => x.similarity, new scoreComparer());
//???ret.Reverse();???
var t = ls.Take(n);
List<objectSimilarity> ret = new List<objectSimilarity>();
foreach (objectSimilarity i in t)
{
ret.Add(i);
}
return ret;
}
#region 基于用户的推荐
/// <summary>
/// 外部接口
/// 当规模小时,userDic可选用所有用户的userDic
/// 当规模较大时,应通过getSimUser获取相似用户,再获取相似用户的itemDic
/// </summary>
/// <param name="person"></param>
/// <param name="n"></param>
/// <returns></returns>
public static List<objectSimilarity> getItemRecommUserBased(int person,int n=3)
{
return getItemRecommUserBased(getUserDic(),person,n);
}
/// <summary>
/// 获得指定用户的基于用户的条目推荐结果
/// 当规模小时,userDic可选用所有用户的userDic
/// 当规模较大时,应通过getSimUser获取相似用户,再获取相似用户的itemDic
/// </summary>
/// <param name="userDic"></param>
/// <param name="person"></param>
/// <param name="n"></param>
/// <returns></returns>
public static List<objectSimilarity> getItemRecommUserBased
(Dictionary<int, Dictionary<int, double>> userDic, int person, int n = 3)
{
Dictionary<int, double> totals = new Dictionary<int, double>();
Dictionary<int, double> simSums = new Dictionary<int, double>();
foreach (int other in userDic.Keys)
{
if (other == person)
continue;
double sim = simDistance(userDic[person], userDic[other]);
if (sim <= 0) continue;
foreach (int item in userDic[other].Keys)
{
if (!userDic[person].Keys.Contains(item) || userDic[person][item] == 0)
{
totals.DefaultIfEmpty(new System.Collections.Generic.KeyValuePair<int, double>(item, 0));
totals[item] += userDic[other][item] * sim;
simSums.DefaultIfEmpty(new System.Collections.Generic.KeyValuePair<int, double>(item, 0));
simSums[item] += sim;
}
}
}
List<objectSimilarity> rankings = new System.Collections.Generic.List<objectSimilarity>();
foreach (int item in totals.Keys)
rankings.Add(new objectSimilarity(item, totals[item] / simSums[item]));
rankings.OrderBy(x => x.similarity, new scoreComparer());
var t = rankings.Take(n);
List<objectSimilarity> ret = new List<objectSimilarity>();
foreach (objectSimilarity item in t)
{
ret.Add(item);
}
return ret;
}
/// <summary>
/// 返回一个带有userId itemId 和 rate的 全部用户字典
/// 是否可以改进为带yeild的?
/// </summary>
/// <returns></returns>
private static Dictionary<int, Dictionary<int, double>> getUserDic()
{
return getDic("USER_ID", "ITEM_ID", "RATE");
}
#endregion 基于用户的推荐
#region 基于条目的推荐
/// <summary>
/// 外部程序部应该直接使用此函数,应使用封装好的另一个重载
/// </summary>
/// <param name="person"></param>
/// <param name="n"></param>
/// <returns>返回相似条目的列表</returns>
private static List<objectSimilarity> getItemRecommItemBased
(Dictionary<int, Dictionary<int, double>> userDic,
Dictionary<int, List<objectSimilarity>> simItemDic, int person, int n)
{
Dictionary<int, double> personDic = new Dictionary<int, double>();
personDic = userDic[person];
Dictionary<int, double> scores = new Dictionary<int, double>();
Dictionary<int, double> totalSum = new Dictionary<int, double>();
foreach (int item in personDic.Keys)
{
foreach (objectSimilarity item2 in simItemDic[item])
{
if(personDic.Keys.Contains(item2.objectId))
continue;
scores.DefaultIfEmpty(new KeyValuePair<int,double>(item2.objectId,0));
scores[item2.objectId] += item2.similarity * personDic[item2.objectId];
totalSum.DefaultIfEmpty(new KeyValuePair<int,double>(item2.objectId,0));
totalSum[item2.objectId]+=personDic[item2.objectId];
}
}
List<objectSimilarity> rankings = new List<objectSimilarity>();
foreach (int item in scores.Keys)
rankings.Add(new objectSimilarity(item, scores[item] / totalSum[item]));
rankings.OrderBy(x => x.similarity, new scoreComparer());
var t = rankings.Take(n);
List<objectSimilarity> ret = new List<objectSimilarity>();
foreach (objectSimilarity item in t)
{
ret.Add(item);
}
return ret;
}
/// <summary>
/// 获得某一条目的基于条目的推荐结果
/// </summary>
/// <param name="item"></param>
/// <param name="n"></param>
/// <returns></returns>
public static List<objectSimilarity> getItemRecommItemBased(int item, int n = 3)
{
List<objectSimilarity> ret = new List<objectSimilarity>();
ret=simItemDic[item];
if (n < ret.Count)
return ret.GetRange(0, n);
else
return ret;
}
/// <summary>
/// 基于物品的过滤过程总体思路就是为媒介物品预先计算好最为相近的其他物品。然后,当我们相位某位用户提供推荐时,就可以查看
/// 他曾经评分过的物品,并从中选出排位靠前者,再构造出一个加权列表,其中包含了与这些选中物品最为相近的物品。此处最为显著
/// 的区别在于,尽管第一步要求我们检查所有的数据,但物品键的比较不会像用户的比较那么频繁变化。无需不停的为每样物品计算最
/// 为相似的物品。我们可将这样的任务安排在网络流量不是很大的时候定期进行,活在独立于主程序之外的另一台计算机上单独进行。
///
/// 实际应用中,此数据应存放于数据库中,演示时,为了方便,设为静态变量放在了程序中。
/// </summary>
private static Dictionary<int, List<objectSimilarity>> simItemDic = new Dictionary<int, List<objectSimilarity>>();
/// <summary>
/// 获得条目的总字典
/// </summary>
/// <returns></returns>
private static Dictionary<int, Dictionary<int, double>> getItemDic()
{
return getDic("ITEM_ID", "USER_ID", "RATE");
}
/// <summary>
/// 为每个条目执行距离向量算法,计算相似度生成simItemDic
/// </summary>
/// <param name="itemDic"></param>
/// <param name="n"></param>
private static void calcSimItemDic(Dictionary<int, Dictionary<int, double>> itemDic, int n = 3)
{
Dictionary<int, List<objectSimilarity>> simItemDicBack=new Dictionary<int,List<objectSimilarity>>();
simItemDicBack=simItemDic;
simItemDic.Clear();
try
{
foreach (int item in itemDic.Keys)
simItemDic.Add(item, getSimObject(itemDic, item, n));
simItemDicBack.Clear();
}
catch (Exception)
{
simItemDic = simItemDicBack;
simItemDicBack.Clear();
throw;
}
}
#endregion 基于条目的推荐
}
} |
Java | UTF-8 | 1,193 | 2.984375 | 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 Figuras;
import java.awt.Color;
/**
*
* @author eduardobaldivieso
*/
public class Empty extends Block{
private boolean occupied;
private boolean inmovable;
public Empty(int x, int y, Color color) {
super(x, y, color);
this.occupied = false;
this.inmovable = false;
}
public Empty(int x, int y, Color color,boolean ocupado) {
super(x, y, color);
this.occupied = ocupado;
this.inmovable = false;
}
public Empty(int x, int y, Color color,boolean occupied, boolean inmovable) {
super(x, y, color);
this.occupied = occupied;
this.inmovable = inmovable;
}
public boolean isOccupied() {
return occupied;
}
public void setOccupied(boolean ocupado) {
this.occupied = ocupado;
}
public boolean isInmovable() {
return inmovable;
}
public void setInmovable(boolean inmovable) {
this.inmovable = inmovable;
}
}
|
C | UTF-8 | 553 | 3.59375 | 4 | [] | no_license | /*
* Program to print the matrix in spiral form
* */
#include<stdio.h>
int main()
{
int arr[100][100],i,j,m,n;
printf("Enter the dimensions : ");
scanf("%d %d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<m;i++)
{
/* if(i%2)
{
for(j=n-1;j>=0;j--)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
*/
for(j=0;j<n;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}
|
Shell | UTF-8 | 1,625 | 3.390625 | 3 | [] | no_license | function git_url() {
if [ -d ".git" ] || git rev-parse --git-dir > /dev/null 2>&1; then
url=`git config --get remote.origin.url`
echo " * $url"
fi
}
function git_branch() {
if [ -d ".git" ] || git rev-parse --git-dir > /dev/null 2>&1 ; then
branch=`git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/\(.*\)/ \1/'`
echo "$branch *"
fi
}
function git_status() {
if [ -d ".git" ] || git rev-parse --git-dir > /dev/null 2>&1 ; then
gitstatus=`git status 2> /dev/null`
output=""
untracked=`git status --porcelain | sed -n -e 's/^?? //p' | wc -l`
unstaged=`git diff --name-only | wc -l`
staged=`git diff --name-only --staged | wc -l`
if [ $untracked != 0 ]; then
output="Untracked: $untracked"
fi
if [ $unstaged != 0 ]; then
output="$output Unstaged: $unstaged"
fi
if [ $staged != 0 ]; then
output="$output Staged: $staged"
fi
echo "$output"
fi
}
PS="""
\[\033[38;5;014m\]\t
\[\033[38;5;047m\] \u
\[\033[38;5;158m\]@
\[\033[38;5;035m\]\H
\[\033[38;5;158m\][
\[\033[38;5;192m\]\w
\[\033[38;5;158m\]]
\[\033[38;5;051m\]\$(git_url)
\[\033[38;5;159m\]\$(git_branch) \[$(tput sgr0)\]
\[\033[48;5;001m\]\$(git_status)\[$(tput sgr0)\]
\[\033[38;5;050m\]\n\[$(tput sgr0)\]
\[\033[38;5;158m\]# > \[$(tput sgr0)\]
"""
export PS1=`echo "${PS}" | tr -d '\n'`
|
JavaScript | UTF-8 | 1,930 | 2.5625 | 3 | [
"MIT"
] | permissive | "use strict";
var fs = require("fs");
var utils = require('./utils');
var tasklogic = {
getPrefix: function (mode) {
return mode === 'repeat' ? 'repeatTask' : 'dailyTask';
},
writeTypeToFile: function (obj) {
fs.writeFileSync('conf/tasksTypelist.json', obj, 'utf-8');
},
readTypeFromFile: function () {
try {
var obj = fs.readFileSync('conf/tasksTypelist.json', 'utf-8');
return obj;
} catch (e) {
return "";
}
},
writeToFile: function (targetDate, taskList, mode) {
var prefix = tasklogic.getPrefix(mode);
var fileName = tasklogic.createFileName(prefix, targetDate);
if (taskList.length === 0) {
fs.access(fileName, fs.F_OK, function (err) {
if (!err) {
fs.unlink(fileName, function () { });
}
});
} else {
fs.writeFileSync(fileName, JSON.stringify(taskList), 'utf-8');
}
},
readFromFile: function (date, mode) {
var prefix = tasklogic.getPrefix(mode);
var taskList;
try {
taskList = JSON.parse(fs.readFileSync(tasklogic.createFileName(prefix, date), 'utf-8'));
} catch (e) {
if (mode !== 'repeat') {
prefix = tasklogic.getPrefix('repeat');
try {
taskList = JSON.parse(fs.readFileSync(tasklogic.createFileName(prefix, date), 'utf-8'));
} catch (e) {
taskList = [];
}
} else {
taskList = [];
}
}
taskList.forEach(function (e) {
e.fromDate = e.fromDate != null ? new Date(e.fromDate) : null;
e.toDate = e.toDate != null ? new Date(e.toDate) : null;
e.focused = false;
});
return taskList;
},
createFileName: function (prefix, date) {
if (prefix === 'repeatTask') {
return 'conf/repeatTask.json';
}
var fileName = 'data/dailyTask';
fileName += utils.getDateString(date);
fileName += ".json";
return fileName;
}
};
module.exports = tasklogic;
|
Markdown | UTF-8 | 11,935 | 2.953125 | 3 | [] | no_license | # Devcards
Devcards aims to provide ClojureScript developers with an interactive
visual REPL. Devcards makes it simple to interactively surface code
examples that have a visual aspect into a browser interface.
Devcards is **not** a REPL, as it is driven by code that exists in
your source files, but it attempts to provide a REPL-like experience
by allowing developers to quickly try different code examples and
see how they behave in an actual DOM.
Devcards is centered around a notion of a *card*. Every card
represents some code to be displayed. Devcards provides an interface
which allows the developer navigate to different namespaces and view
the *cards* that have been defined in that namespace.
When used in conjunction with [lein figwheel][leinfigwheel] the cards can be
created and edited **"live"** in one's ClojureScript source
files.
[See the introduction video.](https://vimeo.com/97078905)
<img src="https://s3.amazonaws.com/bhauman-blog-images/devcards-action-shot.png"/>
For example, the following code will create a *card* for a Sablono
template that you might be working on:
```clojure
(defcard two-zero-48-view
(sab-card [:div.board
[:div.cells
[:div {:class "cell xpos-1 ypos-1"} 4]
[:div {:class "cell xpos-1 ypos-2"} 2]
[:div {:class "cell xpos-1 ypos-3"} 8]]]))
```
When used with [lein-figwheel][leinfigwheel], saving the file that
contains this definition will cause this Sablono template to be
rendered into the Devcards interface.
## Examples
Regardless of which path you take to get started with Devcards please
see the following examples:
[Examples of all the cards](https://github.com/bhauman/devcards/blob/master/example_src/devdemos/core.cljs)
[An example implementation of 2048](https://github.com/bhauman/devcards/blob/master/example_src/devdemos/two_zero.cljs)
## Super Quick Start
There is a Devcards Leiningen template to get you up an running quickly.
Make sure you have the [latest version of leiningen installed](https://github.com/technomancy/leiningen#installation).
Type the following to create a fresh project with devcards setup for you:
```
lein new devcards hello-world
```
Then
```
cd hello-world
lein figwheel
```
to start the figwheel interactive devserver.
Then visit `http://localhost:3449/devcards/index.html`
## Quick Trial
If you want to quickly interact with a bunch of devcards demos:
```
git clone https://github.com/bhauman/devcards.git
cd devcards
lein figwheel
```
Then visit `http://localhost:3449/devcards/index.html`
The code for the cards you are viewing in the devcards interface is
located in the `example_src` directory.
Go ahead and edit the code in the examples and see how the devcards
interface responds.
## Usage
First make sure you include the following `:dependencies` in your `project.clj` file.
```clojure
[org.clojure/clojurescript "0.0-2197"] ;; has to be at least 2197 or greater
[devcards "0.1.2-SNAPSHOT"]
```
lein figwheel is not required to use Devcards but ... if you want to
experience interactive coding with Devcards you will need to have
[lein-figwheel](https://github.com/bhauman/lein-figwheel) configured.
See the [lein-figwheel repo](https://github.com/bhauman/lein-figwheel)
for instructions on how to do that.
Devcards is extremely new so the patterns for using it are completely
up in the air. I am going to show you the very least you need to setup to
get devcards running.
You will need an HTML file to host the devcards interface. It makes
sense to have a separate file to host devcards. I would create the
following `resources/public/devcards/index.html` file.
```html
<!DOCTYPE html>
<html>
<head>
<script src="//fb.me/react-0.9.0.js"></script>
<script src="//code.jquery.com/jquery-1.11.0.js"></script>
<!-- This showdown has been modified a tiny bit -->
<script src="//rigsomelight.com/devcards/devcards-assets/showdown.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"
rel="stylesheet" type="text/css">
<link href="//rigsomelight.com/devcards/devcards-assets/devcards.css"
rel="stylesheet" type="text/css">
<link href="//rigsomelight.com/devcards/devcards-assets/rendered_edn.css"
rel="stylesheet" type="text/css">
</head>
<body>
<div id="devcards-main">
</div>
<script src="js/compiled/out/goog/base.js" type="text/javascript"></script>
<script src="js/compiled/example.js" type="text/javascript"></script>
<script type="text/javascript">goog.require("example.core");</script>
</body>
</html>
```
The key things here are to pull in the Devcards requirements, provide
an element with a `devcards-main` **id** and require your compiled
ClojureScript. If you are using `figwheel` make sure you are using an
`:optimizations :none` build.
Next you will need to include the Devcards library in your
ClojureScript source file.
```clojure
(ns example.core
(:require
[devcards.core :as dc :include-macros true])
(:require-macros
[devcards.core :refer [defcard]])))
(dc/start-devcard-ui!)
;; optional
(dc/start-figwheel-reloader!)
;; required ;)
(defcard my-first-card
(dc/sab-card [:h1 "Devcards is freaking awesome!"]))
```
## The predefined cards
Devcards has several predefined cards. Cards are just functions so you
can compose new cards from these base cards.
### devcards.core/markdown-card
The `markdown-card` is just there to surface documentation into devcards interface.
```clojure
(defcard markdown-example
(dc/markdown-card
"### This is markdown yo
This markdown is filtered so that it can be arbitrarily indented
code blocks have to be delimited like so:
```
(defn myfunc [] :some-code-here)
```
"))
```
### devcards.core/om-root-card
The `om-root-card` has the same function signature as `om/root`. You
can use it to quickly display [Om](https://github.com/swannodette/om) components.
```clojure
(defn widget [data owner]
(reify
om/IRender
(render [this]
(sablono/html [:h2 "This is an om card, " (:text data)]))))
(defcard omcard-ex
(dc/om-root-card widget {:text "yozers"}))
```
### devcards.core/react-card
The `react-card` simply renders a React component. This is the base
for many cards since React components compose so well.
```clojure
(defcard react-card-ex
(dc/react-card (sablono/html [:h1 "I'm a react card."])))
```
### devcards.core/sab-card
The `sab-card` simply renders Sablono.
```clojure
(defcard react-card-ex
(dc/sab-card [:h1 "I'm a react card."]))
```
### devcards.core/react-runner-card
The `react-runner-card` takes a function that takes an atom and
returns a React component. When the atom is changed it will trigger a
rerender.
This lets you quickly define React systems that have interactive behavior.
```clojure
(defn my-react-app [data-atom]
(sablono/html
[:div
[:h1 "Count " (:count @data-atom)]
[:a {:onClick (fn [e] (swap! data-atom update-in [:count] inc)) } "Inc"]]))
(defcard my-react-runner-ex
(dc/react-runner-card my-react-app {:initial-state {:count 50}}))
```
### devcards.core/test-card
The `test-card` lets you define a group of tests.
```clojure
(defcard my-tests-ex
(dc/test-card
"You can have Markdown in test cards"
(dc/is "'is' is an assertion")
(dc/are= "'are=' is an equality test" "are= is an equlity test")
(dc/are-not= "'are-not=' is an disequality test" "yep")))
```
### devcards.core/edn-card
The `edn-card` will display formatted EDN for inspection.
```clojure
(defn my-opaque-func []
{:this "is"
:EDN "yeppers"})
(defcard inspect-opaque
(dc/edn-card (my-opaque-func)))
```
### decards.core/slider-card
The `slider-card` allows you to define a series of sliders over ranges
of inputs.
The first argument to the `slider-card` is a function that will
receive a map of the current value of the sliders. The return value of
this function will be rendered with the `dc/edn->html` renderer.
The second argument is a map where the labels are the value keys and
the values are sequences of values to be chosen by the slider.
There is an optional keyword argument `:value-render-func` that can be
associate with a function that will be passed result of first function
arg and should return a react component.
```clojure
(defcard threed-fun
(dc/slider-card
identity
{:rx (range 360)
:ry (range 360)
:rz (range 360)}
:value-render-func cube-template))
```
## Creating your own cards
Creating your own cards for devcards is not difficult. There are two
main interfaces. There is a simple interface where you can just
define a function and have it be a card. Then there is a more advanced
version where you implement a few protocols.
Creating your own cards gives you a quick peak into how Devcards
works. Devcards keeps track of two major things for each card: a HTML
node and an atom to hold the data that the card will use.
### Function card API
You can create a card quickly by defining a function that takes a map.
For example this is a card:
```clojure
(defn silly-card []
(fn [{:keys [node data-atom]}]
(set! (.-innerHTML node) "<div>I'm a silly card</div>")))
```
And you can use it like this:
```clojure
(defcard silly-card-ex (silly-card))
```
### Protocols API
The protocols API allows you to hook into the devcards lifecycle so
that you can tear down and rebuild anything that needs to be rebuilt
when code is reloaded.
```clojure
(defn super-card [initial-state]
(reify
devcards.system/IMount
(mount [_ {:keys [node data-atom]}]
(render-to (sab/html [:h1 "Super!"]) node))
devcards.system/IUnMount
(unmount [_ {:keys [node]}]
(unmount-react node))
devcards.system/IConfig
(-options [_]
{ :unmount-on-reload false
:initial-state initial-state })))
```
In the above example we are using the `IMount` protocol to define the
cards rendering code. The `IMount` Protocol is the only required protocol.
We are using the `IUnMount` to define any clean up actions that are
needed before potentially destroying the node.
And the `IConfig` protocol is used to pass options for this card type.
The current `IConfig` options are:
* `:unmount-on-reload` default `true`; unmount is called on cards after
a code reload and before they are rendered again with new code
* `:initial-state` default `{}`; the initial state of the data atom for the card
* `:heading` default `true`; whether to deisplay the heading for this card
* `:padding` default `true`; whether or not to have css padding around the body of this card
## FAQ
#### Does Devcards only work with React or Om?
No it doesn't. At its core Devcards manages a raw HTML node and a
data atom for each card. Devcards works with anything you can put in a
node.
#### Does Devcards require Figwheel?
No, you can manually reload the browser after changing your code.
Devcards requires the figwheel client as a dependancy because if you do
decide to use figwheel it hooks into various events fired by the
figwheel client.
You could also integrate Devcards into a Browser REPL workflow
instead of using figwheel.
#### What do I do for deployment?
What pattern to use when working with Devcards is still an open question.
You can move all the cards into a different build similar to the
pattern used for testing in Clojure right now. Or you could start your
coding in this seperate build and then move completed code into your
main build as it matures.
I have been considering a **no-op** release of devcards so that you
can leave Devcards in your source code. I don't know if this is a good
idea but it might be worth a try. Does having the devcards make your
code easier to understand or is it more noisy with them in there?
[leinfigwheel]: https://github.com/bhauman/lein-figwheel
|
Shell | UTF-8 | 1,855 | 2.71875 | 3 | [] | no_license | #!/bin/bash
# variables
TITLE1=$1
TITLE2=$2
TITLE3=$3
TITLE4=$4
Release=$5
CODE=$6
YEAR=$(date +"%Y")
DATE=$(date +"%x")
# cover
# make images
# screenshots
ORDER="ffmpeg -ss 00:03:00 -i "$TITLE1".avi -q:v 0 -vframes 1 "$TITLE1".jpg"
$ORDER
ORDER="ffmpeg -ss 00:03:00 -i "$TITLE2".avi -q:v 0 -vframes 1 "$TITLE2".jpg"
$ORDER
ORDER="ffmpeg -ss 00:03:00 -i "$TITLE3".avi -q:v 0 -vframes 1 "$TITLE3".jpg"
$ORDER
ORDER="ffmpeg -ss 00:03:00 -i "$TITLE4".avi -q:v 0 -vframes 1 "$TITLE4".jpg"
$ORDER
# cut
ORDER="convert "$TITLE1".jpg -crop 854x120 "$TITLE1".jpg"
$ORDER
ORDER="convert "$TITLE2".jpg -crop 854x120 "$TITLE2".jpg"
$ORDER
ORDER="convert "$TITLE3".jpg -crop 854x120 "$TITLE3".jpg"
$ORDER
ORDER="convert "$TITLE4".jpg -crop 854x120 "$TITLE4".jpg"
$ORDER
# montage
ORDER="montage -mode concatenate -tile 1x "$TITLE1"-0.jpg "$TITLE2"-0.jpg "$TITLE3"-0.jpg "$TITLE4"-0.jpg "$Release".jpg"
$ORDER
# gif
ORDER="convert -delay 15 -loop 0 "$TITLE1"-0.jpg "$TITLE1"-1.jpg "$TITLE1"-2.jpg "$TITLE1"-3.jpg "$TITLE1".gif"
$ORDER
ORDER="convert -delay 15 -loop 0 "$TITLE2"-0.jpg "$TITLE2"-1.jpg "$TITLE2"-2.jpg "$TITLE2"-3.jpg "$TITLE2".gif"
$ORDER
ORDER="convert -delay 15 -loop 0 "$TITLE3"-0.jpg "$TITLE3"-1.jpg "$TITLE3"-2.jpg "$TITLE3"-3.jpg "$TITLE3".gif"
$ORDER
ORDER="convert -delay 15 -loop 0 "$TITLE4"-0.jpg "$TITLE4"-1.jpg "$TITLE4"-2.jpg "$TITLE4"-3.jpg "$TITLE4".gif"
$ORDER
# cover
ORDER="convert "$Release".jpg -resize 300% "$Release"-cover1.jpg"
$ORDER
ORDER="convert "$Release"-cover1.jpg -crop 1429x1417+566+11 "$Release"-cover.jpg"
$ORDER
`convert "$Release"-cover.jpg -stroke black -fill white -linewidth 10 -draw 'rectangle 182,638 1247,778' "$Release"-cover.jpg`
`convert "$Release"-cover.jpg -gravity center -font Cabin-Bold -pointsize 40 -annotate 0 'Miquel Parera & Computer - '"$Release" "$Release"-cover.jpg`
|
Python | UTF-8 | 799 | 3.703125 | 4 | [] | no_license | import cv2
# path
path = './Babol/1071.jpg'
# Reading an image in grayscale mode
image = cv2.imread(path, 1)
# Window name in which image is displayed
window_name = 'Image'
# Start coordinate, here (100, 50)
# represents the top left corner of rectangle
start_point = (658, 413)
# Ending coordinate, here (125, 80)
# represents the bottom right corner of rectangle
end_point = (950, 559)
# Black color in BGR
color = (255, 0, 0)
# Line thickness of -1 px
# Thickness of -1 will fill the entire shape
thickness = 0
# Using cv2.rectangle() method
# Draw a rectangle of black color of thickness -1 px
image = cv2.rectangle(image, start_point, end_point, color, thickness)
# Displaying the image
cv2.imshow(window_name, image)
cv2.waitKey(0) |
C | UTF-8 | 351 | 3.03125 | 3 | [] | no_license | #include "../include/cthread.h"
#include <stddef.h>
#include <stdio.h>
void* mythread(void*);
int main() {
int thread1 = ccreate(mythread, (void*)1, 2);
int thread2 = ccreate(mythread, (void*)2, 1);
printf("main: i'm back!!!\n");
return 0;
}
void* mythread(void* arg) {
printf("mytrhead: hello world (%d)\n", (int)arg);
return NULL;
}
|
SQL | UTF-8 | 102 | 2.875 | 3 | [] | no_license | SELECT DISTINCT 'laptop' AS type, model, speed
FROM laptop
WHERE speed < ALL(SELECT speed FROM pc)
|
Python | UTF-8 | 2,870 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python3
import os
import random
import imageio
import time
import numpy as np
# For visualization and stuff
import cv2
def LCD_ShowImageAsArray(Image,Xstart,Ystart):
if (Image.all() == None):
return
imwidth = Image.shape[0] # width
imheight = Image.shape[1] # height
if imwidth != 128 or imheight != 128:
raise ValueError('Image must be same dimensions as display \
({0}x{1}).' .format(128, 128))
pix = np.zeros((128,128,2), dtype = np.uint8)
pix[...,[0]] = np.add(np.bitwise_and(Image[...,[0]],0xF8),np.right_shift(Image[...,[1]],5))
pix[...,[1]] = np.add(np.bitwise_and(np.left_shift(Image[...,[1]],3),0xE0),np.right_shift(Image[...,[2]],3))
pix = pix.flatten().tolist()
def displayGIFWithOpenCV(GIFImage, name):
numOfFrames = len(GIFImage)
print("Total {} frames in the gif \"{}\"!".format(numOfFrames, name))
# convert form RGB to BGR
imgs = [cv2.cvtColor(img, cv2.COLOR_RGB2BGR) for img in GIFImage]
# show the single images
i = 0
try:
repeats = 1
if numOfFrames <= 10:
repeats = 3
elif numOfFrames <= 25:
repeats = 2
for x in range(0, repeats * numOfFrames):
LCD_ShowImageAsArray(imgs[i], 0, 0)
cv2.namedWindow("cat")
cv2.imshow("cat", imgs[i])
if cv2.waitKey(60)&0xFF == 27:
break
i = (i+1)%numOfFrames
else:
print("End of OpenCV vis loop :)")
except Exception as er:
print("OpenCV vis exception! Error: " + str(er))
try:
def main():
#LCD = LCD_1in44.LCD()
#print "**********Init LCD**********"
#Lcd_ScanDir = LCD_1in44.SCAN_DIR_DFT #SCAN_DIR_DFT = D2U_L2R
#LCD.LCD_Init(Lcd_ScanDir)
#LCD.LCD_ShowImage(image,0,0)
#LCD_Config.Driver_Delay_ms(500)
# print("********** Start GIF of single image **********")
# cat = imageio.mimread("cats/Resized/cat_1.gif")
# displayGIFWithOpenCV(cat, "cat")
# Begin with random selected GIF
print("********** Start VIS of random gif ****************")
dir_path = os.path.dirname(os.path.realpath(__file__))
directory = dir_path + "/cats/Resized"
print("Directory: " + directory)
for x in range(1, 20):
#filename = random.choice(os.listdir("cats/Resized"))
filename = random.choice([x for x in os.listdir(directory) if os.path.isfile(os.path.join(directory, x))]) # last part ensures that opened file is a file
print("Random choice file: " + directory + "/" + filename)
try:
catRandom = imageio.mimread(directory + "/" + filename)
displayGIFWithOpenCV(catRandom, "random cat " + filename)
except Exception as er:
print("ImageIO mimread error: " + str(er))
# Destroy all created windows at end
cv2.destroyAllWindows()
print("Stopping cat test monitor. Goodbye :)")
if __name__ == '__main__':
main()
except Exception as er:
print("Catched exception! Error: " + str(er))
|
JavaScript | UTF-8 | 3,934 | 2.96875 | 3 | [] | no_license | function makeReservation(selector) {
$("#submit").on('click', submitInformation);
$("#continue").on("click", continueReservation)
let fullName = $("#fullName");
let email = $("#email");
let phoneNumber = $("#phoneNumber");
let address = $("#address");
let postalCode = $("#postalCode")
function submitInformation() {
if (!fullName.val() == "" && !email.val() == "") {
$("#submit").prop("disabled", true);
$("#edit").on('click', editReservation).prop("disabled", false);
$("#continue").prop("disabled", false);
$("#infoPreview").append($("<li>").text(`Name: ${fullName.val()}`))
.append($("<li>").text(`E-mail: ${email.val()}`))
.append($("<li>").text(`Phone: ${phoneNumber.val()}`))
.append($("<li>").text(`Address: ${address.val()}`))
.append($("<li>").text(`Postal Code: ${postalCode.val()}`));
fullName.val("");
email.val("");
phoneNumber.val("");
address.val("");
postalCode.val("");
}
}
function continueReservation() {
$("#edit").prop("disabled", true);
$("#continue").prop("disabled", true);
($("<h2>").text("Payment details")).appendTo($(selector));
($("<select id=\"paymentOptions\" class=\"custom-select\">")
.append($("<option selected disabled hidden>Choose</option>"))
.append($("<option>").prop("value", "creditCard").text("Credit Card"))
.append($("<option>").prop("value", "bankTransfer").text("Bank Transfer"))).on("change", submitReservation).appendTo(selector);
let extraDetails = ($("<div>").prop("id", "extraDetails")).appendTo(selector);
}
function editReservation() {
$("#submit").prop("disabled", false);
$("#edit").prop("disabled", true);
$("#continue").prop("disabled", true);
let fullNameValue = $("#infoPreview").children()[0].textContent.slice(6);
let emailValue = $("#infoPreview").children()[1].textContent.slice(8);
let phoneValue = $("#infoPreview").children()[2].textContent.slice(7);
let addressValue = $("#infoPreview").children()[3].textContent.slice(9);
let postalCodeValue = $("#infoPreview").children()[4].textContent.slice(13);
$("#infoPreview").children().remove();
fullName.val(fullNameValue);
email.val(emailValue);
phoneNumber.val(phoneValue);
address.val(addressValue);
postalCode.val(postalCodeValue);
}
function submitReservation() {
let optionValue = $("#paymentOptions").val();
let extraDetails = ($("#extraDetails"))
extraDetails.children().remove();
if (optionValue === "creditCard") {
((($("<div class=\"inputLabel\">").text("Card Number"))
.append($('<input>'))))
.appendTo(extraDetails);
$("<br>").appendTo(extraDetails);
((($("<div class=\"inputLabel\">").text("Expiration Date"))
.append($('<input>'))))
.appendTo(extraDetails);
$("<br>").appendTo(extraDetails);
((($("<div class=\"inputLabel\">").text("Security Numbers"))
.append($('<input>'))))
.appendTo(extraDetails);
$("<br>").appendTo(extraDetails);
}
else if (optionValue === "bankTransfer") {
$('<p>You have 48 hours to transfer the amount to:<br>IBAN: GR96 0810 0010 0000 0123 4567 890</p>').appendTo(extraDetails);
}
$("<button>").prop("id", 'checkOut').text("Check Out").on("click", finnish).appendTo(extraDetails);
extraDetails.appendTo(selector);
}
function finnish() {
$("#wrapper").children().remove();
$("<h4>").text("Tank you for your reservation!").appendTo("#wrapper");
}
} |
Python | UTF-8 | 1,418 | 3.53125 | 4 | [
"Apache-2.0"
] | permissive | import os
from IOC import *
class Component(object):
""" Symbolic base class for components
"""
class Bar(Component):
con = RequiredFeature('Console', hasMethods('WriteLine'))
title = RequiredFeature('AppTitle', isInstanceOf(str))
user = RequiredFeature('CurrentUser', isInstanceOf(str))
def __init__(self):
self.x = 0
def printYourself(self):
self.con.WriteLine('-- Bar instance --')
self.con.WriteLine('Title: %s' % self.title)
self.con.WriteLine('User: %s' % self.user)
self.con.WriteLine('X: %d' % self.x)
class SimpleConsole(Component):
def WriteLine(self, s):
print s
class BetterConsole(Component):
def __init__(self, prefix=''):
self.prefix = prefix
def WriteLine(self, s):
lines = s.split('\n')
for line in lines:
if line:
print self.prefix, line
else:
print
def GetCurrentUser():
return os.getenv('USERNAME') or 'Some User'
if __name__ == '__main__':
print ' IOC Demo'
features.provide('AppTitle', 'Inversion of Control ...\n\n... The Python Way')
features.provide('CurrentUser', GetCurrentUser)
# features.provide('Console', BetterConsole, prefix='-->') # <-- transient lifestyle
features.provide('Console', BetterConsole(prefix='-->')) # <-- singleton lifestyle
bar = Bar()
bar.printYourself()
|
Go | UTF-8 | 1,641 | 2.9375 | 3 | [
"BSD-3-Clause"
] | permissive | package main
import (
"bytes"
"encoding/base64"
"fmt"
"log"
"github.com/buaazp/fasthttprouter"
"github.com/ikozinov/fasthttp"
)
var basicAuthPrefix = []byte("Basic ")
// BasicAuth is the basic auth handler
func BasicAuth(h fasthttprouter.Handle, user, pass []byte) fasthttprouter.Handle {
return fasthttprouter.Handle(func(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) {
// Get the Basic Authentication credentials
auth := ctx.Request.Header.Peek("Authorization")
if bytes.HasPrefix(auth, basicAuthPrefix) {
// Check credentials
payload, err := base64.StdEncoding.DecodeString(string(auth[len(basicAuthPrefix):]))
if err == nil {
pair := bytes.SplitN(payload, []byte(":"), 2)
if len(pair) == 2 &&
bytes.Equal(pair[0], user) &&
bytes.Equal(pair[1], pass) {
// Delegate request to the given handle
h(ctx, ps)
return
}
}
}
// Request Basic Authentication otherwise
ctx.Response.Header.Set("WWW-Authenticate", "Basic realm=Restricted")
ctx.Error(fasthttp.StatusMessage(fasthttp.StatusUnauthorized), fasthttp.StatusUnauthorized)
})
}
// Index is the index handler
func Index(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) {
fmt.Fprint(ctx, "Not protected!\n")
}
// Protected is the Protected handler
func Protected(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) {
fmt.Fprint(ctx, "Protected!\n")
}
func main() {
user := []byte("gordon")
pass := []byte("secret!")
router := fasthttprouter.New()
router.GET("/", Index)
router.GET("/protected/", BasicAuth(Protected, user, pass))
log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}
|
Ruby | UTF-8 | 397 | 2.625 | 3 | [] | no_license | module Memory
class Base
attr_accessor :errors
def validate_presence_of(params, *required_attributes)
@errors = {}
required_attributes.each do |attr|
@errors[attr] = "#{attr.to_s.capitalize} is required" if blank(params[attr])
end
end
def valid?
@errors.empty?
end
def blank(params)
params.nil? || params == ""
end
end
end
|
Python | UTF-8 | 443 | 2.71875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3.6
import uuid
from pykeepass import PyKeePass
# load database
kp = PyKeePass('./test.kdbx', password='test')
# find by title
entry = kp.find_entries(title='id_rsa', first=True)
print(entry.title)
# find by path
entry = kp.find_entries(path='dir1/dir2/id_rsa', first=True)
print(entry.path)
# find by uuid
entry = kp.find_entries(uuid=uuid.UUID('de37072b8cec670ff58212b9cae05806'), first=True)
print(entry.uuid) |
C | UTF-8 | 1,172 | 3.53125 | 4 | [] | no_license |
#include <avr/io.h>
#include <util/delay.h>
//Defining constants:
#define SET_DDG1 0x02 // Set bit 1 to output in DDRG
#define SET_PORTG1 0x02 // Set bit 1 to output in PORTG
#define TRUE 1
#define FREQUENCY 16000000 // Microprocessor frequency 16MHz
#define CYCLES 7 // Number of cycles corresponding to one loop instructions(nop,sbiw,sbc(x2),brne,in)
#define CONV_TO_SEC 1000 // Used to convert from milliseconds to seconds
void wait(uint16_t);
int main(void) {
DDRG |= 0x02;
wait(1000);
PORTG ^= 0x02;
wait(1000);
PORTG ^= 0x02;
return 0;
}
/* wait for 16000000 cycles (1 second) multiplied by the required seconds.
i.e. This loop consumes 7 cycles when executed , and 16000000 cycles are needed to pass one second,
so 16000000/7 will give the number of times this loop needs to execute to make one second pass, and
since we take milli seconds as an input we have to converted to seconds by diving by 1000. */
void wait(uint16_t millis)
{
for (uint32_t i=(FREQUENCY/CYCLES*CONV_TO_SEC)*millis; i>0; i--)
{
asm volatile("nop"); // one cycle with no operation
}
}
|
Python | UTF-8 | 360 | 3.609375 | 4 | [] | no_license | def getVolumeOfCubiod(length, width, height):
return length * width * height
print(getVolumeOfCubiod(1, 2, 2), 4)
print(getVolumeOfCubiod(6.3, 2, 5), 63)
'''
# Details
Bob needs a fast way to calculate the volume of a cuboid with three values: length, width and the
height of the cuboid. Write a function to help Bob with this calculation.
'''
|
JavaScript | UTF-8 | 1,914 | 2.5625 | 3 | [] | no_license | const express = require('express');
const router = express.Router();
const Company = require('../models/Company');
// @route GET api/company/showcompanies
// @description Get all companies
// @access Public
const getAllCompanies = async (req, res) => {
//console.log(rech)
Company.find()
.populate('company_id', { company_name: 1 })
.then((companys) => res.json(companys))
.catch((err) =>
res.status(404).json({ nocompaniesfound: 'No companyies found' })
);
};
// @route GET pi/company/:id
// @description Get single book by id
// @access Public
const getCompanyById = async (req, res) => {
Company.findById(req.params.id)
.then((companys) => res.json(companys))
.catch((err) =>
res.status(404).json({ nocompaniesfound: 'No companys found' })
);
};
// @route GET api/company
// @description api/company/addcomp
// @access Public
const createCompany = async (req, res) => {
Company.create(req.body)
.then((companys) => res.json({ msg: 'Company added successfully' }))
.catch((err) =>
res.status(400).json({ error: 'Unable to add this Company' })
);
};
// @route GET api/books/:id
// @description Update book
// @access Public
const updateCompanyById = async (req, res) => {
Company.findByIdAndUpdate(req.params.id, req.body)
.then((companys) => res.json({ msg: 'Updated successfully' }))
.catch((err) =>
res.status(400).json({ error: 'Unable to update the Database' })
);
};
// @route GET api/books/:id
// @description Delete book by id
// @access Public
const deleteCompany = async (req, res) => {
Company.findByIdAndRemove(req.params.id, req.body)
.then((companys) => res.json({ mgs: 'company entry deleted successfully' }))
.catch((err) => res.status(404).json({ error: 'No such a book' }));
};
module.exports = {
getAllCompanies,
getCompanyById,
createCompany,
deleteCompany,
updateCompanyById,
};
|
Java | UTF-8 | 1,005 | 2.078125 | 2 | [] | no_license | package com.java.mapper;
import com.github.pagehelper.Page;
import com.java.bean.Student;
import com.java.bean.StudentSO;
import com.java.bean.base.Query;
import java.util.List;
/**
* 学生管理Mapper
*
* @author yupan@yijiupi.cn
* @date 2018/8/29 20:57
*/
public interface StudentMapper {
/**
* 查询学生信息列表
*
* @return
*/
Page<Student> listStudent(StudentSO studentSO);
/**
* 根据教师id查询学生信息列表
* @param teacherId
* @return
*/
List<Student> listStudentByTeacherId(Long teacherId);
/**
* 查询学生信息
*
* @param id
* @return
*/
Student selectById(Long id);
/**
* 新增学生信息
*
* @param student
*/
void insert(Student student);
/**
* 修改学生信息
*
* @param student
*/
void updateById(Student student);
/**
* 删除学生信息
*
* @param id
*/
void deleteById(Long id);
}
|
Python | UTF-8 | 705 | 4.25 | 4 | [] | no_license |
def binary_search(arr, start, end, num):
if(end > start):
mid = int((start + end) / 2)
if (arr[mid] < num):
new_start = mid + 1
binary_search(arr, new_start, end, num)
elif (arr[mid] > num):
new_end = mid - 1
binary_search(arr, start, new_end, num)
else:
print("Number is found at index ", mid)
else:
print("No. not in the list")
if __name__ == "__main__":
list_of_num = [i for i in range(1,101)]
print(list_of_num)
num_to_search = int(input("Enter no. to search between 1 to 100 : "))
binary_search(list_of_num, 0, len(list_of_num), num_to_search)
|
Java | UTF-8 | 582 | 2.109375 | 2 | [] | no_license | package data;
/**
* Created by Olga Pavlova on 10/22/2015.
*/
public class Factory {
/* private static TesttableDAO testtableDAO = null;
private static Factory instance = null;
public static synchronized Factory getInstance(){
if (instance == null){
instance = new Factory();
}
return instance;
}
public TESTTABLEDAO getBusDAO(){
if (testtableDAO == null){
testtableDAO = new TESTTABLEDAODAOImpl();
}
return testtableDAO;
}
*/
}
|
SQL | UTF-8 | 2,065 | 3.625 | 4 | [] | no_license | /* 用root用户登录系统,执行脚本*/
/*root pwd:123456*/
/*创建数据库*/
create database chat;
/*选择数据库*/
use chat;
/*增加用户chat_root*/
/*创建用户'chat_root'密码为'asdzxc123' 拥有操作数据库chat的所有权限*/
create user char_root@"%" identified by 'asdzxc123';
grant all privileges on chat.* to char_root@"%";
flush privileges;
/* grant select,insert,update,delete on mydb61.* to dbuser61@localhost identified by "dbuser61";*/
/* grant select,insert,update,delete on mydb61.* to dbuser61@'%' identified by "dbuser61";*/
/*创建表*/
/*创建user表*/
DROP TABLE IF EXISTS `user`;
CREATE TABLE IF NOT EXISTS `user`(
`id` int PRIMARY KEY AUTO_INCREMENT comment '用户id',
`name` varchar(50) NOT NULL UNIQUE comment '用户名',
`password` varchar(50) NOT NULL comment '用户密码',
`state` enum('online','offline') DEFAULT 'offline' comment '当前登录状态'
);
commit;
/*创建friend表*/
DROP TABLE IF EXISTS `friend`;
CREATE TABLE IF NOT EXISTS `friend`(
`userid` int NOT NULL comment '用户id',
`friendid` int NOT NULL comment '朋友id',
PRIMARY KEY(`userid`,`friendid`)
);
commit;
/*创建allgroup表*/
DROP TABLE IF EXISTS `allgroup`;
CREATE TABLE IF NOT EXISTS `allgroup`(
`id` int PRIMARY KEY AUTO_INCREMENT comment '组id',
`groupname` varchar(50) NOT NULL UNIQUE comment '组名称',
`groupdesc` varchar(200) DEFAULT '' comment '组功能描述'
);
commit;
/*创建groupuser表*/
DROP TABLE IF EXISTS `groupuser`;
CREATE TABLE IF NOT EXISTS `groupuser`(
`groupid` int NOT NULL comment '组id',
`userid` int NOT NULL comment '用户id',
`grouprole` enum('creator','normal') DEFAULT 'normal' comment '组内角色',
PRIMARY KEY(`groupid`,`userid`)
);
commit;
/*创建offlinemessage表*/
DROP TABLE IF EXISTS `offlinemessage`;
CREATE TABLE IF NOT EXISTS `offlinemessage`(
`userid` int PRIMARY KEY NOT NULL comment '用户id',
`message` varchar(500) NOT NULL comment '离线消息'
);
commit;
|
JavaScript | UTF-8 | 1,484 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | function getFAQs() {
fetch('http://localhost:3001/faqs')
.then(response => {
return response.text();
})
.then(data => {
console.log(JSON.parse(data));
});
}
function createMerchant() {
let name = prompt('Enter merchant name');
let email = prompt('Enter merchant email');
fetch('http://localhost:3001/merchants', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, email }),
})
.then(response => {
return response.text();
})
.then(data => {
alert(data);
});
}
function updateMerchant() {
let id = prompt('Enter marchant id');
let name = prompt('Enter merchant name');
let email = prompt('Enter merchant email');
fetch('http://localhost:3001/merchants', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id, name, email }),
})
.then(response => {
return response.text();
})
.then(data => {
alert(data);
});
}
function deleteMerchant() {
let id = prompt('Enter merchant id');
fetch(`http://localhost:3001/merchants/${id}`, {
method: 'DELETE',
})
.then(response => {
return response.text();
})
.then(data => {
alert(data);
});
} |
Markdown | UTF-8 | 1,555 | 3.34375 | 3 | [] | no_license | # FileSystem 延伸:支援隨機存取
<br>
---
<br>
FileSystem 的 `open()` 方法回傳的是`FSDataInputStream` 這個類別支援隨機存,所以可以讀取資料中的任一位置。
<br>
```java
public class FileSystemDoubleCat {
public static void main(String[] args) throws IOException {
String url = "hdfs://localhost:9000/user/johnny/test.txt";
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(url), conf);
FSDataInputStream in = null;
try{
in = fs.open(new Path(url));
IOUtils.copyBytes(in, System.out, 4096, false);
in.seek(0); // 索引回到開頭
IOUtils.copyBytes(in, System.out, 4096, false);
}finally {
IOUtils.closeStream(in);
}
}
}
```
<br>
`FSDataInputStream` 的 `seek()` 方法可以把資料流指標移動到任意位置。如果移動超過檔案長度時就會丟出 `IOException` 錯誤。
`FSDataInputStream` 還有一個 `getPos()` 方法可以取得目前資料讀取到的位置。
`FSDataInputStream` 也實作了 `PositionedReadable` 介面,可以從一個指定位置讀取檔案中部份資料。
<br>
```java
public interface PositionedReadable{
public int read(long positon, byte[] buffer, int offset, int length) throws IOException;
public void readFully(long position, byte[] buffer, int offset, int length) throws IOException;
public void readFully(long position, byte[] buffer) throws IOException;
}
``` |
Python | UTF-8 | 949 | 2.9375 | 3 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | from typing import Text
class RasaException(Exception):
"""Base exception class for all errors raised by Rasa Open Source."""
class RasaCoreException(RasaException):
"""Basic exception for errors raised by Rasa Core."""
class RasaXTermsError(RasaException):
"""Error in case the user didn't accept the Rasa X terms."""
class YamlSyntaxException(RasaException):
"""Raised when a YAML file can not be parsed properly due to a syntax error."""
def __init__(self, filename: Text, underlying_yaml_exception: Exception):
self.underlying_yaml_exception = underlying_yaml_exception
self.filename = filename
def __str__(self) -> Text:
exception_text = (
f"Failed to read '{self.filename}'. " f"{self.underlying_yaml_exception}"
)
exception_text = exception_text.replace(
'in "<unicode string>"', f'in "{self.filename}"'
)
return exception_text
|
SQL | UTF-8 | 916 | 3.59375 | 4 | [] | no_license | -- // create_users
-- Migration SQL that makes the change goes here.
CREATE TABLE users (
id INT(10) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
account_id INT(20) UNSIGNED,
username VARCHAR(25) NOT NULL UNIQUE,
nick_name VARCHAR(25),
email VARCHAR(255),
phone VARCHAR(50),
password VARCHAR(255) NOT NULL,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
expired BOOLEAN NOT NULL DEFAULT FALSE,
locked BOOLEAN NOT NULL DEFAULT FALSE,
password_expired BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (account_id) REFERENCES accounts(id)
);
-- //@UNDO
-- SQL to undo the change goes here.
DROP TABLE IF EXISTS users;
|
Java | UTF-8 | 476 | 2.265625 | 2 | [] | no_license | package com.huatec.hiot_cloud.test.mvptest.model;
import java.io.Serializable;
public class Guess implements Serializable {
private int realNum;
private int yourGuess;
public int getRealNum() {
return realNum;
}
public void setRealNum(int realNum) {
this.realNum = realNum;
}
public int getYourGuess() {
return yourGuess;
}
public void setYourGuess(int yourGuess) {
this.yourGuess = yourGuess;
}
}
|
Python | UTF-8 | 1,516 | 3.421875 | 3 | [] | no_license | def sock_merchant(unpaired_socks):
pairs = 0
for sock in set(unpaired_socks):
total_count_of_current_sock = unpaired_socks.count(sock)
pairs += total_count_of_current_sock//2
print(pairs)
# sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
# sock_merchant([50, 20, 30, 90, 30, 20, 50, 20, 90])
# sock_merchant([])
def find_fulcrum(list):
for i,v in enumerate(list):
sum_of_right = sum(list[i+1:])
sum_of_left = sum(list[:i])
if sum_of_right==sum_of_left:
print(str(v))
return v
print("-1")
return -1
# find_fulcrum([3, 1, 5, 2, 4, 6, -1])
# find_fulcrum([1, 2, 4, 9, 10, -10, -9, 3])
# find_fulcrum([9, 1, 9])
# find_fulcrum([7, -1, 0, -1, 1, 1, 2, 3])
# find_fulcrum([8, 8, 8, 8])
def pairs(array):
midpoint = round((len(array)-1)/2)
final = []
for i in range(len(array)):
final.append([array[i],array[-i-1]])
if i == midpoint:
break
print(final)
# pairs([1,2,3,4,5,6,7])
# pairs([1,2,3,4,5,6])
# pairs([5,9,8,1,2])
# pairs([])
def count_lone_ones(number):
number_list=[int(d) for d in str(number)]
temp_index = []
try:
for idx,num in enumerate(number_list):
if number_list[idx]==1 and number_list[idx+1]==1 :
temp_index.extend([idx,idx+1])
except:
pass
finally:
for i in set(temp_index):
number_list[i] = 2
print(number_list.count(1))
count_lone_ones(1) |
Java | UTF-8 | 537 | 1.53125 | 2 | [
"MIT"
] | permissive | package com.jtbdevelopment.games.mongo.dao;
import com.jtbdevelopment.games.dao.AbstractMultiPlayerGameRepository;
import com.jtbdevelopment.games.mongo.state.AbstractMongoMultiPlayerGame;
import org.bson.types.ObjectId;
import org.springframework.data.repository.NoRepositoryBean;
/**
* Date: 1/9/15 Time: 10:51 PM
*/
@NoRepositoryBean
public interface AbstractMongoMultiPlayerGameRepository<FEATURES, IMPL extends AbstractMongoMultiPlayerGame<FEATURES>>
extends AbstractMultiPlayerGameRepository<ObjectId, FEATURES, IMPL> {
}
|
Markdown | UTF-8 | 2,943 | 2.671875 | 3 | [] | no_license | ## CoordinatorLayout 及其控件属性
### 基本结构
```xml
<CoordinatorLayout>
<AppbarLayout>
<CollapsingToolbarLayout>
<!--可自定义的expendedView,一般用FrameLayout包裹,需要设置固定高度-->
<FrameLayout/>
<Toolbar/>
</CollapsingToolbarLayout>
</AppbarLayout>
<ScrollView/>
</CoordinatorLayout>
```
### layout_scrollFlags
`layout_scrollFlags` 控制 `AppBarLayout` 下子 View 的行为。
| 值 | 作用 |
| :------------------: | :--------------------: |
| scroll | 跟随滑动 |
| snap | 避免停留在中间态,即滑动结束后全部显示或隐藏 |
| enterAlways | 下拉时立即显示 |
| enterAlwaysCollapsed | 下拉时立即显示(只显示折叠后的高度) |
| exitUntilCollapsed | 上拉的时候,跟随滑动直到折叠 |
| 默认 | 静态显示 |
一些需要注意的点:
* AppBarLayout 实际上是一个 `orientation:vertical` 的 `LinearLayout`
* 若一个 View 静态显示,那么在其下方的 View 即使设置了 `scroll` 也只能停留在其下方而不能继续往上滑动,相当于一个静态显示的 View 污染了下方所有 View 使它们都是静态显示
* `enterAlways` 虽说是下拉时立即显示,但也仅限于其下方没有设置了 `scroll` 的 View 或者下方的第一个 View 是静态显示(第二个点说到的污染问题)
* `enterAlways`, `enterAlwaysCollapsed` 和 `exitUntilCollapsed` 都需要配合 `scroll` 使用,不然跟静态显示没有区别
### layout_collapseMode
`layout_collapseMode` 控制 `CollapsingToolbarLayout` 下 View 的行为。`CollapsingToolbarLayout` 一般放两个 View,一个 `Toolbar` 和一个 View。
| 值 | 作用 |
| :------: | :--------------------------------------: |
| pin | 固定且不会因为 layout_scrollFlags = scroll 而被隐藏 |
| parallax | 视差滚动 |
故 `Toolbar` 设置 `pin` 而 View 作为 expended view 设置 `parallax`。
### title
一些需要注意的点:
* `CollapsingToolbarLayout` 和 `Toolbar` 均有 `title` 属性,但若同时设置前者的会覆盖后者的
* 若要使 `Toolbar` 均有 `title` 属性生效,需要 `CollapsingToolbarLayout` 的 `titleEnabled` 设为 **false**
* `CollapsingToolbarLayout` 的 title 有收缩和位移特性(可定制),而 `Toolbar` 的则只会一直停留在 `Toolbar` 上
### CollapsingToolbarLayout 的动态定制
以下以 `CTL` 代替 `CollapsingToolbarLayout`。
* `CTL.setContentScrimResource()` 来设置折叠后的背景颜色
* `CTL.setTitle()` 来设置有时差效果的 title
`Toolbar` 需要将 `layout_height` 设置为 `?attr/actionBarSize`
|
Java | UTF-8 | 375 | 2.171875 | 2 | [] | no_license | package com.learning.animaldb.animal.db;
import java.util.List;
import com.learning.animaldb.animal.Animal;
/**
* Created by Тичер on 08.06.2017.
*/
public interface AnimalsDao {
long insertAnimal(Animal animal);
List<Animal> getmAnimals();
Animal getAnimalById(long id);
int updateAnimal(Animal animal);
int deleteAnimal(Animal animal);
}
|
Markdown | UTF-8 | 16,380 | 2.9375 | 3 | [] | no_license | ---
title: 超全面详细一条龙教程!从零搭建 React 项目全家桶(下篇)
date: 2020-02-09
description: React 是近几年来前端项目开发非常火的一个框架,其背景是 Facebook 团队的技术支持,市场占有率也很高。很多初学者纠结一开始是学 react 还是 vue。个人觉得,有时间的话,最好两个都掌握一下。从学习难度上来说,react 要比 vue 稍难一些。万事开头难,但是掌握了 react 对于大幅提高前端技能还是非常有帮助的。本文一步步详细梳理了从创建 react、精简项目、集成插件、初步优化等过程。对于 react 开发者来说,能够节省很多探索的时间。下面请跟着我来一步步操作。
image: https://vuepress.vuejs.org/hero.png
---
在开始前,先回顾下【上篇】介绍的内容:
**1 创建 React-APP**
**2 精简项目**
2.1 删除文件
2.2 简化代码
2.3 使用 Fragment 去掉组件外层标签
**3 项目目录结构**
3.1 引入全局公用样式
3.2 支持 Sass/Less/Stylus
**4 路由**
4.1 页面构建
4.2 使用 react-router-dom
4.3 路由跳转
**5 组件引入**
5.1 创建 header 组件
5.2 引入 Header 组件
5.3 组件传参
**6 React Developer Tools 浏览器插件**
在本次的【下篇】中,继续分享以下内容:
先睹为快
----
**7 Redux 及相关插件**
7.1 安装 redux
7.2 安装 react-redux
7.3 安装 redux-thunk
7.4 安装浏览器 Redux 插件
7.5 创建 store
7.6 复杂项目 store 分解
7.7 对接 react-redux 与 store
7.8 启动 Redux DevTools
7.9 安装使用 immutable
**8 Mock.js 安装与使用**
**9 解决本地开发跨域问题**
**10 其他常用工具**
11 附赠章节:集成 Ant Design
11.1 安装 Ant Design
11.2 实现按需加载
11.3 自定义主题颜色
7 Redux 及相关插件
-------------
做过 vue 开发的同学都知道 vuex,react 对应的工具就是 Redux,当然还有一些附属工具,比如 react-redux、redux-thunk、immutable。
redux 涉及内容篇幅较多,可以单独作为一次分享。本次分享篇幅有限,仅简要介绍下安装部署流程,如有看不懂的地方可先跳过或自行查阅官方文档。
### 7.1 安装 redux
执行:
```
npm install redux --save
复制代码
```
仅安装 redux 也是可以使用的,但是比较麻烦。redux 里更新 store 里的数据,需要手动订阅 (subscribe) 更新。可以借助另一个插件(react-redux)提高开发效率。
### 7.2 安装 react-redux
执行:
```
npm install react-redux --save
复制代码
```
react-redux 允许通过 connect 方法,将 store 中的数据映射到组件的 props,省去了 store 订阅。原 state 中读取 store 的属性改用 props 读取。
由于 store(7.5 小节)还没讲到,react-redux 使用方法在 7.6 小节介绍。
### 7.3 安装 redux-thunk
执行:
```
npm install redux-thunk --save
复制代码
```
redux-thunk 允许在 actionCreators 里返回函函数。这样可以把业务逻辑(例如接口请求)集中写在 actionCreator.js,方便复用的同时,可以使组件的主文件更简洁。
### 7.4 安装浏览器 Redux 插件
为了更方便跟踪 redux 状态,建议安装 chrome 插件。
先科学上网,在 chrome 网上应用店里搜索 “Redux DevTools” 并安装。

安装完成后还不能直接使用,需要在项目代码中进行配置。接下来进行说明。
### 7.5 创建 store
安装以上各种插件后,可以 store 用来管理状态数据了。
如果项目比较简单,只有一两个页面,可以只创建一个总 store 管理整体项目。目录结构参考如下:
```
├─ /src
+ | ├─ /store
+ | | ├─ actionCreators.js
+ | | ├─ contants.js <-- 定义方法的常量
+ | | ├─ index.js
+ | | └─ reducer.js
复制代码
```
以下是各文件的代码示例:
src/store/actionCreators.js:
```
import * as constans from './constants'
export const getData = (data) => ({
type: constans.SET_DATA,
data
})
复制代码
```
src/store/contants.js:
```
export const SET_DATA = 'SET_DATA'
复制代码
```
src/store/index.js:
```
import { createStore, applyMiddleware, compose } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
// 这里让项目支持浏览器插件Redux DevTools
const composeEnhancers = typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose
const enhancer = composeEnhancers(
applyMiddleware(thunk)
);
const store = createStore(
reducer,
enhancer
)
export default store
复制代码
```
> 以上是 store 的核心代码,支持了 Redux DevTools。同时,利用 redux 的集成中间件(applyMiddleware)功能将 redux-thunk 集成进来,最终创建了 store。
src/store/reducer.js:
```
import * as constants from './constants'
// 初始默认的state
const defaultState = {
myData: null
}
export default (state = defaultState, action) => {
// 由于state是引用型,不能直接修改,否则是监测不到state发生变化的。因此需要先复制一份进行修改,然后再返回新的state。
let newState = Object.assign({}, state)
switch(action.type) {
case constants.SET_DATA:
newState.myData = action.data
return newState
default:
return state
}
}
复制代码
```
以上代码,我们在 store 设置了一个 myData。如何更好地解决 state 修改问题,在 7.8 小节会提到。
### 7.6 复杂项目 store 分解
应对更多页面的项目,如果数据都集中放在一个 store 里,其维护成本非常高。接下来分享下如何将 store 分解到各个组件中。
一般来说,每个组件有自己的 store,再由 src 下的 store 作为总集,集成每个组件的 store。
以 header 和 login 两个组件为例,分别创建组件自己的 store。
header 的 store 目录结构如下:
```
| | ├─ /components
| | | ├─ /header
+ | | | | ├─ /store
+ | | | | | ├─ actionCreators.js
+ | | | | | ├─ contants.js
+ | | | | | ├─ index.js
+ | | | | | └─ reducer.js
复制代码
```
组件 store 下的 index.js 代码如下:
```
import reducer from './reducer'
import * as actionCreators from './actionCreators'
import * as constants from './constants'
export { reducer, actionCreators, constants}
复制代码
```
其实就是把组件 store 下的其他文件集中起来作为统一输出口。
组件 store 下的 contants.js 代码如下:
```
const ZONE = 'components/header/'
export const SET_DATA = ZONE + 'SET_DATA'
复制代码
```
ZONE 是用来避免与其他组件的 contants 重名。
同样的方式,在 login 下进行创建 store(不再赘述)。
然后修改项目 src 下的总 store,目录结构变动如下:
```
├─ /src
| ├─ /store
- | | ├─ actionCreators.js <-- 删除
- | | ├─ contants.js <--删除
| | ├─ index.js
| | └─ reducer.js
复制代码
```
src/store/index.js 重写如下:
```
import { combineReducers } from 'redux'
import { reducer as loginReducer } from '../pages/login/store'
import { reducer as headerReducer } from '../components/header/store'
const reducer = combineReducers({
login: loginReducer,
header: headerReducer
})
export default reducer
复制代码
```
以上代码的作用就是把 login 和 header 的 store 引入,然后通过 combineReducers 合并在一起,并分别加上唯一的对象 key 值。
这样的好处非常明显:
1. 避免各组件的 store 数据互相污染
2. 组件独立维护自己的 store,减少维护成本
非常建议使用这种方式维护 store。
### 7.7 对接 react-redux 与 store
为了方便每个组件都能使用 store,而不用一遍一遍的引用 store。下面来对接 react-redux 与 store。
修改 src/index.js:
```
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
+ import { Provider } from 'react-redux'
+ import store from './store'
import './common/style/frame.styl'
+ const Apps = (
+ <Provider store={store}>
+ <App />
+ </Provider>
+ )
M ReactDOM.render(Apps, document.getElementById('root'))
复制代码
```
以上代码就是用 react-redux 提供的 Provider,把 store 传给了整个 App。
在需要使用 store 的组件中,要使用 react-redux 提供的 connect 方法对组件进行包装。
以 login 为例,修改 src/pages/login/index.js:
```
import React, { Component } from 'react'
import Header from '../../components/header'
+ import { connect } from 'react-redux'
+ import * as actionCreators from './store/actionCreators'
import './login.styl'
class Login extends Component {
render() {
return (
<div class>
<Header />
<h1>Login page</h1>
+ <p>login: myData = {this.props.myData}</p>
+ <button onClick={()=> {this.props.getData('123456')}}>更改login的myData</button>
<button onClick={this.gotoHome.bind(this)}>跳转Home页</button>
</div>
)
}
gotoHome() {
this.props.history.push('/home')
}
}
+ // 把store中的数据映射到组件的props
+ const mapStateToProps = (state) => ({
+ myData: state.getIn(['login', 'myData']),
+ })
+ // 把store的Dispatch映射到组件的props
+ const mapDispatchToProps = (dispatch) => ({
+ getData(data) {
+ const action = actionCreators.getData(data)
+ dispatch(action)
+ }
+ })
M export default connect(mapStateToProps, mapDispatchToProps)(Login)
复制代码
```
最大的变化就是代码最后一行,被 connect 方法包装了。
然后把 store 里的 state 和 dispatch 都映射到了组件的 props。这样可以直接通过 props 进行访问了,store 中数据的变化会直接改变 props 从而触发组件的视图更新。
点击按钮后,可以看到页面中显示的 myData 发生了变化。

下面通过 Redux DevTools 进行可视化跟踪查看。
### 7.8 启动 Redux DevTools
经过 7.5 小节的设置,7.4 小节的 Redux DevTools 可以正常使用了。点击浏览器右上角的图标,在出现的面板里,可以相信地跟踪查看 store 里各数据的变化,非常方便。

还可以通过调试工具栏启动 Redux DevTools:

具体使用方法这里不赘述了。
### 7.9 安装使用 immutable
在 7.5 小节,提到了 store 里不能直接修改 state,因为 state 是引用类型,直接修改可能导致监测不到数据变化。
immutable.js 从字面上就可以明白,immutable 的意思是 “不可改变的”。使用 immutable 创建的数据是不可改变的,对 immutable 数据的任何修改都会返回一个新的 immutable 数据,不会改变原始 immutable 数据。
immutable.js 提供了很多方法,非常方便修改对象或数组类型的引用型数据。
安装 immutable 和 redux-immutable,执行:
```
npm install immutable redux-immutable --save
复制代码
```
然后对代码进行改造:
src/store/reducer.js:
```
- import { combineReducers } from 'redux'
+ import { combineReducers } from 'redux-immutable'
...(略)
复制代码
```
以上代码就是把 combineReducers 换成 redux-immutable 里的。
然后修改 src/pages/login/store/reducer.js
```
import * as constants from './constants'
+ import { fromJS } from 'immutable'
M const defaultState = fromJS({
myData: null
M })
+ const getData = (state, action) => {
+ return state.set('myData', action.data)
+ }
export default (state = defaultState, action) => {
switch(action.type) {
case constants.SET_DATA:
M return getData(state, action)
default:
return state
}
}
复制代码
```
immutable 的介入,就是利用 fromJS 方法,把原始的 JS 类型转化为 immutable 类型。
由于 state 已经是 immutable 类型了,可以使用 immutable 的 set 方法进行数据修改,并返回一个新的 state。代码简洁很多,不需要手动通过 Object.assign 等方法去复制再处理了。
header 组件的代码修改同理不再赘述。
immutable 还有很多其他非常使用方法,具体请参阅官方文档:
> [immutable-js.github.io/immutable-j…](https://immutable-js.github.io/immutable-js/)
8 Mock.js 安装与使用
---------------
在开发过程中,为了方便前端独自调试接口,经常使用 Mock.js 拦截 Ajax 请求,并返回预置好的数据。本小节介绍下如何在 react 项目中使用 Mock.js。
执行安装:
```
npm install mockjs --save
复制代码
```
在 src 下新建 mock.js,代码如下:
```
import Mock from 'mockjs'
const domain = '/api/'
// 模拟getData接口
Mock.mock(domain + 'getData', function () {
let result = {
code: 200,
message: 'OK',
data: 'test'
}
return result
})
复制代码
```
然后在 src/index.js 中引入 mock.js:
```
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import { Provider } from 'react-redux'
import store from './store'
+ import './mock'
import './common/style/frame.styl'
...(略)
复制代码
```
如此简单。这样,在项目中请求`/api/getData`的时候,就会被 Mock.js 拦截,并返回 mock.js 中写好的数据。
9 解决本地开发跨域问题
------------
在 react 开发环境中,默认启动的是 3000 端口,而后端 API 服务可能在本机的 80 端口,这样在 ajax 请求的时候会出现跨域问题。可以借助 http-proxy-middleware 工具实现反向代理。
执行安装:
```
npm install http-proxy-middleware --save-dev
复制代码
```
在 src 下创建 setupProxy.js,代码如下:
```
const proxy = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'^/api',
proxy({
target: 'http://localhost',
changeOrigin: true
})
)
}
复制代码
```
这代码的意思就是,只要请求地址是以 "/api" 开头,那就反向代理到 http://localhost 域名下,跨域问题解决!大家可以根据实际需求进行修改。
> ※注意:setupProxy.js 设置后,一定要重启项目才生效。
10 其他常用工具
---------
1. Axios - Ajax 请求工具
【官网】[github.com/axios/axios](https://github.com/axios/axios)
【安装命令】
```
npm install axios --save
复制代码
```
2. better-scroll - 页面原生滚动体验效果工具
【官网】[ustbhuangyi.github.io/better-scro…](http://ustbhuangyi.github.io/better-scroll/doc/)
【安装命令】
```
npm install better-scroll --save
复制代码
```
3. react-transition-group - CSS3 动画组合工具
【官网】[github.com/reactjs/rea…](https://github.com/reactjs/react-transition-group)
【安装命令】
```
npm install react-transition-group --save
复制代码
```
4. react-loadable - 动态加载组件工具
【官网】[www.npmjs.com/package/rea…](https://www.npmjs.com/package/react-loadable)
【安装命令】
```
yarn add react-loadable
复制代码
```
11 附赠章节:集成 Ant Design
---------------------
Ant Design 是非常好用的前端 UI 库,很多项目都使用了 Ant Design。
【官网】
> [ant.design/index-cn](https://ant.design/index-cn)
本章节内容基于上述章节将 create-react-app 进行 eject 后集成 Ant Design。
|
TypeScript | UTF-8 | 1,274 | 2.796875 | 3 | [
"MIT",
"OFL-1.1"
] | permissive | import { promises } from 'fs';
import { PathLike, constants } from 'fs';
import { dirname, resolve, join, basename } from 'path';
const { readFile, writeFile, readdir, copyFile, access, mkdir, stat, unlink, rmdir } = promises;
export {
readFile,
writeFile,
readdir,
copyFile
};
export { PathLike };
export { join, basename, dirname };
export const exists = async (path: PathLike): Promise<boolean> => {
try {
await access(resolve(path.toString()), constants.F_OK);
return true;
} catch (error) {
if (error && error.code === 'ENOENT') {
return false;
} else {
throw error;
}
}
};
export const notExists = async (path: PathLike): Promise<boolean> => !(await exists(path));
export const mkdirs = async (path: PathLike): Promise<void> => {
const parent = dirname(resolve(path.toString()));
if (await notExists(parent)) {
await mkdirs(parent);
}
if (await notExists(path)) {
await mkdir(path);
}
};
export const rimraf = async (path: PathLike): Promise<void> => {
if (await notExists(path)) {
return;
}
if ((await stat(path)).isFile()) {
await unlink(path);
return;
}
for (const file of await readdir(path)) {
await rimraf(join(path.toString(), file));
}
await rmdir(path);
};
|
C++ | UTF-8 | 1,370 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
bool safetoplace(int board[][9], int r, int c, int num){
for(int i=0; i<9; i++){
if(board[i][c]==num || board[r][i]==num){
return false;
}
}
int sx= r-r%3;
int sy= c-c%3;
for(int x=sx; x<sx+3; x++){
for (int y=sy; y<sy+3; y++){
if(board[x][y]==num){
return false;
}
}
}
return true;
}
bool sudoku(int board[][9], int r, int c){
if(r==9){
for(int i=0; i<9; i++){
for (int j=0; j<9; j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
return true;
}
if(c==9){
return sudoku(board, r+1, 0);
}
if(board[r][c]!=0){
return sudoku(board, r, c+1);
}
for(int i=1; i<=9; i++){
if (safetoplace(board, r, c, i)){
board[r][c]=i;
int success= sudoku(board, r, c+1);
if(success){
return true;
}
}
}
board[r][c] = 0;
return false;
}
int main() {
int n;
cin>>n;
int board[9][9];
for(int i=0; i<9; i++){
for (int j=0; j<9; j++){
cin>>board[i][j];
}
}
sudoku(board, 0, 0);
return 0;
}
|
C# | UTF-8 | 768 | 3.421875 | 3 | [] | no_license | //using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using static System.Console;
//namespace ConsoleApp7
//{
// class String_Slice
// {
// static void Main(string[] args)
// {
// string greeting = "Good Morning.";
// WriteLine(greeting.Substring(0, 5));
// WriteLine(greeting.Substring(5));
// WriteLine();
// string[] arr = greeting.Split(
// new string[] { " " }, StringSplitOptions.None);
// WriteLine("World Count : {0}", arr.Length);
// foreach (string element in arr)
// WriteLine("{0}", element);
// }
// }
//}
|
TypeScript | UTF-8 | 561 | 2.71875 | 3 | [] | no_license | import Texture from "./Texture";
enum MaterialTexture {
DIFFUSE,
SPECULAR,
NORMAL,
DISPLACEMENT
};
export interface MaterialInitializer {
diffuse: Texture;
specularIntentisy? : number;
specularPower? : number;
normal?: Texture;
displacement?: Texture;
displacementMapScale?: number;
displacementMapBias?: number;
}
export default class Material {
// textures map. keys
textures = new Map<MaterialTexture, Texture>();
private readonly definition: MaterialInitializer;
constructor(init: MaterialInitializer) {
this.definition = init;
}
} |
Shell | UTF-8 | 922 | 3.328125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"OpenSSL"
] | permissive | #!/usr/bin/env bash
#
# Copyright 2019 YugaByte, Inc. and Contributors
#
# Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# https://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt
set -e
# py_wrapper is already in bin/
. "${BASH_SOURCE%/*}"/common.sh
detect_os
# The PEX environment is used if the operating system is not macOS, the
# environment variable YB_USE_VIRTUAL_ENV is unset (default unset), and
# the pexEnv directory exists
if [ "$is_mac" == false ] && \
[[ -z ${YB_USE_VIRTUAL_ENV:-} ]] && \
[ -d "$yb_devops_home/pex/pexEnv" ]; then
activate_pex
$PYTHON_EXECUTABLE $PEX_PATH "$@"
# The PEX environment is used in all other cases.
else
activate_virtualenv
cd "$yb_devops_home"
$PYTHON_EXECUTABLE "$@"
fi
|
Markdown | UTF-8 | 2,735 | 2.59375 | 3 | [
"MIT"
] | permissive | ---
layout: post
#event information
title: "Global CFP Diversity Day - Feb, 2018"
cover: "../assets/index.jpg"
date: 2018-02-03
start_time: "14:00"
end_time: "17:00"
#event organiser details
organiser: "Sriram"
categories: "event"
---
Hello World!
In collaboration with Mozilla TN Community members, we conducted **Global CFP Diversity Day - Feb, 2018** at *KGiSL Institute of Technology*, on 3rd February 2018. The event aimd at encouraging and advising newbie speakers to put together their very first talk proposal and share their own individual perspective on any subject of interest to people in tech.
[Mr. Vigneshwer Dhinakaran](https://twitter.com/dvigneshwer), the speaker of the event gave many tips and tricks for the newbie Tech-Speakers.We discussed on various topics like
- How to Introduce the topic?
- Slide Preparation
- Usage of Fonts and Designs in Slides
- Summarize the content
- Proposal writing
* Short Description
* Long Description
* Identifying potential Keywords
* Session details breakout
* Key takeaways with respect to audience perspective
* Listing Speaking credentials
* Publishing blog series
- Deck and Talk Preparation
* Start off the talk
* Creating the storyline
* Talking about the bigger picture
* Diving into the problem
* Providing Different solutions
* Demonstration
* Leaving the audience with a bigger idea
* Preparation
* FAQ's
* Q&A sessions
- Feedback parameters
* Topic Quality
* Information presented
* Preparedness
* Time Management
* Body Language
* Supporting materials
* Enthusiasm
- Talk Logistical planning
* Backup slides in cloud
* Keeping offline versions of cloud
* Demos in presentation
* Carrying a water bottle
* Reaching the location prior to timing
After discussing these things, the participants splitted into 5 teams. Each team prepared a proposal and presented to the audience.
- Abishek and team - *Smart Grid*
- Sriram and team - *Test Driven Development*
- Kiruthika Sowbarnika and team - *How to spot a lie* and *Not so boring man with a boring company*
- Akksaya Rajasri and team - *Web / Android / Agile development* and *Blue Borne*
- Monesh and team - *Chatbots* and *AI*
[Mr. Makilan](https://twitter.com/selva_makilan) gave a speech on how to contribute to mozilla and the benifits of communities and contributions. We ended the session by distributing the swags and Group Photo.

Thanks to all the participants who participated in the event.
Thanks to KGISL management and Mr.Sudharsan for providing resources for conducting the event.
Thanks to Dept. of CSE ,Dept. of ECE of KGISL Institute of Technology, SNS college of Technology for their support.
|
TypeScript | UTF-8 | 1,783 | 2.640625 | 3 | [
"MIT"
] | permissive | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as WebSocketWS from 'ws';
import { traceInfo } from '../../common/logger';
// We need to override the websocket that jupyter lab services uses to put in our cookie information
// Do this as a function so that we can pass in variables the the socket will have local access to
export function createJupyterWebSocket(log?: boolean, cookieString?: string, allowUnauthorized?: boolean) {
class JupyterWebSocket extends WebSocketWS {
private kernelId: string | undefined;
constructor(url: string, protocols?: string | string[] | undefined) {
let co: WebSocketWS.ClientOptions = {};
if (allowUnauthorized) {
co = { ...co, rejectUnauthorized: false };
}
if (cookieString) {
co = {
...co, headers: {
Cookie: cookieString
}
};
}
super(url, protocols, co);
// Parse the url for the kernel id
const parsed = /.*\/kernels\/(.*)\/.*/.exec(this.url);
if (parsed && parsed.length > 1) {
this.kernelId = parsed[1];
}
}
// tslint:disable-next-line: no-any
public emit(event: string | symbol, ...args: any[]): boolean {
const result = super.emit(event, ...args);
if (log) {
const msgJSON = event === 'message' && args[0] ? args[0] : '';
traceInfo(`Jupyter WebSocket event: ${String(event)}:${String(msgJSON)} for kernel ${this.kernelId}`);
}
return result;
}
}
return JupyterWebSocket;
}
|
Shell | UTF-8 | 3,244 | 3.953125 | 4 | [] | no_license | #!/bin/sh
## User name
################################################################################
## If $USER is some long.username@institution.edu, define $SUSER to be the part
## before the '@' (or leave it unchanged if there is no '@').
export SUSER="${USER%@*}"
## Temporary directory
################################################################################
## Remove trailing slash from $TMPDIR if present
export TMPDIR="${TMPDIR%/}"
## If $TMPDIR is unset, set it to /tmp/$SUSER
if [ -z "$TMPDIR" ] ; then
export TMPDIR="/tmp/$SUSER"
fi
## Make sure that $TMPDIR ends with $SUSER
if [ "${TMPDIR%$SUSER}" = "$TMPDIR" ] ; then
export TMPDIR="$TMPDIR/$SUSER"
fi
## Ensure $TMPDIR is only readable to the current user
mkdir -p -m 700 "$TMPDIR"
chown "$USER" "$TMPDIR"
chmod 700 "$TMPDIR"
## Paths
################################################################################
## Update the given PATH variable by adding the specified path. If the third
## argument is not blank, the path is appended instead of the prepended.
add_path() {
if [ $# -lt 2 -o $# -gt 3 ]; then
echo "add_path PATH_VAR path [append]" >&2
return
fi
local p
p="${2%/}"
case "${!1}" in
*"$p"*)
# Path is already present
;;
"")
# Path is empty are we are adding to it
export "$1"="$p"
;;
*)
# Prepend / append to path
if [ -z "$3" ]; then
export "$1"="$p:${!1}"
else
export "$1"="${!1}:$p"
fi
;;
esac
}
for dir in "$HOME/.local" "/scratch/$USER/local" "/scratch/$SUSER/local" "$TMPDIR/local"; do
if [ -d "$dir/bin" ]; then
add_path PATH "$dir/bin"
fi
if [ -d "$dir/bin" ]; then
add_path LD_LIBRARY_PATH "$dir/lib"
fi
done
## Interactive Shell
################################################################################
# Last couple of things to check when we have an interactive shell
case $- in
*i*)
# Give a warning if $TMPDIR might be readable to other users
if [ \
$(( $(stat --printf='%a' $TMPDIR) % 1000 )) != 700 \
-o "$(id -u)" -ne "$(stat --printf='%u' $TMPDIR)" \
-o "$(id -g)" -ne "$(stat --printf='%g' $TMPDIR)" \
] ; then
echo "TMPDIR may be readable to others." >&2
fi
;;
*)
;;
esac
## Load environment variables from .config/environment.d if needed
################################################################################
# Pending on the outcome of https://github.com/systemd/systemd/issues/7641
if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
SESSION_TYPE=remote/ssh
else
case $(ps -o comm= -p $PPID) in
sshd|*/sshd) SESSION_TYPE=remote/ssh;;
esac
fi
if [ "$SESSION_TYPE" = "remote/ssh" -a -d "$HOME/.config/environment.d" ]; then
set -o allexport
for conf in $(ls "$HOME/.config/environment.d"/*.conf); do
source "$conf"
done
set +o allexport
fi
## GPG SSH agent
################################################################################
if command -v gpgconf 2>&1 1>/dev/null ; then
socket=$(gpgconf --list-dirs agent-ssh-socket)
if [ ! -z "$socket" ]; then
export SSH_AUTH_SOCK="$socket"
fi
fi
## Customizations
################################################################################
|
C++ | UTF-8 | 732 | 2.8125 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <deque>
using namespace std;
int compute(const vector<int> &a, const int d) {
deque<int> q;
int n = a.size();
int kq = 10000000;
for (int i=0; i<n; i++) {
if (!q.empty() && q.front() <= i - d) q.pop_front();
while (!q.empty() && a[q.back()]<=a[i]) q.pop_back();
q.push_back(i);
if (i>=d-1 && kq > a[q.front()]) kq = a[q.front()];
}
return kq;
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int n, Q; cin >> n >> Q;
vector<int> a(n);
for (int i=0;i<n;i++)
{
int x;
cin>>x;
a.push_back(x);
}
while (Q--) {
int d; cin >> d;
cout << compute(a, d) << "\n";
}
return 0;
}
|
C++ | UTF-8 | 3,998 | 3.015625 | 3 | [
"MIT"
] | permissive | #ifndef _REACTIVE_VARIABLE_H_
#define _REACTIVE_VARIABLE_H_
#include "Reactable.h"
namespace Reactivity
{
template<typename T>
class ReactiveVariable : public Reactable<T>
{
public:
//Default contructor for T
ReactiveVariable()
{}
//Contructor with initial value for T
ReactiveVariable(T initialValue)
{
this->m_value = initialValue;
}
const T& GetValue();
operator T();
ReactiveVariable<T>& operator=(T rhs);
ReactiveVariable<T>& operator+=(T rhs);
ReactiveVariable<T>& operator-=(T rhs);
ReactiveVariable<T>& operator*=(T rhs);
ReactiveVariable<T>& operator/=(T rhs);
friend T operator+=(T& lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return lhs += rhs.m_value;
}
friend T operator-=(T& lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return lhs += rhs.m_value;
}
friend T operator*=(T& lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return lhs *= rhs.m_value;
}
friend T operator/=(T& lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
lhs /= rhs.m_value;
return lhs;
}
friend T operator+(T lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
lhs += rhs.m_value;
return lhs;
}
friend T operator-(T lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
lhs -= rhs.m_value;
return lhs;
}
friend T operator*(T lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
lhs *= rhs.m_value;
return lhs;
}
friend T operator/(T lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
lhs /= rhs.m_value;
return lhs;
}
friend bool operator==(const Reactivity::ReactiveVariable<T>& lhs, const T& rhs)
{
return lhs.m_value == rhs;
}
friend bool operator==(const T& lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return lhs == rhs.m_value;
}
friend bool operator!=(const Reactivity::ReactiveVariable<T>& lhs, const T & rhs)
{
return !operator==(lhs, rhs);
}
friend bool operator!=(const T & lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return !operator==(lhs, rhs);
}
friend bool operator<(const Reactivity::ReactiveVariable<T>& lhs, const T & rhs)
{
return lhs.m_value < rhs;
}
friend bool operator<(const T& lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return lhs < rhs.m_value;
}
friend bool operator<=(const Reactivity::ReactiveVariable<T>& lhs, const T & rhs)
{
return !operator>(lhs, rhs);
}
friend bool operator<=(const T & lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return !operator>(lhs, rhs);
}
friend bool operator>(const Reactivity::ReactiveVariable<T>& lhs, const T & rhs)
{
return lhs.m_value > rhs;
}
friend bool operator>(const T& lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return lhs > rhs.m_value;
}
friend bool operator>=(const Reactivity::ReactiveVariable<T>& lhs, const T & rhs)
{
return !operator<(lhs, rhs);
}
friend bool operator>=(const T& lhs, const Reactivity::ReactiveVariable<T>& rhs)
{
return !operator<(lhs, rhs);
}
};
template<typename T>
inline const T& ReactiveVariable<T>::GetValue()
{
return this->m_value;
}
template<typename T>
inline ReactiveVariable<T>::operator T()
{
return this->m_value;
}
template<typename T>
inline ReactiveVariable<T>& ReactiveVariable<T>::operator=(T rhs)
{
this->OnChange(rhs);
return *this;
}
template<typename T>
inline ReactiveVariable<T>& ReactiveVariable<T>::operator+=(T rhs)
{
this->OnChange(this->m_value + rhs);
return *this;
}
template<typename T>
inline ReactiveVariable<T>& ReactiveVariable<T>::operator-=(T rhs)
{
this->OnChange(this->m_value - rhs);
return *this;
}
template<typename T>
inline ReactiveVariable<T>& ReactiveVariable<T>::operator*=(T rhs)
{
this->OnChange(this->m_value*rhs);
return *this;
}
template<typename T>
inline ReactiveVariable<T>& ReactiveVariable<T>::operator/=(T rhs)
{
this->OnChange(this->m_value / rhs);
return *this;
}
}
#endif //_REACTIVE_VARIABLE_H_ |
Python | UTF-8 | 571 | 3.046875 | 3 | [] | no_license | import numpy as np
A=np.array([[2.0,-1.0,0.0],[1.0,6.0,-2.0],[4.0,-3.0,8.0]]).reshape(3,3)
b=np.reshape(np.array([2.0,-4.0,5.0]),(3,1))
n=np.shape(A)[0]
print("Matriz inicial: ")
print(A)
print("***********")
for k in range(0,n-1):
for i in range(k+1,n):
if A[i,k] != 0.0 :
lam = A[i,k]/A[k,k]
print("lam= "+str(lam))
A[i,k:n] = A[i,k:n] - lam*A[k,k:n]
b[i,:] = b[i,:] - lam*b[k,:]
print(A)
print("Matriz final : ")
print(A)
print(b)
for k in range(n-1,-1,-1):
b[k]=(b[k] - A[k,k+1:n].dot(b[k+1:n]) )/A[k,k]
print("Solucion final: ")
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.