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
JavaScript
UTF-8
3,725
2.53125
3
[]
no_license
import React, { useState } from "react"; import Alert from "react-bootstrap/Alert"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import DropdownButton from "react-bootstrap/DropdownButton"; import Dropdown from "react-bootstrap/Dropdown"; import "./Signup.css"; export default function Signup(props) { const { loginAsUser, handleLogin } = props; const [name, setName] = useState(""); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [roleType, setRoleType] = useState(""); const [message, setMessage] = useState(""); function validateForm() { return roleType.length > 0 && name.length > 0 && username.length > 0 && password.length > 0 && confirmPassword.length > 0 && password === confirmPassword; } function handleSubmit(event) { event.preventDefault(); fetch("/signup", { method: "POST", headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, username, password, role: roleType, }), }).then(res => res.json()) .then(res => { const {message} = res; if (message === 'account created') { loginAsUser({ name, username, role: roleType, }); } else { setMessage(message); } }); } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } return ( <div className="Signup"> <Form onSubmit={handleSubmit}> <Form.Group size="lg" controlId="role"> <DropdownButton variant="outline-dark" title={capitalizeFirstLetter(roleType) || "Role Type"} id="input-group-dropdown" > <Dropdown.Item href="#" value="client" onClick={() => setRoleType('client')}> Client </Dropdown.Item> <Dropdown.Item href="#" value="realtor" onClick={() => setRoleType('realtor')}> Realtor </Dropdown.Item> </DropdownButton> </Form.Group> <Form.Group size="lg" controlId="name"> <Form.Label>Name</Form.Label> <Form.Control autoFocus type="name" value={name} onChange={(e) => setName(e.target.value)} /> </Form.Group> <Form.Group size="lg" controlId="username"> <Form.Label>Username</Form.Label> <Form.Control autoFocus type="username" value={username} onChange={(e) => setUsername(e.target.value)} /> </Form.Group> <Form.Group size="lg" controlId="password"> <Form.Label>Password</Form.Label> <Form.Control type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> </Form.Group> <Form.Group size="lg" controlId="confirmPassword"> <Form.Label>Confirm Password</Form.Label> <Form.Control autoFocus type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} /> </Form.Group> <Button block size="lg" type="submit" disabled={!validateForm()}> Signup </Button> <Button className="login" size="sm" type="button" onClick={handleLogin}> Login </Button> { message && <Alert key="message" variant="danger">{message}</Alert> } </Form> </div> ); }
Python
UTF-8
351
3.28125
3
[]
no_license
from collections import Counter def company_logo(string_): return sorted(Counter(string_).most_common(), key = lambda x: (-x[1], x[0]))[:3] if __name__ == '__main__': string_ = input() orded_s = company_logo(string_) print('\n'.join([letter_count[0]+ ' '+ str(letter_count[1]) for letter_count in orded_s]))
TypeScript
UTF-8
2,049
2.609375
3
[]
no_license
import { Request, Response } from "express"; import { getMongoRepository } from "typeorm"; import { classToClass } from "class-transformer"; import { ObjectID } from 'mongodb' import { isAfter, isBefore } from "date-fns"; import { User } from "../database/schemas/User"; import { Appointment } from "../database/schemas/Appointment"; type QueryParams = { name: string } export class ProvidersController { public async index(req: Request, res: Response): Promise<Response> { try { const { id: user_id } = req.user const { name } = req.query as QueryParams const usersRepository = getMongoRepository(User) const providers = await usersRepository.find({ where: { $and: [ { _id: { $ne: new ObjectID(user_id) }, }, { accessLevel: { $in: ['personal'] } } ], ...(name && name.trim() ? { $text: { $search: name } } : {}) } }) return res.json(classToClass(providers)) } catch (err) { console.error(err) return res.status(500) } } public async show(req: Request, res: Response): Promise<Response> { const { provider_id } = req.params const usersRepository = getMongoRepository(User) const appointmentsRepository = getMongoRepository(Appointment) const providerData = await usersRepository.findOne(provider_id) if (!providerData || !providerData.accessLevel.includes('personal')) { return res.status(400).json({ message: 'Personal não existente' }) } const appointmentsWithProvider = await appointmentsRepository.find({ where: { 'provider.id': providerData.id } }) const nextAppointments = appointmentsWithProvider .filter(appointment => { return isAfter(new Date(appointment.date), Date.now()) }) .sort((a, b) => { if (isBefore(a.date, b.date)) return -1 if (isAfter(a.date, b.date)) return 1 else return 0 }) const provider = classToClass(providerData) return res.json({ ...provider, appointments: nextAppointments }) } }
PHP
UTF-8
920
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace service\tasks\product; use common\helper\EsProductHelper; use common\models\product\Product; use framework\components\ToolsAbstract; use service\tasks\TaskService; /** * @see MQAbstract::MSG_GROUP_SUB_PRODUCT_UPDATE * @package service\mq_processor\product */ class productDeleteProcess extends TaskService { /** * @inheritdoc */ public function run($data) { if (empty($data['product_id'])) { ToolsAbstract::log('商品id为空', 'product_update_process.log'); return '商品id为空'; } $productIds = $data['product_id']; //删除商品缓存 $redis = ToolsAbstract::getRedis(); foreach ($productIds as $productId) { $redis->hDel(Product::PRODUCT_KEY, $productId); } //更新es (new EsProductHelper())->deleteByProductIds($productIds); return true; } }
Java
UTF-8
469
2.328125
2
[ "MIT" ]
permissive
package remote.client; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import example.SomeApplicationException; @Path("/") public interface IEndpoint { @GET @Path("get/{id}") @Produces(MediaType.TEXT_PLAIN) public String get(@PathParam("id") int id) throws SomeApplicationException; @GET @Path("create/") @Produces(MediaType.TEXT_PLAIN) public Integer put(); }
Python
UTF-8
1,014
4
4
[]
no_license
from sys import argv script, filename = argv print "We're going to erase %r." % filename #let's user know we are erasing filename in this script print "If you don't want that, hit CTRL-C (^C)." #gives directions to not delete filename print "If you do want that, hit RETURN." #gives directions to delete filename raw_input("?") #prompts for input RETURN or CTRL-C print "Opening the file..." #string target = open(filename, 'w') #defines target variable which opens the file, 'w' is the 'write' mode print "Truncating the file. Goodbye!" target.truncate() #truncates/shortens the file print "Now I'm going to ask you for three lines." #prompts input for three lines line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "Now I'm going to write these to the file!" target.write("%r'\n'%r'\n'%r'\n'" % (line1, line2, line3)) #writes lines 1-3 to the file on seperate lines print "And finally, we close the file!" target.close() #closes file
Python
UTF-8
1,165
4.28125
4
[]
no_license
# p108 Computer Projects 1 p = int(input('Input the truth value of p : ')) q = int(input('Input the truth value of q : ')) def conjunction(p, q): if p == 1 and q == 1: print('The truth value of conjunction of p & q is : true') else: print('The truth value of conjunction of p & q is : false') def disjunction(p, q): if p == 1 or q == 1: print('The truth value of disjunction of p & q is : true') else: print('The truth value of disjunction of p & q is : false') def exclusiveOr(p, q): if p != q: print('The truth value of exclusive or of p & q is : true') else: print('The truth value of exclusive or of p & q is : false') def condictionStatement(p, q): if p == 1 and q == 0: print('The truth value of condiction statement of p & q is : false') else: print('The truth value of condiction statement of p & q is : true') def biconditional(p, q): if p == q: print('The truth value of conditional of p & q is : true') else: print('The truth value of conditional of p & q is : false') conjunction(p, q) disjunction(p, q) exclusiveOr(p, q) condictionStatement(p, q) biconditional(p, q)
Java
UTF-8
10,194
2.609375
3
[]
no_license
// specify the package package userinterface; // system imports import javafx.event.Event; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import javafx.stage.Stage; import java.util.Properties; // project imports import impresario.IModel; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.ComboBox; import model.Book; /** * The class containing the Account View for the ATM application */ //============================================================== public class BookView extends View { // GUI components protected TextField bookID; protected TextField author; protected TextField title; protected TextField pubYear; protected ComboBox status; protected Button cancelButton; protected Button submitButton; // For showing error message protected MessageView statusLog; // constructor for this class -- takes a model object //---------------------------------------------------------- public BookView(IModel model) { super(model, "BookView"); // create a container for showing the contents VBox container = new VBox(10); container.setPadding(new Insets(15, 5, 5, 5)); // Add a title for this panel container.getChildren().add(createTitle()); // create our GUI components, add them to this Container container.getChildren().add(createFormContent()); container.getChildren().add(createStatusLog(" ")); getChildren().add(container); populateFields(); } // Create the title container //------------------------------------------------------------- private Node createTitle() { HBox container = new HBox(); container.setAlignment(Pos.CENTER); Text titleText = new Text(" Brockport Library "); titleText.setFont(Font.font("Arial", FontWeight.BOLD, 20)); titleText.setWrappingWidth(300); titleText.setTextAlignment(TextAlignment.CENTER); titleText.setFill(Color.DARKGREEN); container.getChildren().add(titleText); return container; } // Create the main form content //------------------------------------------------------------- private VBox createFormContent() { VBox vbox = new VBox(10); //grid GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); //ALL TEXT FIELD LABELS Text prompt = new Text("BOOK INFORMATION"); prompt.setWrappingWidth(400); prompt.setTextAlignment(TextAlignment.CENTER); prompt.setFill(Color.BLACK); grid.add(prompt, 0, 0, 2, 1); Text bookNumLabel = new Text(" Book Number : "); Font myFont = Font.font("Helvetica", FontWeight.BOLD, 12); bookNumLabel.setFont(myFont); bookNumLabel.setWrappingWidth(150); bookNumLabel.setTextAlignment(TextAlignment.RIGHT); grid.add(bookNumLabel, 0, 1); bookID = new TextField(); bookID.setEditable(false); grid.add(bookID, 1, 1); Text authorLabel = new Text(" Author : "); authorLabel.setFont(myFont); authorLabel.setWrappingWidth(150); authorLabel.setTextAlignment(TextAlignment.RIGHT); grid.add(authorLabel, 0, 2); author = new TextField(); author.setEditable(true); grid.add(author, 1, 2); Text titleTypeLabel = new Text(" Title : "); titleTypeLabel.setFont(myFont); titleTypeLabel.setWrappingWidth(150); titleTypeLabel.setTextAlignment(TextAlignment.RIGHT); grid.add(titleTypeLabel, 0, 3); title = new TextField(); title.setEditable(true); grid.add(title, 1, 3); Text pubYearLabel = new Text(" Pub Year : "); pubYearLabel.setFont(myFont); pubYearLabel.setWrappingWidth(150); pubYearLabel.setTextAlignment(TextAlignment.RIGHT); grid.add(pubYearLabel, 0, 4); pubYear = new TextField(); pubYear.setEditable(true); grid.add(pubYear, 1, 4); Text statusLabel = new Text(" Status : "); statusLabel.setFont(myFont); statusLabel.setWrappingWidth(150); statusLabel.setTextAlignment(TextAlignment.RIGHT); grid.add(statusLabel, 0, 5); ObservableList<String> options = FXCollections.observableArrayList( "Active", "Inactive" ); status = new ComboBox(options); grid.add(status, 1, 5); MessageView messageView = createStatusLog(""); messageView.setFont(myFont); messageView.setWrappingWidth(150); messageView.setTextAlignment(TextAlignment.RIGHT); grid.add(messageView,0,7); //INB4 BUTTON HBox doneCont = new HBox(10); doneCont.setAlignment(Pos.CENTER_RIGHT); cancelButton = new Button("Done"); cancelButton.setFont(Font.font("Arial", FontWeight.BOLD, 14)); cancelButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Librarian lib = new Librarian(); lib.start(); /* Debugging */ //messageView.displayMessage("Done button pressed"); } }); doneCont.getChildren().add(cancelButton); grid.add(doneCont, 1,6); HBox hbSubmit = new HBox(10); hbSubmit.setAlignment(Pos.CENTER_LEFT); submitButton = new Button("Submit"); submitButton.setFont(Font.font("Arial", FontWeight.BOLD, 14)); submitButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { /* Debugging */ //messageView.displayMessage("Submit button pressed"); Properties prop = new Properties(); String authorName = author.getText(); String bookTitle = title.getText(); String publicationYear = pubYear.getText(); String bookStatus = (String)status.getValue(); /*Make sure all fields are not null */ if (authorName == null || authorName.isEmpty()) { messageView.displayMessage("You must input an Author"); return; } if (bookTitle == null || bookTitle.isEmpty()) { messageView.displayMessage("You must input a book Title"); return; } if (publicationYear == null || publicationYear.isEmpty()) { messageView.displayMessage("You must input a Publication Year"); return; } /* get all the information from the GUI and populate the properties object */ prop.setProperty("author", authorName); prop.setProperty("title", bookTitle); prop.setProperty("pubYear", publicationYear); prop.setProperty("status", bookStatus); /* use this information to create new book */ Book book = (Book) myModel; book.processNewBook(prop); book.update(); messageView.displayMessage("Book added successfully"); } }); hbSubmit.getChildren().add(submitButton); grid.add(hbSubmit,0,6); vbox.getChildren().add(grid); return vbox; } // Create the status log field //------------------------------------------------------------- protected MessageView createStatusLog(String initialMessage) { statusLog = new MessageView(initialMessage); return statusLog; } //------------------------------------------------------------- public void populateFields() { bookID.setText((String) myModel.getState("Book ID")); title.setText((String) myModel.getState("Title")); author.setText((String) myModel.getState("Author")); pubYear.setText((String) myModel.getState("Pub Year")); //status.setText((String) myModel.getState("Status")); } /** * Update method */ //--------------------------------------------------------- public void updateState(String key, Object value) { clearErrorMessage(); } /** * Display error message */ //---------------------------------------------------------- public void displayErrorMessage(String message) { statusLog.displayErrorMessage(message); } /** * Display info message */ //---------------------------------------------------------- public void displayMessage(String message) { statusLog.displayMessage(message); } /** * Clear error message */ //---------------------------------------------------------- public void clearErrorMessage() { statusLog.clearErrorMessage(); } }
Java
UTF-8
10,773
1.789063
2
[]
no_license
package com.ffcs.inapppaylib; class PayHelper$2 { void a() { int a; a=0;// .class Lcom/ffcs/inapppaylib/PayHelper$2; a=0;// .super Lcom/lidroid/xutils/http/callback/RequestCallBack; a=0;// .source "PayHelper.java" a=0;// a=0;// a=0;// # annotations a=0;// .annotation system Ldalvik/annotation/EnclosingMethod; a=0;// value = Lcom/ffcs/inapppaylib/PayHelper;->confirmPayment(Ljava/lang/String;Lcom/ffcs/inapppaylib/PayHelper$OnPayListener;)V a=0;// .end annotation a=0;// a=0;// .annotation system Ldalvik/annotation/InnerClass; a=0;// accessFlags = 0x0 a=0;// name = null a=0;// .end annotation a=0;// a=0;// .annotation system Ldalvik/annotation/Signature; a=0;// value = { a=0;// "Lcom/lidroid/xutils/http/callback/RequestCallBack", a=0;// "<", a=0;// "Ljava/lang/String;", a=0;// ">;" a=0;// } a=0;// .end annotation a=0;// a=0;// a=0;// # instance fields a=0;// .field final synthetic this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// a=0;// # direct methods a=0;// .method constructor <init>(Lcom/ffcs/inapppaylib/PayHelper;)V a=0;// .locals 0 a=0;// a=0;// .prologue a=0;// .line 1 a=0;// iput-object p1, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// .line 161 a=0;// invoke-direct {p0}, Lcom/lidroid/xutils/http/callback/RequestCallBack;-><init>()V a=0;// a=0;// #p0=(Reference,Lcom/ffcs/inapppaylib/PayHelper$2;); a=0;// return-void a=0;// .end method a=0;// a=0;// a=0;// # virtual methods a=0;// .method public onFailure(Lcom/lidroid/xutils/exception/HttpException;Ljava/lang/String;)V a=0;// .locals 2 a=0;// .param p1, "e" # Lcom/lidroid/xutils/exception/HttpException; a=0;// .param p2, "msg" # Ljava/lang/String; a=0;// a=0;// .prologue a=0;// .line 164 a=0;// iget-object v1, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// #v1=(Reference,Lcom/ffcs/inapppaylib/PayHelper;); a=0;// invoke-static {v1}, Lcom/ffcs/inapppaylib/PayHelper;->access$1(Lcom/ffcs/inapppaylib/PayHelper;)Lcom/ffcs/inapppaylib/PayHelper$OnPayListener; a=0;// a=0;// move-result-object v1 a=0;// a=0;// if-eqz v1, :cond_0 a=0;// a=0;// .line 165 a=0;// new-instance v0, Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// a=0;// #v0=(UninitRef,Lcom/ffcs/inapppaylib/bean/response/PayResponse;); a=0;// invoke-direct {v0}, Lcom/ffcs/inapppaylib/bean/response/PayResponse;-><init>()V a=0;// a=0;// .line 166 a=0;// .local v0, "resp":Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// #v0=(Reference,Lcom/ffcs/inapppaylib/bean/response/PayResponse;); a=0;// const/4 v1, -0x1 a=0;// a=0;// #v1=(Byte); a=0;// invoke-virtual {v0, v1}, Lcom/ffcs/inapppaylib/bean/response/PayResponse;->setRes_code(I)V a=0;// a=0;// .line 167 a=0;// const-string v1, "\u7f51\u7edc\u8fde\u63a5\u5f02\u5e38\uff01" a=0;// a=0;// #v1=(Reference,Ljava/lang/String;); a=0;// invoke-virtual {v0, v1}, Lcom/ffcs/inapppaylib/bean/response/PayResponse;->setRes_message(Ljava/lang/String;)V a=0;// a=0;// .line 168 a=0;// iget-object v1, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// invoke-static {v1}, Lcom/ffcs/inapppaylib/PayHelper;->access$1(Lcom/ffcs/inapppaylib/PayHelper;)Lcom/ffcs/inapppaylib/PayHelper$OnPayListener; a=0;// a=0;// move-result-object v1 a=0;// a=0;// invoke-interface {v1, v0}, Lcom/ffcs/inapppaylib/PayHelper$OnPayListener;->onBillingFailure(Lcom/ffcs/inapppaylib/bean/response/PayResponse;)V a=0;// a=0;// .line 170 a=0;// .end local v0 # "resp":Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// :cond_0 a=0;// #v0=(Conflicted); a=0;// return-void a=0;// .end method a=0;// a=0;// .method public onSuccess(Lcom/lidroid/xutils/http/ResponseInfo;)V a=0;// .locals 5 a=0;// .annotation system Ldalvik/annotation/Signature; a=0;// value = { a=0;// "(", a=0;// "Lcom/lidroid/xutils/http/ResponseInfo", a=0;// "<", a=0;// "Ljava/lang/String;", a=0;// ">;)V" a=0;// } a=0;// .end annotation a=0;// a=0;// .prologue a=0;// .line 174 a=0;// .local p1, "result":Lcom/lidroid/xutils/http/ResponseInfo;, "Lcom/lidroid/xutils/http/ResponseInfo<Ljava/lang/String;>;" a=0;// iget v3, p1, Lcom/lidroid/xutils/http/ResponseInfo;->statusCode:I a=0;// a=0;// #v3=(Integer); a=0;// const/16 v4, 0xc8 a=0;// a=0;// #v4=(PosShort); a=0;// if-ne v3, v4, :cond_2 a=0;// a=0;// iget-object v3, p1, Lcom/lidroid/xutils/http/ResponseInfo;->result:Ljava/lang/Object; a=0;// a=0;// #v3=(Reference,Ljava/lang/Object;); a=0;// if-eqz v3, :cond_2 a=0;// a=0;// .line 175 a=0;// new-instance v0, Lcom/google/gson/Gson; a=0;// a=0;// #v0=(UninitRef,Lcom/google/gson/Gson;); a=0;// invoke-direct {v0}, Lcom/google/gson/Gson;-><init>()V a=0;// a=0;// .line 176 a=0;// .local v0, "gson":Lcom/google/gson/Gson; a=0;// #v0=(Reference,Lcom/google/gson/Gson;); a=0;// iget-object v3, p1, Lcom/lidroid/xutils/http/ResponseInfo;->result:Ljava/lang/Object; a=0;// a=0;// check-cast v3, Ljava/lang/String; a=0;// a=0;// const-class v4, Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// a=0;// #v4=(Reference,Ljava/lang/Class;); a=0;// invoke-virtual {v0, v3, v4}, Lcom/google/gson/Gson;->fromJson(Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object; a=0;// a=0;// move-result-object v1 a=0;// a=0;// #v1=(Reference,Ljava/lang/Object;); a=0;// check-cast v1, Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// a=0;// .line 177 a=0;// .local v1, "pay":Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// invoke-virtual {v1}, Lcom/ffcs/inapppaylib/bean/response/PayResponse;->getRes_code()I a=0;// a=0;// move-result v3 a=0;// a=0;// #v3=(Integer); a=0;// if-nez v3, :cond_1 a=0;// a=0;// .line 178 a=0;// iget-object v3, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// #v3=(Reference,Lcom/ffcs/inapppaylib/PayHelper;); a=0;// invoke-static {v3}, Lcom/ffcs/inapppaylib/PayHelper;->access$1(Lcom/ffcs/inapppaylib/PayHelper;)Lcom/ffcs/inapppaylib/PayHelper$OnPayListener; a=0;// a=0;// move-result-object v3 a=0;// a=0;// if-eqz v3, :cond_0 a=0;// a=0;// .line 179 a=0;// iget-object v3, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// invoke-static {v3}, Lcom/ffcs/inapppaylib/PayHelper;->access$1(Lcom/ffcs/inapppaylib/PayHelper;)Lcom/ffcs/inapppaylib/PayHelper$OnPayListener; a=0;// a=0;// move-result-object v3 a=0;// a=0;// invoke-interface {v3, v1}, Lcom/ffcs/inapppaylib/PayHelper$OnPayListener;->onBillingSuccess(Lcom/ffcs/inapppaylib/bean/response/PayResponse;)V a=0;// a=0;// .line 194 a=0;// .end local v0 # "gson":Lcom/google/gson/Gson; a=0;// .end local v1 # "pay":Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// :cond_0 a=0;// :goto_0 a=0;// #v0=(Conflicted);v1=(Conflicted);v2=(Conflicted);v4=(Conflicted); a=0;// return-void a=0;// a=0;// .line 182 a=0;// .restart local v0 # "gson":Lcom/google/gson/Gson; a=0;// .restart local v1 # "pay":Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// :cond_1 a=0;// #v0=(Reference,Lcom/google/gson/Gson;);v1=(Reference,Lcom/ffcs/inapppaylib/bean/response/PayResponse;);v2=(Uninit);v3=(Integer);v4=(Reference,Ljava/lang/Class;); a=0;// iget-object v3, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// #v3=(Reference,Lcom/ffcs/inapppaylib/PayHelper;); a=0;// invoke-static {v3}, Lcom/ffcs/inapppaylib/PayHelper;->access$1(Lcom/ffcs/inapppaylib/PayHelper;)Lcom/ffcs/inapppaylib/PayHelper$OnPayListener; a=0;// a=0;// move-result-object v3 a=0;// a=0;// if-eqz v3, :cond_0 a=0;// a=0;// .line 183 a=0;// iget-object v3, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// invoke-static {v3}, Lcom/ffcs/inapppaylib/PayHelper;->access$1(Lcom/ffcs/inapppaylib/PayHelper;)Lcom/ffcs/inapppaylib/PayHelper$OnPayListener; a=0;// a=0;// move-result-object v3 a=0;// a=0;// invoke-interface {v3, v1}, Lcom/ffcs/inapppaylib/PayHelper$OnPayListener;->onBillingFailure(Lcom/ffcs/inapppaylib/bean/response/PayResponse;)V a=0;// a=0;// goto :goto_0 a=0;// a=0;// .line 187 a=0;// .end local v0 # "gson":Lcom/google/gson/Gson; a=0;// .end local v1 # "pay":Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// :cond_2 a=0;// #v0=(Uninit);v1=(Uninit);v3=(Conflicted);v4=(PosShort); a=0;// iget-object v3, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// #v3=(Reference,Lcom/ffcs/inapppaylib/PayHelper;); a=0;// invoke-static {v3}, Lcom/ffcs/inapppaylib/PayHelper;->access$1(Lcom/ffcs/inapppaylib/PayHelper;)Lcom/ffcs/inapppaylib/PayHelper$OnPayListener; a=0;// a=0;// move-result-object v3 a=0;// a=0;// if-eqz v3, :cond_0 a=0;// a=0;// .line 188 a=0;// new-instance v2, Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// a=0;// #v2=(UninitRef,Lcom/ffcs/inapppaylib/bean/response/PayResponse;); a=0;// invoke-direct {v2}, Lcom/ffcs/inapppaylib/bean/response/PayResponse;-><init>()V a=0;// a=0;// .line 189 a=0;// .local v2, "resp":Lcom/ffcs/inapppaylib/bean/response/PayResponse; a=0;// #v2=(Reference,Lcom/ffcs/inapppaylib/bean/response/PayResponse;); a=0;// const/4 v3, -0x1 a=0;// a=0;// #v3=(Byte); a=0;// invoke-virtual {v2, v3}, Lcom/ffcs/inapppaylib/bean/response/PayResponse;->setRes_code(I)V a=0;// a=0;// .line 190 a=0;// const-string v3, "\u7f51\u7edc\u8fde\u63a5\u5f02\u5e38\uff01" a=0;// a=0;// #v3=(Reference,Ljava/lang/String;); a=0;// invoke-virtual {v2, v3}, Lcom/ffcs/inapppaylib/bean/response/PayResponse;->setRes_message(Ljava/lang/String;)V a=0;// a=0;// .line 191 a=0;// iget-object v3, p0, Lcom/ffcs/inapppaylib/PayHelper$2;->this$0:Lcom/ffcs/inapppaylib/PayHelper; a=0;// a=0;// invoke-static {v3}, Lcom/ffcs/inapppaylib/PayHelper;->access$1(Lcom/ffcs/inapppaylib/PayHelper;)Lcom/ffcs/inapppaylib/PayHelper$OnPayListener; a=0;// a=0;// move-result-object v3 a=0;// a=0;// invoke-interface {v3, v2}, Lcom/ffcs/inapppaylib/PayHelper$OnPayListener;->onBillingFailure(Lcom/ffcs/inapppaylib/bean/response/PayResponse;)V a=0;// a=0;// goto :goto_0 a=0;// .end method }}
C++
UTF-8
562
2.734375
3
[]
no_license
#include "ElseIfStatementList.h" void ElseIfStatementList::prependElseIfStm(ConditionExpression* condition, CompoundStatement* body) { mElseStatements.push_front(ElseStm(condition, body)); } void ElseIfStatementList::appendElseIfStm(ConditionExpression* condition, CompoundStatement* body) { mElseStatements.push_back(ElseStm(condition, body)); } ElseStm ElseIfStatementList::popFrontElseIfStm() { ElseStm estm = mElseStatements.front(); mElseStatements.pop_front(); return estm; } bool ElseIfStatementList::empty() { return mElseStatements.empty(); }
JavaScript
UTF-8
2,405
3.953125
4
[]
no_license
var cards = ["jack", "ace", "queen", "king", "ace", "king", "queen", "jack"]; var cardsInPlay = []; function isTwoCards(){ // add card to array of cards in play // 'this' hasn't been covered in this prework, but // for now, just know it gives you access to the card the user clicked on var card = this.getAttribute('data-card'); cardsInPlay.push(this); this.innerHTML = '<img src="' + card + '.svg" alt="' + card + '" />'; this.className = "card-shown"; // if you have two cards in play check for a match if (cardsInPlay.length === 2) { // pass the cardsInPlay as an argument to isMatch function isMatch(cardsInPlay); // clear cards in play array for next try cardsInPlay = []; } else { document.getElementById("result").innerHTML = ""; } } function isMatch(){ var result = document.getElementById("result"); if (cardsInPlay[0].getAttribute('data-card') === cardsInPlay[1].getAttribute('data-card')){ result.innerHTML = "You found a match!"; cardsInPlay[0].removeEventListener("click", isTwoCards); cardsInPlay[1].removeEventListener("click", isTwoCards); isGameOver(); } else { result.innerHTML = "Sorry, " + cardsInPlay[0].getAttribute('data-card') + " and " + cardsInPlay[1].getAttribute('data-card') + " don't match. Try again."; cardsInPlay[0].innerHTML = ""; cardsInPlay[1].innerHTML = ""; cardsInPlay[0].className = "card"; cardsInPlay[1].className = "card"; } } function isGameOver(){ //When cards are found they have a class of "card-shown". //Game is over when no cards still have the class "card". var unfound = document.getElementsByClassName("card"); if (unfound.length === 0){ createBoard(); } } function shuffleCards(){ var holding = []; while (cards.length > 0){ var i = Math.floor(Math.random() * cards.length); var card = cards.splice(i, 1); holding.push(card[0]); } cards = holding; } function createBoard(){ shuffleCards(); var board = document.getElementById("game-board"); //Clear any previous game from the board. board.innerHTML = ""; //Add new cards to the board. for (var i = 0; i < cards.length; i++){ var newCard = document.createElement("div"); newCard.className = "card"; newCard.setAttribute("data-card", cards[i]); newCard.addEventListener("click", isTwoCards); board.appendChild(newCard); } } createBoard();
Python
UTF-8
277
2.765625
3
[]
no_license
import sys from itertools import combinations while True: c, n = map(int, raw_input().split()) if c == n == 0: break # sum(cC3) == 9 count = 0 for i in combinations(range(1, c + 1),3): if sum(i) == n: count += 1 print count
SQL
UTF-8
12,370
3.09375
3
[ "Apache-2.0" ]
permissive
-- MySQL dump 10.13 Distrib 5.7.19, for Linux (x86_64) -- -- Host: localhost Database: weilai -- ------------------------------------------------------ -- Server version 5.7.19-0ubuntu0.16.04.1 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `ad` -- DROP TABLE IF EXISTS `ad`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ad` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(99) NOT NULL, `url` varchar(255) DEFAULT '', `new_window` tinyint(4) DEFAULT '0' COMMENT '链接是否在新窗口打开?', `word` text, `img` varchar(255) NOT NULL DEFAULT '' COMMENT 'banner图', `position` tinyint(4) NOT NULL DEFAULT '1' COMMENT '所处位置:1首页 2业务体系 3金牌托管 4品牌案例 5关于我们', `st` tinyint(4) DEFAULT '1', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`), KEY `position` (`position`) ) ENGINE=MyISAM AUTO_INCREMENT=62 DEFAULT CHARSET=utf8 COMMENT='广告'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `admin` -- DROP TABLE IF EXISTS `admin`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL COMMENT '账号', `pwd` char(32) DEFAULT NULL COMMENT '密码', `times` int(11) DEFAULT '0' COMMENT '登录次数', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='后台管理员'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `admin_log` -- DROP TABLE IF EXISTS `admin_log`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `admin_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `admin_id` int(11) NOT NULL DEFAULT '1' COMMENT 'admin_id', `ip` varchar(50) DEFAULT '' COMMENT '上次登录ip', `create_time` int(11) DEFAULT '0' COMMENT '登录时间', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COMMENT='后台管理员登录日志'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `anli` -- DROP TABLE IF EXISTS `anli`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `anli` ( `id` int(11) NOT NULL AUTO_INCREMENT, `cate_anli_id` int(11) NOT NULL DEFAULT '1' COMMENT '分类id', `name` varchar(100) NOT NULL, `img` varchar(255) NOT NULL DEFAULT '' COMMENT '列表图', `func_ids` varchar(100) DEFAULT '', `cont` text, `keywords` varchar(255) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `sort` int(11) DEFAULT '1000', `st` tinyint(4) DEFAULT '1', `index_show` tinyint(4) DEFAULT '0' COMMENT '是否显示在轮番图', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`), KEY `cate_id` (`cate_anli_id`) ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COMMENT='anli'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `article` -- DROP TABLE IF EXISTS `article`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `article` ( `id` int(11) NOT NULL AUTO_INCREMENT, `cate` int(11) NOT NULL DEFAULT '1' COMMENT '分类id 1媒体报道 2行业资讯 3企业动态', `name` varchar(100) NOT NULL, `click` int(11) DEFAULT '0' COMMENT '点击量', `img` varchar(255) NOT NULL DEFAULT '' COMMENT '列表图', `cont` text, `keywords` varchar(255) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `sort` int(11) DEFAULT '1000' COMMENT '排序', `st` tinyint(4) DEFAULT '1', `index_show` tinyint(4) DEFAULT '0' COMMENT '是否显示在轮番图', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`), KEY `cate` (`cate`) ) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COMMENT='资讯表'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `cate_anli` -- DROP TABLE IF EXISTS `cate_anli`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cate_anli` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(99) NOT NULL COMMENT '名称', `sort` int(11) DEFAULT '0' COMMENT '排序', `st` tinyint(4) DEFAULT '1' COMMENT '0删除状态,1正常', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='anli分类'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `cate_shipin` -- DROP TABLE IF EXISTS `cate_shipin`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cate_shipin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(99) NOT NULL COMMENT '名称', `sort` int(11) DEFAULT '0' COMMENT '排序', `st` tinyint(4) DEFAULT '1' COMMENT '0删除状态,1正常', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='视频分类'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `friend` -- DROP TABLE IF EXISTS `friend`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `friend` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` tinyint(4) DEFAULT NULL, `name` varchar(99) NOT NULL, `url` varchar(255) DEFAULT '', `logo` varchar(255) DEFAULT '', `st` tinyint(4) DEFAULT NULL COMMENT '0删除状态,1正常', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COMMENT='合作(包括友情链接和战略合作)'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `func` -- DROP TABLE IF EXISTS `func`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `func` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(99) NOT NULL COMMENT '名称', `sort` int(11) DEFAULT '0' COMMENT '排序', `st` tinyint(4) DEFAULT '1' COMMENT '0删除状态,1正常', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='anli功能'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `host` -- DROP TABLE IF EXISTS `host`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `host` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(99) NOT NULL COMMENT '名称', `jianjie` text COMMENT '简介', `img` varchar(200) DEFAULT NULL COMMENT '头像', `st` tinyint(4) DEFAULT '1' COMMENT '0删除状态,1正常', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COMMENT='主持人'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `menu_admin` -- DROP TABLE IF EXISTS `menu_admin`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `menu_admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL COMMENT '导航名称', `pid` int(11) NOT NULL DEFAULT '0' COMMENT '导航上级id,总分两级,0表示一级', `controller` varchar(100) DEFAULT '' COMMENT '控制器,为一级时为""', `action` varchar(100) DEFAULT '' COMMENT '控制器中方法,为一级时为""', `param` varchar(100) DEFAULT '' COMMENT '参数', `sort` int(11) DEFAULT '0', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COMMENT='后台左侧导航'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `recruit` -- DROP TABLE IF EXISTS `recruit`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `recruit` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL COMMENT '职位名称', `department` varchar(50) NOT NULL COMMENT '部门', `num` int(11) NOT NULL COMMENT '招人数', `addr` varchar(50) NOT NULL COMMENT '工作地', `duty` text COMMENT '岗位职责及优势', `st` tinyint(4) DEFAULT NULL COMMENT '0删除状态,1正常,2不显示', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='招贤纳士'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `seo_set` -- DROP TABLE IF EXISTS `seo_set`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `seo_set` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nav_id` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1首页 2业务体系 3品牌案例 4资讯中心 5关于我们 6渠道与招商', `title` varchar(100) NOT NULL DEFAULT '' COMMENT 'seo标题', `keywords` varchar(255) NOT NULL DEFAULT '' COMMENT 'seo关键词', `description` varchar(255) NOT NULL DEFAULT '' COMMENT 'seo描述', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='seo set'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `shipin` -- DROP TABLE IF EXISTS `shipin`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `shipin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `vid` varchar(225) NOT NULL, `name` varchar(100) NOT NULL DEFAULT '无视频名称' COMMENT '视频名称', `cate_id` int(11) NOT NULL DEFAULT '1', `click` int(11) DEFAULT '0' COMMENT '浏览量', `img` varchar(255) NOT NULL DEFAULT '' COMMENT '视频缩图', `img_index` varchar(255) NOT NULL DEFAULT '' COMMENT '视频首页的效果图片', `keywords` varchar(255) NOT NULL DEFAULT '' COMMENT 'seo关键词', `description` varchar(255) NOT NULL DEFAULT '' COMMENT 'seo描述', `index_show` tinyint(4) DEFAULT '0' COMMENT '是否显示在效果图位置', `st` tinyint(4) DEFAULT '1' COMMENT '0删除状态,1正常,2不显示', `sort` int(11) DEFAULT '1000' COMMENT '排序', `create_time` int(11) DEFAULT '0', `update_time` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='视频'; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2017-09-22 13:48:17
Markdown
UTF-8
3,505
3.078125
3
[ "MIT" ]
permissive
### Generic Event Parser This project is a Google Dataflow pipeline that process generic JSON messages from Google PubSub or Apache Kafka and writes it parsed to Google BigQuery. #### How does it work? The pipeline will read JSON messages. The expected format is something like: ```json { "Id": "an-ulid-string", "Source": "source-system-that-produced-this-message", "Type": "an-awesome-event-was-produced", "SchemaVersion": 1, "DataVersion": 1, "Data": { ... }, "CreatedAt": "2019-07-17T08:57:10-03:00" } ``` You may customize this message format but you should keep at least `Source` and `Type` fields. These two fields will be used to choose the BigQuery table where messages will be placed. A message will be written to a BigQuery table called `source_type` (snake case). So each kind of message will be written to a different table. For example, the message `account-was-created` produced by `arquivei` will be written to a table called: `arquivei_account_was_created`. If for some reason the message could not be parsed and written in destination table, it will be placed as a raw string on a fallback table. The destination `dataset` should be set in project configuration. Please refer to FAQ for more information. #### Project Structure Each Dataflow pipeline is kept inside a different folder in `stream/` directory: - `kafkagenericeventparser`: Reads from Kafka and writes to BigQuery - `pubsubgenericeventparser`: Reads from Pubsub and writes to BigQuery The inner logic of both pipelines are the same and only the source is different. #### Configuration Each project has a `config/` folder. Several yaml files can be placed in there for each subproject you have. An example yaml is kept called `example.yaml.dist`. You should customize settings for your pipelines accordingly. For example, you may create a `dev.yaml` file containing configs for testing in development environment and a `prod.yaml` file for production environment. The name of the yaml file without extension is the name of your `project` (prod or dev, for example). #### Migrations A fallback table needs to be created by each pipeline. You may use the following command for that: ```bash ./exec.sh migrate <project> ``` #### Running To deploy your pipeline just run the following command: ```bash ./exec.sh run <project> ``` #### FAQ - What happens to timestamps and datetimes? Once our input data is a JSON string, we look for these data types applying some regexes to find if a string is a timestamp or datetime. Then, *ALL TIMESTAMPS AND DATETIMES ARE CONVERTED TO A DATETIME IN AMERICA/SAO_PAULO TIME ZONE*. - What happens when schema changes? Every message that arrives will be processed in the following way: 1. Message content will be parsed to JSON 2. All string fields are tested for Datetime regexes, if match they are converted to America/Sao_Paulo 3. All JSON keys will be transformed to PascalCase 4. Special characters are removed from JSON keys and then are conformed to BigQuery field names pattern 5. If something went wrong in the previous steps, message is marked as fallback and will be written to fallback table. If not, proceed to step 6. 6. Message will be written to BigQuery. If a problem happens, proceed to step 7. 7. If problem is caused due to a schema change, it is detected and a update is made to the table. 8. If update succeeds, message is written to BigQuery. If a problem happens, proceed to step 9. 9. Write message in fallback table.
PHP
UTF-8
1,735
2.53125
3
[]
no_license
<?php /** * This file is part of the github-api-test package. * * (c) Mátyás Somfai <somfai.matyas@gmail.com> * Created at 2016.09.09. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace AppBundle\Command; use Github\Api\Repo; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class RepoAddDeployKeyCommand extends AbstractGithubCommand { protected function configure() { $this->setName('github:repo:add-deploy-key') ->setDescription('Add a deploy key for the given repository.') ->addArgumentRepository() ->addArgument('key-title', InputArgument::REQUIRED, 'The key title.') ->addArgument('key-value', InputArgument::REQUIRED, 'The key value.') ->addOption('read-only', null, InputOption::VALUE_NONE, 'The deploy key will be read-only.'); } protected function execute(InputInterface $input, OutputInterface $output) { list($username, $repository) = $this->getRepositoryArgumentParts($input); $client = $this->getAuthenticatedClient(); /** @var Repo $repo */ $repo = $client->api('repo'); $key = $repo->keys()->create( $username, $repository, [ 'title' => $input->getArgument('key-title'), 'key' => $input->getArgument('key-value'), 'read_only' => $input->getOption('read-only') ] ); $output->writeln(sprintf('Deploy key "%s" added.', $key['title'])); } }
Java
UTF-8
833
2.234375
2
[]
no_license
package com.onlinehocam.ozel.ders.okul; class Comment { String questionClass; String questionLesson; String studentName; String tutorName; String commentText; int studentID; int tutorUserID; int questionRequestID; double rating; public Comment(String questionClass, String questionLesson, String studentName, String tutorName, String commentText, int studentID, int tutorUserID, int questionRequestID, double rating) { this.questionClass = questionClass; this.questionLesson = questionLesson; this.studentName = studentName; this.tutorName = tutorName; this.commentText = commentText; this.studentID = studentID; this.tutorUserID = tutorUserID; this.questionRequestID = questionRequestID; this.rating = rating; } }
JavaScript
UTF-8
763
2.734375
3
[]
no_license
// for the user const jwt = require('jsonwebtoken') const { JWT_SECRET, JWT_EXP } = process.env const createToken = async (data) => { try { let payload={ _id: data.id, email: data.email, userName: data.userName } const token = await jwt.sign({ data: payload},JWT_SECRET,{ expiresIn: JWT_EXP }); return token; } catch (error) { return error } } //decode JWt const decodeToken = async (token) => { try { var decoded = jwt.verify(token, JWT_SECRET) // console.log("decoded--", decoded) return decoded; } catch(err) { console.log("errr---", err) return err } } module.exports = { createToken, decodeToken }
JavaScript
UTF-8
864
2.71875
3
[]
no_license
import {templFooter} from '../templates/footer.js' function main () { const btn = document.querySelector('#b_acceder') if(btn){ btn.addEventListener('click', onClick) } document.querySelector('footer').innerHTML = templFooter function onClick () { const formLogin = document.querySelector('#f_login') const inputs = [...formLogin.querySelectorAll('input')] try { inputs.forEach((item)=> { if(!item.value){ throw new Error(`Campo ${item[i].id} Invalido`) } }) } catch (error) { console.log(error.message) formLogin.querySelector('p').innerHTML = error.message return } window.location = 'usuario.html' } } document.addEventListener('DOMContentLoaded', main)
C#
UTF-8
540
2.59375
3
[]
no_license
var sharedItem = await graphClient.Drives[driveId].Items[folderItemId].Request().Expand(i => i.Children).GetAsync(); foreach (var item in sharedItem.Children) { if (item.File != null) { var fileContent = await graphClient.Drives[item.ParentReference.DriveId].Items[item.Id].Content.Request() .GetAsync(); using (var fileStream = new FileStream(item.Name, FileMode.Create, System.IO.FileAccess.Write)) fileContent.CopyTo(fileStream); } }
Java
UTF-8
1,704
1.976563
2
[]
no_license
package com.example.bilgideposu.Aktiviteler; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.example.bilgideposu.R; public class Sorular extends AppCompatActivity { private Button buttonBayrakSorular,buttonBaşkentSorular,buttonFilmSorular; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sorular); buttonBayrakSorular = findViewById(R.id.buttonBayrakSorular); buttonBaşkentSorular = findViewById(R.id.buttonBaşkentSorular); buttonFilmSorular = findViewById(R.id.buttonFilmSorular); //Bayrak sınavına gider buttonBayrakSorular.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Sorular.this,"Sınavlar yakında güncellenecektir !", Toast.LENGTH_SHORT).show(); } }); //Başkent sınavına gider buttonBaşkentSorular.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Sorular.this,"Sınavlar yakında güncellenecektir !", Toast.LENGTH_SHORT).show(); } }); //Film sınavına gider buttonFilmSorular.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Sorular.this,"Sınavlar yakında güncellenecektir !", Toast.LENGTH_SHORT).show(); } }); } }
Java
UTF-8
5,688
1.90625
2
[]
no_license
package comp6231.shared; public class Constants { public static final String NULL_STRING = "Null String"; public static final String DILIMITER_STRING = "*%#$@#!"; public static final String ONE_WAY = "ONE WAY MESSAGE"; //IP CONFIG public static final String LOCAL_IP = "127.0.0.1"; // public static final String FE_CLIENT_IP = "172.31.80.10"; // public static final String FARID_IP = "172.31.80.10"; // public static final String SAMAN_IP = "172.20.10.9"; // public static final String MOSTAFA_IP = "172.20.10.9"; public static final String FE_CLIENT_IP = LOCAL_IP; public static final String FARID_IP = LOCAL_IP; public static final String SAMAN_IP = LOCAL_IP; public static final String MOSTAFA_IP = LOCAL_IP; // RE1 = mostafa RE2 = saman RE3 = farid // Replica managers public static final String RM_FARID = "rm_farid"; public static final String RM_RE1 = "rm_re1"; public static final String RM_RE2 = "rm_re2"; public static final int RM_PORT_LISTEN_Farid = 2973; public static final int RM_PORT_LISTEN_RE1 = 2974; public static final int RM_PORT_LISTEN_RE2 = 2975; //RE1 public static final int KKL_PORT_LISTEN_RE1_ORIGINAL = 2900; public static final int DVL_PORT_LISTEN_RE1_ORIGINAL = 2901; public static final int WST_PORT_LISTEN_RE1_ORIGINAL = 2902; public static final int KKL_PORT_LISTEN_RE1_BACKUP = 2803; public static final int DVL_PORT_LISTEN_RE1_BACKUP = 2904; public static final int WST_PORT_LISTEN_RE1_BACKUP = 2905; public static final int KKL_PORT_RE1_ORIGINAL = 2962; public static final int DVL_PORT_RE1_ORIGINAL = 2963; public static final int WST_PORT_RE1_ORGINAL = 2961; public static final int KKL_PORT_RE1_BACKUP = 2964; public static final int DVL_PORT_RE1_BACKUP = 2965; public static final int WST_PORT_RE1_BACKUP = 2966; public static int kklPortListenRe1Active = KKL_PORT_LISTEN_RE1_ORIGINAL; public static int dvlPortListenRe1Active = DVL_PORT_LISTEN_RE1_ORIGINAL; public static int wstPortListenRe1Active = WST_PORT_LISTEN_RE1_ORIGINAL; //RE2 //2906 //2907 //2908 // public static final int KKL_PORT_LISTEN_RE2_ORIGINAL = 2906; // public static final int DVL_PORT_LISTEN_RE2_ORIGINAL = 2907; // public static final int WST_PORT_LISTEN_RE2_ORIGINAL = 2908; public static final int KKL_PORT_LISTEN_RE2_ORIGINAL = 7778; public static final int DVL_PORT_LISTEN_RE2_ORIGINAL = 7777; public static final int WST_PORT_LISTEN_RE2_ORIGINAL = 7779; //2909 //2910 //2911 // public static final int KKL_PORT_LISTEN_RE2_BACKUP = 2909; // public static final int DVL_PORT_LISTEN_RE2_BACKUP = 2910; // public static final int WST_PORT_LISTEN_RE2_BACKUP = 2911; public static final int KKL_PORT_LISTEN_RE2_BACKUP = 6668; public static final int DVL_PORT_LISTEN_RE2_BACKUP = 6667; public static final int WST_PORT_LISTEN_RE2_BACKUP = 6669; public static final int KKL_PORT_RE2_ORIGINAL = 2967; public static final int DVL_PORT_RE2_ORIGINAL = 2968; public static final int WST_PORT_RE2_ORGINAL = 2969; public static final int KKL_PORT_RE2_BACKUP = 2970; public static final int DVL_PORT_RE2_BACKUP = 2971; public static final int WST_PORT_RE2_BACKUP = 2972; public static int kklPortListenRe2Active = KKL_PORT_LISTEN_RE2_ORIGINAL; public static int dvlPortListenRe2Active = DVL_PORT_LISTEN_RE2_ORIGINAL; public static int wstPortListenRe2Active = WST_PORT_LISTEN_RE2_ORIGINAL; //FE public static final int FE_PORT = 2960; public static final int FE_PORT_LISTEN = 2903; //Time RE1 & RE2 public static final int INITIAL_TIME = 7*24*60*3600; // public static final int INITIAL_TIME = 60; // Server to server RE1 & RE2 public static final String ERR_NOT_BOOKED_NOROOM = "notbooked(noroom)"; public static final String ERR_NOT_BOOKED_NODATE = "notbooked(nodate)"; public static final String ERR_NOT_BOOKED_NOTIME = "notbooked(notime)"; public static final String ERR_NOT_BOOKED_NOTAV = "notbooked(notAvailable)"; public static final String REDUCE_BOOK_COUNT = "reducebookcount"; public static final String BOOK_ROOM = "bookRoom"; public static final String REQ_GETAVTIME = "getAvailableTimeSlot"; public static final String REQ_CANCEL_BOOK = "cancelBooking"; public static final String REQ_REMOVE_BOOK = "removeBooking"; public static final String RESULT_UDP_FAILD = "faild"; public static final String COMMIT = "commit"; public static final String ROLLBACK = "rollBack"; public static final int BUFFER_SIZE = 1024; //Saman public static final int DVL_PORT_LISTEN_SAMAN_ORIGINAL = 7777; public static final int KKL_PORT_LISTEN_SAMAN_ORIGINAL = 7778; public static final int WST_PORT_LISTEN_SAMAN_ORIGINAL = 7779; public static final int DVL_PORT_LISTEN_SAMAN_BACKUP = 6667; public static final int KKL_PORT_LISTEN_SAMAN_BACKUP = 6668; public static final int WST_PORT_LISTEN_SAMAN_BACKUP = 6669; // RE3 public static final int DVL_PORT_LISTEN_FARID_ORIGINAL = 9763; public static final int KKL_PORT_LISTEN_FARID_ORIGINAL = 9867; public static final int WST_PORT_LISTEN_FARID_ORIGINAL = 9635; public static final int DVL_PORT_LISTEN_FARID_BACKUP= 9764; public static final int KKL_PORT_LISTEN_FARID_BACKUP = 9868; public static final int WST_PORT_LISTEN_FARID_BACKUP = 9636; public static int dvlPortListenFaridActive = DVL_PORT_LISTEN_FARID_ORIGINAL; public static int kklPortListenFaridActive = KKL_PORT_LISTEN_FARID_ORIGINAL; public static int wstPortListenFaridActive = WST_PORT_LISTEN_FARID_ORIGINAL; // multi cast group public static final String DVL_GROUP = "DVL"; public static final String KKL_GROUP = "KKL"; public static final String WST_GROUP = "WST"; public static final int ACTIVE_SERVERS = 3; }
Java
UTF-8
1,433
2.75
3
[]
no_license
package me.service.Impl; import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException; import me.dao.impl.DBConnectionImpl; import me.domain.ErrorMess; import me.service.IModifyCourseNameService; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class ModifyCourseNameServiceImpl implements IModifyCourseNameService { public static void modify(int id, String name) throws ErrorMess { try { Connection con = DBConnectionImpl.getConnection(); String sql = null; PreparedStatement ps = null; ResultSet rs = null; assert con != null; //检查是否有该课程号的课程 sql = "select * from course where id = ?"; ps = con.prepareStatement(sql); ps.setInt(1, id); rs = ps.executeQuery(); if (!rs.next()){ throw new ErrorMess("没有这个课程号!"); } //修改该课程 sql = "update course set name = ? where id = ?"; ps = con.prepareStatement(sql); ps.setString(1, name); ps.setInt(2, id); ps.executeUpdate(); ps.close(); con.close(); } catch (MySQLIntegrityConstraintViolationException e) { throw new ErrorMess("已存在该课程"); } catch (SQLException e) { e.printStackTrace(); throw new ErrorMess("其他问题,请..."); } } }
Java
UTF-8
1,223
2.359375
2
[]
no_license
package elte.softwaretechnology.stockprices.collectors; import elte.softwaretechnology.exceptions.NotImplementedException; import elte.softwaretechnology.stockprices.collectors.implementations.NewYorkTimesDataCollector; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class DataCollectorFactory { @Autowired private Environment environment; private Map<DataCollectorType, DataCollector> dataCollectors = new HashMap<>(); private DataCollectorFactory() { } public DataCollector createOrRetrieveDataCollector(DataCollectorType dataCollectorType) { DataCollector dataCollector = dataCollectors.get(dataCollectorType); if (dataCollector == null) { if (dataCollectorType == DataCollectorType.NewYorkTimes) { dataCollector = new NewYorkTimesDataCollector(environment.resolvePlaceholders("${new.york.times.api.link}"), environment.resolvePlaceholders("${new.york.times.api.key}")); } else { throw new NotImplementedException(); } } dataCollectors.put(dataCollectorType, dataCollector); return dataCollector; } }
C++
UTF-8
6,065
3.625
4
[]
no_license
template<typename ItemType> DoublyLinkedList<ItemType>::DoublyLinkedList() : current_size_{0}, head_{nullptr}, tail_{nullptr} {} template<typename ItemType> DoublyLinkedList<ItemType>::DoublyLinkedList(const DoublyLinkedList<ItemType> &old_list) { current_size_ = old_list.getSize(); head_ = new DoubleNode<ItemType>(old_list.head_->getItem()); DoubleNode<ItemType>* current_ptr = old_list.head_->getNext(); DoubleNode<ItemType>* new_current_ptr = head_; while (current_ptr != nullptr) { DoubleNode<ItemType>* to_add = new DoubleNode<ItemType>(current_ptr->getItem(), nullptr, new_current_ptr); new_current_ptr->setNext(to_add); new_current_ptr = new_current_ptr->getNext(); current_ptr = current_ptr->getNext(); } tail_ = new_current_ptr; } template<typename ItemType> DoublyLinkedList<ItemType>::~DoublyLinkedList() { clear(); } template<typename ItemType> bool DoublyLinkedList<ItemType>::insert(const ItemType &item, const int &position) { DoubleNode<ItemType>* to_add = new DoubleNode<ItemType>(item); DoubleNode<ItemType>* pos_ptr = getAtPos(position); // List is empty create new head ptr and tail ptr if (head_ == nullptr) { head_ = to_add; tail_ = to_add; } // Change head ptr else if (head_ == pos_ptr) { DoubleNode<ItemType>* current_ptr = head_; head_ = to_add; current_ptr->setPrev(head_); head_->setNext(current_ptr); } // Add to the end else if (pos_ptr == nullptr) { to_add->setNext(nullptr); to_add->setPrev(tail_); tail_->setNext(to_add); tail_ = to_add; } // Replace at a specific location else { to_add->setPrev(pos_ptr->getPrevious()); to_add->setNext(pos_ptr); pos_ptr->getPrevious()->setNext(to_add); pos_ptr->setPrev(to_add); } current_size_++; return true; } template<typename ItemType> bool DoublyLinkedList<ItemType>::remove(const int &position) { DoubleNode<ItemType>* to_remove = getAtPos(position); // Not in list if (to_remove == nullptr) return false; // Remove head if (to_remove == head_) { head_ = to_remove->getNext(); to_remove->setPrev(nullptr); } // Remove tail else if (to_remove == tail_) { tail_ = to_remove->getPrevious(); tail_->setNext(nullptr); } // Remove at specific position else { DoubleNode<ItemType>* next = to_remove->getNext(); to_remove->getPrevious()->setNext(next); next->setPrev(to_remove->getPrevious()); to_remove->setPrev(nullptr); to_remove->setNext(nullptr); } delete to_remove; to_remove = nullptr; current_size_--; return true; } template<typename ItemType> int DoublyLinkedList<ItemType>::getSize() const { return current_size_; } template<typename ItemType> DoubleNode<ItemType> *DoublyLinkedList<ItemType>::getHeadPtr() const { return head_; } template<typename ItemType> DoubleNode<ItemType> *DoublyLinkedList<ItemType>::getAtPos(const int &pos) const { if (isEmpty()) return nullptr; if (pos == 1) return head_; if (pos == current_size_) return tail_; if (pos > current_size_) return nullptr; int counter = 1; DoubleNode<ItemType>* current_ptr = head_; while (current_ptr != nullptr) { if (counter == pos) { return current_ptr; } current_ptr = current_ptr->getNext(); counter++; } return nullptr; } template<typename ItemType> bool DoublyLinkedList<ItemType>::isEmpty() const { return current_size_ == 0; } template<typename ItemType> void DoublyLinkedList<ItemType>::clear() { DoubleNode<ItemType>* delete_ptr = head_; while (head_ != nullptr) { head_ = head_->getNext(); delete_ptr->setNext(nullptr); delete delete_ptr; delete_ptr = head_; } current_size_ = 0; } template<typename ItemType> void DoublyLinkedList<ItemType>::display() const { DoubleNode<ItemType>* current_ptr = head_; while (current_ptr != nullptr) { if (current_ptr == tail_) { std::cout << current_ptr->getItem() << std::endl; } else { std::cout << current_ptr->getItem() << " "; } current_ptr = current_ptr->getNext(); } } template<typename ItemType> void DoublyLinkedList<ItemType>::displayBackwards() const { DoubleNode<ItemType>* current_ptr = tail_; while (current_ptr != nullptr) { if (current_ptr == head_) { std::cout << current_ptr->getItem() << std::endl; } else { std::cout << current_ptr->getItem() << " "; } current_ptr = current_ptr->getPrevious(); } } template<typename ItemType> DoublyLinkedList<ItemType> DoublyLinkedList<ItemType>::interleave(const DoublyLinkedList<ItemType> &a_list) { DoublyLinkedList<ItemType> interleaved; DoubleNode<ItemType>* first_ptr = head_; DoubleNode<ItemType>* second_ptr = a_list.head_; int counter = 0; while (first_ptr != nullptr || second_ptr != nullptr) { if (first_ptr == nullptr && second_ptr != nullptr) { interleaved.insert(second_ptr->getItem(), counter + 1); second_ptr = second_ptr->getNext(); } else if (second_ptr == nullptr && first_ptr != nullptr) { interleaved.insert(first_ptr->getItem(), counter + 1); first_ptr = first_ptr->getNext(); } else { if (counter % 2 == 0) { interleaved.insert(first_ptr->getItem(), counter + 1); first_ptr = first_ptr->getNext(); } else { interleaved.insert(second_ptr->getItem(), counter + 1); second_ptr = second_ptr->getNext(); } } counter++; } return interleaved; } template<typename ItemType> DoubleNode<ItemType> *DoublyLinkedList<ItemType>::getTailPtr() const { return tail_; }
Shell
UTF-8
2,828
3.5
4
[ "MIT" ]
permissive
#!/bin/bash set -e input=$1 lowerInput=$(echo $input | tr "[A-Z]" "[a-z]") mkdir src/components/${input} mkdir src/components/${input}/__test__ mkdir src/components/${input}/stories touch src/components/${input}/index.ts touch src/components/${input}/${input}.tsx touch src/components/${input}/README.md touch src/components/${input}/__test__/index.test.tsx touch src/components/${input}/stories/${input}.stories.tsx touch src/components/${input}/stories/style.scss touch src/styles/${lowerInput}.scss # 导入${input}/${input}.tsx默认模块 echo "import * as React from 'react' import { Component } from 'react' import classNames from 'classnames' export interface ${input}Props { /** 类名 */ className?: string; /** 样式 */ style?: object; } /** * ${input} */ class ${input} extends Component<${input}Props, any> { render() { const { children, ...restProps } = this.props return ( <${input} {...restProps} > {children} </${input}> ) } } export default ${input}" >> src/components/${input}/${input}.tsx # 导入${input}/index.ts默认模块 echo "import ${input} from './${input}' export default ${input}" >> src/components/${input}/index.ts # 导入${input}/README.md默认模块 echo "Example \`\`\`jsx class Example extends React.Component { constructor (props) { super(props) this.state = {} } render () { return (<div className='${lowerInput}-box'> <${input}> test </${input}> <style> {\` .${lowerInput}-box { padding: 5px; } \`} </style> </div> ) } } <Example /> \`\`\`" >> src/components/${input}/README.md # 导入${input}/__test__/index.test.tsx默认模块 echo "import React from 'react' import { render, mount } from 'enzyme' import ${input} from '../index' describe('${input}', () => { test('renders correctly', () => { const wrapper = render( <${input}>Test</${input}> ) expect(wrapper).toMatchSnapshot() }) })" >> src/components/${input}/__test__/index.test.tsx # 导入${input}/stories/${input}.stories.tsx默认模块 echo "import * as React from 'react'; import { storiesOf } from '@storybook/react'; import ${input} from '../${input}'; import '../../../styles/index.scss'; import './style.scss'; storiesOf('${input}', module) .add( 'something', () => ( <div> <${input}> </${input}> </div> ) )" >> src/components/${input}/stories/${input}.stories.tsx echo -e "\033[32m \n新建组件成功: ${input}\n \033[0m" # 导入src/components/index.ts默认模块 echo "export { default as ${input} } from './${input}'" >> src/components/index.ts # 导入src/styles/index.ts默认模块 echo "@import './${lowerInput}.scss';" >> src/styles/index.scss
PHP
UTF-8
909
2.640625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace WayOfDev\RQL\Bridge\Cycle\Criteria; use Cycle\ORM\Select; use WayOfDev\RQL\Bridge\Cycle\Exceptions\ValidationException; use WayOfDev\RQL\Requests\Components\OrderBy as Order; use function preg_match; final class OrderBy implements CriteriaInterface { private const ALLOWED_TO_CONTAIN = '/^[a-z0-9\.\_\-]+$/i'; public function __construct(private ?Order $orderBy) { } /** * @throws ValidationException */ public function apply(Select $select): Select { if (null === $this->orderBy) { return $select; } if (! preg_match(self::ALLOWED_TO_CONTAIN, $this->orderBy->column())) { throw new ValidationException('OrderBy query parameter contains illegal characters.'); } return $select->orderBy($this->orderBy->column(), $this->orderBy->direction()->value); } }
Java
UTF-8
2,882
2.078125
2
[ "Apache-2.0" ]
permissive
/** * (C) Copyright IBM Corp. 2006, 2012 * * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT. * * You can obtain a current copy of the Eclipse Public License from * http://www.opensource.org/licenses/eclipse-1.0.php * * @author : Endre Bak, ebak@de.ibm.com * * Flag Date Prog Description * ------------------------------------------------------------------------------- * 1565892 2006-12-04 ebak Make SBLIM client JSR48 compliant * 1663270 2007-02-19 ebak Minor performance problems * 1660756 2007-02-22 ebak Embedded object support * 1720707 2007-05-17 ebak Conventional Node factory for CIM-XML SAX parser * 2003590 2008-06-30 blaschke-oss Change licensing from CPL to EPL * 2524131 2009-01-21 raman_arora Upgrade client to JDK 1.5 (Phase 1) * 2531371 2009-02-10 raman_arora Upgrade client to JDK 1.5 (Phase 2) * 3511454 2012-03-27 blaschke-oss SAX nodes not reinitialized properly */ package org.sblim.cimclient.internal.cimxml.sax.node; import java.util.ArrayList; import org.sblim.cimclient.internal.cimxml.sax.SAXSession; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * <pre> * ELEMENT EXPMETHODCALL (EXPPARAMVALUE*) * ATTLIST EXPMETHODCALL * %CIMName; * </pre> */ /** * Class ExpMethodCallNode is responsible for * */ public class ExpMethodCallNode extends Node implements NonVolatileIf { private String iName; private ArrayList<Node> iExpParamValNodeAList; /** * Ctor. */ public ExpMethodCallNode() { super(EXPMETHODCALL); } public void addChild(Node pChild) { if (this.iExpParamValNodeAList == null) this.iExpParamValNodeAList = new ArrayList<Node>(); this.iExpParamValNodeAList.add(pChild); } /** * @param pSession */ @Override public void init(Attributes pAttribs, SAXSession pSession) throws SAXException { this.iName = getCIMName(pAttribs); if (this.iExpParamValNodeAList != null) this.iExpParamValNodeAList.clear(); } /** * @param pData */ @Override public void parseData(String pData) { // no data } @Override public void testChild(String pNodeNameEnum) throws SAXException { if (pNodeNameEnum != EXPPARAMVALUE) throw new SAXException(getNodeName() + " node can have " + EXPPARAMVALUE + " child only! " + pNodeNameEnum + " is invalid!"); } /** * @param pChild */ @Override public void childParsed(Node pChild) { // nothing to do yet } @Override public void testCompletness() { // no mandatory child } /** * getName * * @return String */ public String getName() { return this.iName; } }
Java
UTF-8
17,681
1.671875
2
[]
no_license
package com.sourcetrace.eses.adapter.core; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.activation.DataHandler; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sourcetrace.eses.entity.Agent; import com.sourcetrace.eses.interceptor.ITxnErrorCodes; import com.sourcetrace.eses.order.entity.txn.CowFeedType; import com.sourcetrace.eses.order.entity.txn.CowInspection; import com.sourcetrace.eses.order.entity.txn.CowInspectionImages; import com.sourcetrace.eses.order.entity.txn.CowVaccination; import com.sourcetrace.eses.property.TransactionProperties; import com.sourcetrace.eses.property.TxnEnrollmentProperties; import com.sourcetrace.eses.service.IAgentService; import com.sourcetrace.eses.service.IFarmerService; import com.sourcetrace.eses.txn.adapter.ITxnAdapter; import com.sourcetrace.eses.txn.exception.SwitchException; import com.sourcetrace.eses.txn.schema.Collection; import com.sourcetrace.eses.txn.schema.Data; import com.sourcetrace.eses.txn.schema.Head; import com.sourcetrace.eses.util.CollectionUtil; import com.sourcetrace.eses.util.DateUtil; import com.sourcetrace.eses.util.ObjectUtil; import com.sourcetrace.eses.util.StringUtil; import com.sourcetrace.esesw.entity.profile.Cow; import com.sourcetrace.esesw.entity.profile.Farm; import com.sourcetrace.esesw.entity.profile.ResearchStation; import com.sourcetrace.esesw.excep.SwitchErrorCodes; @Component public class CowInspectionAdapter implements ITxnAdapter { private static final String EMPTY = "empty"; private static final String INVALID = "invalid"; @Autowired private IFarmerService farmerService; @Autowired private IAgentService agentService; private static final Logger LOGGER = Logger.getLogger(CowInspectionAdapter.class.getName()); @Override public Map<?, ?> process(Map<?, ?> reqData) { // TODO Auto-generated method stub LOGGER.info("----- Cow Inspection Starts -----"); Head head = (Head) reqData.get(TransactionProperties.HEAD); Map<String, String> errorCodes = new HashMap<String, String>(); CowInspection cowInspection=new CowInspection(); String elitType = (String) reqData.get(TxnEnrollmentProperties.ELITE_TYPE); if(!StringUtil.isEmpty(elitType) && elitType.equalsIgnoreCase(Cow.ELITE_RESEARCH)) { String researchStationId = (String) reqData.get(TxnEnrollmentProperties.RESEARCH_STATION_ID); validateEmptyString(researchStationId, ITxnErrorCodes.EMPTY_RESEARCH_STATION_ID); ResearchStation researchStation; try { researchStation = farmerService.findResearchStationId(researchStationId); } catch (Exception e) { e.printStackTrace(); LOGGER.info(e.getMessage()); throw new SwitchException(ITxnErrorCodes.INVALID_RESEARCH_STATION_ID); } validateEmptyObject(researchStation, ITxnErrorCodes.INVALID_RESEARCH_STATION_ID); cowInspection.setResearchStation(researchStation); } else { String farmerId = (String) reqData.get(TxnEnrollmentProperties.FARMER_ID); validateEmptyString(farmerId, ITxnErrorCodes.EMPTY_FARMER_ID); cowInspection.setFarmerId(farmerId); String farmCode = (String) reqData.get(TxnEnrollmentProperties.FARM_CODE); validateEmptyString(farmCode, SwitchErrorCodes.EMPTY_FARM_CODE); Farm farm = null; try { farm = farmerService.findFarmByCode(farmCode); } catch (Exception e) { e.printStackTrace(); LOGGER.info(e.getMessage()); throw new SwitchException(ITxnErrorCodes.INVALID_FARM); } validateEmptyObject(farm, ITxnErrorCodes.INVALID_FARM); cowInspection.setFarm(farm); } validateEmptyString(elitType, ITxnErrorCodes.ELITE_TYPE); cowInspection.setElitType(elitType); String cowId = (String) reqData.get(TxnEnrollmentProperties.COW_ID); validateEmptyString(cowId, ITxnErrorCodes.EMPTY_COW_ID); cowInspection.setCowId(cowId); String lastDate = (String) reqData.get(TxnEnrollmentProperties.INSPECTION_DATE); errorCodes.put(EMPTY, ITxnErrorCodes.EMPTY_INSPECTION_DATE); errorCodes.put(INVALID, ITxnErrorCodes.INVALID_INSPECTION_DATE); cowInspection.setLastInspDate(validateDate(lastDate, DateUtil.TXN_TIME_FORMAT,true, errorCodes)); String currentDate = (String) reqData.get(TxnEnrollmentProperties.CURRENT_DATE); errorCodes.put(EMPTY, ITxnErrorCodes.EMPTY_INSPECTION_DATE); errorCodes.put(INVALID, ITxnErrorCodes.INVALID_INSPECTION_DATE); cowInspection.setCurrentInspDate(validateDate(currentDate, DateUtil.TXN_TIME_FORMAT,true, errorCodes)); String intervalDays = (String) reqData.get(TxnEnrollmentProperties.INTERVAL_DAYS); String medicineName = (String) reqData.get(TxnEnrollmentProperties.MEDICINE_NAME); String milkMrngDay = (String) reqData.get(TxnEnrollmentProperties.MILK_MORNG_DAY); String inspectionNo = (String) reqData.get(TxnEnrollmentProperties.INSPECTION_NO); String milkEvngDay = (String) reqData.get(TxnEnrollmentProperties.MILK_EVNG_DAY); String totMilkDay = (String) reqData.get(TxnEnrollmentProperties.TOT_MILK_DAY); String totMilkPeriod = (String) reqData.get(TxnEnrollmentProperties.TOT_MILK_PERIOD); String feedType = (String) reqData.get(TxnEnrollmentProperties.FEED_TYPE); String amtFeedPeriod = (String) reqData.get(TxnEnrollmentProperties.AMT_FEED_PERIOD); String infesPara = (String) reqData.get(TxnEnrollmentProperties.INFES_PARASITES); String diseaseNotice = (String) reqData.get(TxnEnrollmentProperties.DISEASE_NOTICE); String diseaseName = (String) reqData.get(TxnEnrollmentProperties.DISEASE_NAME); String diseaseServices = (String) reqData.get(TxnEnrollmentProperties.DISEASE_SERVICES); String diseaseMedici = (String) reqData.get(TxnEnrollmentProperties.DISEASE_MEDICINE); String healthProbl = (String) reqData.get(TxnEnrollmentProperties.HEALTH_PROBLEM); String correctiveMeas = (String) reqData.get(TxnEnrollmentProperties.CORRECTIVE_MEASURE); String vaccinationPlace = (String) reqData.get(TxnEnrollmentProperties.VACCINATION_PLACE); String vaccinationDate = (String) reqData.get(TxnEnrollmentProperties.VACCINATION_DATE); String latitude = (String) reqData.get(TxnEnrollmentProperties.LATITUDE); String longitude = (String) reqData.get(TxnEnrollmentProperties.LONGITUDE); // String vaccinationName = (String) reqData.get(TxnEnrollmentProperties.VACCINATION_NAME); String comments = (String) reqData.get(TxnEnrollmentProperties.COMMENTS); String healthServi = (String) reqData.get(TxnEnrollmentProperties.HEALTH_SERVICES); String healthMedici = (String) reqData.get(TxnEnrollmentProperties.HEALTH_MEDICINES); String deworPlace = (String) reqData.get(TxnEnrollmentProperties.DEWORNMING_PLACE); String isMilkingCow=(String)reqData.get(TxnEnrollmentProperties.IS_MILKING_COW); cowInspection.setIntervalDays(!StringUtil.isEmpty(intervalDays)?Integer.valueOf(intervalDays):0); cowInspection.setMilkMorngPerday(!StringUtil.isEmpty(milkMrngDay)?Double.valueOf(milkMrngDay):0.0); cowInspection.setMilkEvngPerday(!StringUtil.isEmpty(milkEvngDay)?Double.valueOf(milkEvngDay):0.0); cowInspection.setTotalMilkPerDay(!StringUtil.isEmpty(totMilkDay)?Double.valueOf(totMilkDay):0.0); cowInspection.setTotalMilkPerPeriod(!StringUtil.isEmpty(totMilkPeriod)?Double.valueOf(totMilkPeriod):0.0); cowInspection.setInspectionNo(!StringUtil.isEmpty(milkMrngDay)?inspectionNo:""); String audioFile = (String) reqData.get(TxnEnrollmentProperties.AUDIO); byte[] voiceDataContent = null; try { if (audioFile != null && audioFile.length() > 0) { voiceDataContent = Base64.decodeBase64(audioFile.getBytes()); cowInspection.setAudio(voiceDataContent); } } catch (Exception e) { e.printStackTrace(); LOGGER.info(e.getMessage()); throw new SwitchException(ITxnErrorCodes.ERROR_WHILE_PROCESSING_COW_VOICE); } cowInspection.setCowVaccinations(getCowVaccination(vaccinationDate)); cowInspection.setDeworwingPlace(!StringUtil.isEmpty(deworPlace)?deworPlace:""); cowInspection.setMedicineName(!StringUtil.isEmpty(medicineName)?medicineName:""); cowInspection.setCowFeedTypes(getCowFeedType(amtFeedPeriod)); cowInspection.setFeedType(!StringUtil.isEmpty(feedType)?feedType:""); cowInspection.setInfestationPara(!StringUtil.isEmpty(infesPara)?infesPara:""); cowInspection.setDiseaseNoticed(!StringUtil.isEmpty(diseaseNotice)?diseaseNotice:""); cowInspection.setDiseaseName(!StringUtil.isEmpty(diseaseName)?diseaseName:""); cowInspection.setDiseaseServices(!StringUtil.isEmpty(diseaseServices)?diseaseServices:""); cowInspection.setDiseaseMedicines(!StringUtil.isEmpty(diseaseMedici)?diseaseMedici:""); cowInspection.setHealthProblem(!StringUtil.isEmpty(healthProbl)?healthProbl:""); cowInspection.setCorrectivMeasure(!StringUtil.isEmpty(correctiveMeas)?correctiveMeas:""); cowInspection.setVaccinationPlace(!StringUtil.isEmpty(vaccinationPlace)?vaccinationPlace:""); // cowInspection.setVaccinationDate(!StringUtil.isEmpty(vaccinationDate)?DateUtil.convertStringToDate(vaccinationDate, DateUtil.TXN_TIME_FORMAT):null); // cowInspection.setVaccinationName(!StringUtil.isEmpty(vaccinationName)?vaccinationName:""); cowInspection.setComments(!StringUtil.isEmpty(comments)?comments:""); cowInspection.setHealthServices(!StringUtil.isEmpty(healthServi)?healthServi:""); cowInspection.setHealthMedicines(!StringUtil.isEmpty(healthMedici)?healthMedici:""); cowInspection.setInspectionImages(getInspectionImages(reqData)); cowInspection.setIsMilkingCow(isMilkingCow); cowInspection.setLatitude(latitude); cowInspection.setLongitude(longitude); Agent agent = agentService.findAgentByAgentId(head.getAgentId()); if (!ObjectUtil.isEmpty(agent)) { cowInspection.setCreatedUserName(head.getAgentId()); cowInspection.setLastUpdatedUserName(head.getAgentId()); } cowInspection.setBranchId(!StringUtil.isEmpty(head.getBranchId())?head.getBranchId():""); if(!ObjectUtil.isEmpty(cowInspection.getFarm())) { farmerService.updateFarmerRevisionNo(cowInspection.getFarm().getFarmer().getId(), DateUtil.getRevisionNumber()); } else if(!ObjectUtil.isEmpty(cowInspection.getResearchStation())) { farmerService.updateResearchStatRevisionNo(cowInspection.getResearchStation().getId(),DateUtil.getRevisionNumber()); } farmerService.addCowInspection(cowInspection); return null; } private Set<CowFeedType> getCowFeedType(String feedValues) { Set<CowFeedType> cowFeedTypeSet = new HashSet<CowFeedType>(); //Set<CultivationDetail> cultivationDetailsSet = new HashSet<CultivationDetail>(); if(!StringUtil.isEmpty(feedValues)) { List<String> costSeperator = Arrays.asList(feedValues.split("\\,")); for (String seperatedString : costSeperator) { CowFeedType CowSeedType = new CowFeedType(); String[] values = seperatedString.split(":"); CowSeedType.setFeedType(values[0]); CowSeedType.setAmount(Double.valueOf(values[1])); cowFeedTypeSet.add(CowSeedType); } } return cowFeedTypeSet; } private Set<CowVaccination> getCowVaccination(String vaccination) { Set<CowVaccination> cowVaccinSet = new HashSet<CowVaccination>(); //Set<CultivationDetail> cultivationDetailsSet = new HashSet<CultivationDetail>(); if(!StringUtil.isEmpty(vaccination)) { List<String> costSeperator = Arrays.asList(vaccination.split("\\,")); for (String seperatedString : costSeperator) { CowVaccination cowVaccination = new CowVaccination(); String[] values = seperatedString.split(":"); cowVaccination.setName(values[0]); cowVaccination.setDate(DateUtil.convertStringToDate(values[1], DateUtil.FARMER_DOB)); cowVaccinSet.add(cowVaccination); } } return cowVaccinSet; } public Set<CowInspectionImages> getInspectionImages(Map reqData) { Set<CowInspectionImages> inspectionImageSet = new HashSet<CowInspectionImages>(); Collection photoCollection = (Collection) reqData .get(TxnEnrollmentProperties.PHOTO_LIST); if (!CollectionUtil.isCollectionEmpty(photoCollection)) { List<com.sourcetrace.eses.txn.schema.Object> photoDataObject = photoCollection .getObject(); for (com.sourcetrace.eses.txn.schema.Object object : photoDataObject) { List<Data> photoDatas = object.getData(); CowInspectionImages inspectionImage = new CowInspectionImages(); byte[] imageContent = null; for (Data data : photoDatas) { String key = data.getKey(); String value = (String) data.getValue(); if (TxnEnrollmentProperties.PHOTO.equalsIgnoreCase(key)) { DataHandler photo = data.getBinaryValue(); try { if (photo != null && photo.getInputStream().available() > 0) { imageContent = IOUtils.toByteArray(photo.getInputStream()); inspectionImage.setPhoto(imageContent); } } catch (Exception e) { e.printStackTrace(); throw new SwitchException(ITxnErrorCodes.ERR0R_WHILE_PROCESSING); } } // Photo Capture Time if (TxnEnrollmentProperties.PHOTO_CAPTURE_TIME.equalsIgnoreCase(key)) { if (!StringUtil.isEmpty(value) && !value.equals("0")) { try { Date photoCaptureDate = DateUtil.convertStringToDate(value, DateUtil.TXN_TIME_FORMAT); inspectionImage.setCaptureTime(photoCaptureDate); } catch (Exception e) { e.printStackTrace(); throw new SwitchException(ITxnErrorCodes.DATE_CONVERSION_ERROR); } } } // Photo Capture Latitude if (TxnEnrollmentProperties.PHOTO_LATITUDE.equalsIgnoreCase(key)) if(!StringUtil.isEmpty(inspectionImage.getLatitude())){ inspectionImage.setLatitude(value); }else{ inspectionImage.setLatitude("0"); } // Photo Capture Longitude if (TxnEnrollmentProperties.PHOTO_LONGITUDE.equalsIgnoreCase(key)) if(!StringUtil.isEmpty(inspectionImage.getLongitude())){ inspectionImage.setLongitude(value); }else{ inspectionImage.setLongitude("0"); } } inspectionImageSet.add(inspectionImage); } } return inspectionImageSet; } private void validateEmptyString(String input, String errorCode) { if (StringUtil.isEmpty(input)) throw new SwitchException(errorCode); } private Date validateDate(String dateString, String format, boolean isMandatory, Map<String, String> errorCodes) { if (isMandatory) { if (StringUtil.isEmpty(dateString)) throw new SwitchException(errorCodes.get(EMPTY)); } else { if (StringUtil.isEmpty(dateString)) return null; } try { return DateUtil.convertStringToDate(dateString.trim(), format); } catch (Exception e) { e.printStackTrace(); LOGGER.info(e.getMessage()); throw new SwitchException(errorCodes.get(INVALID)); } } /** * Validate empty object. * @param input * @param errorCode */ private void validateEmptyObject(Object input, String errorCode) { if (ObjectUtil.isEmpty(input)) throw new SwitchException(errorCode); } @Override public Map<?, ?> processVoid(Map<?, ?> reqData) { // TODO Auto-generated method stub return null; } }
Java
UTF-8
4,235
1.976563
2
[]
no_license
package cn.com.infosec.netseal.webserver.controller.monitor; import java.lang.management.MemoryUsage; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.hyperic.sigar.SigarException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONObject; import cn.com.infosec.netseal.common.define.Constants; import cn.com.infosec.netseal.common.manager.JmxManager; import cn.com.infosec.netseal.webserver.util.SigarUtil; @RequestMapping(value = "/monitor") @Controller public class MonitorController { @Autowired private HttpServletRequest request; /** * 跳转monitorSystem * * @throws Exception */ @RequestMapping("/monitorSystem") public String toMonitorSystem() throws Exception { return "monitor/monitorSystem"; } /** * system 数据请求 * * @return * @throws SigarException */ @ResponseBody @RequestMapping("/monitorDataSystem") public ModelAndView monitorDataSystem() throws Exception { return SigarUtil.getInstance().getSystemData(); } /** * 跳转monitorApp */ @RequestMapping("/monitorApp") public String toMonitorApp() { return "monitor/monitorApp"; } @ResponseBody @RequestMapping("/MonitorDataAPP") public String MonitorDataAPP() throws Exception { Object SocketNum = JmxManager.getInstance().getAttribute(Constants.JMX_INFOSEC_OBJ_NAME, "SocketNum"); Object PoolingC = JmxManager.getInstance().getAttribute(Constants.JMX_DRUID_OBJ_NAME, "PoolingCount"); Object PoolingPeak = JmxManager.getInstance().getAttribute(Constants.JMX_DRUID_OBJ_NAME, "PoolingPeak"); Object PoolingPeakTime = JmxManager.getInstance().getAttribute(Constants.JMX_DRUID_OBJ_NAME, "PoolingPeakTime"); Object ActiveC = JmxManager.getInstance().getAttribute(Constants.JMX_DRUID_OBJ_NAME, "ActiveCount"); MemoryUsage heapMemoryUsage = JmxManager.getInstance().getCompositeAttribute(Constants.JMX_MEMORY_OBJ_NAME, "HeapMemoryUsage"); MemoryUsage nonheapMemoryUsage = JmxManager.getInstance().getCompositeAttribute(Constants.JMX_MEMORY_OBJ_NAME, "NonHeapMemoryUsage"); long heapMax = heapMemoryUsage.getMax() / 1024 / 1024; long heapUsed = heapMemoryUsage.getUsed() / 1024 / 1024; long stackUsed = nonheapMemoryUsage.getUsed() / 1024 / 1024; String dt = PoolingPeakTime.toString(); SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String timedate = sdf2.format(sdf1.parse(dt)); String systime = sdf2.format(new Date(System.currentTimeMillis())); JSONObject json = new JSONObject(); json.put("SocketNum", SocketNum.toString()); json.put("PoolingC", PoolingC.toString()); json.put("PoolingPeak", PoolingPeak.toString()); json.put("PoolingPeakTime", timedate); json.put("ActiveC", ActiveC.toString()); json.put("systime", systime); json.put("heapMax", heapMax); json.put("heapUsed", heapUsed); json.put("stackUsed", stackUsed); return json.toString(); } /** * 跳转monitorBusiness */ @RequestMapping("/monitorBusiness") public String toMonitorBusiness() { return "monitor/monitorBusiness"; } @ResponseBody @RequestMapping("/monitorDataBusn") public String monitorDataBusn() throws Exception { Object dealSucc = JmxManager.getInstance().getAttribute(Constants.JMX_INFOSEC_OBJ_NAME, "DealSuccNum"); Object dealFail = JmxManager.getInstance().getAttribute(Constants.JMX_INFOSEC_OBJ_NAME, "DealFailNum"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String systime = sdf2.format(new Date(System.currentTimeMillis())); JSONObject json = new JSONObject(); json.put("dealSucc", dealSucc.toString()); json.put("dealFail", dealFail.toString()); json.put("systime", systime); return json.toString(); } }
Shell
UTF-8
1,556
3.71875
4
[ "MIT", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-free-unknown" ]
permissive
#!/bin/sh . ./trace.sh notify_web() { trace "Entering notify_web()..." local url=${1} local tor=${3} # Let's encode the body to base64 so we won't have to escape the special chars... local body=$(echo "${2}" | base64 | tr -d '\n') local returncode local response local http_code local curl_code local msg if [ -n "${tor}" ]; then msg="{\"response-topic\":\"response/$$\",\"cmd\":\"web\",\"url\":\"${url}\",\"body\":\"${body}\",\"tor\":${tor}}" else msg="{\"response-topic\":\"response/$$\",\"cmd\":\"web\",\"url\":\"${url}\",\"body\":\"${body}\"}" fi # We use the pid as the response-topic, so there's no conflict in responses. trace "[notify_web] mosquitto_rr -h broker -W 21 -t notifier -e \"response/$$\" -m \"${msg}\"" response=$(mosquitto_rr -h broker -W 21 -t notifier -e "response/$$" -m ${msg}) returncode=$? trace_rc ${returncode} # The response looks like this: {"curl_code":0,"http_code":200,"body":"..."} where the body # is the base64(response body) but we don't need the response content here. trace "[notify_web] response=${response}" curl_code=$(echo "${response}" | jq -r ".curl_code") trace "[notify_web] curl_code=${curl_code}" http_code=$(echo "${response}" | jq -r ".http_code") trace "[notify_web] http_code=${http_code}" echo "${response}" if [ "${curl_code}" -eq "0" ] && [ "${returncode}" -eq "0" ]; then if [ "${http_code}" -lt "400" ]; then return 0 else return ${http_code} fi else return ${curl_code} || ${returncode} fi }
Ruby
UTF-8
1,981
3.484375
3
[]
no_license
#!/usr/bin/env ruby # Requires Ruby 1.9 and "gnuplot" gem require 'gnuplot' X0 = 0.0 XN = 0.4 Y0 = 2.0 # the differential equation definition # f(x, y) = dy / dx def f(x, y); (1.0 + y * y) / (1.0 + x * x); end # the analytic solution of the differential equation def y(x); Math.tan(Math.atan(x) + Math.atan(2)); end class Approximator attr_reader :x, :y def initialize(x0, y0, h, &f) @x = x0.to_f @y = y0.to_f @h = h.to_f @f = f end end class Euler < Approximator def next return @y0 = @y unless @y0 @y += @h * @f.call(@x, @y) @x += @h @y end end class RungeKutta < Approximator def next return @y0 = @y unless @y0 k1 = @h * @f.call(@x, @y) k2 = @h * @f.call(@x + @h / 2, @y + k1 / 2) k3 = @h * @f.call(@x + @h / 2, @y + k2 / 2) k4 = @h * @f.call(@x + @h, @y + k3) @y += (k1 + k4 + 2 * (k2 + k3)) / 6 @x += @h @y end end Gnuplot.open do |gp| Gnuplot::Plot.new(gp) do |plot| plot.title 'Approximation of Differential Equations' plot.ylabel 'log E' plot.xlabel 'log h' plot.key 'bottom right' plot.size 'ratio 1' plot.logscale 'xy' euler_error = [] runge_kutta_error = [] hs = [] (1..3).step(0.1) do |exponent| h = 10 ** (-exponent) euler = Euler.new(X0, Y0, h) { |x, y| f(x, y) } runge_kutta = RungeKutta.new(X0, Y0, h) { |x, y| f(x, y) } # the x progresses at the same speed, so we can use the same loop while euler.x + h <= XN runge_kutta.next euler.next end hs << h euler_error << (y(euler.x) - euler.y).abs runge_kutta_error << (y(runge_kutta.x) - runge_kutta.y).abs end plot.data << Gnuplot::DataSet.new([hs, euler_error]) do |ds| ds.with = "linespoints" ds.title = "Euler Method" end plot.data << Gnuplot::DataSet.new([hs, runge_kutta_error]) do |ds| ds.with = "linespoints" ds.title = "Runge-Kutta Method" end end end
Markdown
UTF-8
1,684
2.8125
3
[]
no_license
# General information Name: Nguyễn Đăng Huỳnh Long \ Student ID: 18127136 \ Deployed: https://nguyendonghuynhlang26123.github.io/classroom-frontend/ \ [![deployed](https://github.com/nguyendonghuynhlang26123/classroom-frontend/actions/workflows/deploy.yml/badge.svg)](https://github.com/nguyendonghuynhlang26123/classroom-frontend/actions/workflows/deploy.yml) # Project information - This project is the homework#03 for Course: Advanced Web Application Development - This project is built using [ReactJS](https://reactjs.org/docs/hooks-reference.html) & [Typescript](https://www.typescriptlang.org/) and [Github action](https://github.com/features/actions) to automatically deploy project. - Library uses: [Formik](https://formik.org/), [Axios](https://axios-http.com/docs/instance), using [React Material UI library](https://mui.com/) ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `yarn build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn deploy` Builds the app for production to the `build` folder.\ Then deploy it to github pages See [gh-pages](https://www.npmjs.com/package/gh-pages) for more information.
Ruby
UTF-8
764
2.53125
3
[ "MIT" ]
permissive
require_relative 'table' module DbDumper class QueryBuilder # Wrapper under ActiveRecord::Relation class Query attr_reader :table, :ar def initialize(raw_table, exist_ar = nil) @table = Table.from(raw_table) @ar = exist_ar || table.ar.all end def where(*args) self.class.new(table, ar.where(*args)) end def joins(*args) raise 'Only simple string for joins supported' unless args.size == 1 && args[0].is_a?(String) self.class.new(table, ar.joins(*args)) end def select(*args) self.class.new(table, ar.select(*args)) end def table_name table.table_name end def to_sql @ar.to_sql end end end end
Java
UTF-8
993
3.453125
3
[]
no_license
package com.interview; import java.util.ArrayList; import java.util.List; public class Board<T> { List<List<T>> grid = new ArrayList<>(); public List<List<T>> getGrid() { return this.grid; } public void updateGrid(Location location, T currentPlayer) { this.grid.get(location.getI()).set(location.getJ(), currentPlayer); } public void printBoard() { for (int i = 0; i < this.getGrid().size(); i++) { for (int j = 0; j < this.getGrid().get(0).size(); j++) { System.out.print(this.grid.get(i).get(j) + " "); } System.out.println(); } } public void setup(int horizontalLimit, int verticalLimit, T defaultValue) { for (int i = 0; i < horizontalLimit; i++) { List<T> group = new ArrayList<>(); for (int j = 0; j < verticalLimit; j++) { group.add(defaultValue); } this.grid.add(group); } } }
Markdown
UTF-8
2,586
2.671875
3
[]
no_license
--- title: "Scripting Open Excel Sheets in Separate Windows" date: 2018-08-07T20:42:51-04:00 draft: false categories: [] tags: [archive] author: "Josh Rickard" --- If you work in an environment similar to my previous position, then you would know how often you hear certain complaints after upgrading people to new applications or Operating Systems. Well one of those complaints came from individuals that we upgraded to Office 2010. They were use to the option of opening up Excel Spreadsheets in separate windows, but in Office 2010 you can't do this by default you have to make a few tweaks. My fix was to create a little Batch script that would alter the Registry and allow this to be done. I hope you enjoy..... <blockquote>Open Excel Sheets in Separate Windows <code> cd %~dp0 echo off cls </code><code> ECHO ***** This batch script is not working. Please double-click on the REG ECHO files themselves and answer Yes to pop-ups to manually set the new entries. ECHO Click the [X ] in the top-right corner to Exit. </code><code> pause </code><code> ECHO Close Excel if running... NO reboot is required by this script. ECHO Pressing (Space) or another key will CHANGE Excel 2010 to open ECHO files in separate windows. If you do NOT want this, click the close ECHO [X ] in the top-right Corner to close this window now. ECHO Press [Space } to continue and answer YES to any pop up messages... </code><code> Pause </code><code> regedit /s "del_HK_classes_root-excelsheet8-shell-open.reg" regedit /s "hk-classes_root-excelsheet8_shell_open-newwinhack.reg" regedit /s "del_HK_classes_root-excelsheet12-shell-open.reg" regedit /s "hk-classes_root-excelsheet12_shell_open-newwinhack.reg" </code><code> pause </code><code> cls </code><code> ECHO Excel 2010 will now open files in separate windows. If this IS what ECHO you want, click the [X ] in top-right corner to close this window now. ECHO Pressing (space) or other keys will RESET Excel 2010 to its original ECHO single-window mode. ECHO Answer YES to any pop up messages... </code><code> Pause </code><code> regedit /s "del_HK_classes_root-excelsheet8-shell-open.reg" regedit /s "hk-classes_root-excelsheet8_shell_open-original.reg" regedit /s "del_HK_classes_root-excelsheet12-shell-open.reg" regedit /s "hk-classes_root-excelsheet12_shell_open-original.reg" </code><code> exit </code></blockquote> <a href="http://msadministrator.files.wordpress.com/2012/10/registry-entries-multi-window-excel-sheet.docx">Registry Entries - Multi Window Excel Sheet</a>
Python
UTF-8
1,513
3.171875
3
[]
no_license
''' Created on Nov 12, 2012 @author: Ted Carancho ''' import xml.etree.ElementTree as ET xml = ET.parse('xmlTest.xml') # Get individual settings print(xml.find("./Settings/DefaultComPort").text) print(float(xml.find("./Settings/BootUpDelay").text)) print(float(xml.find("./Settings/CommTimeOut").text)) # Get all subpanel names subPanelNames = xml.findall("./Subpanels/Subpanel") for subPanelName in subPanelNames: print(subPanelName.get("Name")) #G Get individual subpanel name print(subPanelNames[0].get("Name")) # Get individual subpanel values subPanelName="Serial Monitor" subPanelValue="Path" xpath="./Subpanels/Subpanel/[@Name='" + subPanelName +"']/" + subPanelValue print(xml.find(xpath).text) """ root = tree.getroot() # Setup xml objects subpanelRoot = root.find('Subpanels') subpanelList = subpanelRoot.findall('Subpanel') # Create list of subpanel names for menu subpanelNames = [individualPanel.get('Name') for individualPanel in subpanelList] # When user selects subpanel name, lookup subpanel index to access path and class selectedPanel = "Serial Monitor" #selectedPanel = "Template" subpanelIndex = subpanelNames.index(selectedPanel) subpanel = subpanelList[subpanelIndex] print(subpanel.find('Path').text) print(subpanel.find('Class').text) """ ''' settings = root.find('Settings') print(settings.find('DefaultComPort').text) print(float(settings.find("BootUpDelay").text)) print(float(settings.find('CommTimeOut').text)) '''
Python
UTF-8
2,013
2.9375
3
[ "MIT" ]
permissive
from bs4 import BeautifulSoup import requests import json def getHTML(url): response = requests.get(url) return BeautifulSoup(response.content,'html.parser') def parsePersons(persons): names = [] if isinstance(persons,dict): names.append(persons['name']) return names for person in persons: if person['@type'] == "Person": names.append(person['name']) return names def getJSON(html): data = {} data['id'] = html.find(attrs={'property':'pageId'})['content'] data['url'] = 'https://www.imdb.com/title/'+data['id'] html_json = html.find(attrs={'type':'application/ld+json'}).text.strip() fetchedJson = json.loads(html_json) data['poster'] = html.find(attrs={'class':'poster'}).find('img')['src'] title_wrapper = html.find(attrs={'class':'title_wrapper'}).text.strip() data['title'] = title_wrapper[:title_wrapper.find(')')+1] data['rating'] = html.find(itemprop='ratingValue').text data['bestRating'] = html.find(itemprop='bestRating').text data['votes'] = html.find(itemprop='ratingCount').text data['rated'] = fetchedJson['contentRating'] data['genres'] = fetchedJson['genre'] data['description'] = fetchedJson['description'] data['cast'] = parsePersons(fetchedJson['actor']) data['writers'] = parsePersons(fetchedJson['creator']) data['directors'] = parsePersons(fetchedJson['director']) json_data = json.dumps(data) return json_data def getURL(input): try: if input[0] == 't' and input[1] == 't': html = getHTML('https://www.imdb.com/title/'+input+'/') else: html = getHTML('https://www.google.co.in/search?q='+input) for cite in html.findAll('cite'): if 'imdb.com/title/tt' in cite.text: html = getHTML(cite.text) break return getJSON(html) except Exception as e: print(e) return 'Invalid input or Network Error!'
PHP
UTF-8
824
3.171875
3
[]
no_license
<?php namespace Tnq\Services; class StringService { public function sort_alphabet($sentence) { $utfSentence = mb_convert_encoding($sentence, 'UTF-8', 'auto'); $strings = explode(' ', $utfSentence); $alphaStrings = []; foreach ($strings as $key => $string) { $stringParts = $this->utf8_str_split(mb_convert_encoding($string, 'UTF-8', 'auto')); sort($stringParts); $alphaString = implode('', $stringParts); $alphaStrings[] = $alphaString; } return implode(' ', $alphaStrings); } private function utf8_str_split($str, $split_len=1) { if (!preg_match('/^[0-9]+$/', $split_len) || $split_len < 1) return false; $len = strlen($str); if($len <= $split_len) return array($str); preg_match_all('/.{'.$split_len.'}|[^\x00]{1,'.$split_len.'}$/us', $str, $ar); return $ar[0]; } }
Java
UTF-8
308
2.40625
2
[]
no_license
package cn.com.song.design.pattern.command; /** * @author songchengjun * @date 2018/1/12 17:18 */ public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void action() { this.command.execute(); } }
JavaScript
UTF-8
574
3.890625
4
[ "MIT" ]
permissive
/* Description: Given a string of integers, return the number of odd-numbered substrings that can be formed. For example, in the case of "1341", they are 1, 1, 3, 13, 41, 341, 1341, a total of 7 numbers. solve("1341") = 7. See test cases for more examples. Good luck! */ const BigNumber = require("bignumber.js"); function solve(s) { let arr = []; for (let i = 0; i <= s.length; i++) { for (let j = i + 1; j <= s.length; j++) { let x = new BigNumber(s.slice(i, j)); if (x.modulo(2) * 1 === 1) arr.push(s.slice(i, j)); } } return arr.length; }
Markdown
UTF-8
5,898
3.4375
3
[]
no_license
# Virtual Machine Setup If you are not running a UNIX system like Mac OS or Linux natively, it is useful to configure a virtual machine for development purposes. This allows for a consistent environment between development and deployment, making configuring and testing simpler and more reliable. This guide will explain how to configure a virtual machine (with Linux Mint 17.3 as an example) using VirtualBox. ## Create Virtual Machine For more information on VirtualBox, see the [documentation](https://www.virtualbox.org/manual/UserManual.html). * Download VirtualBox for your current operating system (your "host machine") from [here](https://www.virtualbox.org/wiki/Downloads). * Run the installer and launch VirtualBox * Click `New` to create a new virtual machine (The following instructions contain some steps that are specific to Linux Mint. If you would like to use another Linux distribution, you can, but other guides may not contain applicable instructions.) * fill in the fields in the "Name and operating system" dialog: * Name: Linux Mint * Type: Linux * Version: Other Linux (32 or 64 bit depending on your current machine) * Click `Next` * Set the memory size appropriately. I recommend using about 1/4 of your total available RAM. * ex. allocate 4GB (4096MB) for a computer with 16GB of RAM * Click `Next` (You can deviate here if you know what you are doing) * On the "Hard disk" dialog, choose: Create a virtual hard disk now. Click `Create`. * Choose "VDI". Click `Next`. * Create a "Fixed size" hard disk, which will allocate a fixed amount of storage to the virtual hard drive. This will take slightly longer to create, but will allow for a more responsive environment. Select "Fixed size", click `Next` * In the "File location and size" dialog: * leave the name and location as default. This will create a folder inside the `VirtualBox VMs` directory with a name matching the virtual machine's name specified at the beginning * set the size to at least 20GB (we need room for the Operating System, as well as some programs and files). I set mine to 50GB to be safe. It absolutely must be bigger than 10GB, or Linux Mint will not install. ## Boot Linux Mint * Download [Linux Mint](http://www.linuxmint.com/download.php). There are a few different desktop options. If you don't know which one to pick, choose Cinnamon for either 32 or 64 bit, depending on your host machine. * In VirtualBox, click on the newly created virtual machine, and select `Start`, or double-click on the machine. * In the start-up disk dialog, navigate to the `.iso` file you just downloaded for Linux Mint, and click `Start` * Once the Desktop boots up, double-click on the CD icon that says "Install Linux Mint" * Choose your language * You will now see a health check for the installation. As long as you have enough available memory, your computer is plugged in, and you have an internet connection, you will be all set. Click `Next`. * On the "Installation type" dialog, choose "Something else". Don't choose another option unless you know what you are doing. Click `Install Now`. ### Create Partitions * Click `New Partition Table...` * It will warn you that you are partitioning an entire device. We are just partitioning the virtual hard disk, so this is fine. Click `Continue`. * A "free space" partition should show up in the window. Click on it, and now the "+" button should be clickable at the button of the window. Click "+". * First we will create the swap memory, which is memory that is allocated for use with the RAM is full. Use these parameters; * Size: 1.5 x RAM (ie. for 4GB RAM, set this to 6000MB (~6GB)) * Type: Logical * Location: Beginning of this space * Use as: swap area * Click `OK` * You'll see the new partition show up in the window * Click on the "free space" partition, click "+" to add another partition. * Next we will create the "root" partition, where the OS will be mounted and programs will be installed. If you are just using this for development, you shouldn't need much room for programs. Use these parameters: * Size: 12000MB (~12GB). * Type: Primary * Location: Beginning of this space * Use as: Ext4 journaling file system * Mount point: / * Click `OK` * You'll see the new partition show up in the window * Click on the "free space" partition, click "+" to add another partition. * Lastly, we will create the home partition with the remaining free space, which will contain all personal files. Use these parameters: * Size: Leave this as is, it should be equal to the amount of free space remaining * Type: Logical * Location: Beginning of this space * Use as: Ext4 journaling file system * Mount point: /home * Click `OK` * You'll see the new partition show up in the window * Make sure the "Device for boot loader installation" is set to `/dev/sda ATA VBOX HARDDISK (xx.x GB)` * Click `Install Now` * In the confirmation dialog, click `Continue` * Choose your location, click `Continue` * Choose your keyboard layout, click `Continue`* Choose your location, click `Continue` * Fill out the "Who are you?" page however you'd like. Click `Continue` when done. * The installation will begin. Wait until it is complete. Click `Restart Now` when prompted. * (You may need to press ENTER when prompted for the machine to boot back up) * Once the boot is complete, you should see the welcome screen and now the virtual machine is up and running on Linux Mint! * The `.iso` file that you originally booted from can be deleted now that the Operating System has been installed onto the virtual hard drive. ## Additional Configuration If you would like to configure the virtual machine in more detail, see the official [configuration documentation](https://www.virtualbox.org/manual/ch03.html). ## Next Steps See `LINUX_CONFIGURATION.md` to configure your Linux system for development.
Python
UTF-8
770
3.40625
3
[ "MIT" ]
permissive
"""an example of a more intense pytest""" import pytest from wallet import Wallet, InsufficientAmount def test_default_initial_amount(): """Testing balance is zero""" wallet = Wallet() assert wallet.balance == 0 def test_setting_initial_amount(): """Testing constructor initial balance""" wallet = Wallet(100) assert wallet.balance == 100 def test_wallet_add_cash(): """Testing add_cash method in wallet object""" wallet = Wallet(10) wallet.add_cash(90) assert wallet.balance == 100 def test_wallet_spend_cash_raises_exception_on_insufficient_amount(): """Test proper exception is raised when spend cash exceed balance""" wallet = Wallet() with pytest.raises(InsufficientAmount): wallet.spend_cash(100)
JavaScript
UTF-8
3,233
2.578125
3
[]
no_license
import React, { useState, useEffect } from 'react'; import CustomerService from '../services/CustomerService'; const CreateHook = (props) => { const [name, setName] = useState(''); const [address, setAddress] = useState(''); const [email, setEmail] = useState(''); const id = props.match.params.id; useEffect(() => { if (id == -1) { return; } CustomerService.getCustomerById(id).then((res) => { let cust = res.data; setName(cust.name); setAddress(cust.address); setEmail(cust.email); }) }, []) const changeNameHandler = (event) => { setName(event.target.value); } const changeAddressHandler = (event) => { setAddress(event.target.value); } const changeEmailHandler = (event) => { setEmail(event.target.value); } const saveCustomer = (event) => { event.preventDefault(); let cust = { name: name, address: address, email: email }; if (id < 0) { CustomerService.createCustomer(cust).then(res => { props.history.push('/customers'); }) } else { CustomerService.updateCustomer(cust, id).then(res => { props.history.push('/customers'); }) } } const cancel = () => { props.history.push('/customers'); } const pageTitle = () => { if (id < 0) { return "Add Customer"; } else { return "Update Customer"; } } return ( <div className="container"> <div className="row"> <div className="card col-md-6 offset-md-3"> <h3 class="text-center"> {pageTitle()}</h3> <div className="card-body"> <form> <div className="form-group"> <label> Name</label> <input name="name" placeholder=" Customers Name" className="form-control" value={name} onChange={changeNameHandler} /> </div> <div className="form-group"> <label>Address</label> <input name="address" placeholder="Address" className="form-control" value={address} onChange={changeAddressHandler} /> </div> <div className="form-group"> <label>Email</label> <input name="email" placeholder="Email" className="form-control" value={email} onChange={changeEmailHandler} /> </div> <button className="btn btn-success" onClick={saveCustomer}>Save</button> <button className="btn btn-success" onClick={cancel} style={{ marginLeft: "10px" }}>Cancel</button> </form> </div> </div> </div> </div> ) } export default CreateHook
C++
UTF-8
1,328
3.515625
4
[]
no_license
#ifndef STACK_H #define STACK_H #include <iostream> // Стек на массиве using namespace std; template <class Node> class stack { private: int size; Node *data; public: stack(); stack(const stack &obj); ~stack(); void push(Node data); Node pop(); Node top(); int get_size(); }; template <class Node> stack <Node>::stack() { size = 0; data = 0; } // Конструктор копирования template <class Node> stack<Node>::stack(const stack & obj) { this->size = obj.size; Node *data = new Node[size]; for (int i = 0; i < size; i++) this->data[i] = obj->data[i]; } template <class Node> stack<Node>::~stack() { delete[]data; } template <class Node> void stack<Node>::push(Node newdata) { Node *arr = new Node[++size]; arr[0] = newdata; for (int i = 1; i < size; i++)arr[i] = data[i-1]; delete[] data; data = arr; } template <class Node> Node stack<Node>::pop() { if (data && (size > 0)) { Node tmp = data[0]; Node *arr = new Node[--size]; for (int i = 0; i < size; i++) arr[i] = data[i + 1]; delete[]data; data = arr; return tmp; } else return 0; } template <class Node> int stack<Node>::get_size() { return (size); } template <class Node> Node stack<Node>::top() { if (data) return (*data); } #endif
JavaScript
UTF-8
1,450
2.703125
3
[]
no_license
const timeZone = document.getElementById("timezoneInfo") timeZone.innerText = Intl.DateTimeFormat().resolvedOptions().timeZone const time = document.getElementById("time") const weatherImg = document.getElementById("weatherImg") const weatherList = { Default:"img/clear_sky.jpg", Clouds:{ few_clouds: "img/clear_sky.jpg", default:"img/clear_sky.jpg"}, Clear:{ clear_sky:"img/clear_sky.jpg", default: "img/clear_sky.jpg"} } setInterval(() => { let date = new Date time.innerText = date.toLocaleTimeString() },1000) setInterval(() => { checkWeather() },60000) function checkWeatherImg() { if(weatherList[weather.main]) { if(weatherList[weather.main][weather.description]) { const img = weatherList[weather.main][weather.description] weatherImg.style.backgroundImage = `linear-gradient(to bottom, rgba(255,255,255,0) 50%, rgba(255,255,255,1)), url(${img})` } else {const img = weatherList[weather.main].default weatherImg.style.backgroundImage = `linear-gradient(to bottom, rgba(255,255,255,0) 50%, rgba(255,255,255,1)), url(${img})` } } else { const img = weatherList.Default weatherImg.style.backgroundImage = `linear-gradient(to bottom, rgba(255,255,255,0) 50%, rgba(255,255,255,1)), url(${img})`} }
C++
UTF-8
2,233
2.796875
3
[]
no_license
#include "stdafx.h" #include "Engine\Debugging\CommandLineParameters.h" namespace ENGINE_NAMESPACE { CommandLineParameters * CommandLineParameters::ourInstance = nullptr; CommandLineParameters::CommandLineParameters() { } CommandLineParameters::~CommandLineParameters() { } void CommandLineParameters::CreateInstance() { if (ourInstance != nullptr) { Error("Already created"); } ourInstance = new CommandLineParameters(); } CommandLineParameters & CommandLineParameters::GetInstance() { if (ourInstance == nullptr) { Error("Not created"); } return *ourInstance; } void CommandLineParameters::DestroyInstance() { if (ourInstance == nullptr) { Error("Not created"); } delete ourInstance; ourInstance = nullptr; } void CommandLineParameters::Parse(int argc, char * argv[]) { auto && currentParameterIt = myParameters.end(); for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { std::string currentParameter = argv[i]; currentParameter.erase(currentParameter.begin()); currentParameterIt = myParameters.find(currentParameter); if (currentParameterIt == myParameters.end()) { myParameters.emplace(currentParameter, std::unordered_set<std::string>()); currentParameterIt = myParameters.find(currentParameter); } } else { if (currentParameterIt == myParameters.end()) { Error("Invalid parameter format"); } currentParameterIt->second.emplace(argv[i]); } } } bool CommandLineParameters::CheckParameterForValue(const std::string & aParameter, const std::string & aValue) const { auto &&parameterIt = myParameters.find(aParameter); if (parameterIt != myParameters.end()) { auto &&valueIt = parameterIt->second.find(aValue); return valueIt != parameterIt->second.end(); } return false; } const std::unordered_set<std::string> & CommandLineParameters::GetValuesForParameter(const std::string & aParameter) { auto &&parameterIt = myParameters.find(aParameter); if (parameterIt != myParameters.end()) { return parameterIt->second; } myParameters.emplace(aParameter, std::unordered_set<std::string>()); return myParameters.find(aParameter)->second; } }
Java
UTF-8
1,066
2.328125
2
[ "MIT" ]
permissive
package io.muun.apollo.presentation.ui.adapter.holder; import io.muun.apollo.R; import io.muun.apollo.domain.model.Contact; import io.muun.apollo.presentation.ui.adapter.viewmodel.ContactViewModel; import io.muun.apollo.presentation.ui.view.ProfilePictureView; import android.view.View; import android.widget.TextView; import butterknife.BindView; public class ContactViewHolder extends BaseViewHolder<ContactViewModel> { @BindView(R.id.home_contacts_item_profile_picture) protected ProfilePictureView profilePicture; @BindView(R.id.home_contacts_item_text_full_name) protected TextView name; /** * View holder for the contact list items. */ public ContactViewHolder(View view) { super(view); } /** * Bind this viewHolder to a Contact. */ @Override public void bind(ContactViewModel viewModel) { final Contact contact = viewModel.model; profilePicture.setPictureUri(contact.publicProfile.profilePictureUrl); name.setText(contact.publicProfile.getFullName()); } }
Shell
UTF-8
999
3.4375
3
[]
no_license
#!/bin/sh # get the url via `terraform output` URL=`make output | grep base_url | awk -F '=' '{print $2}' | awk '{$1=$1};1'` PUBLIC_URL="https://castlewebhook-test.optimizely.com/v1" JSON="../test.json" HMAC=`cat $JSON | openssl dgst -binary -sha256 -hmac "$TF_VAR_hmac_secret" | openssl base64` echo "Test 1: Calling the API endpoint directly. Make sure HMAC_SECRET is set in your environment." echo "curl \"$URL\" --data-binary @${JSON} -H \"X-Castle-Signature: $HMAC\"" curl "$URL" --data-binary @${JSON} -H "X-Castle-Signature: $HMAC" if [ $? -eq 0 ]; then echo "call succeeded 😀" else echo "call failed 😱" fi echo "" echo "Test 2: Calling the public DNS entry API endpoint. Make sure HMAC_SECRET is set in your environment." echo "Note: This will fail unless the DNS for castlewebhook-test.optimizely.com --> Target Domain Name" URL=$PUBLIC_URL echo "" echo "To proceed run the following:" echo "curl \"$URL\" --data-binary @${JSON} -H \"X-Castle-Signature: $HMAC\"" echo ""
Markdown
UTF-8
9,043
2.96875
3
[]
no_license
[TOC] # 使用 umi 和 dva ## redux-saga 更好的再redux中管理异步数据,具有更强大的异步数据管理功能 于`redux-thunk`不同的是 + `redux-thunk`返回的是一个函数 ### 在store文件夹新建sagas.js ```react /** * call: 调用异步函数 * put: 当异步函数执行有结果了,去通知状态进行更新 * takeEvery: 负责在全局监听action */ import { call, put, takeEvery } from 'redux-saga/effects' // 登录的api调用 const userService = { login(username) { return new Promise((resolve, reject) => { setTimeout(() => { if (username === 'Jerry') { resolve({ id: 1, name: 'Jerry', age: 20 }) } else { reject(new Error('用户名或密码错误!')) } }, 2000) }) } }; // 当函数名和函数之间有星号的时候 此函数就是一个生成器函数 (按照yield顺序执行) // 程序是不会停止的 function* login(action) { try { // 按顺序执行 卡在这 yield put({type: 'requestLogin'}) // 拿到返回 const result = yield call(userService.login, action.username) yield put({type: 'loginSuccess', result}) // 如果失败 捕获错误 } catch (err) { yield put({type: 'loginFailure', err}) } } // 全局拦截住 action 让其执行我们定义好的login function* mySaga() { yield takeEvery('login', login) } // 必须导出的是一个函数 export default mySaga ``` ### 在store.js ```javascript // 创建store,应用中间件方法 import { createStore, applyMiddleware, combineReducers } from 'redux' import createSagaMiddlewate from 'redux-saga' // 引入sagas import mySaga from './sagas' // 日志记录 import reduxLogger from 'redux-logger' //把 count 这个 reducer 抽出来 import { counterReducer } from './countReducer' import { userReducerSaga } from './userReducerSaga' // 创建一下saga 的 中间件 const sagaMiddleware = createSagaMiddlewate(); // 把应用中间件这个函数当作第二个参数给 createStore const store = createStore( combineReducers({ counterReducer, userReducerSaga }), applyMiddleware( // 先做日志记录 (控制台打印的日志) reduxLogger, // 使用 saga 的 中间件 sagaMiddleware ) ); // 运行中间件 接收的是一个函数 sagaMiddleware.run(mySaga); export default store ``` ### user ```javascript const init = { isLogin: false, loading: false, error: '' }; export const userReducerSaga = (state = init, action) => { switch (action.type) { // 其实还可以把action.type 给抽出来 单独做为一个变量 // 抽出来作为变量 有利于更改 和 编写代码(不容易打错) case 'loginPending': // 因为这里的state是一个值 如果这里的state是一个对象的话 则应该返回一个新的对象 return { isLogin: false, loading: true }; case 'loginSuccess': return { isLogin: true, loading: false }; case 'loginFailure': return { isLogin: false, loading: false, error: '登录失败' }; default: return state } }; // 可以把action 单独抽出来 给到一个单独的文件里面去 // 此login 会被 saga 监听到 export const login = (username) => ({ type: 'login', username }); ``` ### 组件中使用 ```react import React, { useState } from 'react'; // 用于浏览器的router import { BrowserRouter as Router, Link, Route, Switch, Redirect } from 'react-router-dom' import { connect } from 'react-redux' import { login } from '../store/userReducerSaga' // 登录页面 const Login = connect( state => ({ isLogin: state.userReducerSaga.isLogin, loading: state.userReducerSaga.loading, error: state.userReducerSaga.error }), { login } )( ({ isLogin, loading, location, login, error }) => { let [username, setUserNmae] = useState('') // 如果已经登录的话 直接去重定向页面 if (isLogin) { console.log(location.state.redirect) return <Redirect to={{ pathname: location.state.redirect }}/> } return ( <div> <p>登录页</p> <hr/> { error && <p>{ error }</p> } <input type="text" value={ username } onChange={ e => setUserNmae(e.target.value) } /> <button onClick={_ => login(username)} disabled={ loading }> { loading? '登录中...' : '登录' } </button> </div> ) } ); ``` ## umi ### 安装 > 更多的看文档 ```javascript npm install umi -g ``` ### 自定路由 `/config/index` ```javascript export default { // 以 pases 作为根目录 routes: [ { path: '/', component: './index' }, { path: '/about', component: './about/index' }, { path: '/goodList', component: './goodList/index' }, { // 只能算是一个布局 不能算是一个页面 path: '/user', component: './user/index', routes: [ { // 需要有一个默认路由的默认页面 path: '/user', component: './user/index' }, { path: '/user/:id', component: './user/$id' } ] } ] } ``` ### 使用antd ```javascript npm install antd -S npm install umi-plugin-react -D ``` ```javascript export default { plugins: [ [ // 启用就是按需引用 'umi-plugin-react', { antd: true, // 内置dva 直接启用 dva: true } ] ] } ``` ```javascript // 页面 import { Button, Card } from 'antd' <Button onClick={ () => props.addGood('商品' + new Date().getTime()) }>添加商品</Button> ``` ### 使用dva ```javascript // 直接启用 内置 都不需要安装 export default { plugins: [ [ // 启用就是按需引用 'umi-plugin-react', { antd: true, // 内置dva 直接启用 dva: true } ] ] } ``` ### mock数据 > 直接在根目录新建Mock文件夹并在其中新建Js文件即可 > > 会自动拦截ajax请求 `/mock/goods.js` ```javascript const data = [ { title: "web全栈" }, { title: 'java架构师' } ] export default { 'get /api/goods': (req, res) => { setTimeout(() => { res.json({result: data}) }, 1500) } } ``` ### 全局models > 新建下方文件夹及文件,文件名字为默认的命名空间 `/src/models/goodList.js` ```javascript import axios from 'axios' function getGoodList () { return axios.get('/api/goods') } export default { // 命名空间 namespace: 'goodList', state: [ { title: "web全栈" }, { title: "java架构师1" } ], // 异步操作 effects:{ *getGoodList (action, { call, put }) { // 调用 const res = yield call(getGoodList) // 更新 yield put({ type: 'initGoods', payload: res.data.result }) } }, // 更新状态 reducers: { // 直接更新 返回一个 addGood (state, action) { return [...state, { title: action.title }] }, // 初始化列表 直接返回 initGoods (state, action) { return action.payload } } } ``` #### 页面中使用 状态 及操作异步方法 使用loading ```javascript import React, { useEffect } from 'react' import { Button, Card } from 'antd' import { connect } from 'dva' // 要保持pages 目录 也在src 目录下 才生效 export default connect( // 返回一个对象 映射需要使用到的state state => { console.log('state', state) return { goodList: state.goodList, loading: state.loading } }, // 返回一个对象 { // 有一些对象属性返回的是函数 addGood: title => ({ // action 的 type 需要以命名空间为前缀 type: 'goodList/addGood', title }), getGoodList: () => ({ // action 的 type 需要以命名空间为前缀 type: 'goodList/getGoodList' }) } )((props) => { console.log(props) // 只会执行一次 useEffect(() => { props.getGoodList() }, []) return ( <div> <h1>good list</h1> <div> { // 找到模型 /** * loading: { global: false, models: { goodList: false }, effects: { 'goodList/getGoodList': false } } */ props.loading.models.goodList && <p>Loading....</p> } { props.goodList.map(item => { return ( <Card key={ item.title }> <div>{ item.title }</div> </Card> ) }) } <Button onClick={ () => props.addGood('商品' + new Date().getTime()) }>添加商品</Button> </div> </div> ) }) ```
JavaScript
UTF-8
1,873
2.875
3
[]
no_license
/** * Parses and validates data from formObject, then it updates Tariff. * * @param formObject Object received from client's browser form. * @param {Object} opts received URL params and loaded data * @return {Object} object which designates success or failure (in a case form had nonvalid data) * @throws Exception if updating Tariff failed */ function processTariffObj(formObject, opts) { var errorMsg = {nameErr:'',priceErr:'',defaultErr:''}; var tariffs = Utils.findTariffs(); var oldTariff = opts.updateObj; var tariff = {shortcut:oldTariff.shortcut}; tariff['default'] = oldTariff['default']; if(formObject.nameBox === oldTariff.name ){ tariff.name = oldTariff.name; }else{ tariff.name = Utils.validate(errorMsg,formObject.nameBox,{ actions:['trim','unique','notNull'], actionObjs:[{},{uniqueArray:tariffs,uniqueProp:'name'},{}], actionErrors:[{},{nameErr:'*tento název je již registrován'},{nameErr:'*vyplňte pásmo'}] }); } if(formObject.priceBox == oldTariff.price ){ tariff.price = oldTariff.price; }else{ tariff.price = Utils.validate(errorMsg,formObject.priceBox,{ actions:['notNull','isNonNegativeNumber'], actionObjs:[{},{}], actionErrors:[{priceErr:'*vyplňte cenu'},{priceErr:'*vyplňte nezáporné číslo'}] }); } Utils.validate(errorMsg,Utils.AccessEnums.TARIFF,{ actions:['canEdit'], actionObjs:[{}], actionErrors:[{nameErr:'*nemáte oprávnění pro tento typ akce'}] }); if(Utils.isObjErrorFree(errorMsg)) { if(!shallowEquals_(oldTariff,tariff)){ if(Utils.updateTariff(tariff)){ errorMsg.success = 'Cenové pásmo uspěšně změněno.'; }else{ throw {message:'updateTariff'}; } }else{ errorMsg.success = 'Cenové pásmo nebylo změněno'; } } return errorMsg; }
Java
UTF-8
4,137
3
3
[]
no_license
package ru.dkuleshov.service; import com.threed.jpct.SimpleVector; /** * Created by dkuleshov3 on 09.06.2017. */ public class SimpleMath { public static class Point2D { public float x; public float y; public Point2D(float _x, float _y) {x = _x; y = _y;} public Point2D() {x = 0; y = 0;} public Point2D(SimpleVector _v) {x = _v.x; y = _v.z;} public float distance(Point2D s) { float var2 = -this.x + s.x; float var3 = -this.y + s.y; return (float)Math.sqrt((double)(var2 * var2 + var3 * var3)); } } static float det (float a, float b, float c, float d) { return a * d - b * c; } static float det(float a11, float a12, float a13, float a21, float a22, float a23, float a31, float a32, float a33) { return a11 * a22 * a33 + a13 * a21 * a32 + a31 * a12 * a23 - a13 * a22 * a31 - a11 * a23 * a12 - a33 * a12 * a21; } public static Point2D calcIntersection (Point2D a, Point2D b, Point2D c, Point2D d) { float A1 = a.y-b.y; float B1 = b.x-a.x; float C1 = -A1*a.x - B1*a.y; float A2 = c.y-d.y; float B2 = d.x-c.x; float C2 = -A2*c.x - B2*c.y; float zn = det (A1, B1, A2, B2); if (zn != 0) { float x = - det (C1, B1, C2, B2) * 1f / zn; float y = - det (A1, C1, A2, C2) * 1f / zn; return new Point2D(x, y); } return null; } public static Point2D calc3DotBezierPoint(Point2D points[], float t) { Point2D ret = new Point2D(); float t1 = 1f - t; ret.x = t1 * t1 *points[0].x + 2 * t * t1 * points[1].x + t * t * points[2].x; ret.y = t1 * t1 *points[0].y + 2 * t * t1 * points[1].y + t * t * points[2].y; return ret; } public static Point3D calc3DotBezierPoint(Point3D points[], float t) { Point3D ret = new Point3D(0f, 0f, 0f); float t1 = 1f - t; ret.x = t1 * t1 *points[0].x + 2 * t * t1 * points[1].x + t * t * points[2].x; ret.y = t1 * t1 *points[0].y + 2 * t * t1 * points[1].y + t * t * points[2].y; ret.z = t1 * t1 *points[0].z + 2 * t * t1 * points[1].z + t * t * points[2].z; return ret; } public static float calc3DotBezierLength(Point2D points[], int accuracy) { Point2D prev = points[0]; float ret = 0; for (int i = 1; i <= accuracy; i++) { Point2D next = calc3DotBezierPoint(points, (float)i / (float)accuracy); ret += prev.distance(next); prev = next; } return ret; } public static float calc3DotBezierLength(Point3D points[], int accuracy) { Point3D prev = points[0]; float ret = 0; for (int i = 1; i <= accuracy; i++) { Point3D next = calc3DotBezierPoint(points, (float)i / (float)accuracy); ret += prev.distance(next); prev = next; } return ret; } /** * Проверка принадлежности точки checkedPoint к линии start-direction * @param start точка начала прямой * @param direction направление прямой * @param checkedPoint точка которую необходимо проеверить * @param checkedDirection направление * @return true если все три точки на одной прямой */ public static boolean isPointOnLine(Point2D start, Point2D direction, Point2D checkedPoint, Point2D checkedDirection) { boolean ret = false; float x; if (start.x + direction.x == 0) x = 0; else x = checkedPoint.x / (start.x + direction.x); float x2; if (checkedDirection.x == 0) x2 = 0; else x2 = direction.x / checkedDirection.x; if ((start.y + direction.y) * x == checkedPoint.y && direction.y == checkedDirection.y * x2) ret = true; return ret; } }
JavaScript
UTF-8
452
2.546875
3
[]
no_license
function check_val(input) { $(input).val() != "" ? $(input).addClass("has_value") : $(input).removeClass("has_value"); } $(document).ready(function(){ $(".check_val").each(function(){ check_val(this); }).on("keyup click blur focus change paste", function(){ check_val(this); }); $("input, select, textarea").on("focus",function(e){ $("body").addClass("fix_fixed"); }).on("blur", function(e){ $("body").removeClass("fix_fixed"); }); });
Shell
UTF-8
1,620
3.484375
3
[ "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
#!/usr/bin/env sh # Create the imagenet lmdb inputs # N.B. set the path to the imagenet train + val data dirs jsonData="`cat $1`" RESIZE_VAL=`echo $jsonData | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["RESIZE"]'` TRAIN_FILE=`echo $jsonData | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["TRAIN_FILE"]'` TEST_FILE=`echo $jsonData | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["TEST_FILE"]'` DB_TRAIN=`echo $jsonData | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["DBNAME_TRAIN"]'` DB_TEST=`echo $jsonData | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["DBNAME_TEST"]'` DB_TYPE=`echo $jsonData | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["DBTYPE"]'` DATASET_ROOT=`echo $jsonData | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["DATASET_ROOT"]'` TOOLS=../../build/tools # Set RESIZE=true to resize the images to 256x256. Leave as false if images have # already been resized using another tool. RESIZE=true if $RESIZE; then RESIZE_HEIGHT=$RESIZE_VAL RESIZE_WIDTH=$RESIZE_VAL else RESIZE_HEIGHT=0 RESIZE_WIDTH=0 fi echo "Creating train $DB_TYPE..." GLOG_logtostderr=1 $TOOLS/convert_imageset \ --resize_height=$RESIZE_HEIGHT \ --resize_width=$RESIZE_WIDTH \ --backend="$DB_TYPE" \ $DATASET_ROOT \ $TRAIN_FILE \ $DB_TRAIN echo "Creating val $DB_TYPE..." GLOG_logtostderr=1 $TOOLS/convert_imageset \ --resize_height=$RESIZE_HEIGHT \ --resize_width=$RESIZE_WIDTH \ --backend="$DB_TYPE" \ $DATASET_ROOT \ $TEST_FILE \ $DB_TEST echo "Done."
C++
UTF-8
347
2.515625
3
[]
no_license
#pragma once #ifndef SOCCER_MESSAGES_H #define SOCCER_MESSAGES_H #include <string> //An easy translator for the message send-receive by the entities enum MessageType { Msg_ReceiveBall, Msg_PassToMe, Msg_SupportAttacker, Msg_GoHome, Msg_Wait }; //converts an enumerated value to a string inline std::string MessageToString(int msg); #endif
Java
UTF-8
1,804
2.015625
2
[]
no_license
package smartshop.com.smartshop.helpers; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import static org.junit.Assert.*; /** * Created by Vicky on 11/12/2017. */ @RunWith(PowerMockRunner.class) public class InputValidationTest { @Before public void setUp() throws Exception { Assert.assertTrue("Passed", true); } @After public void tearDown() throws Exception { Assert.assertTrue("Passed", true); } @Test public void isInputEditTextFilled() throws Exception { InputValidation inpVal = Mockito.mock(InputValidation.class); //boolean output = inpVal.isInputEditTextFilled(null, null, Mockito.anyString()); assertTrue("Passed", true); } @Test public void isInputEditTextEmail() throws Exception { InputValidation inpVal = Mockito.mock(InputValidation.class); //boolean output = inpVal.isInputEditTextEmail(null, null, Mockito.anyString()); assertTrue("Passed", true); } @Test public void isInputEditTextMatches() throws Exception { InputValidation inpVal = Mockito.mock(InputValidation.class); //boolean output = inpVal.isInputEditTextMatches(null, null, null, Mockito.anyString()); assertTrue("Passed", true); } }
Java
UTF-8
591
2.65625
3
[ "Apache-2.0" ]
permissive
package saivenky.neural.c; /** * Created by saivenky on 2/19/17. */ public class ReluLayer extends Layer { public ReluLayer(Layer previousLayer) { shape = previousLayer.shape; int size = previousLayer.shape[0] * previousLayer.shape[1] * previousLayer.shape[2]; nativeLayerPtr = create(size, previousLayer.nativeLayerPtr); adjustByteOrderOnBuffers(); } private native long create(int size, long previousLayerNativePtr); private native long destroy(long nativeLayerPtr); @Override public void gradientDescent(float rate) { } }
C#
UTF-8
3,210
2.703125
3
[]
no_license
//Inspired by this thread: https://forum.unity.com/threads/simple-udp-implementation-send-read-via-mono-c.15900/ //thanks OP la1n //thanks MattijsKneppers for letting me know that I also need to lock my queue while enqueuing //adapted during projects according to my needs using System; using System.Net; using System.Net.Sockets; using System.Text; using UnityEngine; /// <summary> /// General purpose UDP receiver class. see also: <see cref="UdpReceiver"/> /// </summary> public class UdpSender { public string IpAddress { get; private set; } public int SourcePort { get; private set; } //sometimes we need to define the source port, since some devices only accept messages coming from a predefined sourceport. public int RemotePort { get; private set; } private IPEndPoint _remoteEndPoint; private UdpClient _client; public UdpSender(string ipAddress, int remotePort, int sourcePort = -1) //if sourceport is not set, its being chosen randomly by the system { IpAddress = ipAddress; SourcePort = sourcePort; RemotePort = remotePort; _remoteEndPoint = new IPEndPoint(IPAddress.Parse(IpAddress), RemotePort); if (this.SourcePort <= -1) { _client = new UdpClient(); Debug.Log($"Sending to {IpAddress}:{RemotePort}"); } else { _client = new UdpClient(this.SourcePort); Debug.Log($"Sending to {IpAddress}:{RemotePort} from Source Port:{SourcePort}"); } } ~UdpSender() { _client.Close(); } // sendData in different ways. Can be extended accordingly public void SendData(byte[] data) { try { _client.Send(data, data.Length, _remoteEndPoint); } catch (Exception err) { Debug.Log(err.ToString()); } } public void sendString(string message) { try { byte[] data = Encoding.UTF8.GetBytes(message); _client.Send(data, data.Length, _remoteEndPoint); } catch (Exception err) { Debug.Log(err.ToString()); } } public void sendInt32(Int32 myInt) { try { byte[] data = BitConverter.GetBytes(myInt); _client.Send(data, data.Length, _remoteEndPoint); } catch (Exception err) { Debug.Log(err.ToString()); } } public void sendInt32Array(Int32[] myInts) { try { byte[] data = new byte[myInts.Length * sizeof(Int32)]; Buffer.BlockCopy(myInts, 0, data, 0, data.Length); _client.Send(data, data.Length, _remoteEndPoint); } catch (Exception err) { Debug.Log(err.ToString()); } } public void sendInt16Array(Int16[] myInts) { try { byte[] data = new byte[myInts.Length * sizeof(Int16)]; Buffer.BlockCopy(myInts, 0, data, 0, data.Length); _client.Send(data, data.Length, _remoteEndPoint); } catch (Exception err) { Debug.Log(err.ToString()); } } }
PHP
UTF-8
2,611
2.65625
3
[]
no_license
<?php $config['hostname'] = "localhost"; $config['dbuser'] = "root"; $config['dbpassword'] = ""; $config['dbname'] = "hoonigan"; $name = ""; $email = ""; $msg = ""; $errors = array(); $db = mysqli_connect($config['hostname'], $config['dbuser'], $config['dbpassword'], $config['dbname']); if (isset($_POST['kuld'])) { $name = mysqli_real_escape_string($db, $_POST['name']); $email = mysqli_real_escape_string($db, $_POST['email']); $msg = mysqli_real_escape_string($db, $_POST['msg']); if (empty($name)) { array_push($errors, "Név mező üres!"); } if (empty($email)) { array_push($errors, "Email mező üres!"); } if (empty($msg)) { array_push($errors, "Szöveg mező üres!"); } if (count($errors) == 0) { $query = "INSERT INTO messages (name, email, msg) VALUES('$name', '$email', '$msg')"; mysqli_query($db, $query); header('location: index.php'); }else{ print_r($errors); } } ?> <script> function validateForm() { var x = document.forms["myForm"]["name"].value; var y = document.forms["myForm"]["email"].value; var z = document.forms["myForm"]["msg"].value; if (x == "") { alert("A név mezőt ki kell tölteni!"); return false; } if (y == "") { alert("Az email mezőt ki kell tölteni!"); return false; } if (z == "") { alert("A szöveg mezőt ki kell tölteni!"); return false; } if (x.length > 30) { alert("A név túl hosszú!"); return false; } if (y.length > 30) { alert("Az email túl hosszú!"); return false; } if (z.length > 100) { alert("A szöveg túl hosszú!"); return false; } } </script> <header class="major"><h2>Kapcsolat</h2></header> <div class="regcontent"> <div class="login-container"> <h3 class="login-title">Írj üzenetet, ha mersz! :)</h3> <form name="myForm" action="pages/contact_content.php" onsubmit="return validateForm()" method="post"> <div class="input-group"> <input type="text" id="name" name="name" placeholder="neved" required> </div> <div class="input-group"> <input type="email" id="email" name="email" placeholder="email címed" required> </div> <div class="input-group"> <textarea id="szoveg" name="msg" cols="40" rows="10" placeholder="üzeneted..." required></textarea> </div> <div class="input-group"> <input name="kuld" type="submit" value="Küld" class="login-button"> </div> </form> </div> </div>
Python
UTF-8
196
3.015625
3
[]
no_license
from pandas import DataFrame, Series pop = {'Nevada': {2001: 2.4, 2002: 2.9}, 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}} frame = DataFrame(pop) print(frame) frame = frame.T print(frame)
C
UTF-8
949
3.421875
3
[]
no_license
#include <sys/stat.h> #include <unistd.h> #include <time.h> #include <stdio.h> #include <stdlib.h> char * get_binary(int n) { int i = 8; char * s; s = malloc(sizeof(char) * 9); while (n) { if (n & 1) { if ((i % 3) == 0) { * (s + i) = 'r'; } if ((i % 3) == 1) { * (s + i) = 'w'; } if ((i % 3) == 2) { * (s + i) = 'x'; } } else { * (s + i) = '-'; } i -= 1; n >>= 1; } return s; } int main() { struct stat stats; stat("info_stat.c", &stats); printf("File size: %lldB\n", (long long int)stats.st_size); printf("File size: %fkB\n", (float)stats.st_size / 1000); printf("File size: %fMB\n", (float)stats.st_size / 10000); printf("File size: %fGB\n", (float)stats.st_size / 100000); printf("Mode: %o\n", stats.st_mode); int a = 0; a = stats.st_mode % 512; char * perm; perm = get_binary(a); printf("%s\n", perm); printf("Access time: %s", ctime(&stats.st_atime)); return 0; }
JavaScript
UTF-8
2,086
2.890625
3
[]
no_license
import React from "react"; //import GetWordOfDay from "../../util/getWordOfDayHelper"; import { getWordOfDay } from "../../util/getWordOfDayHelper"; import { Link } from "react-router-dom"; import './WordOfDay.css'; class WordOfDay extends React.Component { constructor() { super(); this.state = { word: '', text: '', note: '', date: '', }; } getWordOfDayFn = async () => { let day = ("0" + new Date().getDate()).slice(-2); //This was done so we could get the day always with two digits let month = new Date().getMonth()+1; //console.log(month);//There's a problem with the getMonth(), it's returning 10 instead of 11 - check this let year = new Date().getFullYear(); let date = `${year}-${month}-${day}`; let GetWordOfDay = await getWordOfDay(date); //console.log(GetWordOfDay[0], GetWordOfDay[1], GetWordOfDay[2]); let word = GetWordOfDay[0]; let text = GetWordOfDay[1]; let note = GetWordOfDay[2]; this.setState({ word: word, text: text, note: note, date: date }); } componentDidMount() { this.getWordOfDayFn(); } render(){ return ( <div className="wordOfDayContainer"> <h1>Spelling Masta</h1> <h2 className="titleWOD">And the word of the day is:</h2> {/* <GetWordOfDay date = {date}/> */} <div> <h1 className="word">{this.state.word}</h1> <h2 className="text">{this.state.text}</h2> <h2 className="origin"><i>Origin of the word:</i></h2> <h2 className="originText"><i>{this.state.note}</i></h2> </div> <h3 className="date"> {this.state.date} </h3> <div className="exit" id="exit"> <Link to="/"><button>Back</button></Link> </div> </div> ) } } export default WordOfDay;
PHP
UTF-8
17,239
2.609375
3
[]
no_license
<?php if(isset($_GET['place_id'])){ $place=$_GET['place_id']; $place_request=file_get_contents("https://maps.googleapis.com/maps/api/place/details/json?placeid=".$place."&key=AIzaSyCkQkQOa6xaqAu3Is6yhQBla6Jj-icdj8A"); $place_json=json_decode($place_request,true); $response=array("results"=>getReviews($place_json),"photos"=>getPhotos($place_json)); $response_json=json_encode($response); echo $response_json; die(); } function getReviews($element){ $review_array=array(); if(!array_key_exists('reviews',$element['result'])){ return $review_array; } $review=$element['result']['reviews']; $num_of_reviews=count($review); if($num_of_reviews>5){ $num_of_reviews=5; } for($i=0;$i<$num_of_reviews;$i++){ array_push($review_array,array($review[$i]['profile_photo_url'],$review[$i]['author_name'],$review[$i]['text'])); } return $review_array; } function getPhotos($element){ $num_of_photos=0; if(!array_key_exists('photos',$element['result'])){ return $num_of_photos; } $photos=$element['result']['photos']; $num_of_photos=count($photos); if($num_of_photos>5){ $num_of_photos=5; } for($i=0;$i<$num_of_photos;$i++){ $photo=file_get_contents("https://maps.googleapis.com/maps/api/place/photo?maxwidth=4096&photoreference=".$photos[$i]['photo_reference']."&key=AIzaSyClk73-b29Q043BLKzkIPpSDkSe6N8naKI"); $photo_url="./".$i.".jpeg"; $boolean=file_put_contents($photo_url,$photo); chmod($photo_url,0755); } return $num_of_photos; } ?> <?php if(isset($_GET['search'])){ $keyword=$_GET['key_value']; $category=$_GET['category_value']; $radio=$_GET['radio_select']; $distance=$_GET['distance_value']*1.609*1000; $location=$_GET['location_value']; $latitude=$_GET['lat']; $longitude=$_GET['lon']; if($radio=="1"){ $geoloc_request=file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($location)."&key="."AIzaSyD1Pwm8mjfqj7s1UEkVzP76hgERs1Kp3UM"); $new_location=json_decode($geoloc_request,true); $new_lat=$new_location['results'][0]['geometry']['location']['lat']; $new_long=$new_location['results'][0]['geometry']['location']['lng']; $place_request=file_get_contents("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="."$new_lat".","."$new_long"."&radius="."$distance"."&type=".urlencode($category)."&keyword=".urlencode($keyword)."&key="."AIzaSyDEPqDLabDaCnKEP7TLfXHEFUetaLexb4c"); $place_array=json_decode($place_request,true); $place_array["latitude"]=$new_lat; $place_array["longitude"]=$new_long; echo json_encode($place_array); die(); } else{ $place_request=file_get_contents("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="."$latitude".","."$longitude"."&radius="."$distance"."&type=".urlencode($category)."&keyword=".urlencode($keyword)."&key="."AIzaSyDEPqDLabDaCnKEP7TLfXHEFUetaLexb4c"); //$place_array=json_decode($place_request,true); //$place_array["latitude"]=$latitude; //$place_array["longitude"]=$longitude; echo $place_request; die(); } } ?> <html> <style> #border-box{ margin-left:250px; border:1px; border-color:grey; border-style: solid; height: 230px; width: 600px; padding-left: 150px; } #line{ margin-left:-150px; margin-top:-20px; color: grey; } .button{ background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none; } #loc{ margin-left:305px; } #map { height: 300px; width:300px; z-index:3; } #way{ z-index:5; display:none; } a{ text-decoration: none; color: black; } </style> <head> <title>Travel and Entertainment Search</title> <script> var lat,long; function getloc(element){ lat=element.lat; long=element.lon; document.getElementById("search").disabled=false; } function disable(){ document.getElementById("loc1").disabled=true; } function enable(){ document.getElementById("loc1").disabled=false; function disablesearch(){ document.getElementById("search").disabled=true; } } var reviewboolean,photoboolean; var rev_open=0,photo_open=0; //var latitude,longitude; function getFormAttributes(){ var keyword=document.getElementById("keyword_value").value; var category=document.getElementById("category_value").value; var distance=document.getElementById("distance_value").value; if(distance==""){ distance="10"; } var radio=""; if(document.getElementById("here").checked) { radio="0"; } else{ radio="1"; } var location=""; if(radio=="1"){ location=document.getElementById("loc1").value; } var search=document.getElementById("search").value; var parameters="key_value="+keyword+"&category_value="+category+"&distance_value="+distance+"&radio_select="+radio+"&location_value="+location+"&search="+search+"&lat="+lat+"&lon="+long; parameters=parameters.split(' ').join('+'); return parameters; } function decode_json(element){ var number_of_places=element.results.length; data= "<table border=2 width=800px;><th>Category</th><th>Name</th><th>Address</th>"; for(var i=0;i<number_of_places;i++){ data+="<tr><td>"+'<img src="'+element.results[i].icon+ '" height="50" weight="50"></td>'; data+="<td>"+'<a href="#" onclick=getReviewsAndPhotos("'+element.results[i].place_id+'","'+encodeURIComponent(element.results[i].name)+'")>'+element.results[i].name+'</a></td>'; data+="<td>"+'<a href="#!" id="'+element.results[i].place_id+'" onclick=getMaps(this,'+element.results[i].geometry.location.lat+','+element.results[i].geometry.location.lng+')>'+element.results[i].vicinity+"</a></td></tr>"; } data+="</table>"; if(number_of_places==0){ data="No results are found!"; } document.getElementById("newelement").innerHTML=data; } function get_table(){ var check = document.querySelector('#inputs').reportValidity(); if(check==false){ return;} var attributes=getFormAttributes(); var page_url="http://cs-server.usc.edu:36193/Homework6.php?"+attributes; var req=new XMLHttpRequest(); req.onreadystatechange=function(){ if (req.readyState == 4 && req.status == 200){ //console.log(req.responseText); console.log(lat); console.log(long); json_object=JSON.parse(req.responseText); decode_json(json_object); if(!json_object.latitude=="") { lat=json_object.latitude; long=json_object.longitude; } console.log(lat); console.log(long); } } req.open("GET",page_url,true); req.setRequestHeader("Content-type","application/x-www-form-urlencoded"); req.send(); } function showreviews(){ if(rev_open==1){ //close the review section rev_open=0; document.getElementById("reviewarrow").src="http://cs-server.usc.edu:45678/hw/hw6/images/arrow_down.png"; document.getElementById("reviewinfo").innerHTML="click here to show reviews"; document.getElementById("reviewspace").style.display="none"; } else{ if(photo_open==1){ showphotos(); } //open the review section rev_open=1; document.getElementById("reviewarrow").src="http://cs-server.usc.edu:45678/hw/hw6/images/arrow_up.png"; document.getElementById("reviewinfo").innerHTML="click here to hide reviews"; document.getElementById("reviewspace").style.display="block"; } } function showphotos(){ if(photo_open==1){ //close photo section photo_open=0; document.getElementById("photoarrow").src="http://cs-server.usc.edu:45678/hw/hw6/images/arrow_down.png"; document.getElementById("photoinfo").innerHTML="click here to show photos"; document.getElementById("photospace").style.display="none"; } else{ if(rev_open==1){ showreviews(); } //open photo section photo_open=1; document.getElementById("photoarrow").src="http://cs-server.usc.edu:45678/hw/hw6/images/arrow_up.png"; document.getElementById("photoinfo").innerHTML="click here to hide photos"; document.getElementById("photospace").style.display="block"; } } function showhtml(){ var buttonhtml='<a onclick="showreviews()" ><div id ="reviewinfo" style="font-size:16;">click here to show reviews.</div><div><img id="reviewarrow" src="http://cs-server.usc.edu:45678/hw/hw6/images/arrow_down.png" height=25 width=35;></div> <div id="reviewspace" style="display:none;"></div>'; buttonhtml+='<a onclick="showphotos()" ><div id ="photoinfo" style="font-size:16;">click here to show photos.</div><div><img id="photoarrow" src="http://cs-server.usc.edu:45678/hw/hw6/images/arrow_down.png" height=25 width=35;></div> <div id="photospace" style="display:none;"></div>'; document.getElementById("newelement").innerHTML+=buttonhtml; } function getReviewsAndPhotos(id,name) { //set the innerhtml with photos and reviews links document.getElementById("newelement").innerHTML="<p>"+decodeURIComponent(name)+"</p>"; showhtml(); var p_id="place_id="+id; var pageurl="http://cs-server.usc.edu:36193/Homework6.php?"+p_id; var req =new XMLHttpRequest(); req.onreadystatechange=function() { if (req.readyState == 4 && req.status == 200) { //document.getElementById("newelement").innerHTML=request.responseText; json_obj=JSON.parse(req.responseText); console.log(req.responseText); review_table=""; var num_of_reviews=json_obj.results.length; review_table="<center><table width=700px border=2>" for(var i=0;i<num_of_reviews;i++) { review_table+='<tr><td><span><center><img height=40 width=40 src="'+json_obj.results[i][0]+'"><b> '+json_obj.results[i][1]+'</b><center></span></td></tr>'; review_table+='<tr><td>'+json_obj.results[i][2]+'</td></tr>'; } review_table+="</table></center>"; photos_table=""; var num_of_photos=json_obj.photos; // document.write('num_reviews'); photos_table="<center><table width=700px border=2>" for(var i=0;i<num_of_photos;i++) { photos_table+='<tr><td><center><a target="_blank" href="http://cs-server.usc.edu:36193/'+i+'.jpeg">'+'<img height=500 width=700 src="http://cs-server.usc.edu:36193/'+i+'.jpeg"></a><center></td></tr>'; } photos_table+="</table></center>"; if(num_of_photos==0) { photos_table="No photos found."; } if(num_of_reviews==0) { review_table="No reviews found."; } //document.getElementById("newelement").innerHTML=review_table+"<br>"+photos_table; document.getElementById("photospace").innerHTML=photos_table; document.getElementById("reviewspace").innerHTML=review_table; } } req.open("GET",pageurl,true); req.setRequestHeader("Content-type","application/x-www-form-urlencoded"); req.send(); } function getMaps(link,new_lat,new_lon){ //display maps and buttons on and off if(document.getElementById("map").style.display=="block"){ document.getElementById("map").style.display="none"; document.getElementById("way").style.display="none"; return; } var clickedlink=document.getElementById(link.id); var pos=clickedlink.getBoundingClientRect(); var ver=pos.top+pageYOffset+20; var hor=pos.left+pageXOffset; document.getElementById("map").style="z-index:3;position:absolute;top:"+ver+"px;left:"+hor+"px;display:block;"; document.getElementById("way").style="z-index:5;position:absolute;top:"+ver+"px;left:"+hor+"px;display:block;"; var showDirections = new google.maps.DirectionsRenderer; var directionsService = new google.maps.DirectionsService; var map = new google.maps.Map(document.getElementById('map'), { zoom: 14, center: {lat: new_lat, lng: new_lon}}); var marker = new google.maps.Marker({ position: {lat:new_lat,lng:new_lon}, map: map }); showDirections.setMap(map); //showRoute(directionsService, showDirections,new_lat,new_lon); document.getElementById('1').addEventListener('click', function() { showRoute(marker,directionsService, showDirections,new_lat,new_lon,"WALKING");}); document.getElementById('2').addEventListener('click', function() { showRoute(marker,directionsService, showDirections,new_lat,new_lon,"BICYCLING");}); document.getElementById('3').addEventListener('click', function() { showRoute(marker,directionsService, showDirections,new_lat,new_lon,"DRIVING");}); } function showRoute(marker,directionsService, showDirections,new_lat,new_lon,type){ marker.setMap(null); var chosenPath = type; directionsService.route({ origin: {lat: lat, lng: long}, destination: {lat: new_lat, lng: new_lon}, travelMode: google.maps.TravelMode[chosenPath]}, function(response, status) { if (status == 'OK') { showDirections.setDirections(response); } else { window.alert('Directions request failed due to ' + status); } }); } function clear_page(){ document.getElementById("inputs").reset(); document.getElementById("newelement").innerHTML=""; document.getElementById("map").style.display="none"; document.getElementById("way").style.display="none"; return; } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDhfGkSkeHkRy2uKNTqTsz9YXNjRJa3iSA"></script> </head> <body> <div id="border-box" > <p style="font-size:30px; color: black; font-style:italic;">Travel and Entertainment Search</p> <hr id="line"> <div> <form id= "inputs"> <b>Keyword</b><input id="keyword_value" type="text" name="keyword" required><br> <b>Category</b><select id="category_value" name="category"> <option value="default">default</option> <option value="cafe">cafe</option> <option value="bakery">bakery</option> <option value="restaurant">restaurant</option> <option value="beauty_salon">beauty salon</option> <option value="casino">casino</option> <option value="movie_theatre">movie theatre</option> <option value="lodging">lodging</option> <option value="airport">airport</option> <option value="train_station">train station</option> <option value="subway_station">subway station</option> <option value="bus_station">bus station</option> </select><br> <b>Distance(miles)</b><input id="distance_value" type="text" name="distance" value="10";><b>from</b> <input id="here" type="radio" name="radio" value="here" checked="checked" onclick="disable();"> Here<br> <input id="loc" type="radio" name="radio" value="location" onclick="enable();"><input id="loc1" type="text" placeholder="location" name="location" required disabled><br><br> <input id="search" type="button" name="search" value="Search" disabled="disabled" onclick="get_table()"> <input type="reset" name="Clear" value="Clear" onclick="clear_page()"> </form> </div> </div> <br> <br> <br> <center> <div id="newelement"> </div> <div id="map"></div> <div id="way"> <button id="1" value="WALKING">Walk There</button><br> <button id="2" value="BICYCLING">Bike there</button><br> <button id="3" value="DRIVING">Drive there</button> </div> </center> </body> <script src="http://ip-api.com/json?callback=getloc"></script> </html>
JavaScript
UTF-8
896
3.4375
3
[]
no_license
//************************************************** // // Javascript homework // Lecture Loops // author Viktor Ivanov // date: 15.13.2012 // editor: Visual Studio 2012 // //************************************************** //************************************************** //task 8 //************************************************** function gcd() { var nStr = document.getElementById("num-n").value; var kStr = document.getElementById("num-k").value; var numN = parseInt(nStr); var numK = parseInt(kStr); var result = document.getElementById("result"); var chkResult = 1; while (chkResult > 0) { chkResult = numN % numK; numN = numK; numK = chkResult; console.log(" chkResult = " + chkResult + " numK = " + numK + " numN = " + numN); } result.innerHTML = numN; } //************************************************* */
C#
UTF-8
932
2.78125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Text; namespace UniRx { public interface IConnectableObservable<T> : IObservable<T> { IDisposable Connect(); } public static partial class Observable { class ConnectableObservable<T> : IConnectableObservable<T> { readonly IObservable<T> source; readonly ISubject<T> subject; public ConnectableObservable(IObservable<T> source, ISubject<T> subject) { this.source = source; this.subject = subject; } public IDisposable Connect() { var subscription = source.Subscribe(subject); return subscription; } public IDisposable Subscribe(IObserver<T> observer) { return subject.Subscribe(observer); } } } }
C++
UTF-8
1,888
2.671875
3
[]
no_license
// // GameObject.h // CATLIEN // // Created by Wander on 8/19/12. // // #ifndef __CATLIEN__GameObject__ #define __CATLIEN__GameObject__ #include "cocos2d.h" #include "Box2D.h" #include "../Graphics/AnimationTexture.h" #include <string> // GameObject types typedef enum { GameObjectTypeNone, GameObjectTypePlanet, GameObjectTypePlayer } GameObjectType; // for the subclass of GameObject, each has to implement the static "create" method #define GAME_OBJECT_CREATE_FUNC(clz) \ static clz* create() \ { \ clz *pRet = new clz(); \ if (pRet && pRet->init()) \ { \ pRet->autorelease(); \ return pRet; \ } \ else \ { \ CC_SAFE_DELETE(pRet); \ pRet = NULL; \ return NULL; \ } \ } #define GAME_OBJECT_TYPE_FUNC(type) virtual GameObjectType getType() const {return (type);} class GameObject : public cocos2d::CCNode { private: protected: std::string _name; std::string _texturePath; int _frameCount; cocos2d::CCNode* _texture; b2Body* _b2Body; public: GameObject(); virtual bool init(); virtual void onEnter(); virtual void onExit(); virtual bool containsPoint(const cocos2d::CCPoint& p); virtual void drawSelection(); virtual GameObjectType getType() const = 0; inline std::string getName() const { return _name; } inline void setName(const std::string& name) {_name = name;} std::string getTexturePath() {return _texturePath;} int getFrameCount() {return _frameCount;} //return true if the texture is changed. virtual bool setTexturePath(const char* texturePath); virtual void setFrameCount(int frameCount); virtual void createB2Body(); virtual void destroyB2Body(); virtual void update(float deltaTime); void resetB2Body(); inline b2Body* getB2Body() const {return _b2Body; } }; #endif /* defined(__CATLIEN__GameObject__) */
Ruby
UTF-8
785
2.640625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module PagesCore module PubSub class << self def publish(name, payload = {}) subscribers.select { |s| s.name == name } .each { |s| s.call(payload) } end def subscribe(name, &block) subscriber = PagesCore::PubSub::Subscriber.new(name, block) subscribers << subscriber subscriber end def subscribers @subscribers ||= [] end def unsubscribe(subscriber) @subscribers = subscribers.reject { |s| s == subscriber } end end class Subscriber attr_reader :name, :callback delegate :call, to: :callback def initialize(name, callback) @name = name @callback = callback end end end end
SQL
UTF-8
917
3.875
4
[]
no_license
# agores pou eginan me karta apo ton pelath me onoma... SELECT * FROM Transaction AS T, Customer as C WHERE C.Card_number = 1 AND T.Card_number = C.Card_number ORDER BY T.DateTime; # agores pou eginan sto katasthma me kwdiko i DROP TABLE IF EXISTS Agores_i; CREATE TABLE Agores_i SELECT * FROM Transaction AS T WHERE T.Store_id = 1; # view the contents of the most expensive transaction SELECT P.Name, P.Price, Cat.Name FROM Product as P, Contains as C, Agores_i as T, Category as Cat WHERE T.DateTime = C.DateTime AND T.Card_number = C.Card_number AND P.Barcode = C.Product_barcode AND P.Category_id = Cat.Category_id AND T.Total_amount = (SELECT MAX(Total_amount) FROM Agores_i) SELECT T.Datetime, T.Total_amount, T.Store_id, C.COUNT(*) FROM Transaction as T, Contains as C WHERE C.Card_number = T.Card_number AND T.DateTime = C.DateTime AND T.Total_amount > 1 AND T.Store_id = 1 AND T.DateTime LIKE
Java
UTF-8
1,252
2
2
[]
no_license
package com.coldchain.project.business.user.vo; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * 企业注册参数 */ @Data public class RegisterVo { /** * 用户名 */ @ApiModelProperty(name = "username", value = "用户名", dataType = "String", example = "ntsitech") private String username; /** * 密码 */ @ApiModelProperty(name = "password", value = "密码", dataType = "String", example = "123456") private String password; /** * 手机号 */ @ApiModelProperty(name = "mobile", value = "手机号", dataType = "String", example = "18027613030") private String mobile; /** * 短信验证码 */ @ApiModelProperty(name = "smsCode", value = "短信验证码", dataType = "String", example = "789678") private String smsCode; /** * 公司名称 */ @ApiModelProperty(name = "name", value = "公司名称", dataType = "String", example = "新时空智能系统有限公司") private String companyName; /** * 公司地址 */ @ApiModelProperty(name = "address", value = "公司地址", dataType = "String", example = "深圳市福田区爱地大厦21D") private String address; }
C++
UTF-8
476
2.5625
3
[]
no_license
#include "Booster.h" const int Booster::SCORE; Booster::Booster( void ) : Object('*', 3, true, false, false) {} int Booster::Update( const int &timeDiff ) { return 0; } bool Booster::Destroy( int &power ) { m_Destroyed = true; return false; } bool Booster::PickUp( int &power, int &bombCnt, bool &confusion ) { AddBooster(power, bombCnt, confusion); m_Destroyed = true; return true; } int Booster::GetScore( void ) const { return SCORE; }
Java
UTF-8
344
1.539063
2
[]
no_license
package com.company.pizza.web.screens.pizzarecipe; import com.haulmont.cuba.gui.screen.*; import com.company.pizza.entity.PizzaRecipe; @UiController("pizza_PizzaRecipe.edit") @UiDescriptor("pizza-recipe-edit.xml") @EditedEntityContainer("pizzaRecipeDc") @LoadDataBeforeShow public class PizzaRecipeEdit extends StandardEditor<PizzaRecipe> { }
TypeScript
UTF-8
1,532
2.5625
3
[ "MIT" ]
permissive
import { it } from 'angular2/testing'; import {EncryptionSchemeResolverService} from '../resolver/encryption-scheme.resolver.service'; import {EncryptionSchemeProviderService} from './encryption-scheme.provider.service'; describe('encryption-scheme-provider', () => { let encryptionSchemeResolverService = jasmine.createSpyObj('encryptionSchemeResolverService', ['fromJson']); let encryptionScheme = jasmine.createSpyObj('encryptionScheme', [ 'getUniqueName' ]); encryptionScheme.getUniqueName.and.returnValue('pailler'); encryptionSchemeResolverService.fromJson.and.returnValue(encryptionScheme); let encryptionSchemeProviderService: EncryptionSchemeProviderService; beforeEach(() => { encryptionSchemeProviderService = new EncryptionSchemeProviderService( encryptionSchemeResolverService ); }); it('should return an encryption scheme given by its name', () => { expect(encryptionSchemeProviderService.getEncryptionSchemeByName('pailler')) .toBe(encryptionScheme) ; }); it('should throw an error for an unknown encryption encryption-scheme', () => { expect(() => { encryptionSchemeProviderService.getEncryptionSchemeByName('abcd'); }).toThrowError() ; }); it('should return the encryption schemes', () => { let schemes = encryptionSchemeProviderService.getEncryptionSchemes(); expect(schemes.length) .toBe(1) ; }); });
Markdown
UTF-8
14,482
2.6875
3
[]
no_license
# Laravel Valet - Introdução - Valet ou Homestead - Instalação - Atualizando - Servindo Sites - O comando "Park" - O comando "Link" - Protegendo sites com TLS - Compartilhamento de sites - Valet Drivers personalizados - Drivers Locais - Outros Comandos do Valet ## Introdução Valet é um ambiente de desenvolvimento Laravel para minimalistas do Mac. Sem Vagrant, sem `/etc/hosts`. Você pode compartilhar seus sites publicamente usando túneis locais. *Sim, também gostamos.* Laravel Valet configura seu Mac para executar sempre o [Nginx](https://www.nginx.com/) em segundo plano quando sua máquina for iniciada. Em seguida, usando o [DnsMasq](https://en.wikipedia.org/wiki/Dnsmasq), o Valet pega todas as solicitações para o domínio `*.test` e aponta para sites instalados em sua máquina local. Em outras palavras, um ambiente de desenvolvimento Laravel rápido que usa cerca de 7 MB de RAM. Valet não é uma substituição completa do Vagrant ou Homestead, mas fornece uma ótima alternativa se você quiser algo básico e flexível, prefira velocidade extrema ou está trabalhando em uma máquina com uma quantidade limitada de RAM. O Valet inclui, mas não está limitado a: - [Laravel](https://laravel.com/) - [Lumen](https://lumen.laravel.com/) - [Bedrock](https://roots.io/bedrock/) - [CakePHP 3](https://cakephp.org/) - [Concrete5](http://www.concrete5.org/) - [Contao](https://contao.org/en/) - [Craft](https://craftcms.com/) - [Drupal](https://www.drupal.org/) - [Jigsaw](http://jigsaw.tighten.co/) - [Joomla](https://www.joomla.org/) - [Katana](https://github.com/themsaid/katana) - [Kirby](https://getkirby.com/) - [Magento](https://magento.com/) - [OctoberCMS](https://octobercms.com/) - [Sculpin](https://sculpin.io/) - [Slim](https://www.slimframework.com/) - [Statamic](https://statamic.com/) - Static HTML - [Symfony](https://symfony.com/) - [WordPress](https://wordpress.org/) - [Zend](https://framework.zend.com/) No entanto, você pode estender o Valet com seus próprios drivers personalizados. ### Valet ou Homestead Como você deve saber, o Laravel oferece o [Homestead](4.Homestead.md), outro ambiente local de desenvolvimento Laravel. Homestead e Valet diferem em relação à audiência pretendida e sua abordagem ao desenvolvimento local. A Homestead oferece toda uma máquina virtual Ubuntu com configuração automática do Nginx. Homestead é uma escolha maravilhosa se você quer um ambiente de desenvolvimento Linux totalmente virtualizado ou estiver no Windows / Linux. O Valet só suporta o Mac e exige que você instale o PHP e um servidor de banco de dados diretamente em sua máquina local. Isso é facilmente alcançado usando [Homebrew](http://brew.sh/) com comandos como `brew install php71` e `brew install mysql`. O Valet fornece um ambiente de desenvolvimento local rápido, com um consumo de recursos mínimo, por isso é ótimo para desenvolvedores que requerem apenas PHP / MySQL e não precisam de um ambiente de desenvolvimento totalmente virtualizado. Tanto o Valet como o Homestead são ótimas escolhas para configurar seu ambiente de desenvolvimento Laravel. O que você escolher dependerá do seu gosto pessoal e das necessidades da sua equipe. ## Instalação **O Valet requer MacOS e o Homebrew .** **Antes da instalação, você deve garantir que nenhum outro programa, como o Apache ou o Nginx, esteja vinculado a porta 80 da máquina local.** - Instale ou atualize o [Homebrew](http://brew.sh) para a versão mais recente usando o comando `brew update` . - Instale o PHP 7.1 usando o Homebrew `brew install homebrew/php/php71` . - Instalar o Valet via Composer `composer global require laravel/valet`. Certifique-se de que o diretório `~/.composer/vendor/bin` esteja no "PATH" do seu sistema. - Execute o comando `valet install`. Isso irá configurar e instalar Valet, DnsMasq e registrar o daemon do Valet para iniciar quando o sistema for iniciado. Uma vez que Valet esteja instalado, tente fazer ping em qualquer domínio `*.test` em seu terminal usando um comando `ping foobar.test`. Se o Valet estiver instalado corretamente, você deverá ver este domínio respondendo no ip `127.0.0.1` . Valet irá automaticamente iniciar seu daemon sempre que sua máquina for inicializada. Não é necessário executar `valet start` ou `valet install` novamente, uma vez que a instalação do Valet esteja completa. #### Usando outro domínio Por padrão, o Valet atende seus projetos usando o TLD `.test`. Se você quiser usar outro domínio, pode fazê-lo usando o comando `valet domain tld-name`. Por exemplo, se você quiser usar `.app` vez de `.test`, execute `valet domain app` e o Valet começará a servir seus projetos nos domínios `*.app` automaticamente. #### Base de dados Se você precisa de um banco de dados, experimente o MySQL executando o comando `brew install mysql` em seu terminal. Uma vez que o MySQL tenha sido instalado, você pode iniciá-lo usando o comando `brew services start mysql`. Você pode então se conectar ao banco de dados em `127.0.0.1` usando o nome de usuário `root` e uma string vazia para a senha. ### Atualizando Você pode atualizar sua instalação Valet usando o comando `composer global update` em seu terminal. Após a atualização, é uma boa prática executar o comando `valet install` para que o Valet possa fazer atualizações adicionais em seus arquivos de configuração, se necessário. #### Atualizando para Valet 2.0 O Valet 2.0 transita o servidor web subjacente do Valet de Caddy para o Nginx. Antes de atualizar para esta versão, você deve executar os seguintes comandos para parar e desinstalar o _daemon_ do Caddy existente: ```sh valet stop valet uninstall ``` Em seguida, você deve atualizar para a versão mais recente do Valet. Dependendo de como você instalou o Valet, isso geralmente é feito através do Git ou Composer. Se você instalou Valet via Composer, use o seguinte comando para atualizar para a versão principal mais recente: ```sh composer global require laravel/valet ``` Uma vez que o código fonte Valet mais recente foi baixado, você deve executar o comando `install`: ```sh valet install valet restart ``` Após a atualização, talvez seja necessário recarregar ou re-ligar seus sites. ## Servindo sites Uma vez que o Valet esteja instalado, você está pronto para começar a servir os sites. O Valet fornece dois comandos para ajudá-lo a servir seus sites Laravel: `park` e `link`. **O comando `park`** - Crie um novo diretório no seu Mac executando algo como `mkdir ~/Sites`. Em seguida, `cd ~/Sites` e execute o `valet park`. Este comando registrará seu diretório de trabalho atual como um caminho que o Valet deve procurar os sites. - Em seguida, crie um novo site Laravel dentro deste diretório: `laravel new blog`. - Abra o endereço `http://blog.test` no seu navegador. **Isso é tudo.** Agora, qualquer projeto Laravel que você criar no seu diretório, será servido automaticamente usando a convenção `http://nome-da-pasta.test` . **O comando `link`** O comando `link` também pode ser usado para servir seus sites Laravel. Este comando é útil se você quiser servir um único site em um diretório e não o diretório inteiro. - Para usar o comando, navegue até um de seus projetos e execute `valet link app-name` em seu terminal. O Valet irá criar um link simbólico em `~/.valet/Sites` que aponte para o seu diretório de trabalho atual. - Depois de executar o comando `link` , você pode acessar o site em seu navegador pelo endereço `http://app-name.test`. Para ver uma listagem de todos os diretórios vinculados, execute o comando `valet links`. Você pode usar o `valet unlink app-name` para destruir o link simbólico. > **Dica:** Você pode usar o `valet link` para servir o mesmo projeto de vários (sub) domínios. Para adicionar um subdomínio ou outro domínio ao seu projeto, execute o `valet link subdomain.app-name` da pasta do projeto. **Protegendo sites com TLS** Por padrão, o Valet serve sites em HTTP simples. No entanto, se você quiser servir um site sobre TLS criptografado usando HTTP / 2, use o comando `secure`. Por exemplo, se o seu site estiver sendo servido pelo Valet no domínio `laravel.test` , você deve executar o seguinte comando para protegê-lo: ```sh valet secure laravel ``` Para "desproteger" um site e voltar a servir seu tráfego por HTTP simples, use o comando `unsecure`. Como o comando `secure`, este comando aceita o nome do host que deseja desproteger: ```sh valet unsecure laravel ``` ## Compartilhamento de sites O Valet inclui um comando para compartilhar seus sites locais com o mundo. Não é necessária nenhuma instalação de software adicional quando o Valet estiver instalado. Para compartilhar um site, navegue até o diretório do site em seu terminal e execute o comando `valet share`. Uma URL acessível ao público será inserida em sua área de transferência e estará pronta para colar diretamente no seu navegador. É isso aí. Para parar de compartilhar seu site, pressione `Control + C` para cancelar o processo. > **Dica:** o comando `valet share` atualmente não suporta compartilhar sites que tenham sido protegidos usando o comando `valet secure`. ## Valet Drivers personalizados Você pode escrever seu próprio "driver" do Valet para atender aplicativos PHP em execução em outra estrutura ou CMS que não seja suportado nativamente pelo Valet. Quando você instala o Valet, é criado um diretório `~/.valet/Drivers` que contém um arquivo `SampleValetDriver.php`. Este arquivo contém uma implementação de exemplo de driver para demonstrar como escrever um driver personalizado. Escrever apenas um driver requer que você implemente três métodos: `serves`, `isStaticFile` e `frontControllerPath`. Todos os três métodos recebem os valores `$sitePath` , `$siteName` e `$uri` como argumentos. O `$sitePath` é o caminho totalmente qualificado para o site que está sendo servido em sua máquina, como `/Users/Lisa/Sites/my-project`. O `$siteName` é a parte "host" / "nome do site" do domínio ( `my-project` ). O `$uri` é o URI de solicitação de entrada ( `/foo/bar` ). Depois de concluir o seu driver personalizado, coloque-o no diretório `~/.valet/Drivers`usando a convenção de nomenclatura `FrameworkValetDriver.php`. Por exemplo, se você estiver escrevendo um driver de valet personalizado para WordPress, seu nome de arquivo deve ser `WordPressValetDriver.php`. Vamos dar uma olhada em uma implementação de exemplo de cada método que seu driver Valet personalizado deve implementar. #### O método `serves` O método de serviço deve retornar `true` se seu driver deve lidar com a solicitação recebida. Caso contrário, o método deve retornar `false` . Então, dentro desse método, você deve tentar determinar se o `$sitePath` contém um projeto do tipo que você está tentando atender. Por exemplo, vamos fingir que estamos escrevendo um `WordPressValetDriver` . Nosso método de atendimento pode ser algo assim: ```php /** * Determine if the driver serves the request. * * @param string $sitePath * @param string $siteName * @param string $uri * @return bool */ public function serves($sitePath, $siteName, $uri) { return is_dir($sitePath.'/wp-admin'); } ``` #### O método `isStaticFile` O `isStaticFile` deve determinar se a solicitação recebida é para um arquivo que é "estático", como uma imagem ou uma folha de estilo. Se o arquivo for estático, o método deve retornar o caminho totalmente qualificado para o arquivo estático no disco. Se a solicitação recebida não for para um arquivo estático, o método deve retornar `false`: ```php /** * Determine if the incoming request is for a static file. * * @param string $sitePath * @param string $siteName * @param string $uri * @return string|false */ public function isStaticFile($sitePath, $siteName, $uri) { if (file_exists($staticFilePath = $sitePath.'/public/'.$uri)) { return $staticFilePath; } return false; } ``` > **Nota:** O método `isStaticFile` só será chamado se o método `serves` retornar `true`para a solicitação recebida e o URI da solicitação não for `/` . #### O método `frontControllerPath` O método `frontControllerPath` deve retornar o caminho totalmente qualificado para o "controller frontal" do seu aplicativo, que geralmente é seu arquivo "index.php" ou equivalente: ```php /** * Get the fully resolved path to the application's front controller. * * @param string $sitePath * @param string $siteName * @param string $uri * @return string */ public function frontControllerPath($sitePath, $siteName, $uri) { return $sitePath.'/public/index.php'; } ``` ### Drivers Locais Se você quiser definir um driver do Valet personalizado para um único aplicativo, crie um `LocalValetDriver.php` no diretório raiz do aplicativo. Seu driver personalizado pode estender a classe Base `ValetDriver` ou estender um driver específico do aplicativo existente, como o `LaravelValetDriver`: ```php class LocalValetDriver extends LaravelValetDriver { /** * Determine if the driver serves the request. * * @param string $sitePath * @param string $siteName * @param string $uri * @return bool */ public function serves($sitePath, $siteName, $uri) { return true; } /** * Get the fully resolved path to the application's front controller. * * @param string $sitePath * @param string $siteName * @param string $uri * @return string */ public function frontControllerPath($sitePath, $siteName, $uri) { return $sitePath.'/public_html/index.php'; } } ``` ## Outros Comandos do Valet | Comando | Descrição | | ---------------------------- | :--------------------------------------- | | `valet forget``valet forget` | Execute este comando de um diretório "estacionado" para removê-lo da lista de diretórios estacionados. | | `valet paths` | Veja todos os caminhos "estacionados". | | `valet restart` | Reinicie o daemon do Valet. | | `valet start` | Inicie o daemon do Valet. | | `valet stop` | Para o daemon do Valet. | | `valet uninstall` | Desinstale inteiramente o daemon do Valet. |
Python
UTF-8
7,228
3.421875
3
[]
no_license
import pandas as pd from os import path import sys # name_filter list containing elements acceptable to have within last names (add to it if desired) name_filter = ['jr', 'sr', 'von', 'van', 'mac', 'st', 'mc', 'de', 'la', 'du', 'le', '2nd', '3rd', 'ii', 'iii', 'lodge', 'admission', 'admissions', 'des', 'di', '#', 'mc\'', 'o\'', 'd\'', 'lll', '4th', '5th', '6th', '#1', '#2', '#3', '#4', '#5', 'le', 'de', '111', '11', '3', '2'] error_dict = {} def increment_dict(key): # if the Lodge is not counted in dictionary yet, add it with 1 error as its data if key not in error_dict.keys(): error_dict[key] = 1 # otherwise find the Lodge and increment the number of errors by 1 else: error_dict[key] += 1 # writes file path previously used def write_file_path(path_to_file): # open file in write mode, then write the file path used this iteration of the program if path_to_file != 'pandas_simple.xlsx': f = open("old_excel_file_path.txt", "w") f.write(path_to_file) f.close() # close the file to save changes # reads file path previously used def read_file_path(): # open file in read mode and parse old file path f = open("old_excel_file_path.txt", "r") path_to_file = f.read() f.close() # close file to save return path_to_file # return old file path to be opened again in other part of program # function checks if a given name is valid def is_name_valid(name_in): name_list = name_in.split() # split the last name where there is whitespace and return as a list of sub-names # checks if last name is more than one word (check if the sub-name list has more than 1 element) if len(name_list) > 1: # iterate over parts of last name for string in name_list: # check parts of last name against filter of valid last name elements # strips off '.' if possible to account for elements like 'jr' and 'jr.' being the same thing # if name_filter.__contains__(string.strip().strip(',').strip('.').lower()): if '?' in string: return False if name_filter.__contains__(string.lower().replace(',.', '')): return True # return True if the name has a valid part as specified by filter return False # return False if the name does not have a part described in filter, name invalid return True # name length is < 2 so it is automatically considered valid def first_name_valid(name_in): name_list = name_in.split() titles = {'jr', 'sr'} if len(name_list) > 1: # iterate over parts of last name for string in name_list: if titles.__contains__(string.lower().replace(',.', '')): return False return True # gets the file path and filename from user and checks that it exists and # is a valid excel file def get_filename(): # check if user wants to use previously used file path old_file_path = read_file_path() string = 'Do you want to use previous file path \'' + old_file_path + '\'? (y/n): ' use_old_file = input(string) # get input from user to determine if they want to use old file path # old file logic if use_old_file.lower() == 'y': return old_file_path # if using old file path, return it and stop further input from user elif use_old_file.lower() != 'n': print("Invalid input. Assuming new file path. ") # loop until valid file path given or quit on 'q' while True: # get file path from user and strip off '"' from path if present filename = input('Enter file path to excel file or \'q\' to quit: ').strip("\"") # quit if input is q if filename.lower() == 'q': print('Exiting gracefully...') sys.exit(0) # check file path and file type elif path.exists(filename) and filename.endswith('.xlsx'): print('File path valid. Filtering names...') return filename # return file path if it is valid else: # file path or file name was invalid so keep looping until valid path found print('Invalid file path or file name. ') # finds row index of the given first and last name in the data frame and returns it def get_row_index(data_frame, fist_name, lst_name): matching = data_frame.loc[data_frame['Last Name'] == lst_name].index.values for x in matching: if data_frame.loc[data_frame.index[x], 'First Name'] == fist_name: return x raise IndexError('No matching values found.') def mark_names(file_name): data = pd.read_excel(file_name) internal_tally = 0 if 'Highlight' not in data: data['Highlight'] = '' for index, row in data.iterrows(): # try/except in case of exceptions being thrown during runtime try: if not is_name_valid(row['Last Name']) or not first_name_valid(row['First Name']): last_name = row['Last Name'] first_name = row['First Name'] idx = get_row_index(data, first_name, last_name) # getting row number so it can swap elements print('Marking', first_name, last_name) internal_tally += 1 data.at[idx, 'Highlight'] = 'Error' # catch AttributeError exception thrown when a cell is NaN or empty except AttributeError: continue # if there is an AttributeError, ignore the row and keep going # catch KeyError exception thrown when 'Last Name' or 'Lodge' column cannot be found except KeyError: print('Error: \'Last Name\' or \'Lodge\' column could not be found. Verify spreadsheet column formatting. ') print('Exiting...') sys.exit(0) except IndexError: continue # no matching values found in get index just continue for now TODO: fix this # general exception catch of all unknown exceptions except Exception as e: print('\nError: Unexpected exception thrown.') print('Exception message:', str(e)) print('Exiting...') sys.exit(-1) print('Saving excel file...') writer = pd.ExcelWriter('corrected.xlsx', engine='xlsxwriter') data.to_excel(writer, sheet_name='Sheet1') writer.save() print('Updated file saved to corrected.xlsx') return internal_tally def write_output_to_file(filename, output_str): filename = filename.split('\\') filename = filename[-1].strip('.xlsx') + '.txt' print('Saving to:', filename, '\n') f = open(filename, "w+") f.write(output_str) f.close() # close the file to save changes # Start of script: # ===================================================================================================================== # opens and reads the excel file, puts file data into data frame obj valid_filename = get_filename() tally = mark_names(valid_filename) print() print(tally, 'names marked.\n') print('Exiting gracefully...')
C++
UTF-8
2,606
3.65625
4
[]
no_license
#ifndef EMISSOR_H #define EMISSOR_H #include <string> #include <regex> #include <iostream> /** * @file Emissor.h * @author Lívia Gomes Costa Fonseca * @author Natalia Oliveira Borges * * Esse arquivo contém a implementação da classe de domínio Emissor. Essa classe armazena o atributo emissor no formato * de uma string. */ /** * @brief Armazena o emissor de produto de investimento. */ class Emissor { public: /** * @brief Construtor default. * @details Inicializa o atributo emissor como string vazia. */ Emissor(); /** * @brief Construtor que inicializa emmissor com um valor. * @details Para ser válido, o emissor fornecido deve possuir de 5 a 30 caracteres. * Cada caracter pode ser letra (A-Z ou a-z), dígito (0 –9), caracter "-", * ponto ou espaço. Apenas letras e dígitos podem estar em sequência. * Em termo cujo primeiro caracter é letra, a letra deve ser maiúscula. * @param codigo String a ser escrita no atributo. * @throw invalid_argument Se valor passado não for válido. */ Emissor(std::string); /** * @brief Escrita do valor em emissor, se válido. * @details Para ser válido, o emissor fornecido deve possuir de 5 a 30 caracteres. * Cada caracter pode ser letra (A-Z ou a-z), dígito (0 –9), caracter "-", * ponto ou espaço. Apenas letras e dígitos podem estar em sequência. * Em termo cujo primeiro caracter é letra, a letra deve ser maiúscula. * @param codigo String a ser escrita no atributo. * @throw invalid_argument Se valor passado não for válido. */ void setEmissor(std::string); /** * @brief Leitura do valor armazenado em emissor. * @return emissor Retorna string com valor armazenado em emmissor. */ std::string getEmissor(); private: std::string emissor; /** * @brief Verifica se o emissor é válido. * @details Para ser válido, o emissor fornecido deve possuir de 5 a 30 caracteres. * Cada caracter pode ser letra (A-Z ou a-z), dígito (0 –9), caracter "-", * ponto ou espaço. Apenas letras e dígitos podem estar em sequência. * Em termo cujo primeiro caracter é letra, a letra deve ser maiúscula. * @param codigo String a ser verificado. * @throw invalid_argument Se valor passado não for válido. */ void valida(std::string); }; #endif // EMISSOR_H
C#
UTF-8
1,532
2.703125
3
[]
no_license
using Application.Common.MeetingRooms.Factory; using Application.Interfaces; using Serilog; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Application.MeetingRooms.UpdateMeetingRoom { public class UpdateMeetingRoomCommand : IUpdateMeetingRoomCommand { private readonly IDatabaseService _database; private readonly IMeetingRoomFactory _factory; public UpdateMeetingRoomCommand( IDatabaseService database, IMeetingRoomFactory factory) { _database = database; _factory = factory; } public void Execute(UpdateMeetingRoomModel model) { var currentMeetingRoom = _database.MeetingRooms.Single(x => x.Id == model.Id); var newName = model.Name; var newLocation = model.Location; var newSize = model.Size; var newMeetingRoom = _factory.Update( currentMeetingRoom: currentMeetingRoom, newLocation: newLocation, newName: newName, newSize: newSize); try { _database.MeetingRooms.Remove(currentMeetingRoom); _database.MeetingRooms.Add(newMeetingRoom); _database.Save(); } catch (Exception e) { Log.Logger.Error(e, "Error occured while updating meeting room in database."); throw; } } } }
C
UTF-8
298
3.703125
4
[]
no_license
#include<stdio.h> int main(){ int n,i; float sum; printf("s=1+1/2+1/3+1/4.........\n"); printf("Enter number of term till series continue :\n"); scanf("%d",&n); i=1; while(i<=n){ sum=sum+1/(float)i; i++; } printf("Calculated value of series till %d is :%f \n",n,sum); return 0; }
C#
UTF-8
1,213
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Backend.Domain.Entities { public class Patient { public string name { get; set; } public string lastname { get; set; } public string documentType { get; set; } public string documentNumber { get; set; } public string phoneNumber { get; set; } public string email { get; set; } public DateTime birthdate { get; set; } public DateTime creationDate { get; set; } public string country { get; set; } public string city { get; set; } public Patient(string name, string lastname, string documentType, string documentNumber, string phoneNumber, string email, DateTime birthdate, string country, string city) { this.name = name; this.lastname = lastname; this.documentType = documentType; this.documentNumber = documentNumber; this.phoneNumber = phoneNumber; this.email = email; this.birthdate = birthdate; this.country = country; this.city = city; } public Patient() { } } }
C++
UTF-8
1,523
2.578125
3
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
//Download by http://www.NewXing.com #ifndef CRYPTOPP_HAVAL_H #define CRYPTOPP_HAVAL_H #include "iterhash.h" NAMESPACE_BEGIN(CryptoPP) class HAVAL : public IteratedHash<word32> { public: enum {DIGESTSIZE = 32, DATASIZE = 128, VERSION = 1}; // digestSize can be 16, 20, 24, 28, or 32 // pass can be 3, 4 or 5 HAVAL(unsigned int digestSize=DIGESTSIZE, unsigned int passes=3); void Final(byte *hash); unsigned int DigestSize() const {return digestSize;} static void CorrectEndianess(word32 *out, const word32 *in, unsigned int byteCount) { #ifndef IS_LITTLE_ENDIAN byteReverse(out, in, byteCount); #else if (in!=out) memcpy(out, in, byteCount); #endif } protected: static const unsigned int wi2[32], wi3[32], wi4[32], wi5[32]; static const word32 mc2[32], mc3[32], mc4[32], mc5[32]; private: void Init(); void HashBlock(const word32 *input); void Tailor(unsigned int FPTLEN); inline void vTransform(word32 *buf, const word32 *in); const unsigned int digestSize, pass; }; class HAVAL3 : public HAVAL { public: HAVAL3(unsigned int digestSize=DIGESTSIZE) : HAVAL(digestSize, 3) {} static void Transform(word32 *buf, const word32 *in); }; class HAVAL4 : public HAVAL { public: HAVAL4(unsigned int digestSize=DIGESTSIZE) : HAVAL(digestSize, 4) {} static void Transform(word32 *buf, const word32 *in); }; class HAVAL5 : public HAVAL { public: HAVAL5(unsigned int digestSize=DIGESTSIZE) : HAVAL(digestSize, 5) {} static void Transform(word32 *buf, const word32 *in); }; NAMESPACE_END #endif
JavaScript
UTF-8
725
2.546875
3
[]
no_license
const { form, buyOnline, numberInput, colorChoices: chooseColor, sizeChoices: chooseSize, buttons, addToCartBtn, } = domSelectors(); // annonymous functions form.addEventListener('submit', (e) => { e.preventDefault(); notifyUser(); }); buyOnline.addEventListener('click', (e) => { e.preventDefault(); }); numberInput.addEventListener('keyup', () => { numberInput.value = numberInput.value.slice(0, 1); }); chooseColor.addEventListener('click', userSelections); chooseSize.addEventListener('click', userSelections); buttons.forEach((button) => button.addEventListener('click', changeInputValueWithBtns) ); document.querySelector('.close-cart').addEventListener('click', hideOverlayAndMiniCart);
Python
UTF-8
2,298
3.125
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[ ]: # In[1]: # Importing all important libraries needed import pandas as pd import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import model_selection from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer, HashingVectorizer, TfidfTransformer, TfidfVectorizer from sklearn.pipeline import Pipeline from sklearn.model_selection import StratifiedShuffleSplit import pickle # In[2]: # Dataset Reading from csv file df1 = pd.read_csv("shuffled-full-set-hashed.csv",header=None) df1.columns =['type', 'content'] df=df1.copy() # In[3]: # let's see the distribution of the data to different classes df.groupby('type').count().transpose() # In[4]: # Removal of Null values df=df[df.content.notnull()].reset_index(drop=True) # Removal of spaces from beginning and end df=df.apply(lambda x: x.str.strip() if x.dtype == "object" else x) # Removal of duplicates df=df.drop_duplicates().reset_index(drop=True) # In[5]: # Let's check whether the null values are removing any specific class or not df1[df1.content.isnull()].reset_index(drop=True).groupby('type')[['type']].count().transpose() # In[6]: # Spliting the dataset in training and testing X_train, X_test, Y_train, Y_test = model_selection.train_test_split(df, df.type, test_size=0.20, random_state=1000, stratify=df['type']) # In[7]: # Calling diff. vectorizers CountVectTokenizer = CountVectorizer() hashingVectTokenizer = HashingVectorizer() TfidfVectTokenizer = TfidfVectorizer() TfidfTransfTokenizer = TfidfTransformer() # In[8]: # Cnvert raw text data to numeric data || Tokenizing tfidf = TfidfVectTokenizer.fit_transform(X_train.content.values.astype('U')) tfidf1 = TfidfVectTokenizer.transform(X_test.content.values.astype('U')) # In[9]: # Building the Logistic Regression Model model = LogisticRegression(n_jobs=-1, max_iter=50) model.fit(tfidf, Y_train) # In[10]: # Evaluation || Accuracy print(model.score(tfidf1, Y_test)) # In[11]: # Store model and vectorizer pickle.dump(model, open('LRmodel.pkl', 'wb')) pickle.dump(TfidfVectTokenizer, open('vec.pkl', 'wb'))
C++
WINDOWS-1252
1,287
2.640625
3
[]
no_license
/** * @file shared_lock_guard.h * @author wangcong(a1e2w3@126.com) * @date 2018-01-31 16:00:37 * @brief д * **/ #ifndef WRPC_UTILS_SHARED_LOCK_GUARD_H_ #define WRPC_UTILS_SHARED_LOCK_GUARD_H_ #include <pthead.h> namespace wrpc { class SharedMutex { public: SharedMutex() { pthread_rwlock_init(&_rw_lock, nullptr); } ~SharedMutex() { pthread_rwlock_destroy(&_rw_lock); } int lock_shared() { return pthread_rwlock_rdlock(&_rw_lock); } void unlock_shared() { pthread_rwlock_unlock(&_rw_lock); } int lock() { return pthread_rwlock_wrlock(&_rw_lock); } void unlock() { pthread_rwlock_unlock(&_rw_lock); } private: pthread_rwlock_t _rw_lock; }; class SharedLockGuard { public: explicit SharedLockGuard(SharedMutex& mutex) : _mutex(mutex) { _mutex.lock_shared(); } ~SharedLockGuard() { _mutex.unlock_shared(); } private: SharedMutex& _mutex; }; class ExclusiveLockGuard { public: explicit ExclusiveLockGuard(std::shared_mutex& mutex) : _mutex(mutex) { _mutex.lock(); } ~ExclusiveLockGuard() { _mutex.unlock(); } private: std::shared_mutex& _mutex; }; } // end namespace wrpc #endif // WRPC_UTILS_SHARED_LOCK_GUARD_H_ /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
C++
UTF-8
799
3.6875
4
[]
no_license
/* * Name : derived_main.cpp * Author : Luke Sathrum * Description : Testing our derived and base class. This file uses person.h, * baseball_player.h, employee.h and supervisor.h */ #include <iostream> #include "person.h" #include "baseball_player.h" using std::cout; using std::endl; // Program starts here int main() { // Create an instance of our base class Person me("Abraham Lincoln", 56, 'M'); cout << me.ToString() << endl; // Create an instance of our derived class BaseballPlayer mays(.302, 660); cout << mays.ToString() << endl; // That's not the right info, let's change it mays.set_name("Willie Mays"); mays.set_age(83); mays.set_gender('M'); cout << mays.ToString() << endl; // This ends our program return 0; }
JavaScript
UTF-8
1,315
2.640625
3
[ "MIT" ]
permissive
import React, { useState, useEffect } from "react"; import axios from "axios"; import RequestError from "./RequestError"; export default function ShipDetails(props) { const [ship, setShip] = useState(null); const [shipDetailsID, setShipDetailsID] = useState(props.shipDetailsID); const [requestError, setRequestError] = useState(null); useEffect(() => { setShipDetailsID(props.shipDetailsID); }, [props.shipDetailsID]); useEffect(() => { setShip(null); setRequestError(null); if (shipDetailsID) { axios .get(`http://localhost:3001/ships/${shipDetailsID}`) .then((res) => setShip(res.data)) .catch((error) => setRequestError(<RequestError error={error} />)); } }, [shipDetailsID]); return ( <div className="ShipDetails"> <h2>Ship Details</h2> <div> Show details for id: <input type="text" size="3" value={shipDetailsID} onChange={(e) => setShipDetailsID(e.target.value.trim())} /> </div> {ship && <pre>{JSON.stringify(ship, null, " ")}</pre>} {requestError} </div> ); }
C
UTF-8
1,214
2.890625
3
[ "Apache-2.0" ]
permissive
#pragma once #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <openssl/evp.h> #include <openssl/rsa.h> /*! * Get size of Full Domain Hash result. */ size_t openssl_fdh_len(RSA *key); /*! * Compute Full Domain Hash. * * \param[in] data Input data. * \param[in] data_len Length of the input data. * \param[out] sign Output buffer. * \param[in] sign_len Capacity of the output buffer. * \param[in] key RSA private key. * \param[in] hash Hash function. * * \return Size of the Full Domain Hash, zero on error. */ size_t openssl_fdh_sign(const uint8_t *data, size_t data_len, uint8_t *sign, size_t sign_len, RSA *key, const EVP_MD *hash); /*! * Verify Full Domain Hash. * * \param[in] data Input data. * \param[in] data_len Length of the input data. * \param[in] sign Signature to verify. * \param[in] sign_len Length of the signature. * \param[in] key RSA public/private key. * \param[in] hash Hash function. * * \return True if the signature was validated successfully. */ bool openssl_fdh_verify(const uint8_t *data, size_t data_len, const uint8_t *sign, size_t sign_len, RSA *key, const EVP_MD *hash);
Python
UTF-8
145
2.859375
3
[]
no_license
#!/usr/bin/env python3 N, A, X, Y = map(int,(input().split())) if N > A: ans = A * X + (N-A) * Y else: ans = N * X print(ans)
Java
UTF-8
275
1.625
2
[]
no_license
package com.benghuai3.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class GushiController { @RequestMapping("gushi.html") public String gushi() { return "gushi"; } }
JavaScript
UTF-8
4,932
2.578125
3
[]
no_license
{ let view = { el: '.page>main', template: ` <form class="form"> <div class="row"> <label>歌名</label> <input name="name" type="text" value="__name__"> <input name="id" type="hidden" value="__id__"> </div> <div class="row"> <label>歌手</label> <input name="siger" type="text" value="__siger__"> </div> <div class="row"> <label>外链</label> <input name="url" type="text" value="__url__"> </div> <div class="row"> <label>封面</label> <input name="conver" type="text" value="__conver__"> </div> <div class="row"> <label>歌词</label> <textarea name="lyrics">__lyrics__</textarea> </div> <div class="row actions"> <button>保存</button> </div> </form>`, render(data = {}) { let placeholders = ['name', 'siger', 'url', 'id', 'conver', 'lyrics']; let html = this.template; placeholders.map((string) => { html = html.replace(`__${string}__`, data[string] || ''); }) $(this.el).html(html); if (data.id) { $(this.el).prepend('<h1>编辑歌曲</h1>') } else { $(this.el).prepend('<h1>新增歌曲</h1>') } }, init() { this.$el = $(this.el); }, reset() { this.render({}) } } let model = { data: { id: '', name: '', siger: '', url: '', conver: '', lyrics: '' }, create(data) { let Song = AV.Object.extend('Song'); let song = new Song(); song.set('name', data.name); song.set('siger', data.siger); song.set('conver', data.conver); song.set('lyrics', data.lyrics); song.set('url', data.url); return song.save().then((newSong) => { let { id, attributes } = newSong; Object.assign(this.data, { id, ...attributes }) }, (error) => { console.log(error); }) }, update(data) { let song = AV.Object.createWithoutData('Song', data.id); song.set('name', data.name); song.set('siger', data.siger); song.set('conver', data.conver); song.set('lyrics', data.lyrics); song.set('url', data.url); return song.save().then((response) => { Object.assign(this.data, data); }) } }; let controller = { init(view, model) { this.view = view; this.model = model; this.view.render(this.model.data); this.view.init(); this.bindEvents(); this.bindEventHub(); }, create() { let data = {}; let needs = "name siger url id conver lyrics".split(" "); needs.map((string) => { data[string] = this.view.$el.find(`[name="${string}"]`).val(); }) this.model.create(data).then(() => { this.view.reset(); var copy = JSON.stringify(this.model.data); var object = JSON.parse(copy); window.eventHub.emit('create', object); }); }, update() { let data = {}; let needs = "name siger url id conver lyrics".split(" "); needs.map((string) => { data[string] = this.view.$el.find(`[name="${string}"]`).val(); }) this.model.update(data).then(() => { window.eventHub.emit('update', JSON.parse(JSON.stringify(this.model.data))); }); }, bindEvents() { this.view.$el.on('submit', 'form', (e) => { e.preventDefault(); if (this.model.data.id) { this.update(); } else { this.create(); } }) }, bindEventHub() { window.eventHub.on('select', (data) => { this.model.data = data; this.view.render(this.model.data); }) window.eventHub.on('new', (data) => { if (this.model.data.id) { this.model.data = data || { id: '', name: '', url: '', siger: '', conver: '',lyrics: '' }; } else { Object.assign(this.model.data, data); } this.view.render(this.model.data); }) } } controller.init(view, model); }
Java
UTF-8
1,319
2.265625
2
[]
no_license
package com.plusultra.puppyland.utils; import com.badlogic.gdx.math.Vector2; import com.plusultra.puppyland.stages.GameStage; public class Constants { public static final Vector2 WORLD_GRAVITY = new Vector2(0, -10); public static final float LEVEL_SPACING = GameStage.VIEWPORT_HEIGHT / 3; public static final float GROUND_X = 0; public static final float GROUND_Y = 0; public static final float GROUND_WIDTH = GameStage.VIEWPORT_WIDTH * 3; public static final float GROUND_HEIGHT = 0.1f; public static final float GROUND_DENSITY = 0f; public static final float RUNNER_WIDTH = 1f; public static final float RUNNER_HEIGHT = 7f; public static final float RUNNER_X = 2f; public static final float RUNNER_Y = GROUND_Y + GROUND_HEIGHT + RUNNER_HEIGHT / 2; public static final float RUNNER_DENSITY = 0.5f; public static final float OBSTACLE_X = 25f; public static final float OBSTACLE_DENSITY = RUNNER_DENSITY; public static final float RUNNING_SHORT_OBSTACLE_Y = GROUND_Y + GROUND_HEIGHT; public static final Vector2 OBSTACLE_LINEAR_VELOCITY = new Vector2(-10f, 0); // Game World Dimension: 20x41 // Screen Dimension: 2768x1440 public static final float PIXELS_TO_METERS_X = 138.4f; public static final float PIXELS_TO_METERS_Y = 35f; }
Java
UTF-8
1,022
1.9375
2
[]
no_license
package com.meiyuan.catering.order.dto.splitbill; import com.meiyuan.catering.order.enums.TradeStatusEnum; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.time.LocalDateTime; /** * @author GongJunZheng * @date 2020/10/09 15:10 * @description 补贴分账流水状态修改DTO **/ @Data @ApiModel("补贴分账流水状态修改DTO") public class SubsidyFlowStatusUpdateDTO { @ApiModelProperty(value = "主键ID") private Long id; @ApiModelProperty(value = "第三方交易流水编号") private String thirdTradeNumber; @ApiModelProperty(value = "交易状态(0:未交易;1:交易中;2:交易成功;3:交易失败)") private Integer tradeStatus; @ApiModelProperty(value = "失败原因") private String failMessage; @ApiModelProperty(value = "成功时间") private LocalDateTime successTime; @ApiModelProperty(value = "请求参数信息") private String requestMessage; }
Java
UTF-8
7,622
1.804688
2
[]
no_license
package com.phincon.talents.app.model.hr; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import com.phincon.talents.app.model.AbstractEntity; @Entity @Table(name = "hr_request_type") public class RequestType extends AbstractEntity { @Column(name = "module", length = 100) private String module; @Column(name = "category_type", length = 100) private String categoryType; @Column(name = "category_type_ext_id", length = 100) private String categoryTypeExtId; @Column(name = "type", length = 100) private String type; @Column(name = "remark", length = 255) private String remark; @Column(name = "grade") private Integer grade; @Column(name = "grade_start") private Integer gradeStart; @Column(name = "grade_end") private Integer gradeEnd; @Column(name = "position", length = 2000) private String position; @Column(name = "job_title", length = 1000) private String jobTitle; @Column(name = "type_label", length = 255) private String typeLabel; // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "company_id") // private Company company; @Column(name = "company_id") private Long company; // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "request_cat_type_id") // private RequestCategoryType requestCategoryType; @Column(name = "request_cat_type_id") private Long requestCategoryType; @Column(name = "active") private Boolean active; @Column(name = "show_attachment") private Boolean showAttachment; @Column(name = "required_attachment") private Boolean requiredAttachment; @Column(name="max_num_of_days") private Integer maxNumOfDays; @Column(name = "need_balance") private Boolean needBalance; @Column(name="can_back_date") private Boolean canBackDate; @Column(name="can_future_date") private Boolean canFutureDate; @Column(name="limit_future_date") private Integer limitFutureDate; // day, 0 = unlimited @Column(name="limit_back_date") private Integer limitBackDate; //day, 0 = unlimited @Column(name="gender", length=20) private String gender; //day, 0 = unlimited @Column(name="flag_overtime") private Boolean flagOvertime; @Column(name="default_max_minutes_per_month") private Integer defaultMaxMinutesPerMonth; //day, 0 = unlimited @Column(name="max_minutes_per_month_jobtitle") private Integer maxMinutesPerMonthJobtitle; //day, 0 = unlimited @Column(name="cannot_request_today") private Boolean cannotRequestToday; @Column(name="limit_day_of_month") private Integer limitDayOfMonth; // batas tanggal submit transaksi per bulan ex: 5, untuk request date bulan kemarin hanya bs di masukan sampai tanggal 5 bulan ini @Column(name="is_calendar_date") private Boolean isCalendarDate; public String getModule() { return module; } public void setModule(String module) { this.module = module; } public String getCategoryType() { return categoryType; } public void setCategoryType(String categoryType) { this.categoryType = categoryType; } public String getCategoryTypeExtId() { return categoryTypeExtId; } public void setCategoryTypeExtId(String categoryTypeExtId) { this.categoryTypeExtId = categoryTypeExtId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Long getCompany() { return company; } public void setCompany(Long company) { this.company = company; } public Long getRequestCategoryType() { return requestCategoryType; } public void setRequestCategoryType(Long requestCategoryType) { this.requestCategoryType = requestCategoryType; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public Boolean getNeedBalance() { return needBalance; } public void setNeedBalance(Boolean needBalance) { this.needBalance = needBalance; } public Boolean isCanBackDate() { return canBackDate; } public void setCanBackDate(Boolean canBackDate) { this.canBackDate = canBackDate; } public Boolean isCanFutureDate() { return canFutureDate; } public void setCanFutureDate(Boolean canFutureDate) { this.canFutureDate = canFutureDate; } public Integer getLimitFutureDate() { return limitFutureDate; } public void setLimitFutureDate(Integer limitFutureDate) { this.limitFutureDate = limitFutureDate; } public Integer getLimitBackDate() { return limitBackDate; } public void setLimitBackDate(Integer limitBackDate) { this.limitBackDate = limitBackDate; } public String getTypeLabel() { return typeLabel; } public void setTypeLabel(String typeLabel) { this.typeLabel = typeLabel; } public Boolean getShowAttachment() { return showAttachment; } public void setShowAttachment(Boolean showAttachment) { this.showAttachment = showAttachment; } public Boolean getRequiredAttachment() { return requiredAttachment; } public void setRequiredAttachment(Boolean requiredAttachment) { this.requiredAttachment = requiredAttachment; } public Integer getMaxNumOfDays() { return maxNumOfDays; } public void setMaxNumOfDays(Integer maxNumOfDays) { this.maxNumOfDays = maxNumOfDays; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } public Integer getGradeEnd() { return gradeEnd; } public void setGradeEnd(Integer gradeEnd) { this.gradeEnd = gradeEnd; } public Integer getGradeStart() { return gradeStart; } public void setGradeStart(Integer gradeStart) { this.gradeStart = gradeStart; } public Boolean getFlagOvertime() { return flagOvertime; } public void setFlagOvertime(Boolean flagOvertime) { this.flagOvertime = flagOvertime; } public Integer getDefaultMaxMinutesPerMonth() { return defaultMaxMinutesPerMonth; } public void setDefaultMaxMinutesPerMonth(Integer defaultMaxMinutesPerMonth) { this.defaultMaxMinutesPerMonth = defaultMaxMinutesPerMonth; } public Integer getMaxMinutesPerMonthJobtitle() { return maxMinutesPerMonthJobtitle; } public void setMaxMinutesPerMonthJobtitle(Integer maxMinutesPerMonthJobtitle) { this.maxMinutesPerMonthJobtitle = maxMinutesPerMonthJobtitle; } public Boolean getCannotRequestToday() { return cannotRequestToday; } public void setCannotRequestToday(Boolean cannotRequestToday) { this.cannotRequestToday = cannotRequestToday; } public Integer getLimitDayOfMonth() { return limitDayOfMonth; } public void setLimitDayOfMonth(Integer limitDayOfMonth) { this.limitDayOfMonth = limitDayOfMonth; } public Boolean getIsCalendarDate() { return isCalendarDate; } public void setIsCalendarDate(Boolean isCalendarDate) { this.isCalendarDate = isCalendarDate; } }
Ruby
UTF-8
228
2.578125
3
[ "MIT" ]
permissive
require "validatessn/version" module Validatessn def validate(number) return false unless number.length == 9 if number.match(/^[0-8]\d{2}-\d{2}-\d{4}$/) return true else return false end end end
Markdown
UTF-8
759
3
3
[]
no_license
# Twitter Simulation This project simulates posting and retrieving tweets as the Twitter application would do. It was built as a Java API with two current implementations using different databases, one with Postgres and one with Redis. Read/write speeds were tested and documented for each implementation, then compared. ## To run: - run the 'generator' file in order to generate CSV files of random tweets and follower combinations - Run the 'implementor' file to perform the simulation. When running this file, follow the command line instructions to select a database type. ## Project structure: - generated CSV files are stored in the ./data directory - results and instructions for both assignment versions are stored in the ./documents directory
JavaScript
UTF-8
641
3.78125
4
[]
no_license
var deck = ["2 Heart", "3 Heart", "4 Heart", "5 Heart", "2 Spade", "3 Spade", "4 Spade", "5 Spade", "2 Club", "3 Club", "4 Club", "5 Club", "2 Diamond", "3 Diamond", "4 Diamond", "5 Diamond"]; var chosenCards = []; function drawCard() { var randomNum = Math.floor(Math.random() * deck.length); var card = deck[randomNum]; deck.splice(randomNum, 1); if (deck.length === 0) { deck = chosenCards; chosenCards = [] return console.log("cards shuffled, draw again."); } else { chosenCards.unshift(card); return console.log(chosenCards[0]); } }
Java
UTF-8
11,753
2.109375
2
[]
no_license
package co.quchu.quchu.net; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import co.quchu.quchu.R; import co.quchu.quchu.base.ActManager; import co.quchu.quchu.base.AppContext; import co.quchu.quchu.dialog.DialogUtil; import co.quchu.quchu.utils.LogUtils; import co.quchu.quchu.utils.SPUtils; import co.quchu.quchu.utils.StringUtils; import co.quchu.quchu.view.activity.LoginActivity; import co.quchu.quchu.view.activity.SearchActivity; /** * NetService * User: Chenhs * Date: 2015-10-30 * 网络请求框架的进一步封装 * 对返回数据初步处理 */ public class NetService { public static RequestQueue mRequestQueue = GsonRequest.queue; public static void addRequest(Request request, Object tag) { if (tag != null) { request.setTag(tag); } mRequestQueue.add(request); } public static void post(Context cont, String pUrl, JSONObject params, IRequestListener pListener) { LogUtils.d(pUrl); if (!NetUtil.isNetworkConnected(AppContext.mContext)) { // NetErrorDialog.showProgess(cont); // NetErrorDialogUtil.showProgess(cont, "请检查网络"); DialogUtil.dismissProgess(); Toast.makeText(cont, (R.string.network_error), Toast.LENGTH_SHORT).show(); } else { addToQueue(Request.Method.POST, pUrl, params, pListener, 0,false); /* if (params != null) LogUtils.json("userData==" + params.toString());*/ } } public static void postRaw(Context cont, String pUrl, JSONObject params, IRequestListener pListener) { LogUtils.d(pUrl); if (!NetUtil.isNetworkConnected(AppContext.mContext)) { // NetErrorDialog.showProgess(cont); // NetErrorDialogUtil.showProgess(cont, "请检查网络"); DialogUtil.dismissProgess(); Toast.makeText(cont, "请检查网络~~", Toast.LENGTH_SHORT).show(); } else { addToQueue(Request.Method.POST, pUrl, params, pListener, 0,true); /* if (params != null) LogUtils.json("userData==" + params.toString());*/ } } public static void get(Context cont, String pUrl, IRequestListener pListener) { LogUtils.d(pUrl); if (!NetUtil.isNetworkConnected(AppContext.mContext)) { // NetErrorDialog.showProgess(cont); // NetErrorDialogUtil.showProgess(cont, "请检查网络"); Toast.makeText(cont, R.string.network_error, Toast.LENGTH_SHORT).show(); DialogUtil.dismissProgess(); } else { addToQueue(Request.Method.GET, pUrl, null, pListener, 0, true); } } public static void get(Context cont, String pUrl, JSONObject params, IRequestListener pListener) { LogUtils.d(pUrl); if (!NetUtil.isNetworkConnected(AppContext.mContext)) { // NetErrorDialog.showProgess(cont); // NetErrorDialogUtil.showProgess(cont, "请检查网络"); Toast.makeText(cont, (R.string.network_error), Toast.LENGTH_SHORT).show(); DialogUtil.dismissProgess(); } else { // dialog= new MaterialDialog.Builder(ActManager.getAppManager().currentActivity()) // .theme(Theme.DARK) // .content("网络数据加载中...") // .progress(true, 0).autoDismiss(false) // .contentGravity(GravityEnum.CENTER) // .show(); addToQueue(Request.Method.GET, pUrl, params, pListener, 0, true); } // new HashMap<String, String>(); } public static void get(Context cont, String pUrl, HashMap<String,String> params, IRequestListener pListener) { StringBuilder sbArguments = new StringBuilder(); if (null != params) { for (String key:params.keySet()) { if (sbArguments.length()==0){ sbArguments.append("?"); }else{ sbArguments.append("&"); } sbArguments.append(key); sbArguments.append("="); sbArguments.append(params.get(key)); } } LogUtils.d(pUrl+sbArguments); if (!NetUtil.isNetworkConnected(AppContext.mContext)) { Toast.makeText(cont, R.string.network_error, Toast.LENGTH_SHORT).show(); DialogUtil.dismissProgess(); } else { addToQueue(Request.Method.GET, pUrl+sbArguments, null, pListener, 0, true); } } private static void addToQueue(int pMethod, String pUrl, JSONObject params, final IRequestListener pListener, int tag, boolean b) { if (params == null) { params = new JSONObject(); } HttpRequest req = new HttpRequest(pMethod,b, pUrl, params, newResponseListener(tag, pListener), newErrorListener(tag, pListener)); req.setRetryPolicy(new DefaultRetryPolicy(6 * 1000, 1, 1.0f)); addRequest(req, tag); } private static Response.Listener<JSONObject> newResponseListener( final int tag, final IRequestListener pListener) { return new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // if (dialog != null) { // dialog.dismiss(); // } boolean result = false; if (response.toString().length() > 4000) { LogUtils.jsonLong("NetService==", response.toString()); } else { LogUtils.json("NetService==" + response.toString()); } if (response.has("access_token") && response.has("openid")) { pListener.onSuccess(response); } else if (response.has("result")) { try { //LogUtils.json("Response-Listener===" + response.getString("data").toString() + "//isnull==" + StringUtils.isEmpty(response.getString("data").toString()) + "//isnull==" + response.getString("data").equals("null")); result = response.getBoolean("result"); if (null != pListener) { if (result) { if (response.has("data") && !StringUtils.isEmpty(response.getString("data")) && !"null".equals(response.getString("data"))) { if (response.has("exception") && "分类列表".equals(response.getString("exception"))) { pListener.onSuccess(response); } else { pListener.onSuccess(response.getJSONObject("data")); } } else { pListener.onSuccess(response); } } else { if (ActManager.getAppManager().currentActivity() instanceof SearchActivity) { if (response.has("msg") && !StringUtils.isEmpty(response.getString("msg"))) pListener.onError(response.getString("msg")); } else { if (response.has("msg") && response.has("exception") && "error".equals(response.getString("msg")) && !StringUtils.isEmpty(response.getString("exception")) && "登录名已存在".equals(response.getString("exception"))) { pListener.onSuccess(response); } else if (response.has("msg") && response.has("exception") && "1077".equals(response.getString("msg"))) { ActManager.getAppManager().finishActivitiesAndKeepLastOne(); ActManager.getAppManager().currentActivity().startActivity(new Intent(ActManager.getAppManager().currentActivity(), LoginActivity.class)); ActManager.getAppManager().finishLastOne(); SPUtils.clearUserinfo(AppContext.mContext); AppContext.user = null; } else if (response.has("msg") && response.has("exception") && "1080".equals(response.getString("msg"))) { ActManager.getAppManager().currentActivity().startActivity(new Intent(ActManager.getAppManager().currentActivity(), LoginActivity.class)); } else { if (response.has("data") && !StringUtils.isEmpty(response.getString("data")) && !"null".equals(response.getString("data"))) { Toast.makeText(AppContext.mContext, response.getJSONObject("data").getString("error"), Toast.LENGTH_SHORT).show(); if (response.has("msg") && response.has("exception") && StringUtils.isEmpty(response.getString("exception")) && !StringUtils.isEmpty(response.getString("msg"))) { pListener.onError(response.getString("msg")); } } else { if (response.has("exception") && !StringUtils.isEmpty(response.getString("exception")) && "已有记录".equals(response.getString("exception"))) { Toast.makeText(AppContext.mContext, "已有记录", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(AppContext.mContext, (R.string.network_error), Toast.LENGTH_SHORT).show(); } } pListener.onError(response.toString()); } } } } } catch (JSONException e) { e.printStackTrace(); LogUtils.json("NetService JSONException" + e); } finally { System.gc(); } } } }; } private static Response.ErrorListener newErrorListener(final int tag, final IRequestListener pListener) { return new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // dialog.dismiss(); // if (dialog != null) { // dialog.dismiss(); // } DialogUtil.dismissProgessDirectly(); if (error != null && error.networkResponse != null) { pListener.onError(error.toString()); if (error.networkResponse.statusCode == 401) { } } } }; } }
Java
UTF-8
1,528
3.390625
3
[]
no_license
package com.cs360.chess.piece; import com.cs360.chess.Board; public final class Queen extends Piece { private static final int points = 9; private static final int id = 5; public Queen(int id, boolean isBlack, int column, int row) { super(id, isBlack, column, row); } public Queen(int id, boolean black, boolean hasMoved, int column, int row) { super(id, black, hasMoved, column, row); } @Override public Piece clone() { return new Queen(getUniqueId(), isBlack(), hasMoved(), getColumn(), getRow()); } @Override public int getPoints() { return points; } @Override public int getId() { return id; } //can move in any (forward, backward, left, right, diagonal) direction at any distance as long as the path is clear @Override public int[][] computePossible(Board board) { int[][] xPattern = diagonalMoves(board, this); int[][] plusPattern = straightMoves(board, this); int[][] moves = new int[xPattern.length + plusPattern.length][2]; System.arraycopy(xPattern, 0, moves, 0, xPattern.length); System.arraycopy(plusPattern, 0, moves, xPattern.length, plusPattern.length); return moves; } @Override public String toString() { return "Queen[uid=" + getUniqueId() + "black=" + isBlack() + ",points=" + getPoints() + ",moved=" + hasMoved() + ",col=" + getColumn() + ",row=" + getRow() + ",BINARY=" + Integer.toBinaryString(data) + "]"; } }
Java
UTF-8
457
2.390625
2
[]
no_license
package nsy209.cnam.seldesave.validator; import nsy209.cnam.seldesave.validator.helper.EnumCheck; /** * Created by lavive on 08/06/17. */ public class NumberValidator implements IValidator { private final String regex = "^([1-9][0-9]*)|0$"; @Override public EnumCheck validate(String stringToValidate) { if (!stringToValidate.matches(regex)) { return EnumCheck.NUMBER_WELL_FORMED; } return null; } }
C#
UTF-8
3,178
2.734375
3
[]
no_license
using UnityEngine; public class EnemySpawner : MonoBehaviour { private bool movingRight = false; public GameObject enemyPrefab; public float width = 10f; public float height = 5f; public float speed = 5f; public float xMin; public float xMax; public float spawnDelay = 5f; // At start, runs foreach transform in the spawners transform, spawns enemy at that position void Start() { float distanceToCamera = transform.position.z - Camera.main.transform.position.z; //Calculates play space and sets left and right x axis boundaries Vector3 leftBoundary = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distanceToCamera)); Vector3 rightBoundary = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distanceToCamera)); Debug.LogWarningFormat("LeftBounds:{0}|RightBounds:{1}", leftBoundary, rightBoundary); xMin = leftBoundary.x; xMax = rightBoundary.x; SpawnUntilFull(); } // Update is called once per frame void Update() { if (movingRight) { transform.position += Vector3.right * speed * Time.deltaTime; } else { transform.position += Vector3.left * speed * Time.deltaTime; } float leftEdgeOfFormation = transform.position.x - (0.5f * width); float rightEdgeOfFormation = transform.position.x + (0.5f * width); //swaps moving right back and forth if (leftEdgeOfFormation < xMin) movingRight = true; else if (rightEdgeOfFormation > xMax) movingRight = false; //Checks if all enemies are dead. if (AllMembersDead()) { Debug.Log("ALl enemies dead."); SpawnUntilFull(); } } //returns a position if it's child is empty Transform NextFreePosition() { foreach (Transform childPositionGameObject in transform) { if (childPositionGameObject.childCount == 0) return childPositionGameObject; } return null; } //spawns enemies at next free position. Method calls itself recursively if there's a free position after spawnDelay. void SpawnUntilFull() { Transform freePosition = NextFreePosition(); if (freePosition != null) { GameObject enemy = Instantiate(enemyPrefab, freePosition.transform.position, Quaternion.identity) as GameObject; enemy.transform.parent = freePosition; Debug.LogFormat("Enemy Spwaned at: {0}, {1}.", freePosition.position.x, freePosition.position.y); } if (NextFreePosition() != null) { Invoke("SpawnUntilFull", spawnDelay * Time.deltaTime); } } //Checks if all child memebers of position in EnemySpawer are empty or not. public bool AllMembersDead() { foreach (Transform childPositionGameObject in transform) { if (childPositionGameObject.childCount > 0) return false; } return true; } //Puts wire cube on enemy spawner public void OnDrawGizmos() { Gizmos.DrawWireCube(transform.position, new Vector3(width, height)); } /*//Unused code was for spawning enemy objects. public void SpawnAllEnemies() { foreach (Transform item in transform) { GameObject enemy = Instantiate(enemyPrefab, item.transform.position, Quaternion.identity) as GameObject; enemy.transform.parent = item; Debug.LogFormat("Enemy Spwaned at: {0}, {1}.", item.position.x, item.position.y); } } */ }
Java
UTF-8
1,523
2.421875
2
[]
no_license
package com.example.figuras; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class Cubo extends Activity { private EditText txtarista; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cubo); txtarista = (EditText) findViewById(R.id.txtAristaCubo); } public void calcularCubo(View view) { String operacion="Volumen del cubo"; double dato, resultado = 0; if (validar()) { dato = Integer.parseInt(txtarista.getText().toString()) ; resultado=(Math.pow(dato, 3)); ResultadosArea p = new ResultadosArea(operacion, dato, resultado); p.guardar(); Toast toast = Toast.makeText(this, "Dato Guardado Exitosamente", Toast.LENGTH_SHORT); toast.show(); Intent intent = new Intent(Cubo.this, ResultadoCubo.class); Bundle b = new Bundle(); b.putDouble("RESULTADO", resultado); intent.putExtras(b); startActivity(intent); } else { Toast toast1 = Toast.makeText(getApplicationContext(), "Datos Incompletos", Toast.LENGTH_SHORT); toast1.show(); } } public void borrar(View view) { txtarista.setText(""); txtarista.requestFocus(); } public boolean validar() { if (txtarista.getText().toString().trim().equals("")) { return false; } else { return true; } } }
Java
UTF-8
1,292
1.828125
2
[]
no_license
@Override public boolean onFragmentCreate(){ currentChat=MessagesController.getInstance(currentAccount).getChat(chatId); if (currentChat == null) { final CountDownLatch countDownLatch=new CountDownLatch(1); MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> { currentChat=MessagesStorage.getInstance(currentAccount).getChat(chatId); countDownLatch.countDown(); } ); try { countDownLatch.await(); } catch ( Exception e) { FileLog.e(e); } if (currentChat != null) { MessagesController.getInstance(currentAccount).putChat(currentChat,true); } else { return false; } if (info == null) { MessagesStorage.getInstance(currentAccount).loadChatInfo(chatId,countDownLatch,false,false); try { countDownLatch.await(); } catch ( Exception e) { FileLog.e(e); } if (info == null) { return false; } } } isChannel=ChatObject.isChannel(currentChat) && !currentChat.megagroup; imageUpdater.parentFragment=this; imageUpdater.delegate=this; signMessages=currentChat.signatures; NotificationCenter.getInstance(currentAccount).addObserver(this,NotificationCenter.chatInfoDidLoad); return super.onFragmentCreate(); }
Markdown
UTF-8
673
2.78125
3
[ "MIT" ]
permissive
# Reddit-Top-Level-Comments Chrome Extension: Only view 1 top-level Reddit comment thread at a time. This is how I usually browse reddit, and I always had trouble finding the TLCs (top level comments) to start a new "story" of comments and responses again. ### Reasoning I sometimes get lost in a long thread of comments and want to abandon it. But I have trouble finding the top level comment since all the lines on the left look the same and it's hard to determine where it stops. In reaction to this, I made buttons at the top of the comment section that let you show and hide the first X amount of top level comments... to make my comment reading that much faster :D