language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,838
2.90625
3
[]
no_license
/* * Copyright: * License : * The following code is deliver as is. * I take care that code compile and work, but I am not responsible about any damage it may cause. * You can use, modify, the code as your need for any usage. * But you can't do any action that avoid me or other person use, modify this code. * The code is free for usage and modification, you can't change that fact. * @author JHelp * */ package jhelp.util.thread; import com.sun.istack.internal.NotNull; import com.sun.istack.internal.Nullable; import java.util.Objects; /** * Task that launch a task and manage an associated {@link Promise} */ final class LaunchTask<P, R> implements RunnableTask { /** * Task parameter */ private final P parameter; /** * Promise associated to the task */ private final Promise<R> promise; /** * Task to launch */ private final Task<P, R> task; /** * Crete the main task * * @param task Task to play * @param parameter Task parameter */ LaunchTask(@NotNull final Task<P, R> task, @Nullable final P parameter) { Objects.requireNonNull(task, "task MUST NOT be null!"); this.task = task; this.parameter = parameter; this.promise = new Promise<>(); } /** * Future of the task result * * @return Future of the task result */ @NotNull Future<R> future() { return this.promise.future(); } /** * Play the task */ @Override public void run() { try { this.promise.setResult(this.task.playTask(this.parameter)); } catch (Throwable throwable) { this.promise.setError(new TaskException("Failed to launch the task!", throwable)); } } }
C#
UTF-8
4,391
2.765625
3
[]
no_license
using Client.Tools; using GalaSoft.MvvmLight; using Models.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace Client.ViewModels { class SearchViewModel : ViewModelBase { public HttpClient Client { get; set; } private string _text; public string Text { get { return _text; } set { _text = value; OnPropertyChange(Text); } } private ObservableCollection<AbstractItem> _items; public ObservableCollection<AbstractItem> items { get { return _items; } set { _items = value; RaisePropertyChanged(); } } public ICommand FilterTextChangedCommand { get; set; } public ICommand SearchTypeCommand { get; set; } private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChange(Text); } } public SearchViewModel() { Client = new HttpClient(); SearchTypeCommand = new RelayCommand(executemethod, canexecutemethod); FilterTextChangedCommand = new RelayCommand(executemethod, canexecutemethod); } public event PropertyChangedEventHandler PropertyChanged; private async void OnPropertyChange(string textSearch) { try { if (Name == "By Name") { var lst = new List<AbstractItem>(); items = new ObservableCollection<AbstractItem>(lst); if (Text == "") { items.Clear(); return; } if (String.IsNullOrEmpty(textSearch)) { return; } items = await GetItemsByName(Client, items, textSearch); } else if(Name =="By ISBN") { items = new ObservableCollection<AbstractItem>(); if (Text == "") { items.Clear(); return; } if (String.IsNullOrEmpty(textSearch)) { return; } items = await GetItemsByISBN(Client, items, textSearch); } } catch (Exception e) { Console.WriteLine(e.Message); } } private async Task<ObservableCollection<AbstractItem>> GetItemsByISBN(HttpClient client, ObservableCollection<AbstractItem> items, string propertyname) { items = await ApiService.GetAllAvialiabeItems(client, items, "book", "jornal" , "printDate"); ObservableCollection<AbstractItem> toReturn = new ObservableCollection<AbstractItem>(); foreach (var item in items) { if (item.ISBN.ToString().Contains(this.Text)) toReturn.Add(item); } return toReturn; } private async Task<ObservableCollection<AbstractItem>> GetItemsByName(HttpClient client, ObservableCollection<AbstractItem> items, string propertyname) { items = await ApiService.GetAllAvialiabeItems(client, items, "book", "jornal" , "printDate"); ObservableCollection<AbstractItem> toReturn = new ObservableCollection<AbstractItem>(); foreach (var item in items) { if (item.Title.Contains(this.Text)) toReturn.Add(item); } return toReturn; } private bool canexecutemethod(object parameter) { if (parameter != null) { return true; } else { return false; } } private void executemethod(object parameter) { Name = (string)parameter; } } }
Markdown
UTF-8
1,607
3
3
[]
no_license
--- title: Mushroom FAQ layout: default category: EN --- Have questions about Popsy? Check out the FAQ below to help you get started! ## **1. What is Popsy?** Popsy is an app where you can live broadcast and hang out with friends, just like in real life but better. Everybody gets their own room and you can pull anyone into it, while live broadcasting. You can find friends to join you in an instant and watch the same video while talking with others. ## **2. I registered with my phone number. Can people see my number while I broadcast?** Nope! This information is kept secure, and is only used to log in to the app. That being said, you can invite contacts from your phone to broadcast with you. If your contacts join, you will be connected with them as friends on Popsy. ## **3. How can I join a room?** Simply click on your homescreen and select someone who is broadcasting! You can enter any room you’d like. You may also search for a username in the App to find your friends or your favorite broadcasters to join their room. ## **4. How can I join someone else’s broadcast?** Once you’re in a room, the broadcaster who owns the room can drag you on screen to broadcast with them! Similarly, if you are the room owner, you can drag anyone on screen to broadcast with you. ## **5. What are the group chats within a room, and how can I join one?** When you are watching someone broadcast in a room, you can pull up to three other broadcasters into a group with you. You, and up to three other friends, can watch the live broadcaster together. **Have other questions? Email hello@popsy.io!**
JavaScript
UTF-8
1,057
3.140625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
let eastWest = [ '1st Avenue', '2nd Avenue', '3rd Avenue', 'Lexington Avenue', 'Park', 'Madison Avenue', '5th Avenue' ]; class Driver{ constructor(name, startDate){ this.name = name this.startDate = new Date(startDate) } yearsExperienceFromBeginningOf(endDate){ return new Date(endDate).getFullYear() - this.startDate.getFullYear() + 1 } } class Route{ constructor(beginningLocation, endLocation) { this.beginningLocation = beginningLocation; this.endLocation = endLocation; } aveToInt(ave) { return eastWest.indexOf(ave); } blocksTravelled() { let vert = Math.abs(this.beginningLocation.vertical - this.endLocation.vertical); let startHor = this.aveToInt(this.beginningLocation.horizontal); let endHor = this.aveToInt(this.endLocation.horizontal); let hor = Math.abs(startHor - endHor); return hor + vert; } estimatedTime(peak = false) { let travelTime = this.blocksTravelled() peak ? travelTime = travelTime/2 : travelTime = travelTime/3 return travelTime } }
PHP
UTF-8
6,809
2.796875
3
[ "MIT" ]
permissive
<?php /** * Nano Framework * * @package Nano * @author Francesco Saccani <saccani.francesco@gmail.com> * @copyright Copyright (c) 2019 Francesco Saccani * @version 1.0 */ declare(strict_types=1); namespace Nano\Model\QueryBuilder; use Nano\Database\Exception\InvalidArgumentException; use Nano\Database\Exception\QueryExecutionException; use Nano\Database\Facade\Types; use Nano\Database\Facade\UpdateQueryInterface; use Nano\Database\Insert; use Nano\Database\Update; use Nano\Model\Entity; use Nano\Model\Exception\InvalidValueException; use Nano\Model\Exception\ModelExecutionException; use Nano\Model\Metadata\EntityMetadata; /** * Helper class for insert or update an entity and associated relations. * * @package Nano\Model * @author Francesco Saccani <saccani.francesco@gmail.com> */ class EntitySaver { /** * @var EntityMetadata */ private $metadata; /** * @var array */ private $data; /** * @var array */ private $updatedData; /** * Initialize the entity saver. * * @param EntityMetadata $metadata The entity metadata. * @param array $data The associative array of entity data. * @param array $updatedData The associative of entity updated data. */ public function __construct(EntityMetadata $metadata, array $data, array $updatedData) { $this->metadata = $metadata; $this->data = array_merge($data, $updatedData); $this->updatedData = $updatedData; } /** * Convert data from complex format to a database-compatible format. * * @param array $data The array of complex data. * @return array Returns the data in the database-compatible format: * `column` => [`value`, `type`]. */ private function convertData(array $data): array { // Convert relations. foreach ($this->metadata->getRelations() as $relation) { if (array_key_exists($relation->getName(), $data)) { $value = $data[$relation->getName()]; unset($data[$relation->getName()]); if ($value === null) { $data[$relation->getForeignKey()] = [null, Types::NULL]; } elseif ($relation->isOneToOne()) { /** @var Entity $value */ if ($value->isNew()) { $value->save(); } $data[$relation->getForeignKey()] = [ $value->__get($relation->getBindingEntity()->getPrimaryKey()), Types::STRING ]; } } } // Convert native data types. foreach ($this->metadata->getColumns() as $column) { if (! isset($data[$column])) { continue; } $value = $data[$column]; switch ($type = $this->metadata->getPropertyType($column)) { case Entity::TYPE_BOOL: $data[$column] = [$value, Types::BOOL]; break; case Entity::TYPE_FLOAT: $data[$column] = [$value, Types::FLOAT]; break; case Entity::TYPE_INT: $data[$column] = [$value, Types::INT]; break; case Entity::TYPE_DATE: case Entity::TYPE_DATETIME: case Entity::TYPE_TIME: /** @var \DateTimeImmutable $value */ $format = $type === Entity::TYPE_DATE ? EntityMetadata::DATE_FORMAT : ($type === Entity::TYPE_TIME ? EntityMetadata::TIME_FORMAT : EntityMetadata::DATETIME_FORMAT); $data[$column] = [$value->format($format), Types::DATETIME]; break; case Entity::TYPE_JSON: $data[$column] = [json_encode($value), Types::JSON]; break; case Entity::TYPE_STRING: default: $data[$column] = [$value, Types::STRING]; } } return $data; } /** * Create the query to insert new entity in database. * * @return Insert Returns the insert query instance. * * @throws InvalidValueException if the data is not valid. */ public function createInsertQuery(): Insert { $data = $this->convertData($this->data); if ($this->metadata->hasDatetime()) { $data[EntityMetadata::COLUMN_CREATED] = date('Y-m-d H:i:s'); $data[EntityMetadata::COLUMN_UPDATED] = date('Y-m-d H:i:s'); } try { return (new Insert($this->metadata->getTable())) ->addValues($data); } catch (InvalidArgumentException $exception) { throw new InvalidValueException( $exception->getMessage(), $exception->getCode(), $exception ); } } /** * Create the query to update entity in database. * * @param string $id The primary key of the entity to update. * @return Update Returns the update query instance. * * @throws InvalidValueException if the data is not valid. */ public function createUpdateQuery(string $id): Update { $data = $this->convertData($this->updatedData); if ($this->metadata->hasDatetime()) { $data[EntityMetadata::COLUMN_UPDATED] = date('Y-m-d H:i:s'); } try { return (new Update($this->metadata->getTable())) ->addValues($data) ->where($this->metadata->getPrimaryKey(), '=', $id); } catch (InvalidArgumentException $exception) { throw new InvalidValueException( $exception->getMessage(), $exception->getCode(), $exception ); } } /** * Execute the query. * * @param UpdateQueryInterface $query The query to be executed. * * @throws ModelExecutionException if an error occur during query execution. */ public function execute(UpdateQueryInterface $query) { $connection = ConnectionCollector::getConnection(); try { $connection->executeUpdate($query); } catch (QueryExecutionException $exception) { throw new ModelExecutionException( $exception->getMessage(), $exception->getCode(), $exception ); } } /** * Retrieve the last inserted id from database. * * @return string */ public function getNewPrimaryKey(): string { return ConnectionCollector::getConnection()->getLastInsertId(); } }
Java
UTF-8
758
2.140625
2
[]
no_license
package com.cmazxiaoma.mvp.bean; import java.util.List; /** * Description: 沉梦昂志 * Data:2017/5/17-14:06 * Author: xiaoma */ public class ImageEvent { private int currentPosition; private List<String> imageUrls; public ImageEvent(int currentPosition, List<String> imageUrls) { this.currentPosition = currentPosition; this.imageUrls = imageUrls; } public int getCurrentPosition() { return currentPosition; } public void setCurrentPosition(int currentPosition) { this.currentPosition = currentPosition; } public List<String> getImageUrls() { return imageUrls; } public void setImageUrls(List<String> imageUrls) { this.imageUrls = imageUrls; } }
Python
UTF-8
4,614
2.671875
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 14 15:16:43 2017 @author: jjcao """ import torch import torch.nn as nn from collections import OrderedDict import functools from .base_network import BoxBlock, UBoxBlock # Defines the generator that consists of Resnet blocks between a few # downsampling/upsampling operations. # Code and idea originally from Justin Johnson's architecture. # https://github.com/jcjohnson/fast-neural-style/ class Resnet(nn.Module): def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, drop_rate=0.5, n_blocks=9, padding_type='reflect', n_downsampling = 2, fine_size = 256): assert(n_blocks >= 0) super(Resnet, self).__init__() self.input_nc = input_nc self.output_nc = output_nc self.ngf = ngf if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d ############# ############# model_head = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True)] for i in range(n_downsampling): mult = 2**i model_head += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias), norm_layer(ngf * mult * 2), nn.ReLU(True)] mult = 2**n_downsampling for i in range(n_blocks): model_head += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, drop_rate=drop_rate, use_bias=use_bias)] self.model_head = nn.Sequential(*model_head) ############# # box ############# im_size = fine_size // 2**n_downsampling self.model_B = BoxBlock(ngf * mult, ngf, norm_layer=norm_layer, use_bias = use_bias, im_size = im_size, drop_rate=drop_rate) ############# ############# model_tail = [] for i in range(n_downsampling): mult = 2**(n_downsampling - i) model_tail += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias), norm_layer(int(ngf * mult / 2)), nn.ReLU(True)] model_tail += [nn.ReflectionPad2d(3)] model_tail += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] model_tail += [nn.Tanh()] self.model_tail = nn.Sequential(*model_tail) def forward(self, input): out = self.model_head(input) box = self.model_B(out) out = self.model_tail(out) return [out, box] # Define a resnet block class ResnetBlock(nn.Module): def __init__(self, dim, padding_type, norm_layer, drop_rate, use_bias): super(ResnetBlock, self).__init__() self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, drop_rate, use_bias) def build_conv_block(self, dim, padding_type, norm_layer, drop_rate, use_bias): conv_block = [] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)] if drop_rate: conv_block += [nn.Dropout(drop_rate)] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)] return nn.Sequential(*conv_block) def forward(self, x): out = x + self.conv_block(x) return out
Java
UTF-8
676
3.078125
3
[]
no_license
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class TimeDemo { public static void main(String[] args) { long start = System.currentTimeMillis(); try { for (int i = 0; i < 10000; i++) { Thread.sleep(2); } } catch (Exception e){} long end = System.currentTimeMillis(); //System.out.print("Time: " + (end - start)); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String day = dateFormat.format(date); System.out.print(day); } }
Java
UTF-8
5,227
2.625
3
[]
no_license
package auction; import java.io.File; //the list of imports import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import logist.LogistSettings; import logist.behavior.AuctionBehavior; import logist.config.Parsers; import logist.agent.Agent; import logist.simulation.Vehicle; import logist.plan.Plan; import logist.task.Task; import logist.task.TaskDistribution; import logist.task.TaskSet; import logist.topology.Topology; import logist.topology.Topology.City; /** * An auction agent * */ public class AuctionAgent2 implements AuctionBehavior { private TaskDistribution distribution; private ArrayList<Task> tasks; private ArrayList<Task> tasks_lost; private Agent agent; private MarginalLossComputer mlc; private Solution prevSol; private Solution newSolWithTask; // new solution if we get the task we bid for private long planTimeLimit; private long bidTimeLimit; private int maxVehicleCapacity = 0; //Capacity of the largest vehicle of the agent private List<Long[]> bidHistory; // List of array containing the history of the bids private List<Integer> winners; private List<Task>[] task_distr; // our bids are put at the first position @Override public void setup(Topology topology, TaskDistribution distribution, Agent agent) { this.distribution = distribution; this.tasks = new ArrayList<Task>(); this.agent = agent; this.mlc = new MarginalLossComputer(agent); this.prevSol = null; this.newSolWithTask = null; this.bidHistory = new ArrayList<Long[]>(); this.winners = new ArrayList<Integer>(); for(Vehicle vehicle: agent.vehicles()) { if (vehicle.capacity() > maxVehicleCapacity) { maxVehicleCapacity = vehicle.capacity(); } } LogistSettings ls = null; try { ls = Parsers.parseSettings("config" + File.separator + "settings_auction.xml"); } catch (Exception exc) { System.out.println("There was a problem loading the configuration file."); } // the plan method cannot last more than planTimeLimit milliseconds this.planTimeLimit = ls.get(LogistSettings.TimeoutKey.PLAN); // the bid method cannot execute more than bidTimeLimit milliseconds this.bidTimeLimit = ls.get(LogistSettings.TimeoutKey.BID); } @Override public void auctionResult(Task previous, int winner, Long[] bids) { // we put our bid in the first position Long[] bidsCopy = bids.clone(); bidsCopy[agent.id()] = bids[0]; bidsCopy[0] = bids[agent.id()]; bidHistory.add(bidsCopy); winners.add(winner); if (winner == agent.id()) { this.prevSol = this.newSolWithTask; } else { this.tasks.remove(tasks.size()-1); // we remove the task from our // task set since we will not deliver it tasks_lost.add(previous); } } @Override public Long askPrice(Task task) { if (task.weight > maxVehicleCapacity) { return null; } double prevCost = (prevSol == null) ? 0 : prevSol.cost; this.tasks.add(task); // we add it no matter what and will remove it if we don't get the task long timeOut = System.currentTimeMillis() + (long) (0.999*bidTimeLimit) - 5; // 0.999 for safety + 5ms for the rest of the method this.newSolWithTask = mlc.getSolution(this.tasks, timeOut, true); // TODO: add time adaptability // TODO: add adaptation to ennemy // TODO; si on a un cout < 0, on peut suremnt le mettre à 0 comme c'est task specific double bid = newSolWithTask.cost - prevCost; double est_opponent = lengthNewLinks(tasks_lost, task); if (bid <= est_opponent) { bid = est_opponent*0.95; } return (long) Math.round(bid); } @Override public List<Plan> plan(List<Vehicle> vehicles, TaskSet tasks) { long timeOut = System.currentTimeMillis() + (long) (0.999*planTimeLimit) - 25; // 0.999 for safety + 25ms for the plan computing ArrayList<Task> list = new ArrayList<Task>(); for (Task task: tasks) { list.add(task); } Solution newSol = mlc.getSolution(list, timeOut, true); return newSol.getPlans(list); } /** * For every Task in tasks we look at the shortest path from pickup to delivery city. * We then do the same for t2 * We return the lenght of the links that are covered by t2 but not by the list of existing tasks * @param tasks: List of current tasks of an agent * @param t2: One possible new task with pickup and delivery city * @return Sum of the distances as decribed above * */ public int lengthNewLinks(List<Task> tasks, Task t2) { Map<City, Set<City>> covered = new HashMap<City, Set<City>>(); for (Task t : tasks) { List<City> path_t = t.path(); for (int i=0;i<path_t.size()-1;i++) { Set s = covered.get(path_t.get(i)); if (s == null) { s = new HashSet<City>(); covered.put(path_t.get(i), s); } s.add(path_t.get(i+1)); } } int dist = 0; List<City> path_t2 = t2.path(); for (int i = 0; i<t2.path().size()-1; i++) { Set<City> s = covered.get(path_t2.get(i)); if(s != null && s.contains(path_t2.get(i+1))) { dist += path_t2.get(i).distanceTo(path_t2.get(i+1)); } } return dist; } }
Markdown
UTF-8
4,813
3.21875
3
[]
no_license
# Desafio Itaú ## Introdução Este é um Projeto de Desafio do Itaú que consiste em criar uma API que irá expor um endpoint para verificar se uma determinada senha é válida, seguindo os critérios abaixo: - Possuir nove ou mais caracteres - Possuir ao menos 1 dígito numérico - Possuir ao menos 1 letra minúscula - Possuir ao menos 1 letra maiúscula - Possuir ao menos 1 dos caracteres especiais a seguir: !@#$%^&*()-+ - Não possuir caracteres repetidos dentro do conjunto - Não possuir espaços em branco Exemplo: ```c# IsValid("") // false IsValid("aa") // false IsValid("ab") // false IsValid("AAAbbbCc") // false IsValid("AbTp9!foo") // false IsValid("AbTp9!foA") // false IsValid("AbTp9 fok") // false IsValid("AbTp9!fok") // true ``` ## Descrição do Projeto Para a execução deste Desafio, foi criado um Projeto Web API no Visual Studio 2017 utilizando a linguagem C#. Apesar da API expor apenas um endpoint, a aplicação foi construída utilizando algumas das melhores práticas da modelagem DDD. ## Executando a Aplicação **1.** Após clonar o Projeto do Git em seu Ambiente de Desenvolvimento, abra a **Solution** no Visual Studio 2017 ou superior. **2.** Com o botão direito na **Solution** execute a opção **"Restore NuGet Packages"** para baixar os pacotes externos que foram utilizados no desenvolvimento da Aplicação. <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme01.png"> **3.** Novamente com o botão direito na **Solution**, execute a agora a opção **"Build Solution"** para compilar todos os Projetos da aplicação. Se tudo correu bem você terá uma tela igual a imagem abaixo: <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme02.png"> **4.** Agora você já está apto para executar a API. Selecione o Projeto **"MS.Challenge.Services.API"** e com o botão direito sobre o mesmo, escolha a opção **""Set as StartUp Project"**. Agora para executar a aplicação clique botão da Barra de Tarefas conforme a imagem abaixo: <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme03.png"> ## Consumindo a API Ao executar a API pelo Visual Studio, a aplicação irá disponibilizar o endpoint abaixo: ```c# POST /api/auth/checkPassword HTTP/1.1 Host: http://localhost:57524 Content-Type: application/json ``` Este endpoint espera receber a Senha que será validada. Para informar a senha, deverá ser enviado no **body** da mensagem um conteúdo do Tipo Json no formato abaixo: ```c# { "password": "AbTp9!fok" } ``` O endpoint **checkPassword** devolve um valor booleano igual a **true** caso a senha seja válida ou igual a **false** caso a senha seja inválida, de acordo com os critérios definidos no início desta documentação. <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme04.png"> ## Entendendo a Validação da Senha Para validar a senha foram implementados alguns métodos genéricos na nossa camada **Framework** para validar as situações abaixo: - Método para verificar se uma string contém algum dígito numérico - Método para verificar se uma string contém algum caractere com UpperCase - Método para verificar se uma string contém algum caractere com LowerCase Esses métodos, por serem genéricos podem ser utilizados em outras situações que a nossa aplicação possa precisar. Além desses métodos, foram criados mais alguns métodos na Classe **PasswordHelper** por se tratar de regras específicas para a validação de senha. Nesta classe temos: - Método para validar se a senha tem os caracteres especiais válidos - Método para validar se a senha tem algum caractere duplicado. Com esses 5 métodos conseguimos criar facilmente em nosso Helper o método **IsValid** que realizará a validação de senha: <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme05.png"> ## Testes Unitários Para testar o código da nossa API, junto com a aplicação temos o nosso projeto de Testes Unitários onde estamos testando nossa rotina de Validação de Senha: <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme06.png"> A nossa classe de Testes testa algumas situações onde a rotina deverá retornar **true** e algumas onde deverá retornar **false**: <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme07.png"> Para executar os Testes, no Visual Studio, acesse o Menu **Test > Run** e execute a opção **"All Tests"**. <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme08.png"> Abaixo podemos ver o resultados dos nossos Testes: <img src="https://github.com/souzadeveloper/challenge-itau/blob/master/images/readme09.png">
SQL
UTF-8
533
3.453125
3
[]
no_license
/* * Basic Survey Website using php * by Johan Setyobudi * jsetyobudi@gmail.com * sety0002@algonquinlive.com * April 11, 2016 */ CREATE DATABASE survey; GRANT USAGE ON *.* TO survey@localhost IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON survey.* TO survey@localhost; FLUSH PRIVILEGES; USE survey; CREATE TABLE survey( _id int not null AUTO_INCREMENT, firstName VARCHAR(50) NOT NULL, lastName VARCHAR(50) NOT NULL, emailAddress VARCHAR(100) NOT NULL, PRIMARY KEY (_id) ); ALTER TABLE survey ADD UNIQUE INDEX duplicateEmail (emailAddress);
Python
UTF-8
1,155
2.765625
3
[]
no_license
#!/usr/bin/env python import re key = '02070D48030F1C294940041801181C0C140D0A0A20253A3B' def decrypt( ep ): """Cisco Type 7 password decryption. Converted from perl code that was written by jbash /|at|\ cisco.com""" xlat = ( 0x64, 0x73, 0x66, 0x64, 0x3b, 0x6b, 0x66, 0x6f, 0x41, 0x2c, 0x2e, 0x69, 0x79, 0x65, 0x77, 0x72, 0x6b, 0x6c, 0x64, 0x4a, 0x4b, 0x44, 0x48, 0x53, 0x55, 0x42 ) dp = "" regex = re.compile( "^(..)(.+)" ) if not ( len(ep) & 1 ): result = regex.search( ep ) try: s, e = int( result.group(1) ), result.group(2) except ValueError: # typically get a ValueError for int( result.group(1))) because # the method was called with an unencrypted password. For now # SILENTLY bypass the error s, e = (0, "") for ii in range( 0, len( e ), 2 ): # int( blah, 16) assumes blah is base16... cool magic = int( re.search( ".{%s}(..)" % ii, e ).group(1), 16 ) print "S = %s" % s if s <= 25: # Algorithm appears unpublished after s = 25 newchar = "%c" % ( magic ^ int( xlat[ int( s ) ] ) ) else: newchar = "?" dp = dp + str( newchar ) s = s + 1 if s > 25: print "WARNING: password decryption failed." return dp print(decrypt(key))
Java
UTF-8
950
2.453125
2
[]
no_license
package com.springboot.zero.web; /** * Created by hanxirui on 2017/2/21. */ import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * 模板测试. * * @author Administrator */ @Controller public class TemplateController { // 从 application.properties 中读取配置,如取不到默认值为Hello Shanhy @Value("${application.hello:Hello Angel}") private String hello; /** * 返回Thymeleaf模板. */ @RequestMapping("/thymeleafhello") public String helloHtml(Map<String, Object> map) { map.put("hello", hello); return "/helloThymeleaf"; } /** * 返回html模板. */ @RequestMapping("/ftlhello") public String helloFtl(Map<String,Object> map){ map.put("hello",hello); return "helloFtl"; } }
Java
UTF-8
1,042
2.515625
3
[]
no_license
package com.example.thagadur.android_session8_assignment3; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.GridView; public class MainActivity extends AppCompatActivity { //1. Declare the objects to be used GridView gridView; ArrayAdapter<Integer> adapter; //3.Create integer array that holds Image View public static int [] versionImagesId= { R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.icecream, R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //4.create gridView object gridView=(GridView)findViewById(R.id.images_grid_view); //set the custom adapter and call it gridView.setAdapter(new ImageAdapter(this,versionImagesId )); } }
Markdown
UTF-8
6,441
2.53125
3
[ "MIT" ]
permissive
# VisualLinter # DEPRECATED The development of this Visual Studio extension has been suspended since 1) I'm no longer is using this extension myself 2) I don't have as much time to dedicate into this project that I'd like I'd like to thank everyone who helped contributing to this project in one way or another, whether it be code changes or submitting bugs/feature requests etc. With that being said: If anyone would like to maintain this project, let me know. :smiley: --------------------------------------- [![Build status](https://ci.appveyor.com/api/projects/status/9ihx1afw1cc1e9b4?svg=true)](https://ci.appveyor.com/project/jwldnr/visuallinter) Visual Studio JavaScript linter using [ESLint](https://github.com/eslint/eslint). Download this extension from the [VS Gallery](https://marketplace.visualstudio.com/vsgallery/a71a5b0d-9f75-4cd2-b1f1-c4afb79a0638) or get the [CI build](http://vsixgallery.com/extension/21d9f99b-ec42-4df4-8b16-2a62db5392a5/). --------------------------------------- See the [change log](CHANGELOG.md) for changes and road map. ## Table of Contents - [Features](#features) - [Getting Started](#getting-started) - [Language Support](#language-support) - [Troubleshooting](#troubleshooting) - [Known Issues](#known-issues) - [Contributing](#contributing) - [Inspiration](#inspiration) ## Features - Lint files using ESLint on file open/save - Visually mark errors/warnings in open document - Include tooltip content with info on errors/warnings ![Markers](media/markers.png) - Fully integrated with Visual Studio error list ![Error List](media/error-list.png) ## Getting Started ##### Requirements - ESLint installed locally (per project) _or_ globally (ESLint added to `PATH`) - A valid configuration located in the current project directory (local) _or_ your user home directory (`~/.eslintrc`, global) ##### Notes The default behavior is set to use a local ESLint installation and config. If you instead wish to use a global installation and/or config, you can enable each respective option in Visual Studio under `Tools` > `Options` > `VisualLinter`. Please note that enabling the option `Use global ESLint installation instead of local` has no effect on the use of a config file (and vice versa). A local config will still be used unless `Use personal ESLint config instead of local` is also enabled in options. The closest installation/config found relative to the file being linted will always be used. If no `node_modules` directory or `.eslintrc` file is found in the same directory as the file being linted, `VisualLinter` will try and resolve the paths from ancestor directories up to, and including the root directory (e.g. `C:\\` on Windows). For instance, suppose you have the following structure: ``` your-project ├── .eslintrc ├─┬ lib │ └── source.js └─┬ tests ├── .eslintrc └── test.js ``` When `source.js` is being opened or saved the `.eslintrc` file at the root of the project will be used as its config. When `test.js` is being opened or saved the `.eslintrc` file in the `tests/` directory will be used as its config. If there are multiple config files in the same directory, `VisualLinter` will only use one. The priority order is: 1. `.eslintrc.js` 2. `.eslintrc.yaml` 3. `.eslintrc.yml` 4. `.eslintrc.json` 5. `.eslintrc` Currently, VisualLinter does NOT support the use of `package.json` as its config file. Please note that additional ESLint plugins may be required in order to lint files depending on your configuration. The VisualLinter output window will help identify these plugins, if any. ## Language Support | Language | File Extensions | Required Plugins | | --- | --- | ---- | | HTML | `.html` | [`eslint-plugin-html`](https://github.com/BenoitZugmeyer/eslint-plugin-html) | | JavaScript | `.js` | No additional plugins required! | | Reactjs |`.jsx` | [`eslint-plugin-react`](https://github.com/yannickcr/eslint-plugin-react) | | Vuejs | `.vue` | [`eslint-plugin-vue`](https://github.com/vuejs/eslint-plugin-vue) | | TypeScript | `.ts` | [`@typescript-eslint/parser`](https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/parser) [`@typescript-eslint/eslint-plugin`](https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin) | | TypeScript Reactjs | `.tsx` | [`eslint-plugin-react`](https://github.com/yannickcr/eslint-plugin-react) [`@typescript-eslint/parser`](https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/parser) [`@typescript-eslint/eslint-plugin`](https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin) | You can enable or disable each respective language in Visual Studio under `Tools` > `Options` > `VisualLinter`. By default only JavaScript `(.js)` is enabled. ## Troubleshooting - If you're using a global installation of ESLint and you're sure you've added ESLint to `PATH` but still receive an error saying that ESLint could not be found in `PATH`, restarting your computer would reload the environment variables. - If you receive a message saying that ESLint could not verify your configuration, refer to the docs on [how to configure ESLint](https://ESLint.org/docs/user-guide/configuring) - Visual Studio 2017 has built in ESLint support but does not visually mark errors in buffer. If you're seeing duplicate messages in the error list window, you can disable the built in features by changing the following options: | Option | Value | Location | | --- | --- | ---- | | Enable ESLint | `false` | Options -> Text Editor -> JavaScript/TypeScript -> ESLint | | Enable JavaScript errors | `false` | Options -> Text Editor -> JavaScript/TypeScript -> Code Validation | Please note that VisualLinter is a direct replacement for both options. ## Known Issues - None ## Contributing ⇄ Pull requests and ★ Stars are always welcome. For bugs and feature requests, please create an issue. [See all contributors on GitHub.](https://github.com/jwldnr/VisualLinter/graphs/contributors) Check out the [contribution guidelines](.github/CONTRIBUTING.md) if you want to contribute to this project. ## Inspiration - [SonarSource/SonarLint](https://github.com/SonarSource/sonarlint-visualstudio) extension for Visual Studio. - [AtomLinter/linter-eslint](https://github.com/AtomLinter/linter-eslint/) package for the Atom text editor. ## License [MIT](LICENSE)
Java
UTF-8
866
2.125
2
[]
no_license
package com.winston.springcloud.controller; import com.winston.springcloud.entities.Dept; import com.winston.springcloud.service.DeptClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author Winston * @title: DeptController_Consumer * @projectName microservicecloud * @description: * @date 2019/5/17 17:19 */ @RestController @RequestMapping("/consumer") public class DeptController_Consumer { @Autowired private DeptClientService service; @GetMapping public List<Dept> getDept(){ return service.list(); } @GetMapping("/{id}") public Dept getById(@PathVariable("id") Long id){ return service.get(id); } @PostMapping public boolean add(Dept dept){ return service.add(dept); } }
Java
UTF-8
1,776
2.125
2
[]
no_license
package org.flexpay.httptester.outerrequest.request; import org.apache.commons.digester3.Digester; import org.flexpay.httptester.outerrequest.request.response.ReversalPayResponse; import java.security.Signature; import java.util.Properties; public class ReversalPayRequest extends Request<ReversalPayResponse> { static { paramNames.add("requestId"); paramNames.add("operationId"); paramNames.add("totalPaySum"); } public ReversalPayRequest(Properties props) { super(props); } @Override protected void initResponseParser() { parser = new Digester(); parser.addObjectCreate("response", ReversalPayResponse.class); parser.addBeanPropertySetter("response/reversalInfo/requestId", "requestId"); parser.addBeanPropertySetter("response/reversalInfo/statusCode", "statusCode"); parser.addBeanPropertySetter("response/reversalInfo/statusMessage", "statusMessage"); parser.addBeanPropertySetter("response/signature", "signature"); } @Override protected void addParamsToSignature() throws Exception { updateRequestSignature(params.get("requestId")); updateRequestSignature(params.get("operationId")); updateRequestSignature(params.get("totalPaySum")); } @Override public void addParamsToResponseSignature(Signature signature) throws Exception { updateSignature(signature, response.getRequestId()); updateSignature(signature, response.getStatusCode()); updateSignature(signature, response.getStatusMessage()); } @Override protected String getTemlateFilenamePropertyName() { return "request_reversal_pay.file"; } }
JavaScript
UTF-8
3,808
2.578125
3
[]
no_license
var resultsDiv; function search(query) { if (! query) return; showSearch(query); var loader = new HLoader( function(s,r,c) { displayResults(s,r,c); }, function(s,e) { alert("load failed: " + e); } ); loadAllRecords(query, null, loader); } function loadAllRecords(query, options, loader) { var PAGE_SIZE = 500; var records = []; var baseSearch = new HSearch(query, options); var loadingMsgElem = document.getElementById('loading-msg'); var loadMoreLinkTop = document.getElementById('load-more-link-top'); var loadMoreLinkBottom = document.getElementById('load-more-link-bottom'); var bulkLoader = new HLoader( function(s, r, c) { // onload records.push.apply(records, r); loadingMsgElem.innerHTML = '<b>Loaded ' + records.length + ' of ' + c + ' records</b>'; if (records.length < c) { // more records to retrieve if (records.length % PAGE_SIZE == 0) { // don't load any more for now; provide a link to load more loader.onload(baseSearch, records, c); loadMoreLinkTop.innerHTML = loadMoreLinkBottom.innerHTML = "Load more"; loadMoreLinkTop.onclick = loadMoreLinkBottom.onclick = function() { this.innerHTML = "Loading..."; var search = new HSearch(query + " offset:"+records.length, options); HeuristScholarDB.loadRecords(search, bulkLoader); return false; }; } else { // do a search with an offset specified for retrieving the next page of records var search = new HSearch(query + " offset:"+records.length, options); HeuristScholarDB.loadRecords(search, bulkLoader); } } else { // we've loaded all the records: invoke the original loader's onload loader.onload(baseSearch, records, c); loadMoreLinkTop.innerHTML = loadMoreLinkBottom.innerHTML = ''; } }, loader.onerror ); HeuristScholarDB.loadRecords(baseSearch, bulkLoader); } function showSearch(query) { // hide footnotes document.getElementById("footnotes").style.display = "none"; document.getElementById("page").style.bottom = "0px"; // turn off any highlighting if (window.highlightElem) { highlightElem("inline-annotation", null); highlightElem("annotation-link", null); } // hide page-inner and show results div var pageInner = document.getElementById("page-inner"); pageInner.style.display = "none"; if (resultsDiv) { resultsDiv.innerHTML = ""; resultsDiv.style.display = "block"; } else { resultsDiv = pageInner.parentNode.appendChild(document.createElement("div")); resultsDiv.id = "results-div"; } resultsDiv.innerHTML += "<a style=\"float: right;\" href=# onclick=\"hideResults(); return false;\">Return to previous view</a>"; resultsDiv.innerHTML += "<h2>Search results for query \"" + query + "\"</h2>"; resultsDiv.innerHTML += "<p id=loading-msg>Loading...</p>"; resultsDiv.innerHTML += "<p><a id=load-more-link-top href=\"#\"></a></p>"; resultsDiv.innerHTML += "<div id=results-inner />"; resultsDiv.innerHTML += "<p><a id=load-more-link-bottom href=\"#\"></a></p>"; } function displayResults(s,r,c) { //var l = document.getElementById("loading-msg"); //l.parentNode.removeChild(l); var innerHTML = ""; for (var i = 0; i < r.length; i++) { innerHTML += "<img src=\"/dos/images/types/" + r[i].getRecordType().getID() + ".gif\"/>"; innerHTML += " <a href=../" + r[i].getID() + "/ target=\"_blank\">" + r[i].getTitle() + "</a><br/>"; } if (innerHTML.length) { document.getElementById("results-inner").innerHTML = innerHTML; } else { document.getElementById("results-inner").innerHTML = "<p>No matching records</p>"; } } function hideResults() { resultsDiv.style.display = "none"; document.getElementById("page-inner").style.display = "block"; if (window.higlightOnLoad) highlightOnLoad(); }
Java
UTF-8
6,344
2.203125
2
[ "Apache-2.0" ]
permissive
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.am.gateway.handler.oauth2.request; import io.gravitee.am.gateway.handler.oauth2.exception.InvalidRequestException; import io.gravitee.am.gateway.handler.oauth2.exception.RedirectMismatchException; import io.gravitee.am.gateway.handler.oauth2.exception.UnauthorizedClientException; import io.gravitee.am.gateway.handler.oauth2.utils.OAuth2Constants; import io.gravitee.am.model.Client; import io.gravitee.am.model.User; import io.reactivex.Single; import java.net.MalformedURLException; import java.net.URL; import java.util.List; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author GraviteeSource Team */ public class AuthorizationRequestResolver extends AbstractRequestResolver<AuthorizationRequest> { public Single<AuthorizationRequest> resolve(AuthorizationRequest authorizationRequest, Client client, User endUser) { return resolveAuthorizedGrantTypes(authorizationRequest, client) .flatMap(request -> resolveAuthorizedScopes(request, client, endUser)) .flatMap(request -> resolveRedirectUri(request, client)); } /** * To request an access token, the client obtains authorization from the resource owner. * The authorization is expressed in the form of an authorization grant, which the client uses to request the access token. * * See <a href="https://tools.ietf.org/html/rfc6749#section-4">4. Obtaining Authorization</a> * * Authorization endpoint implies that the client should at least have authorization_code ou implicit grant types. * * @param authorizationRequest the authorization request to resolve * @param client the client which trigger the request * @return the authorization request */ private Single<AuthorizationRequest> resolveAuthorizedGrantTypes(AuthorizationRequest authorizationRequest, Client client) { List<String> authorizedGrantTypes = client.getAuthorizedGrantTypes(); if (authorizedGrantTypes == null || authorizedGrantTypes.isEmpty()) { return Single.error(new UnauthorizedClientException("Client should at least have one authorized grand type")); } if (!containsGrantType(authorizedGrantTypes)) { return Single.error(new UnauthorizedClientException("Client must at least have authorization_code or implicit grant type enable")); } return Single.just(authorizationRequest); } /** * redirect_uri request parameter is OPTIONAL, but the RFC (rfc6749) assumes that * the request fails due to a missing, invalid, or mismatching redirection URI. * If no redirect_uri request parameter is supplied, the client must at least have one registered redirect uri * * See <a href="https://tools.ietf.org/html/rfc6749#section-4.1.2.1">4.1.2.1. Error Response</a> * * @param authorizationRequest the authorization request to resolve * @param client the client which trigger the request * @return the authorization request */ public Single<AuthorizationRequest> resolveRedirectUri(AuthorizationRequest authorizationRequest, Client client) { String redirectUri = authorizationRequest.getRedirectUri(); List<String> registeredClientRedirectUris = client.getRedirectUris(); try { if (registeredClientRedirectUris != null && !registeredClientRedirectUris.isEmpty()) { redirectUri = obtainMatchingRedirect(registeredClientRedirectUris, redirectUri); authorizationRequest.setRedirectUri(redirectUri); return Single.just(authorizationRequest); } else if (redirectUri != null && !redirectUri.isEmpty()) { return Single.just(authorizationRequest); } else { return Single.error(new InvalidRequestException("A redirect_uri must be supplied.")); } } catch (Exception e) { return Single.error(e); } } private boolean containsGrantType(List<String> authorizedGrantTypes) { return authorizedGrantTypes.stream() .anyMatch(authorizedGrantType -> OAuth2Constants.AUTHORIZATION_CODE.equals(authorizedGrantType) || OAuth2Constants.IMPLICIT.equals(authorizedGrantType)); } private String obtainMatchingRedirect(List<String> redirectUris, String requestedRedirect) { // no redirect_uri parameter supplied, return the first client registered redirect uri if (requestedRedirect == null) { return redirectUris.iterator().next(); } for (String redirectUri : redirectUris) { if (redirectMatches(requestedRedirect, redirectUri)) { return requestedRedirect; } } throw new RedirectMismatchException("The redirect_uri MUST match the registered callback URL for this application"); } private boolean redirectMatches(String requestedRedirect, String redirectUri) { try { URL req = new URL(requestedRedirect); URL reg = new URL(redirectUri); int requestedPort = req.getPort() != -1 ? req.getPort() : req.getDefaultPort(); int registeredPort = reg.getPort() != -1 ? reg.getPort() : reg.getDefaultPort(); boolean portsMatch = registeredPort == requestedPort; if (reg.getProtocol().equals(req.getProtocol()) && reg.getHost().equals(req.getHost()) && portsMatch) { return req.getPath().startsWith(reg.getPath()); } } catch (MalformedURLException e) { } return requestedRedirect.equals(redirectUri); } }
Java
UTF-8
659
1.867188
2
[]
no_license
package com.ssafy.IMS.controller; import com.ssafy.IMS.service.ScheduleService; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Api(value = "자소서에 관한 정보 처리") @RequestMapping("/api/schedule") @CrossOrigin(origins = "http://localhost:3000") @RestController public class ScheduleController { @Autowired private ScheduleService scheduleService; }
Java
UTF-8
5,022
1.710938
2
[]
no_license
package com.example.jungle.weixin.Activity; import android.support.v7.app.ActionBar; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.bumptech.glide.Glide; import com.example.jungle.weixin.Adapter.AMeAdapter; import com.example.jungle.weixin.Adapter.CommentListAdapter; import com.example.jungle.weixin.Bean.BaseBean.Comment; import com.example.jungle.weixin.Bean.BaseBean.Status; import com.example.jungle.weixin.Bean.ParticularBean.ReadCommentsData; import com.example.jungle.weixin.Bean.ParticularBean.StatusList; import com.example.jungle.weixin.CustomControls.AppCompatSwipeBack; import com.example.jungle.weixin.PublicUtils.CodeUtils; import com.example.jungle.weixin.R; import com.example.jungle.weixin.RetrofitUtil.HttpResultSubscriber; import com.example.jungle.weixin.RetrofitUtil.MyService; import com.example.jungle.weixin.RetrofitUtil.NetRequestFactory; import com.example.jungle.weixin.RetrofitUtil.Transform; import java.util.Arrays; import java.util.List; import retrofit2.Response; public class AMeActivity extends BaseActivity { private String token; private List<Status> status; private RecyclerView recyclerView; private AMeAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ame); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if(actionBar!=null){ actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle("@我"); } NetRequestFactory.getInstance().createService(MyService.class).getMentions(CodeUtils.getmToken()).compose(Transform.<Response<StatusList>>defaultSchedulers()).subscribe(new HttpResultSubscriber<Response<StatusList>>() { @Override public void onSuccess(Response<StatusList> StatusList) { status = StatusList.body().getStatuses(); recyclerView = (RecyclerView) findViewById(R.id.weibo_list); LinearLayoutManager layoutManager = new LinearLayoutManager(AMeActivity.this); recyclerView.setLayoutManager(layoutManager); adapter = new AMeAdapter(AMeActivity.this, status ); recyclerView.setAdapter(adapter); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); switch(newState){ case 0: try { if(AMeActivity.this!= null) Glide.with(AMeActivity.this).resumeRequests(); } catch (Exception e) { e.printStackTrace(); } break; case 1: try { if(AMeActivity.this!= null) Glide.with(AMeActivity.this).resumeRequests(); } catch (Exception e) { e.printStackTrace(); } break; case 2: try { if(AMeActivity.this!= null) Glide.with(AMeActivity.this).pauseRequests(); } catch (Exception e) { e.printStackTrace(); } break; } } }); } @Override public void _onError(Response<StatusList> StatusList) { } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override protected void onDestroy() { super.onDestroy(); Glide.get(AMeActivity.this).clearMemory(); } @Override public void onBackPressed() { scrollToFinishActivity();//左滑退出activity } }
JavaScript
UTF-8
1,856
2.546875
3
[]
no_license
// Simple HTTP server that renders barcode images using bwip-js. const http = require('http'); const bwipjs = require('bwip-js'); const DrawingSVG = require('./drawing-svg'); var url = require('url'); // This shows how to load the Inconsolata font, supplied with the bwip-js distribution. // The path to your fonts will be different. //bwipjs.loadFont('Inconsolata', 100, // require('fs').readFileSync('./fonts/Inconsolata.otf', 'binary')); http.createServer(function(req, res) { // If the url does not begin /?bcid= then 404. Otherwise, we end up // returning 400 on requests like favicon.ico. if (req.url.indexOf('/?bcid=') != 0) { res.writeHead(404, { 'Content-Type':'text/plain' }); res.end('BWIPJS: Unknown request format. http://192.168.1.22:3030/?bcid=code39&text=DJD545484&includetext', 'utf8'); } else { // bwipjs.request(req, res); // Executes asynchronously requestSvg(req, res); } }).listen(3030, "0.0.0.0"); function requestSvg(req, res, extra) { var opts = url.parse(req.url, true).query; // Convert boolean empty parameters to true for (var id in opts) { if (opts[id] === '') { opts[id] = true; } } // Add in server options/overrides if (extra) { for (var id in extra) { opts[id] = extra[id]; } } ToBuffer(opts, function(err, svg) { if (err) { res.writeHead(400, { 'Content-Type':'text/plain' }); res.end('' + (err.stack || err), 'utf-8'); } else { res.writeHead(200, { 'Content-Type':'image/svg+xml' }); res.end(svg, 'binary'); } }); } function ToBuffer(opts, callback) { try { bwipjs.fixupOptions(opts); var svg = bwipjs.render(opts, DrawingSVG(opts, bwipjs.FontLib)) callback(null, svg); } catch (e) { if (callback) { callback(e); } else { return new Promise(function(resolve, reject) { reject(e); }); } } }
C++
UTF-8
1,442
2.59375
3
[]
no_license
/* mjrenderable.h Matthew Jee mcjee@ucsc.edu Abstract class meant to be subclassed before usage. Definitely not the most efficient nor the most flexible, but it is very convenient for this project. */ #ifndef MJ_RENDERABLE_H #define MJ_RENDERABLE_H #include "mjutil.h" #include "mjmatrix.h" #include "mjshader.h" #include "mjlight.h" #include "mjgeometry.h" namespace mcjee { class Renderable { friend class Scene; private: GLuint vertexArrayObject; public: Geometry *geometry; Shader *shader; Material material; GLenum drawType; GLenum polygonMode; Matrix4 rotation; Vector3 center; Vector3 scale; Vector3 position; int visible; Renderable(Geometry *, Shader *, GLenum drawType); virtual ~Renderable(); void init(); void render(void); void resetRotation(); void rotateGlobal(float angle, Vector3 axis); void rotateLocal(float angle, Vector3 axis); void translateGlobal(float amount, Vector3 axis); void translateLocal(float amount, Vector3 axis); void scaleUniform(float s); void addScaleUniform(float s); Matrix4 modelMatrix(); Matrix4 inverseModelMatrix(); // To be overridden by subclasses virtual void setupVertexAttributes() = 0; virtual void setupUniforms() = 0; }; } #endif
Java
UTF-8
1,820
2.265625
2
[]
no_license
package com.cire.apps.twitterclient.fragments; import java.util.ArrayList; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.cire.apps.twitterclient.R; import com.cire.apps.twitterclient.adapters.TweetArrayAdapter; import com.cire.apps.twitterclient.listeners.EndlessScrollListener; import com.cire.apps.twitterclient.models.Tweet; public abstract class TweetListFragment extends Fragment { private ArrayList<Tweet> tweets; private TweetArrayAdapter tweetAdapter; private ListView lvTweets; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tweets = new ArrayList<Tweet>(); tweetAdapter = new TweetArrayAdapter(getActivity()); } public abstract void loadmore(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_tweets_list, container, false); lvTweets = (ListView)view.findViewById(R.id.lvTweets); lvTweets.setAdapter(tweetAdapter); lvTweets.setOnScrollListener(new EndlessScrollListener() { @Override public void onLoadMore(int page, int totalItemsCount) { Log.d("debug", "onLoadMore: " + "total: " + totalItemsCount + " page: " + page); loadmore(); } }); return view; } public TweetArrayAdapter getAdapter() { return tweetAdapter; } public void addAll(ArrayList<Tweet> tweets) { tweetAdapter.addAll(tweets); // tweetAdapter.notifyDataSetChanged(); } }
Python
UTF-8
1,398
2.640625
3
[]
no_license
#!/usr/bin/env python2 def emit_define(name, postfix, value): if name.find("#") != -1 and value.find("#") != -1: raise ValueError("Found processor metacharacters") return "#define " + name + postfix + " " + value + "\n" f = open("pins.def", "r").read() fOut = open("pins.def.h", "w") for line in f.split("\n"): if not line.startswith("PINOUT"): fOut.write(line + "\n") continue line = line[line.find("(")+1:line.find(")")] args = line.split(',') args = [a.strip() for a in args] pinName = args[0] port = args[1] pinDef = args[2] fOut.write(emit_define(pinName, "_PORT", "PORT" + port)) fOut.write(emit_define(pinName, "_DDR", " DDR" + port)) fOut.write(emit_define(pinName, "_PIN", " PIN" + port)) if pinDef.isdigit(): pinNumber = int(pinDef) if pinNumber < 0 or pinNumber > 7: raise ValueError("invalid pin bit definition") fOut.write(emit_define(pinName, "_MSK", " _BV(%s)" % pinDef)) fOut.write(emit_define(pinName, "_NUMBER", " %s" % pinDef)) elif pinDef.startswith("0b"): pinNumber = int(pinDef[2:], 2) # parse binary value if pinNumber < 0 or pinNumber > 255: raise ValueError("invalid pin bit definition: %s" % pinDef) fOut.write(emit_define(pinName, "_MSK", " " + hex(pinNumber))) fOut.write("\n") #print args
SQL
UTF-8
257
2.515625
3
[]
no_license
DROP TABLE GATHERING_MEMBER; CREATE TABLE GATHERING_MEMBER( ID VARCHAR2(300) PRIMARY KEY, PW VARCHAR2(300), TEL VARCHAR2(300), ADDR VARCHAR2(300), EMAIL VARCHAR2(300) ) SELECT * FROM GATHERING_MEMBER; delete from GATHERING_MEMBER where id='lee'
C++
UTF-8
1,311
3.015625
3
[]
no_license
#ifndef HMLIB_SHAREDMEMORY_INC #define HMLIB_SHAREDMEMORY_INC 100 # #include <boost/pool/object_pool.hpp> #include <vector> namespace hmLib{ template<class T> class shared_memory{ typedef unsigned int size_type; static boost::object_pool<T> Pool; private: T* Ptr; public: shared_memory() :Ptr(Pool.construct()){ } shared_memory(const T& t_):Ptr(Pool.construct(t_)){} shared_memory(const shared_memory& My_); ~shared_memory(){Pool.destroy(Ptr);} const shared_memory& operator=(const shared_memory& My_); operator T*()const{return Ptr;} T* operator ->()const{return Ptr;} void destroy(){ if(Ptr!=NULL)Pool.destroy(Ptr); Ptr=NULL; } }; template<class T> boost::object_pool<T> shared_memory<T>::Pool; template<class T> class shared_array_memory{ typedef unsigned int size_type; static boost::pool<> Pool; private: array_type* Ptr; public: shared_array_memory():Ptr(Pool.construct()){} shared_array_memory(size_type Size_):Ptr(Pool.construct(array_type(Size_))){} shared_array_memory(size_type Size_,const T& t_):Ptr(Pool.construct(array_type(Size_,t_))){} ~shared_array_memory(){Pool.destroy(Ptr);} operator T*()const{return Ptr;} T* operator ->()const{return Ptr;} void destroy(){ if(Ptr!=NULL)Pool.destroy(Ptr); Ptr=NULL; } }; } # #endif
Java
UTF-8
39,945
2.09375
2
[ "MIT", "EPL-1.0", "Apache-2.0" ]
permissive
/* Copyright 2002-2023 CS GROUP * Licensed to CS GROUP (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.orekit.models.earth.tessellation; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Queue; import org.hipparchus.exception.LocalizedCoreFormats; import org.hipparchus.geometry.euclidean.threed.Vector3D; import org.hipparchus.geometry.partitioning.BSPTree; import org.hipparchus.geometry.partitioning.Hyperplane; import org.hipparchus.geometry.partitioning.RegionFactory; import org.hipparchus.geometry.partitioning.SubHyperplane; import org.hipparchus.geometry.spherical.oned.ArcsSet; import org.hipparchus.geometry.spherical.twod.Circle; import org.hipparchus.geometry.spherical.twod.S2Point; import org.hipparchus.geometry.spherical.twod.Sphere2D; import org.hipparchus.geometry.spherical.twod.SphericalPolygonsSet; import org.hipparchus.geometry.spherical.twod.SubCircle; import org.hipparchus.util.FastMath; import org.hipparchus.util.MathUtils; import org.orekit.bodies.GeodeticPoint; import org.orekit.bodies.OneAxisEllipsoid; import org.orekit.errors.OrekitException; import org.orekit.errors.OrekitInternalError; /** Class used to tessellate an interest zone on an ellipsoid in either * {@link Tile tiles} or grids of {@link GeodeticPoint geodetic points}. * <p> * This class is typically used for Earth Observation missions, in order to * create tiles or grids that may be used as the basis of visibility event * detectors. Tiles are used when surface-related elements are needed, the * tiles created completely cover the zone of interest. Grids are used when * point-related elements are needed, the points created lie entirely within * the zone of interest. * </p> * <p> * One should note that as tessellation essentially creates a 2 dimensional * almost Cartesian map, it can never perfectly fulfill geometrical dimensions * because neither sphere nor ellipsoid are developable surfaces. This implies * that the tesselation will always be distorted, and distortion increases as * the size of the zone to be tessellated increases. * </p> * @author Luc Maisonobe * @since 7.1 */ public class EllipsoidTessellator { /** Safety limit to avoid infinite loops during tesselation due to numerical noise. * @since 10.3.1 */ private static final int MAX_ITER = 1000; /** Number of segments tiles sides are split into for tiles fine positioning. */ private final int quantization; /** Aiming used for orienting tiles. */ private final TileAiming aiming; /** Underlying ellipsoid. */ private final OneAxisEllipsoid ellipsoid; /** Simple constructor. * <p> * The {@code quantization} parameter is used internally to adjust points positioning. * For example when quantization is set to 4, a complete tile that has 4 corner points * separated by the tile lengths will really be computed on a grid containing 25 points * (5 rows of 5 points, as each side will be split in 4 segments, hence will have 5 * points). This quantization allows rough adjustment to balance margins around the * zone of interest and improves geometric accuracy as the along and across directions * are readjusted at each points. * </p> * <p> * It is recommended to use at least 2 as the quantization parameter for tiling. The * rationale is that using only 1 for quantization would imply all points used are tiles * vertices, and hence would lead small zones to generate 4 tiles with a shared vertex * inside the zone and the 4 tiles covering the four quadrants at North-West, North-East, * South-East and South-West. A quantization value of at least 2 allows to shift the * tiles so the center point is an inside point rather than a tile vertex, hence allowing * a single tile to cover the small zone. A value even greater like 4 or 8 would allow even * finer positioning to balance the tiles margins around the zone. * </p> * @param ellipsoid underlying ellipsoid * @param aiming aiming used for orienting tiles * @param quantization number of segments tiles sides are split into for tiles fine positioning */ public EllipsoidTessellator(final OneAxisEllipsoid ellipsoid, final TileAiming aiming, final int quantization) { this.ellipsoid = ellipsoid; this.aiming = aiming; this.quantization = quantization; } /** Tessellate a zone of interest into tiles. * <p> * The created tiles will completely cover the zone of interest. * </p> * <p> * The distance between a vertex at a tile corner and the vertex at the same corner * in the next vertex are computed by subtracting the overlap width (resp. overlap length) * from the full width (resp. full length). If for example the full width is specified to * be 55 km and the overlap in width is specified to be +5 km, successive tiles would span * as follows: * </p> * <ul> * <li>tile 1 covering from 0 km to 55 km</li> * <li>tile 2 covering from 50 km to 105 km</li> * <li>tile 3 covering from 100 km to 155 km</li> * <li>...</li> * </ul> * <p> * In order to achieve the same 50 km step but using a 5 km gap instead of an overlap, one would * need to specify the full width to be 45 km and the overlap to be -5 km. With these settings, * successive tiles would span as follows: * </p> * <ul> * <li>tile 1 covering from 0 km to 45 km</li> * <li>tile 2 covering from 50 km to 95 km</li> * <li>tile 3 covering from 100 km to 155 km</li> * <li>...</li> * </ul> * @param zone zone of interest to tessellate * @param fullWidth full tiles width as a distance on surface, including overlap (in meters) * @param fullLength full tiles length as a distance on surface, including overlap (in meters) * @param widthOverlap overlap between adjacent tiles (in meters), if negative the tiles * will have a gap between each other instead of an overlap * @param lengthOverlap overlap between adjacent tiles (in meters), if negative the tiles * will have a gap between each other instead of an overlap * @param truncateLastWidth if true, the first tiles strip will be started as close as * possible to the zone of interest, and the last tiles strip will have its width reduced * to also remain close to the zone of interest; if false all tiles strip will have the * same {@code fullWidth} and they will be balanced around zone of interest * @param truncateLastLength if true, the first tile in each strip will be started as close as * possible to the zone of interest, and the last tile in each strip will have its length reduced * to also remain close to the zone of interest; if false all tiles in each strip will have the * same {@code fullLength} and they will be balanced around zone of interest * @return a list of lists of tiles covering the zone of interest, * each sub-list corresponding to a part not connected to the other * parts (for example for islands) */ public List<List<Tile>> tessellate(final SphericalPolygonsSet zone, final double fullWidth, final double fullLength, final double widthOverlap, final double lengthOverlap, final boolean truncateLastWidth, final boolean truncateLastLength) { final double splitWidth = (fullWidth - widthOverlap) / quantization; final double splitLength = (fullLength - lengthOverlap) / quantization; final Map<Mesh, List<Tile>> map = new IdentityHashMap<Mesh, List<Tile>>(); final RegionFactory<Sphere2D> factory = new RegionFactory<Sphere2D>(); SphericalPolygonsSet remaining = (SphericalPolygonsSet) zone.copySelf(); S2Point inside = getInsidePoint(remaining); int count = 0; while (inside != null) { if (++count > MAX_ITER) { throw new OrekitException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAX_ITER); } // find a mesh covering at least one connected part of the zone final List<Mesh.Node> mergingSeeds = new ArrayList<Mesh.Node>(); Mesh mesh = new Mesh(ellipsoid, zone, aiming, splitLength, splitWidth, inside); mergingSeeds.add(mesh.getNode(0, 0)); List<Tile> tiles = null; while (!mergingSeeds.isEmpty()) { // expand the mesh around the seed neighborExpandMesh(mesh, mergingSeeds, zone); // extract the tiles from the mesh // this further expands the mesh so tiles dimensions are multiples of quantization, // hence it must be performed here before checking meshes independence tiles = extractTiles(mesh, zone, lengthOverlap, widthOverlap, truncateLastWidth, truncateLastLength); // check the mesh is independent from existing meshes mergingSeeds.clear(); for (final Map.Entry<Mesh, List<Tile>> entry : map.entrySet()) { if (!factory.intersection(mesh.getCoverage(), entry.getKey().getCoverage()).isEmpty()) { // the meshes are not independent, they intersect each other! // merge the two meshes together mesh = mergeMeshes(mesh, entry.getKey(), mergingSeeds); map.remove(entry.getKey()); break; } } } // remove the part of the zone covered by the mesh remaining = (SphericalPolygonsSet) factory.difference(remaining, mesh.getCoverage()); inside = getInsidePoint(remaining); map.put(mesh, tiles); } // concatenate the lists from the independent meshes final List<List<Tile>> tilesLists = new ArrayList<List<Tile>>(map.size()); for (final Map.Entry<Mesh, List<Tile>> entry : map.entrySet()) { tilesLists.add(entry.getValue()); } return tilesLists; } /** Sample a zone of interest into a grid sample of {@link GeodeticPoint geodetic points}. * <p> * The created points will be entirely within the zone of interest. * </p> * @param zone zone of interest to sample * @param width grid sample cells width as a distance on surface (in meters) * @param length grid sample cells length as a distance on surface (in meters) * @return a list of lists of points sampling the zone of interest, * each sub-list corresponding to a part not connected to the other * parts (for example for islands) */ public List<List<GeodeticPoint>> sample(final SphericalPolygonsSet zone, final double width, final double length) { final double splitWidth = width / quantization; final double splitLength = length / quantization; final Map<Mesh, List<GeodeticPoint>> map = new IdentityHashMap<Mesh, List<GeodeticPoint>>(); final RegionFactory<Sphere2D> factory = new RegionFactory<Sphere2D>(); SphericalPolygonsSet remaining = (SphericalPolygonsSet) zone.copySelf(); S2Point inside = getInsidePoint(remaining); int count = 0; while (inside != null) { if (++count > MAX_ITER) { throw new OrekitException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAX_ITER); } // find a mesh covering at least one connected part of the zone final List<Mesh.Node> mergingSeeds = new ArrayList<Mesh.Node>(); Mesh mesh = new Mesh(ellipsoid, zone, aiming, splitLength, splitWidth, inside); mergingSeeds.add(mesh.getNode(0, 0)); List<GeodeticPoint> sample = null; while (!mergingSeeds.isEmpty()) { // expand the mesh around the seed neighborExpandMesh(mesh, mergingSeeds, zone); // extract the sample from the mesh // this further expands the mesh so sample cells dimensions are multiples of quantization, // hence it must be performed here before checking meshes independence sample = extractSample(mesh, zone); // check the mesh is independent from existing meshes mergingSeeds.clear(); for (final Map.Entry<Mesh, List<GeodeticPoint>> entry : map.entrySet()) { if (!factory.intersection(mesh.getCoverage(), entry.getKey().getCoverage()).isEmpty()) { // the meshes are not independent, they intersect each other! // merge the two meshes together mesh = mergeMeshes(mesh, entry.getKey(), mergingSeeds); map.remove(entry.getKey()); break; } } } // remove the part of the zone covered by the mesh remaining = (SphericalPolygonsSet) factory.difference(remaining, mesh.getCoverage()); inside = getInsidePoint(remaining); map.put(mesh, sample); } // concatenate the lists from the independent meshes final List<List<GeodeticPoint>> sampleLists = new ArrayList<List<GeodeticPoint>>(map.size()); for (final Map.Entry<Mesh, List<GeodeticPoint>> entry : map.entrySet()) { sampleLists.add(entry.getValue()); } return sampleLists; } /** Get an inside point from a zone of interest. * @param zone zone to mesh * @return a point inside the zone or null if zone is empty or too thin */ private S2Point getInsidePoint(final SphericalPolygonsSet zone) { final InsideFinder finder = new InsideFinder(zone); zone.getTree(false).visit(finder); return finder.getInsidePoint(); } /** Expand a mesh so it surrounds at least one connected part of a zone. * <p> * This part of mesh expansion is neighbors based. It includes the seed * node neighbors, and their neighbors, and the neighbors of their * neighbors until the path-connected sub-parts of the zone these nodes * belong to are completely surrounded by the mesh taxicab boundary. * </p> * @param mesh mesh to expand * @param seeds seed nodes (already in the mesh) from which to start expansion * @param zone zone to mesh */ private void neighborExpandMesh(final Mesh mesh, final Collection<Mesh.Node> seeds, final SphericalPolygonsSet zone) { // mesh expansion loop boolean expanding = true; final Queue<Mesh.Node> newNodes = new LinkedList<Mesh.Node>(); newNodes.addAll(seeds); int count = 0; while (expanding) { if (++count > MAX_ITER) { throw new OrekitException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAX_ITER); } // first expansion step: set up the mesh so that all its // inside nodes are completely surrounded by at least // one layer of outside nodes while (!newNodes.isEmpty()) { // retrieve an active node final Mesh.Node node = newNodes.remove(); if (node.isInside()) { // the node is inside the zone, the mesh must contain its 8 neighbors addAllNeighborsIfNeeded(node, mesh, newNodes); } } // second expansion step: check if the loop of outside nodes // completely surrounds the zone, i.e. there are no peaks // pointing out of the loop between two nodes expanding = false; final List<Mesh.Node> boundary = mesh.getTaxicabBoundary(false); if (boundary.size() > 1) { Mesh.Node previous = boundary.get(boundary.size() - 1); for (final Mesh.Node node : boundary) { if (meetInside(previous.getS2P(), node.getS2P(), zone)) { // part of the mesh boundary is still inside the zone! // the mesh must be expanded again addAllNeighborsIfNeeded(previous, mesh, newNodes); addAllNeighborsIfNeeded(node, mesh, newNodes); expanding = true; } previous = node; } } } } /** Extract tiles from a mesh. * @param mesh mesh from which tiles should be extracted * @param zone zone covered by the mesh * @param lengthOverlap overlap between adjacent tiles * @param widthOverlap overlap between adjacent tiles * @param truncateLastWidth true if we can reduce last tile width * @param truncateLastLength true if we can reduce last tile length * @return extracted tiles */ private List<Tile> extractTiles(final Mesh mesh, final SphericalPolygonsSet zone, final double lengthOverlap, final double widthOverlap, final boolean truncateLastWidth, final boolean truncateLastLength) { final List<Tile> tiles = new ArrayList<Tile>(); final List<RangePair> rangePairs = new ArrayList<RangePair>(); final int minAcross = mesh.getMinAcrossIndex(); final int maxAcross = mesh.getMaxAcrossIndex(); for (Range acrossPair : nodesIndices(minAcross, maxAcross, truncateLastWidth)) { int minAlong = mesh.getMaxAlongIndex() + 1; int maxAlong = mesh.getMinAlongIndex() - 1; for (int c = acrossPair.lower; c <= acrossPair.upper; ++c) { minAlong = FastMath.min(minAlong, mesh.getMinAlongIndex(c)); maxAlong = FastMath.max(maxAlong, mesh.getMaxAlongIndex(c)); } for (Range alongPair : nodesIndices(minAlong, maxAlong, truncateLastLength)) { // get the base vertex nodes final Mesh.Node node0 = mesh.addNode(alongPair.lower, acrossPair.lower); final Mesh.Node node1 = mesh.addNode(alongPair.upper, acrossPair.lower); final Mesh.Node node2 = mesh.addNode(alongPair.upper, acrossPair.upper); final Mesh.Node node3 = mesh.addNode(alongPair.lower, acrossPair.upper); // apply tile overlap final S2Point s2p0 = node0.move(new Vector3D(-0.5 * lengthOverlap, node0.getAlong(), -0.5 * widthOverlap, node0.getAcross())); final S2Point s2p1 = node1.move(new Vector3D(+0.5 * lengthOverlap, node1.getAlong(), -0.5 * widthOverlap, node1.getAcross())); final S2Point s2p2 = node2.move(new Vector3D(+0.5 * lengthOverlap, node2.getAlong(), +0.5 * widthOverlap, node2.getAcross())); final S2Point s2p3 = node3.move(new Vector3D(-0.5 * lengthOverlap, node2.getAlong(), +0.5 * widthOverlap, node2.getAcross())); // create a quadrilateral region corresponding to the candidate tile final SphericalPolygonsSet quadrilateral = new SphericalPolygonsSet(zone.getTolerance(), s2p0, s2p1, s2p2, s2p3); if (!new RegionFactory<Sphere2D>().intersection(zone.copySelf(), quadrilateral).isEmpty()) { // the tile does cover part of the zone, it contributes to the tessellation tiles.add(new Tile(toGeodetic(s2p0), toGeodetic(s2p1), toGeodetic(s2p2), toGeodetic(s2p3))); rangePairs.add(new RangePair(acrossPair, alongPair)); } } } // ensure the taxicab boundary follows the built tile sides // this is done outside of the previous loop in order // to avoid one tile changing the min/max indices of the // neighboring tile as they share some nodes that will be enabled here for (final RangePair rangePair : rangePairs) { for (int c = rangePair.across.lower; c < rangePair.across.upper; ++c) { mesh.addNode(rangePair.along.lower, c + 1).setEnabled(); mesh.addNode(rangePair.along.upper, c).setEnabled(); } for (int l = rangePair.along.lower; l < rangePair.along.upper; ++l) { mesh.addNode(l, rangePair.across.lower).setEnabled(); mesh.addNode(l + 1, rangePair.across.upper).setEnabled(); } } return tiles; } /** Extract a sample of points from a mesh. * @param mesh mesh from which grid should be extracted * @param zone zone covered by the mesh * @return extracted grid */ private List<GeodeticPoint> extractSample(final Mesh mesh, final SphericalPolygonsSet zone) { // find how to select sample points taking quantization into account // to have the largest possible number of points while still // being inside the zone of interest int selectedAcrossModulus = -1; int selectedAlongModulus = -1; int selectedCount = -1; for (int acrossModulus = 0; acrossModulus < quantization; ++acrossModulus) { for (int alongModulus = 0; alongModulus < quantization; ++alongModulus) { // count how many points would be selected for the current modulus int count = 0; for (int across = mesh.getMinAcrossIndex() + acrossModulus; across <= mesh.getMaxAcrossIndex(); across += quantization) { for (int along = mesh.getMinAlongIndex() + alongModulus; along <= mesh.getMaxAlongIndex(); along += quantization) { final Mesh.Node node = mesh.getNode(along, across); if (node != null && node.isInside()) { ++count; } } } if (count > selectedCount) { // current modulus are better than the selected ones selectedAcrossModulus = acrossModulus; selectedAlongModulus = alongModulus; selectedCount = count; } } } // extract the sample points final List<GeodeticPoint> sample = new ArrayList<GeodeticPoint>(selectedCount); for (int across = mesh.getMinAcrossIndex() + selectedAcrossModulus; across <= mesh.getMaxAcrossIndex(); across += quantization) { for (int along = mesh.getMinAlongIndex() + selectedAlongModulus; along <= mesh.getMaxAlongIndex(); along += quantization) { final Mesh.Node node = mesh.getNode(along, across); if (node != null && node.isInside()) { sample.add(toGeodetic(node.getS2P())); } } } return sample; } /** Merge two meshes together. * @param mesh1 first mesh * @param mesh2 second mesh * @param mergingSeeds collection where to put the nodes created during the merge * @return merged mesh (really one of the instances) */ private Mesh mergeMeshes(final Mesh mesh1, final Mesh mesh2, final Collection<Mesh.Node> mergingSeeds) { // select the way merge will be performed final Mesh larger; final Mesh smaller; if (mesh1.getNumberOfNodes() >= mesh2.getNumberOfNodes()) { // the larger new mesh should absorb the smaller existing mesh larger = mesh1; smaller = mesh2; } else { // the larger existing mesh should absorb the smaller new mesh larger = mesh2; smaller = mesh1; } // prepare seed nodes for next iteration for (final Mesh.Node insideNode : smaller.getInsideNodes()) { // beware we cannot reuse the node itself as the two meshes are not aligned! // we have to create new nodes around the previous location Mesh.Node node = larger.getClosestExistingNode(insideNode.getV()); while (estimateAlongMotion(node, insideNode.getV()) > +mesh1.getAlongGap()) { // the node is before desired index in the along direction // we need to create intermediates nodes up to the desired index node = larger.addNode(node.getAlongIndex() + 1, node.getAcrossIndex()); } while (estimateAlongMotion(node, insideNode.getV()) < -mesh1.getAlongGap()) { // the node is after desired index in the along direction // we need to create intermediates nodes up to the desired index node = larger.addNode(node.getAlongIndex() - 1, node.getAcrossIndex()); } while (estimateAcrossMotion(node, insideNode.getV()) > +mesh1.getAcrossGap()) { // the node is before desired index in the across direction // we need to create intermediates nodes up to the desired index node = larger.addNode(node.getAlongIndex(), node.getAcrossIndex() + 1); } while (estimateAcrossMotion(node, insideNode.getV()) < -mesh1.getAcrossGap()) { // the node is after desired index in the across direction // we need to create intermediates nodes up to the desired index node = larger.addNode(node.getAlongIndex(), node.getAcrossIndex() - 1); } // now we are close to the inside node, // make sure the four surrounding nodes are available final int otherAlong = (estimateAlongMotion(node, insideNode.getV()) < 0.0) ? node.getAlongIndex() - 1 : node.getAlongIndex() + 1; final int otherAcross = (estimateAcrossMotion(node, insideNode.getV()) < 0.0) ? node.getAcrossIndex() - 1 : node.getAcrossIndex() + 1; addNode(node.getAlongIndex(), node.getAcrossIndex(), larger, mergingSeeds); addNode(node.getAlongIndex(), otherAcross, larger, mergingSeeds); addNode(otherAlong, node.getAcrossIndex(), larger, mergingSeeds); addNode(otherAlong, otherAcross, larger, mergingSeeds); } return larger; } /** Ensure all 8 neighbors of a node are in the mesh. * @param base base node * @param mesh complete mesh containing nodes * @param newNodes queue where new node must be put */ private void addAllNeighborsIfNeeded(final Mesh.Node base, final Mesh mesh, final Collection<Mesh.Node> newNodes) { addNode(base.getAlongIndex() - 1, base.getAcrossIndex() - 1, mesh, newNodes); addNode(base.getAlongIndex() - 1, base.getAcrossIndex(), mesh, newNodes); addNode(base.getAlongIndex() - 1, base.getAcrossIndex() + 1, mesh, newNodes); addNode(base.getAlongIndex(), base.getAcrossIndex() - 1, mesh, newNodes); addNode(base.getAlongIndex(), base.getAcrossIndex() + 1, mesh, newNodes); addNode(base.getAlongIndex() + 1, base.getAcrossIndex() - 1, mesh, newNodes); addNode(base.getAlongIndex() + 1, base.getAcrossIndex(), mesh, newNodes); addNode(base.getAlongIndex() + 1, base.getAcrossIndex() + 1, mesh, newNodes); } /** Add a node to a mesh if not already present. * @param alongIndex index in the along direction * @param acrossIndex index in the across direction * @param mesh complete mesh containing nodes * @param newNodes queue where new node must be put */ private void addNode(final int alongIndex, final int acrossIndex, final Mesh mesh, final Collection<Mesh.Node> newNodes) { final Mesh.Node node = mesh.addNode(alongIndex, acrossIndex); if (!node.isEnabled()) { // enable the node node.setEnabled(); newNodes.add(node); } } /** Convert a point on the unit 2-sphere to geodetic coordinates. * @param point point on the unit 2-sphere * @return geodetic point (arbitrarily set at altitude 0) */ protected GeodeticPoint toGeodetic(final S2Point point) { return new GeodeticPoint(0.5 * FastMath.PI - point.getPhi(), point.getTheta(), 0.0); } /** Build a simple zone (connected zone without holes). * <p> * In order to build more complex zones (not connected or with * holes), the user should directly call Hipparchus * {@link SphericalPolygonsSet} constructors and * {@link RegionFactory region factory} if set operations * are needed (union, intersection, difference ...). * </p> * <p> * Take care that the vertices boundary points must be given <em>counterclockwise</em>. * Using the wrong order defines the complementary of the real zone, * and will often result in tessellation failure as the zone is too * wide. * </p> * @param tolerance angular separation below which points are considered * equal (typically 1.0e-10) * @param points vertices of the boundary, in <em>counterclockwise</em> * order, each point being a two-elements arrays with latitude at index 0 * and longitude at index 1 * @return a zone defined on the unit 2-sphere */ public static SphericalPolygonsSet buildSimpleZone(final double tolerance, final double[]... points) { final S2Point[] vertices = new S2Point[points.length]; for (int i = 0; i < points.length; ++i) { vertices[i] = new S2Point(points[i][1], 0.5 * FastMath.PI - points[i][0]); } return new SphericalPolygonsSet(tolerance, vertices); } /** Build a simple zone (connected zone without holes). * <p> * In order to build more complex zones (not connected or with * holes), the user should directly call Hipparchus * {@link SphericalPolygonsSet} constructors and * {@link RegionFactory region factory} if set operations * are needed (union, intersection, difference ...). * </p> * <p> * Take care that the vertices boundary points must be given <em>counterclockwise</em>. * Using the wrong order defines the complementary of the real zone, * and will often result in tessellation failure as the zone is too * wide. * </p> * @param tolerance angular separation below which points are considered * equal (typically 1.0e-10) * @param points vertices of the boundary, in <em>counterclockwise</em> * order * @return a zone defined on the unit 2-sphere */ public static SphericalPolygonsSet buildSimpleZone(final double tolerance, final GeodeticPoint... points) { final S2Point[] vertices = new S2Point[points.length]; for (int i = 0; i < points.length; ++i) { vertices[i] = new S2Point(points[i].getLongitude(), 0.5 * FastMath.PI - points[i].getLatitude()); } return new SphericalPolygonsSet(tolerance, vertices); } /** Estimate an approximate motion in the along direction. * @param start node at start of motion * @param end desired point at end of motion * @return approximate motion in the along direction */ private double estimateAlongMotion(final Mesh.Node start, final Vector3D end) { return Vector3D.dotProduct(start.getAlong(), end.subtract(start.getV())); } /** Estimate an approximate motion in the across direction. * @param start node at start of motion * @param end desired point at end of motion * @return approximate motion in the across direction */ private double estimateAcrossMotion(final Mesh.Node start, final Vector3D end) { return Vector3D.dotProduct(start.getAcross(), end.subtract(start.getV())); } /** Check if an arc meets the inside of a zone. * @param s1 first point * @param s2 second point * @param zone zone to check arc against * @return true if the arc meets the inside of the zone */ private boolean meetInside(final S2Point s1, final S2Point s2, final SphericalPolygonsSet zone) { final Circle circle = new Circle(s1, s2, zone.getTolerance()); final double alpha1 = circle.toSubSpace(s1).getAlpha(); final double alpha2 = MathUtils.normalizeAngle(circle.toSubSpace(s2).getAlpha(), alpha1 + FastMath.PI); final SubCircle sub = new SubCircle(circle, new ArcsSet(alpha1, alpha2, zone.getTolerance())); return recurseMeetInside(zone.getTree(false), sub); } /** Check if an arc meets the inside of a zone. * <p> * This method is heavily based on the Characterization class from * Hipparchus library, also distributed under the terms * of the Apache Software License V2. * </p> * @param node spherical zone node * @param sub arc to characterize * @return true if the arc meets the inside of the zone */ private boolean recurseMeetInside(final BSPTree<Sphere2D> node, final SubHyperplane<Sphere2D> sub) { if (node.getCut() == null) { // we have reached a leaf node if (sub.isEmpty()) { return false; } else { return (Boolean) node.getAttribute(); } } else { final Hyperplane<Sphere2D> hyperplane = node.getCut().getHyperplane(); final SubHyperplane.SplitSubHyperplane<Sphere2D> split = sub.split(hyperplane); switch (split.getSide()) { case PLUS: return recurseMeetInside(node.getPlus(), sub); case MINUS: return recurseMeetInside(node.getMinus(), sub); case BOTH: if (recurseMeetInside(node.getPlus(), split.getPlus())) { return true; } else { return recurseMeetInside(node.getMinus(), split.getMinus()); } default: // this should not happen throw new OrekitInternalError(null); } } } /** Get an iterator over mesh nodes indices. * @param minIndex minimum node index * @param maxIndex maximum node index * @param truncateLast true if we can reduce last tile * @return iterator over mesh nodes indices */ private Iterable<Range> nodesIndices(final int minIndex, final int maxIndex, final boolean truncateLast) { final int first; if (truncateLast) { // truncate last tile rather than balance tiles around the zone of interest first = minIndex; } else { // balance tiles around the zone of interest rather than truncate last tile // number of tiles needed to cover the full indices range final int range = maxIndex - minIndex; final int nbTiles = (range + quantization - 1) / quantization; // extra nodes that must be added to complete the tiles final int extraNodes = nbTiles * quantization - range; // balance the extra nodes before min index and after maxIndex final int extraBefore = (extraNodes + 1) / 2; first = minIndex - extraBefore; } return new Iterable<Range>() { /** {@inheritDoc} */ @Override public Iterator<Range> iterator() { return new Iterator<Range>() { private int nextLower = first; /** {@inheritDoc} */ @Override public boolean hasNext() { return nextLower < maxIndex; } /** {@inheritDoc} */ @Override public Range next() { if (nextLower >= maxIndex) { throw new NoSuchElementException(); } final int lower = nextLower; nextLower += quantization; if (truncateLast && nextLower > maxIndex && lower < maxIndex) { // truncate last tile nextLower = maxIndex; } return new Range(lower, nextLower); } /** {@inheritDoc} */ @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } /** Local class for a range of indices to be used for building a tile. */ private static class Range { /** Lower index. */ private final int lower; /** Upper index. */ private final int upper; /** Simple constructor. * @param lower lower index * @param upper upper index */ Range(final int lower, final int upper) { this.lower = lower; this.upper = upper; } } /** Local class for a pair of ranges of indices to be used for building a tile. */ private static class RangePair { /** Across range. */ private final Range across; /** Along range. */ private final Range along; /** Simple constructor. * @param across across range * @param along along range */ RangePair(final Range across, final Range along) { this.across = across; this.along = along; } } }
PHP
UTF-8
3,648
2.828125
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); namespace Innmind\Reflection; use Innmind\Reflection\{ InjectionStrategy\InjectionStrategies, Instanciator\ReflectionInstanciator, Exception\InvalidArgumentException, }; use Innmind\Immutable\{ Map, Set, }; use function Innmind\Immutable\assertMap; final class ReflectionClass { /** @var class-string */ private string $class; /** @var Map<string, mixed> */ private Map $properties; private InjectionStrategy $injectionStrategy; private Instanciator $instanciator; /** * @param class-string $class * @param Map<string, mixed>|null $properties */ public function __construct( string $class, Map $properties = null, InjectionStrategy $injectionStrategy = null, Instanciator $instanciator = null ) { /** @var Map<string, mixed> $default */ $default = Map::of('string', 'mixed'); $properties ??= $default; assertMap('string', 'mixed', $properties, 2); $this->class = $class; $this->properties = $properties; $this->injectionStrategy = $injectionStrategy ?? InjectionStrategies::default(); $this->instanciator = $instanciator ?? new ReflectionInstanciator; } /** * @param class-string $class * @param Map<string, mixed>|null $properties */ public static function of( string $class, Map $properties = null, InjectionStrategy $injectionStrategy = null, Instanciator $instanciator = null ): self { return new self($class, $properties, $injectionStrategy, $instanciator); } /** * Add a property to be injected in the new object * * @param mixed $value */ public function withProperty(string $property, $value): self { return new self( $this->class, ($this->properties)($property, $value), $this->injectionStrategy, $this->instanciator, ); } /** * Add a set of properties that need to be injected * * @param array<string, mixed> $properties */ public function withProperties(array $properties): self { $map = $this->properties; /** @var mixed $value */ foreach ($properties as $key => $value) { $map = ($map)($key, $value); } return new self( $this->class, $map, $this->injectionStrategy, $this->instanciator, ); } /** * Return a new instance of the class */ public function build(): object { $object = $this->instanciator->build($this->class, $this->properties); $parameters = $this->instanciator->parameters($this->class); //avoid injecting the properties already used in the constructor $properties = $this ->properties ->filter(static fn(string $property) => !$parameters->contains($property)); $refl = new ReflectionObject( $object, $properties, $this->injectionStrategy, ); return $refl->build(); } /** * Return all the properties defined on the class * * It will not extract properties defined in a parent class * * @return Set<string> */ public function properties(): Set { $refl = new \ReflectionClass($this->class); $properties = Set::strings(); foreach ($refl->getProperties() as $property) { $properties = ($properties)($property->getName()); } return $properties; } }
Python
UTF-8
383
3.671875
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun May 9 12:53:59 2021 @author: Admin """ # dictionary comprehention with if else # {1:'odd',2:'even} d={num:('even' if num%2==0 else 'odd') for num in range(1,11)} print(d) a={i:i**3 for i in range(1,11)} print(a) c=[i**3 if (i%2==0) else (-i) for i in range(1,11)] print(c) q={i**3 for i in range(1,11)} print(q)
Markdown
UTF-8
2,232
3.46875
3
[]
no_license
Il est temps de parler des options. Je reprends l'exemple du début : `mkdir -v dossier1 dossier2 dossier4`{{execute}} * La commande est `mkdir` * Cette commande prend 4 arguments qui sont `-v`, `dossier1`, `dossier2` et `dossier4`. En réalité, `-v` est un argument particulier : c'est une **option**. # Mais comment bash fait-il la distinction entre une option et un argument ? Cette distinction passe par plusieurs conventions. Voici les deux principales : * **Le simple tiret** : les mots qui commencent par un `-` sont des options et les autres sont les arguments. Avec cette convention, il est possible de regrouper plusieurs options dans un même mot. Par exemple, lorsque tu exécutes `du -sh /opt/`{{execute}}, la commande est `du`, il y a **deux** options `-s` et `-h` et un argument, `/opt/` * **Le double tiret** : les options ainsi signalées le sont en version longue. Ainsi : `du -sh /opt/`{{execute}} est équivalent à `du --summarize --human-readable /opt/`{{execute}} C'est plus long à écrire, mais c'est aussi plus compréhensible, à condition de connaître quelques mots techniques en anglais. L'option `-s` de la commande `du` s'écrit, en version longue, `--summarize`. Elle dit à la commande `du` de "faire la somme" Avec cette convention, il n'est possible de regrouper plusieurs options dans un même mot. A partir de maintenant, nous ferons donc la distinction entre un **argument** et une **option**. # Question Lorsque tu exécutes `du -sh /opt/` >> A quoi correspond l'option -s ? << ( ) elle dit à la commande du qu'elle a le seum ! (*) elle dit à la commande du de "faire la somme" ( ) elle ne correspond à rien du tout ( ) elle dit à la commande du de ne pas prendre en compte les dossiers dont le nom commence par un s >> A quoi correspond l'option -h ? << ( ) elle dit à la commande du que la drogue est mauvaise pour la santé ! (*) elle dit à la commande du d'afficher le résultat de façon lisible pour un humain (un nombre ni trop grand, ni trop petit et une unité adaptée) ( ) elle ne correspond à rien du tout ( ) elle dit à la commande du de ne pas prendre en compte les dossiers dont le nom commence par un h
Markdown
UTF-8
706
2.609375
3
[]
no_license
Internet Connection =================== A small script that plays a beep when there is no Internet connection ## Installation 1. Download this repository using `git clone` or clicking on [this link](https://github.com/IonicaBizau/internet-connection/archive/master.zip).: ``` git clone git@github.com:IonicaBizau/internet-connection.git ``` 3. Install `mplayer`: ``` $ sudo apt-get install mplayer ``` ## How to use Enter in the downloaded repository folder and run `start.sh`: ``` $ ./start.sh & ``` Or add `./start.sh` to start at boot: ``` $ crontab -e ``` Then add `@reboot` followed by path to `start.sh` script. ## Utility The script will play a sound when the Internet connectivity is stopped.
Java
UTF-8
15,943
1.734375
2
[]
no_license
package vistas; import controlador.Disponibilidad; import modelo.Archivos; import controlador.ListaViaje; import controlador.Publicacion; import javax.swing.JOptionPane; import javax.swing.JTable; import modelo.PAGO_VIAJE; import modelo.PASAJERO; public final class VentanaViaje extends javax.swing.JDialog { ListaViaje listaViaje; Disponibilidad disponibilidad; Archivos archivo; String indiceViaje; VentanaPublicacion ventanaVi; String cedula; int precio; PASAJERO pasajero; String cedulaConductor; Publicacion publicacion = new Publicacion(); public void VerViaje() { jLabel28.setText(pasajero.getNombre()); jLabel5.setText(listaViaje.buscarViaje(indiceViaje).getLugar_origen()); jLabel6.setText(listaViaje.buscarViaje(indiceViaje).getLugar_destino()); jLabel7.setText(String.valueOf(listaViaje.buscarViaje(indiceViaje).getTotal_asientos_disponibles())); jLabel9.setText(String.valueOf(listaViaje.buscarViaje(indiceViaje).getPrecio())); jLabel10.setText(listaViaje.buscarViaje(indiceViaje).getConductor()); cedu_conductor.setText(String.valueOf(listaViaje.buscarViaje(indiceViaje).getCi_conductor())); jLabel11.setText(listaViaje.buscarViaje(indiceViaje).getAuto()); jLabel12.setText(listaViaje.buscarViaje(indiceViaje).getPlaca()); lblFecha.setText(listaViaje.buscarViaje(indiceViaje).getFecha()); lblSalida.setText(listaViaje.buscarViaje(indiceViaje).getHora_salida()); lblLlegada.setText(listaViaje.buscarViaje(indiceViaje).getHora_llegada()); cedulaConductor=listaViaje.buscarViaje(indiceViaje).getCi_conductor(); } public VentanaViaje(java.awt.Frame parent, boolean modal, ListaViaje listaViajes, String indiceViaje, VentanaPublicacion jfm, PASAJERO pasajero) { super(parent, modal); this.listaViaje = listaViajes; this.indiceViaje = indiceViaje; this.ventanaVi = jfm; this.pasajero = pasajero; archivo = new Archivos(); disponibilidad = new Disponibilidad(listaViajes.getRaiz()); initComponents(); this.setLocationRelativeTo(null); VerViaje(); this.cedula = cedula; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel4 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jLabel24 = new javax.swing.JLabel(); jPanel8 = new javax.swing.JPanel(); jLabel26 = new javax.swing.JLabel(); jLabel28 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); botonCancelar = new javax.swing.JButton(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); lblFecha = new javax.swing.JLabel(); lblSalida = new javax.swing.JLabel(); lblLlegada = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel22 = new javax.swing.JLabel(); txtNumAsi = new javax.swing.JTextField(); jLabel23 = new javax.swing.JLabel(); cedu_conductor = new javax.swing.JLabel(); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel4.setText("CI:"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Detalles del viaje"); setMinimumSize(new java.awt.Dimension(220, 220)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel7.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel24.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Anotación 2020-01-23 030344 (2).png"))); // NOI18N jLabel24.setToolTipText(""); jLabel24.setVerticalAlignment(javax.swing.SwingConstants.TOP); jPanel7.add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 20, 240, 70)); jPanel8.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/perfil (1).png"))); // NOI18N jPanel8.add(jLabel26, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 0, 70, 80)); jLabel28.setText("Usuario"); jPanel8.add(jLabel28, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 70, 120, 20)); jPanel7.add(jPanel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 0, 210, 100)); jPanel2.add(jPanel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(-105, 5, 690, -1)); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 480, 110)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Origen:"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 10, 90, 50)); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Destino:"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 20, 70, 30)); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Precio Asiento"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 190, 190, 40)); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel8.setText("Fecha:"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 150, 120, 40)); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 20, 110, 30)); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 20, 130, 30)); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 60, 30, 20)); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 22)); // NOI18N jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 240, 70, 30)); jLabel11.setText("Vehiculo"); jPanel1.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 160, -1, -1)); jLabel12.setText("Placa"); jPanel1.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 190, -1, -1)); jLabel10.setText("Conductor"); jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 100, -1, -1)); botonCancelar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N botonCancelar.setText("Cancelar"); botonCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonCancelarActionPerformed(evt); } }); jPanel1.add(botonCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 330, 110, 30)); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel14.setText("$"); jPanel1.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 240, 30, 30)); jPanel1.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 220, 70, 20)); jLabel16.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel16.setText("Asientos Disponibles:"); jPanel1.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 150, 40)); jLabel17.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel17.setText("CI conductor:"); jPanel1.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, 120, 150, 40)); jLabel18.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel18.setText("Vehículo:"); jPanel1.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 150, 150, 40)); jLabel19.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel19.setText("Placa:"); jPanel1.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 180, 150, 40)); jLabel20.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel20.setText("Hora de Salida:"); jPanel1.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 90, 110, 40)); jLabel21.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel21.setText("Hora de Llegada:"); jPanel1.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 120, 120, 40)); lblFecha.setText("jLabel4"); jPanel1.add(lblFecha, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 160, -1, -1)); lblFecha.getAccessibleContext().setAccessibleName("lblFecha"); lblSalida.setText("jLabel4"); jPanel1.add(lblSalida, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 100, -1, -1)); lblSalida.getAccessibleContext().setAccessibleName("lblSalida"); lblLlegada.setText("jLabel4"); jPanel1.add(lblLlegada, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 130, -1, 20)); lblLlegada.getAccessibleContext().setAccessibleName("lblLlegada"); jButton1.setText("Unirse"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 330, 80, 30)); jLabel22.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel22.setText("Seleccione el número de asientos:"); jPanel1.add(jLabel22, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 230, -1, -1)); jPanel1.add(txtNumAsi, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 270, 80, -1)); jLabel23.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel23.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel23.setText("Conductor:"); jPanel1.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, 90, 150, 40)); cedu_conductor.setText("jLabel4"); jPanel1.add(cedu_conductor, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 130, -1, 20)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, 500, 390)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed this.setVisible(false); this.dispose(); }//GEN-LAST:event_botonCancelarActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if (Integer.parseInt(this.txtNumAsi.getText()) > 0) { precio = publicacion.PrecioTotal(listaViaje.buscarViaje(indiceViaje).getPrecio(), Integer.parseInt(this.txtNumAsi.getText())); if (listaViaje.buscarViaje(indiceViaje).getTotal_asientos_disponibles() >= Integer.parseInt(this.txtNumAsi.getText())) { if (JOptionPane.showConfirmDialog(null, "El precio total del viaje es de: $" + precio + "\n¿Continuar?\n", "Precio total", JOptionPane.YES_NO_OPTION) == 0) { if (pagarViaje() == true) { this.disponibilidad.bajarDisponibilidad(indiceViaje, Integer.parseInt(this.txtNumAsi.getText())); if(listaViaje.buscarViaje(indiceViaje).getTotal_asientos_disponibles()==0) this.listaViaje.eliminarViaje(indiceViaje); archivo.guardarArchivo(listaViaje); this.dispose(); } } } else { JOptionPane.showMessageDialog(null, "No hay suficientes asientos!"); } } // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed public boolean pagarViaje() { PAGO_VIAJE pg = new PAGO_VIAJE(); return pg.pagar(pasajero, precio, cedulaConductor, indiceViaje, this.txtNumAsi.getText()); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonCancelar; private javax.swing.JLabel cedu_conductor; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JLabel lblFecha; private javax.swing.JLabel lblLlegada; private javax.swing.JLabel lblSalida; private javax.swing.JTextField txtNumAsi; // End of variables declaration//GEN-END:variables }
JavaScript
UTF-8
4,732
3.265625
3
[]
no_license
//Global variables var scene, camera, renderer; var geometry1, material1, mesh1; var geometry2, material2, mesh2; var geometry3, material3, mesh3; var geometry4, material4, mesh4; var geometry5, material5, mesh5; var geometry6, material6, mesh6; var geometry7, material7, mesh7; var geometry8, material8, mesh8; var geometry9, material9, mesh9; function init(){ // Create an empty scene -------------------------- scene = new THREE.Scene(); // Create a basic perspective camera -------------- camera = new THREE.PerspectiveCamera(40, window.innerWidth/window.innerHeight, 300, 10000 ); // Create a renderer with Antialiasing ------------ renderer = new THREE.WebGLRenderer({antialias:true}); // Configure renderer clear color renderer.setClearColor("#000000"); // Configure renderer size renderer.setSize( window.innerWidth, window.innerHeight ); // Append Renderer to DOM document.body.appendChild( renderer.domElement ); } function geometry(){ // Create a Cube Mesh with basic material --------- geometry1 = new THREE.BoxGeometry(1000, 10, 10); material1 = new THREE.MeshBasicMaterial( { color: "#F5F5F5" } ); mesh1 = new THREE.Mesh( geometry1, material1 ); mesh1.position.z = -1000; mesh1.position.y = -100; // Add mesh to scene scene.add( mesh1 ); // Create a Cube Mesh with basic material --------- geometry2 = new THREE.BoxGeometry(1000, 10, 10); material2 = new THREE.MeshBasicMaterial( { color: "#F5F5F5" } ); mesh2 = new THREE.Mesh( geometry2, material2 ); mesh2.position.z = -1000; mesh2.position.y = -100; // Add mesh to scene scene.add( mesh2 ); // Create a Ball Mesh with basic material --------- geometry3 = new THREE.SphereGeometry(50, 50, 50); material3 = new THREE.MeshBasicMaterial( { color: "#F5F5F5" } ); mesh3 = new THREE.Mesh( geometry3, material3 ); mesh3.position.z = -1200; mesh3.position.y = -120; // Add mesh to scene scene.add( mesh3 ); // Create a Cube Mesh with basic material --------- geometry4 = new THREE.BoxGeometry(1000, 10, 10); material4 = new THREE.MeshBasicMaterial( { color: "#F5F5F5" } ); mesh4 = new THREE.Mesh( geometry4, material4 ); mesh4.position.z = -1000; mesh4.position.y = -100; // Add mesh to scene scene.add( mesh4 ); // Create a Cube Mesh with basic material --------- geometry5 = new THREE.BoxGeometry(1000, 10,10); material5 = new THREE.MeshBasicMaterial( { color: "#F5F5F5" } ); mesh5 = new THREE.Mesh( geometry5, material5 ); mesh5.position.z = -1000; mesh5.position.y = -100; // Add mesh to scene scene.add( mesh5 ); // Create a Cube Mesh with basic material --------- geometry6 = new THREE.BoxGeometry(1000, 10,10); material6 = new THREE.MeshBasicMaterial( { color: "#F5F5F5" } ); mesh6 = new THREE.Mesh( geometry6, material6 ); mesh6.position.z = -1000; mesh6.position.y = -100; // Add mesh to scene scene.add( mesh6 ); // Create a Cube Mesh with basic material --------- geometry7 = new THREE.BoxGeometry(1000, 10,10); material7 = new THREE.MeshBasicMaterial( { color: "#F5F5F5" } ); mesh7 = new THREE.Mesh( geometry6, material6 ); mesh7.position.z = -1000; mesh7.position.y = -100; // Add mesh to scene scene.add( mesh7 ); // Create a Ball Mesh with normal material --------- geometry8 = new THREE.SphereGeometry(35,35,35); material8 = new THREE.MeshNormalMaterial( { color: "#000000" } ); mesh8 = new THREE.Mesh( geometry8, material8 ); mesh8.position.z = -1100; mesh8.position.y = -110; // Add mesh to scene //{color} scene.add( mesh8 ); // Create a Icosahedron Mesh with basic material --------- geometry9 = new THREE.IcosahedronGeometry( 200,1 ); material9 = new THREE.MeshBasicMaterial( {wireframe : true} ); mesh9 = new THREE.Mesh( geometry9, material9 ); mesh9 = new THREE.EdgesHelper( mesh9,0xFF0000 ); mesh9.position.z = -900; mesh9.position.y = -50; // Add mesh to scene scene.add( mesh9 ); } // Render Loop var render = function () { requestAnimationFrame( render ); mesh1.rotation.x += 0; //Continuously rotate the mesh mesh1.rotation.z += 0.01; mesh2.rotation.x += 0; //Continuously rotate the mesh mesh2.rotation.z += 0.02; mesh4.rotation.x += 0; //Continuously rotate the mesh mesh4.rotation.z += 0.03; mesh5.rotation.x += 0; //Continuously rotate the mesh mesh5.rotation.z += 0.04; mesh6.rotation.x += 0; //Continuously rotate the mesh mesh6.rotation.z += 0.05; mesh7.rotation.x += 0; //Continuously rotate the mesh mesh7.rotation.z += 0.06; mesh9.rotation.y += 0.01; //Continuously rotate the mesh mesh9.rotation.z += 0; renderer.setClearColor("#000000"); // Render the scene renderer.render(scene, camera); }; init(); geometry(); render();
Python
UTF-8
743
2.859375
3
[]
no_license
from .load_balancer import LoadBalancer from utils import hash_fn """ Broken Load Balancer Doesn't rebalance shards, it puts everything in the first shard and fails to rebalance on removes """ class BrokenLoadBalancer(LoadBalancer): # Initialize data structures def __init__(self): super().__init__() # Adds a shard to the system and rebalances the system def add_shard(self, shard_name): super().add_shard(shard_name) # Removes a shard from the system and rebalances the system def remove_shard(self, shard_name): kvstore = super().remove_shard(shard_name) # Store the given key in a shard def put(self, k): shard = self.shard_list[0] self.shards[shard].put(k, 1)
Python
UTF-8
1,046
4
4
[]
no_license
#Farey Sequence #Euler's Totient Function #related problems: 069, 071 def makePrimes(n): li = [True] * n primes = [] li[0] = False li[1] = False for i in range(2, n): if li[i]: primes.append(i) for j in range(i*i, n, i): li[j] = False return primes primes = makePrimes(1000000) def primeFactorsList(n): factors = [] k = n i = 0 while k!=1: if k % primes[i] == 0: factors.append(primes[i]) while k % primes[i] == 0: k = k / primes[i] else: i = i + 1 return factors def product(ls): prod = 1 for item in ls: prod *= item return prod minus1 = lambda n: n-1 phi = lambda n, f: n * product(map(minus1, f)) / product(f) def FareyLength(n): count = 1 for i in xrange(1, n + 1): if i % 100000 == 0: print i factors = primeFactorsList(i) count += phi(i, factors) return count - 2 print FareyLength(1000000)
C#
UTF-8
2,765
2.515625
3
[]
no_license
using System; using Foundation; using UIKit; using System.Collections.Generic; using Xamarin.Essentials; namespace WhereInTheFuckingWorld { public class TableSource : UITableViewSource { List<Option> options; Option selected; MapKit.MKMapView mapView; public TableSource(List<Option> items, MapKit.MKMapView map) { options = items; mapView = map; } public override nint RowsInSection(UITableView tableview, nint section) { return options.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell("TableCell"); Option item = options[indexPath.Row]; //if there are no cells to reuse, create a new one if (cell == null) { cell = new UITableViewCell(UITableViewCellStyle.Default, "TableCell"); } cell.TextLabel.Text = item.title; //cell.DetailTextLabel.Text = item.title; return cell; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { selected = options[indexPath.Row]; CoreLocation.CLLocationCoordinate2D selectedLoc = new CoreLocation.CLLocationCoordinate2D(selected.location.Latitude, selected.location.Longitude); mapView.SetRegion(new MapKit.MKCoordinateRegion(selectedLoc, new MapKit.MKCoordinateSpan(30, 30)), true); foreach (var annotation in mapView.Annotations) { if (selected.location.Latitude == annotation.Coordinate.Latitude && selected.location.Longitude == annotation.Coordinate.Longitude) { mapView.SelectAnnotation(annotation, true); } } //NSSet annotations= mapView.GetAnnotations(new MapKit.MKMapRect(new MapKit.MKMapPoint(selectedLoc.Latitude,selectedLoc.Longitude), new MapKit.MKMapSize(10,10))); } public Option GetItem() { return selected; } /* public NSIndexPath FindRow(string title) { int i; for (i = 0; i < options.Count; i++) { if (options[i].title == title) break; } return new NSIndexPath(new IntPtr(i)); } */ } //https://docs.microsoft.com/en-us/xamarin/ios/user-interface/controls/tables/populating-a-table-with-data //https://docs.microsoft.com/en-us/xamarin/ios/user-interface/controls/tables/creating-tables-in-a-storyboard }
C#
UTF-8
1,596
3.890625
4
[ "Unlicense" ]
permissive
using System; using System.Collections.Generic; using System.Linq; namespace questions { // Question URL: https://leetcode.com/problems/group-anagrams //Given an array of strings, group anagrams together. //Example: //Input: ["eat", "tea", "tan", "ate", "nat", "bat"], //Output: //[ // ["ate","eat","tea"], // ["nat","tan"], // ["bat"] //] //Note: //All inputs will be in lowercase. //The order of your output does not matter. public class GroupAnagrams { public static IList<IList<string>> groupAnagrams(string[] strs) { IList<IList<string>> output = new List<IList<string>>(); IDictionary<string, List<string>> combinations = new Dictionary<string, List<string>>(); foreach (var str in strs) { char[] strArray = str.ToCharArray(); Array.Sort(strArray); // TODO implement custom sort string buildKey = string.Empty; foreach (var item in strArray) { buildKey += item; } List<string> values = null; if (!combinations.TryGetValue(buildKey, out values)) { values = new List<string>(); combinations.Add(buildKey, values); } values.Add(str); } foreach (var combination in combinations) { output.Add(combination.Value); } return output; } } }
C++
UTF-8
2,099
2.65625
3
[]
no_license
#pragma once #include "MiniginPCH.h" #include <SDL.h> #include <SDL_ttf.h> #include <string> #include <memory> #pragma warning(push) #pragma warning (disable:4201) //#include <glm/vec3.hpp> #include <glm/glm.hpp> //#include "glm/vec2.hpp" #pragma warning(pop) #include "Renderer.h" #include "Font.h" #include "Texture2D.h" class BaseElement { public: BaseElement() = default; virtual ~BaseElement(){}; BaseElement(const BaseElement& other) = delete; BaseElement(BaseElement&& other) = delete; BaseElement& operator=(const BaseElement& other) = delete; BaseElement& operator=(BaseElement&& other) = delete; virtual void Render() = 0; private: }; class TextElement final : public BaseElement { public: TextElement(const std::string& text, const std::shared_ptr<Font>& font, const glm::vec2& position = { 0, 0 }, const glm::vec3& color = { 255, 255, 255 }) : m_Text{ text } , m_Position(position) , m_Font(font) , m_Color(color) , m_NeedsUpdate(true) , m_spTexture{ nullptr } { }; void Render() override { if (m_NeedsUpdate) { const SDL_Color color = { m_Color.x, m_Color.y, m_Color.z }; const auto surf = TTF_RenderText_Blended(m_Font->GetFont(), m_Text.c_str(), color); if (surf == nullptr) { throw std::runtime_error(std::string("Render text failed: ") + SDL_GetError()); } auto texture = SDL_CreateTextureFromSurface(Renderer::GetInstance().GetSDLRenderer(), surf); if (texture == nullptr) { throw std::runtime_error(std::string("Create text texture from surface failed: ") + SDL_GetError()); } SDL_FreeSurface(surf); m_spTexture = std::make_shared<Texture2D>(texture); m_NeedsUpdate = false; } Renderer::GetInstance().RenderTexture(*m_spTexture, m_Position.x, m_Position.y); }; void SetText(const std::string& text) { m_NeedsUpdate = true; m_Text = text; } void SetColor(const glm::vec3& color) { m_Color = color; } private: std::shared_ptr<Font> m_Font; std::string m_Text; glm::vec2 m_Position; glm::tvec3<uint8_t> m_Color; std::shared_ptr<Texture2D> m_spTexture; bool m_NeedsUpdate; };
Markdown
UTF-8
488
2.765625
3
[ "MIT" ]
permissive
### Basic The simplest usage of Steps. ```javascript class Demo extends React.Component{ render(){ return ( <Steps currentIndex={1}> <Steps.Step title="Step1" description="Step1 Description" /> <Steps.Step title="Step2" description="Step2 Description" /> <Steps.Step title="Step3" description="Step3 Description" /> </Steps> ) } } ```
JavaScript
UTF-8
11,103
2.890625
3
[]
no_license
// NOTE: HERE I AM CONSIDERING MAIN USER USER_ID 1 , but in other cases consider login user as a MAIN USER. // IN MY CASE I HAVE THREE TYPE OF USER , 1) EXECUTIVE , 2) MANAGER , 3) BASIC USER. /* THIS IS A TEMPLATE FOR MAIN USER */ var main_user = '<div class="form-group"><label class="col-sm-5">My Events</label><div class="col-sm-1"><input type="checkbox" class="user_data" id="1" value="1" checked="checked"/>' + '</div><div class="demo2 col-sm-1" data-color="${own_event}"><input type="text" name="color[own][event]" id="color1" class="color1" value="${own_event}" /></div></div>' + '<div class="form-group"><label class="col-sm-5">My Tasks</label><div class="col-sm-1"><input type="checkbox" class="user_data" id="2" value="1" checked="checked"/>' + '</div><div class="demo2 col-sm-1" data-color="${own_task}"><input type="text" name="color[own][task]" id="color1" class="color1" value="${own_task}" /></div></div>'; $.template("master_user_display", main_user); /* THIS IS A TEMPLATE FOR DISPLAY OTHER USERS */ var markup = '<div class="form-group"><label class="col-sm-5">${name + " " + last_name} </label><div class="col-sm-1"><input type="checkbox" class="user_data" id="1" value="${user_id}"/></div><div class="demo2 col-sm-1" data-color="${color_event}">' + '<input type="text" name="color[users][${user_id}][event]" id="color1" class="color1" value="${color_event}" /></div><div class="col-sm-1">' + '<input type="checkbox" class="user_data" id="2" value="${user_id}"/></div>' + '<div class="demo2 col-sm-1" data-color="${color_task}"><input type="text" name="color[users][${user_id}][task]" id="color1" class="color1" value="${color_task}" /></div></div>'; $.template("user_display", markup); /* GET ALL USER LIST. */ jQuery.ajax({ type: 'GET', url: "api/v1/calendar_user/1", data: "", beforeSend: function() { }, complete: function() { }, success: function(data) { if(!data.error){ /* Executive Information */ var executive = data.data[1]; /* Manager Information */ var manager = data.data[2]; /* Basic User Information */ var basic_user = data.data[3]; /* Bind Login User Information */ $.tmpl("master_user_display", data.data).appendTo(".main_user"); /* Bind Executive Information */ $.tmpl("user_display", executive).appendTo(".executive_list"); /* Bind Manager Information */ $.tmpl("user_display", manager).appendTo(".manager_list"); /* Bind Basic User Information */ $.tmpl("user_display", basic_user).appendTo(".basic_user_list"); /* Bind color picker for all users */ $('.color1').colorPicker({showHexField: false}); } /* BIND CALANDER BASED ON SELECTED CHECKBOX IN USER LIST */ bind_calendar(); } }); function getEventsTask() { var user_id = []; if ($('.user_data:checked').length) { var chkId = ''; var id = ''; $('.user_data:checked').each(function() { id = $(this).attr('id'); chkId = $(this).val(); var temp = chkId + '-' + id; user_id.push(temp); }); } return user_id; } function bind_calendar(){ /* GET LAST CALANDER VIEW(MONTH,WEEK,DAY) OF USER SCREEN WHICH IS SAVED IN LOCALHOST */ var lastView = localStorage.getItem('lastView'); if (lastView == null) { // IF NOT FIND LOCALHOST THEN SET A MONTH VIEW. lastView = 'month'; } var calendar = $('#calendar-external').fullCalendar({ header: { left: '', center: 'prev title next', right: 'today month,agendaWeek,agendaDay' }, nextDayThreshold: '00:00:00', buttonIcons: { prev: 'left-single-arrow', next: 'right-single-arrow' }, handleWindowResize: true, aspectRatio: 2, events: function(start, end, timezone,callback) { /* DATA IS FETCHED BASED ON START DATE AND END DATE */ $.ajax({ url: 'api/v1/calendar', type: 'GET', data: { start: moment(start).unix(), //start date end: moment(end).unix(), // end date. dataType: 'json', user_id: getEventsTask().toString(), // GET CHECKED USER LIST. created_by: 1 }, success: function(events) { // CALLBACK EVENTS SO IT WILL DISPLAY INTO THE CALENDER callback(events); } }); }, defaultView: lastView, eventLimit: true, editable: true, slotEventOverlap: false, droppable: true, selectable: false, selectHelper: true, timezone: 'local', height: $(window).height()*0.83, eventMouseover: function(calEvent, event, view) { // THIS IS FOR DISPLAY TOOLTIP WHEN MOUSE OVER ON EVENTS AND TASKS. if (calEvent.start_date != undefined && calEvent.end_date != undefined) { var event_background = $(event.currentTarget).css("backgroundColor"); var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var start_date = moment(calEvent.start_date).format('ll'); var end_date = moment(calEvent.end_date).format('ll'); // CHECK THAT EVENT IS CURRENT TIME LINE OR NOT. IN WEEK AND DAY VIEW THERE IS A RED LINE WHICH IS DISPLYING THE CURRENT TIME. if ($(this).hasClass('current-time-event') == false) { if (calEvent.calendar_type == 2) // CALANDER_TYPE = 2 is for the TASK. tooltip = '<div class="tooltiptopicevent" style="width:auto;height:auto;background:#F2F9FF;position:absolute;z-index:10001;padding:10px 10px 10px 10px ;border:3px solid ' + event_background + '; line-height: 200%;"><span style=float:right;>' + start_date + '</span><br />' + calEvent.title + '</br>' + 'Assigned to: ' + calEvent.assignedname + '</div>'; else tooltip = '<div class="tooltiptopicevent" style="width:auto;height:auto;background:#F2F9FF;position:absolute;z-index:10001;padding:10px 10px 10px 10px ;border:3px solid ' + event_background + '; line-height: 200%;"><span style=float:right;>' + start_date + ' - ' + end_date + '</span><br />' + calEvent.title + '</div>'; // Append tooltip to body. $("body").append(tooltip); // Move tooltip on mouse move. $(this).mouseover(function(e) { $(this).css('z-index', 10000); $('.tooltiptopicevent').fadeIn('500'); $('.tooltiptopicevent').fadeTo('10', 1.9); }).mousemove(function(e) { if (e.pageY + 170 > $(window).height()) { $('.tooltiptopicevent').css('top', e.pageY - 100); $('.tooltiptopicevent').css('left', e.pageX + 20); } else { $('.tooltiptopicevent').css('top', e.pageY + 10); $('.tooltiptopicevent').css('left', e.pageX + 20); } }); } } }, eventMouseout: function(data, event, view) { // REMOVE TOOLTIP WHEN MOUSE OUT OF THE EVENT/TASK DISPLAY $(this).css('z-index', 8); $('.tooltiptopicevent').remove(); }, viewRender: function(view, element) { // ADD ONE BLANK HEADER FOR DISPLAY DATE PROPER IN WEEK VIEW. if (view.name == 'agendaWeek') $('th.fc-widget-header:first').before("<th class='fc-day-header fc-widget-header' style='width:51px;'>&nbsp;</th>"); // SET CURRENT VIEW IN LOCALSTORAGE. localStorage.setItem('lastView', view.name); /* THIS FUNCTION IS FOR DISPLAY RED LINE AT CURRENT TIME IN WEEK AND DAY VIEW. */ if (view.name == "agendaWeek" || view.name == "agendaDay") { view.calendar.removeEvents("currenttime"); var f = view.calendar.renderEvent({id: "currenttime", title: "Current Time", start: moment(), end: moment().add('minutes', 1), className: "current-time-event", editable: false}, true); setTimeout(function() { /* This is for remove one length from the event/task count in day view.It is considering current time as a one event. */ if ($('.fc-time-grid-event').hasClass('current-time-event')) { $('.todaysevent').html($('.fc-event-container a.fc-time-grid-event').length - 1); } else { $('.todaysevent').html($('.fc-event-container a.fc-time-grid-event').length); } }, 1500); } else { /* IF USER CHECKING OTHER VIEW THEN REMOE CURREENT TIME. */ view.calendar.removeEvents("currenttime"); } } }); $('.user_data').click(function() { //CHECKBOX CLICK EVENT FOR REFETCH DATA. $('#calendar-external').fullCalendar('refetchEvents'); $('#calendar-external').fullCalendar('refresh'); }); /* ON EVENT AND TASK COLOR CHANGE SAVE NEW SETTING INTO THE DATABASE USING THIS. */ $('.color1').change(function() { jQuery.ajax({ type: 'POST', url: "api/v1/calendarSettings", data: jQuery("#form_settings").serialize(), success: function(data) { if (typeof data != 'object') var result = JSON.parse(jQuery.trim(data)); else var result = jQuery.trim(data); /*Refetch event/task after set new color.*/ setTimeout(function() { calendar.fullCalendar('refetchEvents'); }, 2000); } }); }); // PREPEND CALENDER BEFORE TODAY IN RIGHT LIST , USING THIS CALENDER USER CAN EASILY MOVE TO ANOTHER MONTH , ANOTHER YEAR. $('.fc-right').prepend('<span class="form-group" id="caldatepicker"><i class="fa fa-calendar"></i></span>'); /* BIND CALENDER TO ABOVE DEFIND ICON. */ $('#caldatepicker').datepicker({ closeOnDateSelect: true }).on('changeDate', function (ev) { // CHANGE FULL CALENDER MONTH AND YEAR WHEN THIS CALENDER DATE SELECT. calendar.fullCalendar('gotoDate', ev.date); }); }
TypeScript
UTF-8
2,729
2.6875
3
[]
no_license
import { useState } from 'react'; import { FormChangeEvent, FormSubmitEvent, FieldState, FormState, FormConfig, FormManagerBase, FormManager, runValidators } from '.'; const getInitialState = (config: FormConfig): FormState => { return { isInvalid: false, isDirty: false, fields: config.map( ({ value }) => ({ value: value !== undefined ? value : '', error: '', validation: [] } as FieldState) ) }; }; export const useFormBase = (config: FormConfig): FormManagerBase => { const [state, setState] = useState(getInitialState(config)); const getChangedField = (value: any, idx: number): FieldState => { const { label, validators = [] } = config[idx]; const validation = runValidators(value, label)(...validators); const result = validation.find((result) => result.isInvalid); const error = result ? result.text : ''; return { value, error, validation }; }; return [state, setState, getChangedField]; }; export const useForm = (config: FormConfig): FormManager => { const [state, setState, getChangedField] = useFormBase(config); const change = (e: FormChangeEvent) => { const { value, dataset } = e.target; if (dataset.idx === undefined) { throw new Error('Attribute data-idx is missing'); } const datasetIdx = +dataset.idx; if (isNaN(datasetIdx)) { throw new Error('Attribute data-idx must be number'); } if (datasetIdx >= config.length) { throw new Error('Invalid data-idx attribute'); } const newState: FormState = { ...state, fields: [...state.fields] }; newState.fields[datasetIdx] = getChangedField(value, datasetIdx); newState.isInvalid = newState.fields.some((f) => f.error); setState(newState); }; const directChange = (positions: number[], values: any[]) => { const newState: FormState = { ...state, fields: [...state.fields] }; positions.forEach((position, idx) => { newState.fields[position] = getChangedField(values[idx], position); }); newState.isInvalid = newState.fields.some((f) => f.error); setState(newState); }; const submit = (e?: FormSubmitEvent): boolean => { e && e.preventDefault(); const newState: FormState = { ...state, isDirty: true, isInvalid: false }; newState.fields = newState.fields.map((field, idx) => { const { value, validation, error } = getChangedField(field.value, idx); if (error) { newState.isInvalid = true; } return { value, validation, error }; }); setState(newState); return newState.isInvalid; }; return [state, change, directChange, submit]; };
SQL
UTF-8
63,347
3.09375
3
[]
no_license
CREATE SCHEMA IF NOT EXISTS `dcps`; USE `dcps`; -- -- Table structure for table `apis` -- /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE IF NOT EXISTS `apis` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `company_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `user_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `url` VARCHAR(255) NOT NULL DEFAULT '', `token` VARCHAR(40) NOT NULL DEFAULT '', `request_token` VARCHAR(40) NOT NULL DEFAULT '', `request_token_expire` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', `created_by` INT(10) UNSIGNED NOT NULL DEFAULT '0', `created` BIGINT(20) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `clusters` -- /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE IF NOT EXISTS `clusters` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `company_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `cluster_id` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'This is the cluster_id on the cmon''s cluster, not used in ccui', `api_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `name` VARCHAR(125) NOT NULL DEFAULT '', `ip` VARCHAR(20) NOT NULL DEFAULT '', `token` VARCHAR(255) DEFAULT NULL, `cmon_host` VARCHAR(50) NOT NULL DEFAULT '', `cmon_port` VARCHAR(10) NOT NULL DEFAULT '', `cmon_user` VARCHAR(50) NOT NULL DEFAULT '', `cmon_pass` VARCHAR(50) NOT NULL DEFAULT '', `cmon_db` VARCHAR(10) NOT NULL DEFAULT 'cmon', `cmon_type` TINYINT(4) DEFAULT NULL COMMENT 'Either 0 (on premises), or 1 (cloud based)', `mysql_root_password` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'The mysql root password, used when initializing the Master', `type` ENUM ('mysqlcluster', 'replication', 'galera', 'mongodb', 'mysql_single', 'postgresql_single', 'group_replication') NOT NULL, `status` SMALLINT(6) NOT NULL DEFAULT '204', `created` BIGINT(20) NOT NULL DEFAULT '0', `ssh_key` VARBINARY(1024) DEFAULT NULL DEFAULT '', `cluster_status` TINYINT(3) UNSIGNED DEFAULT NULL, `error_msg` VARCHAR(255) DEFAULT NULL, `error_code` INT(10) UNSIGNED DEFAULT NULL, `updated` TIMESTAMP NOT NULL DEFAULT '2013-01-01 00:00:00', `created_by` INT(10) UNSIGNED NOT NULL DEFAULT '0', `cluster_status_txt` VARCHAR(64) DEFAULT NULL DEFAULT '', `def_server_template_id` INT(10) UNSIGNED DEFAULT NULL, `def_db_template_id` INT(10) UNSIGNED DEFAULT NULL, `def_additional_disk_space_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `companies` -- /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE IF NOT EXISTS `companies` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(125) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `jobs` -- /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE IF NOT EXISTS `jobs` ( `jobid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `cc_vm_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `cluster_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `command` VARCHAR(255) NOT NULL DEFAULT '', `vm_ip` VARCHAR(15) NOT NULL DEFAULT '', `master_vm_ip` VARCHAR(15) DEFAULT NULL, `role` TINYINT(4) NOT NULL DEFAULT '0', `cluster_type` TINYINT(4) NOT NULL DEFAULT '0', `server_template_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `db_template_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `additional_disk_space_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `package_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `size` TINYINT(4) NOT NULL DEFAULT '0', `jobstatus` TINYINT(4) NOT NULL DEFAULT '2', `errmsg` VARCHAR(512) NOT NULL DEFAULT '', `errno` INT(11) NOT NULL DEFAULT '0', `cluster_name` VARCHAR(255) DEFAULT 'default_name', `root_password` VARCHAR(255) DEFAULT 'password', `created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `last_updated` TIMESTAMP NOT NULL DEFAULT '2013-01-01 00:00:00', PRIMARY KEY (`jobid`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `users` -- /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE IF NOT EXISTS `users` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `company_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `email` VARCHAR(125) NOT NULL DEFAULT '', `password` VARCHAR(64) NOT NULL DEFAULT '', `name` VARCHAR(125) NOT NULL DEFAULT '', `timezone` VARCHAR(100) DEFAULT '', `sa` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0', `session_id` VARCHAR(60) NOT NULL DEFAULT '', `created` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', `last_login` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0, `facebook_id` VARCHAR(250) NULL DEFAULT '', `fbaccess_token` VARCHAR(250) NULL DEFAULT '', `logins` INT UNSIGNED NULL DEFAULT 0, `salt` VARCHAR(64) NOT NULL DEFAULT 'fIouG9Fzgzp34563b02GyxfUuDm4aJFgaC9mi', `uuid` VARCHAR(64) NOT NULL DEFAULT '', `verification_code` VARCHAR(32) NULL DEFAULT '', `email_verified` INT NOT NULL DEFAULT 0, `reset_password_code` VARCHAR(32) NULL DEFAULT '', `reset_password_date` BIGINT(20) NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `roles` -- CREATE TABLE IF NOT EXISTS `roles` ( `id` SMALLINT(3) NOT NULL DEFAULT '1', `role_name` VARCHAR(100) NOT NULL DEFAULT '', `role_type` CHAR(1) DEFAULT 'u', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; -- -- Table structure for table `user_roles` -- CREATE TABLE IF NOT EXISTS `user_roles` ( `id` INT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` INT(11) NOT NULL DEFAULT '0', `role_id` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 1; -- AWS credentials CREATE TABLE IF NOT EXISTS `aws_credentials` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` INT(11) NOT NULL DEFAULT '0', `keypair_name` VARCHAR(64) NOT NULL DEFAULT '', `private_key` VARCHAR(4096) NOT NULL DEFAULT '', `access_key` VARCHAR(256) NOT NULL DEFAULT '', `secret_access_key` VARCHAR(256) NOT NULL DEFAULT '', `comment` VARCHAR(256) NULL DEFAULT '', `in_use` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; CREATE TABLE IF NOT EXISTS `deployments` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `url` VARCHAR(250) NOT NULL DEFAULT '', `cluster_type` VARCHAR(50) NOT NULL DEFAULT '', `user_id` INT(11) NOT NULL DEFAULT '0', `key_id` INT(11) NOT NULL DEFAULT '0', `created` DATETIME NOT NULL DEFAULT '2013-01-01 00:00:00', `last_updated` DATETIME NOT NULL DEFAULT '2013-01-01 00:00:00', `os_user` VARCHAR(20) NOT NULL DEFAULT '', `session_dir` VARCHAR(256) NOT NULL DEFAULT '', `status` TINYINT(4) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; CREATE TABLE IF NOT EXISTS `settings` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(100) NOT NULL DEFAULT '', `user_id` INT(11) NOT NULL DEFAULT '0', `location_id` INT(11) DEFAULT NULL COMMENT '1-overview,', `cluster_id` INT(11) NOT NULL DEFAULT '0', `selected` TINYINT(4) NOT NULL DEFAULT '0', `dash_order` TINYINT(4) NOT NULL DEFAULT '0', `rs_name` VARCHAR(255) NOT NULL DEFAULT 'none', `type` ENUM ('dashboard', 'refresh_rate') DEFAULT 'dashboard' NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; CREATE TABLE IF NOT EXISTS `settings_items` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `setting_id` INT(11) NOT NULL DEFAULT '0', `item` VARCHAR(2048) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; -- Update clusters table CREATE TABLE IF NOT EXISTS `clusters_new` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `company_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `cluster_id` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'This is the cluster_id on the cmon''s cluster, not used in ccui', `api_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `name` VARCHAR(125) NOT NULL DEFAULT '', `ip` VARCHAR(20) NOT NULL DEFAULT '', `cmon_host` VARCHAR(50) NOT NULL DEFAULT '', `cmon_port` VARCHAR(10) NOT NULL DEFAULT '', `cmon_user` VARCHAR(50) NOT NULL DEFAULT '', `cmon_pass` VARCHAR(50) NOT NULL DEFAULT '', `cmon_db` VARCHAR(10) NOT NULL DEFAULT 'cmon', `cmon_type` TINYINT(4) DEFAULT NULL COMMENT 'Either 0 (on premises), or 1 (cloud based)', `mysql_root_password` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'The mysql root password, used when initializing the Master', `type` ENUM ('mysqlcluster', 'replication', 'galera', 'mongodb', 'mysql_single') NOT NULL, `status` SMALLINT(6) NOT NULL DEFAULT '204', `created` BIGINT(20) NOT NULL DEFAULT '0', `ssh_key` VARBINARY(1024) DEFAULT NULL DEFAULT '', `cluster_status` TINYINT(3) UNSIGNED DEFAULT NULL, `error_msg` VARCHAR(255) DEFAULT NULL, `error_code` INT(10) UNSIGNED DEFAULT NULL, `updated` TIMESTAMP NOT NULL DEFAULT '2013-01-01 00:00:00', `created_by` INT(10) UNSIGNED NOT NULL DEFAULT '0', `cluster_status_txt` VARCHAR(64) DEFAULT NULL DEFAULT '', `def_server_template_id` INT(10) UNSIGNED DEFAULT NULL, `def_db_template_id` INT(10) UNSIGNED DEFAULT NULL, `def_additional_disk_space_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', `is_clone` TINYINT(4) NOT NULL DEFAULT 0, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; DROP PROCEDURE IF EXISTS upgrade_clusters; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE upgrade_clusters() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'clusters' AND column_name = 'is_clone'; IF colName IS NULL THEN DROP TABLE IF EXISTS clusters_old; INSERT INTO clusters_new (id, company_id, cluster_id, api_id, name, ip, cmon_host, cmon_port, cmon_user, cmon_pass, cmon_db, cmon_type, mysql_root_password, type, status, created, ssh_key, cluster_status, error_msg, error_code, updated, created_by, cluster_status_txt, def_server_template_id, def_db_template_id, def_additional_disk_space_id) SELECT id, company_id, cluster_id, api_id, name, ip, cmon_host, cmon_port, cmon_user, cmon_pass, cmon_db, cmon_type, mysql_root_password, type, status, created, ssh_key, cluster_status, error_msg, error_code, updated, created_by, cluster_status_txt, def_server_template_id, def_db_template_id, def_additional_disk_space_id FROM clusters; RENAME TABLE clusters TO clusters_old, clusters_new TO clusters; END IF; END$$ DELIMITER ; CALL upgrade_clusters; DROP PROCEDURE upgrade_clusters; DROP TABLE IF EXISTS clusters_old; DROP TABLE IF EXISTS clusters_new; -- Need to make sure mysql_single, posgresql_single are there for prev versions ALTER TABLE `clusters` CHANGE COLUMN `type` `type` ENUM('mysqlcluster','replication','galera','mongodb','mysql_single','postgresql_single','group_replication') NOT NULL; -- upgrade 1.2.0/1.2.1/1.2.2 -> v1.2.3 settings should have rs_name and type already but in case it's not there DROP PROCEDURE IF EXISTS upgrade_settings; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE upgrade_settings() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'settings' AND column_name = 'rs_name'; IF colName IS NULL THEN ALTER TABLE `settings` ADD COLUMN `rs_name` VARCHAR(255) NOT NULL DEFAULT 'none'; ALTER TABLE `settings` ADD COLUMN `type` ENUM ('dashboard', 'refresh_rate') DEFAULT 'dashboard' NOT NULL; END IF; END$$ DELIMITER ; CALL upgrade_settings; DROP PROCEDURE upgrade_settings; -- v.1.2.4 ALTER TABLE `settings` MODIFY COLUMN `type` ENUM ('dashboard', 'refresh_rate', 'settings') DEFAULT 'dashboard' NOT NULL; CREATE TABLE IF NOT EXISTS `onpremise_credentials` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` INT(11) NOT NULL DEFAULT '0', `keypair_name` VARCHAR(64) NOT NULL DEFAULT '', `comment` VARCHAR(256) DEFAULT '', `in_use` TINYINT(1) NOT NULL DEFAULT '0', `private_key` VARCHAR(4096) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB AUTO_INCREMENT = 19 DEFAULT CHARSET = latin1; CREATE TABLE IF NOT EXISTS `onpremise_deployments` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `user_id` INT(11) NOT NULL DEFAULT '0', `key_id` INT(11) NOT NULL DEFAULT '0', `created` DATETIME NOT NULL DEFAULT '2013-01-01 00:00:00', `last_updated` DATETIME NOT NULL DEFAULT '2013-01-01 00:00:00', `os_user` VARCHAR(20) NOT NULL DEFAULT '', `package_name` VARCHAR(256) NOT NULL DEFAULT '', `cc_ip_address` VARCHAR(100) NOT NULL, `key_from_aws` INT NOT NULL DEFAULT 0, PRIMARY KEY (`id`) ) ENGINE = InnoDB AUTO_INCREMENT = 11 DEFAULT CHARSET = latin1; CREATE TABLE IF NOT EXISTS `backups` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `container_id` INT(11) NOT NULL, `backup_id` INT(11) NOT NULL, `storage` ENUM ('S3', 'Glacier', 'Other') NOT NULL DEFAULT 'Other', `archive_name` VARCHAR(512) DEFAULT NULL, `archive_id` VARCHAR(256) DEFAULT NULL COMMENT 'for glacier backup', `file_size` INT(20) DEFAULT NULL, `creation_date` DATETIME NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 1; CREATE TABLE IF NOT EXISTS `containers` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(512) NOT NULL DEFAULT '', `cluster_id` INT(11) NOT NULL, `key_id` INT(11) NOT NULL, `region` VARCHAR(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 1; CREATE TABLE IF NOT EXISTS `glacier_jobs` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `job_id` VARCHAR(512) NOT NULL DEFAULT '', `uri` VARCHAR(1024) NOT NULL DEFAULT '', `status` VARCHAR(100) DEFAULT NULL, `cloud_backup_id` INT(11) DEFAULT NULL, `creation_date` DATETIME DEFAULT NULL, `last_update` DATETIME DEFAULT NULL, `completion_time` INT(11) UNSIGNED DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 1; CREATE TABLE IF NOT EXISTS `cluster_keys` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `cluster_id` INT(11) NOT NULL, `key_id` INT(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 1; CREATE TABLE IF NOT EXISTS `cluster_aws_keys` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `cluster_id` INT(11) NOT NULL, `key_id` INT(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 1; -- not used atm DROP TABLE IF EXISTS reports_emails; DROP TABLE IF EXISTS smtp_server; -- post v1.2.5 CREATE TABLE IF NOT EXISTS `openstack_credentials` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` INT(11) NOT NULL, `keypair_name` VARCHAR(64) NOT NULL, `username` VARCHAR(255) NOT NULL DEFAULT '', `password` VARCHAR(2048) NOT NULL DEFAULT '', `tenant_name` VARCHAR(255) NOT NULL DEFAULT '', `identity_url` VARCHAR(512) NOT NULL DEFAULT '', `private_key` VARCHAR(4096) NOT NULL DEFAULT '', `comment` VARCHAR(256) NOT NULL DEFAULT '', `in_use` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 1; CREATE TABLE IF NOT EXISTS `ldap_settings` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `enable_ldap_auth` INT(11) NOT NULL DEFAULT '0', `host` VARCHAR(50) NOT NULL, `port` VARCHAR(10) NOT NULL DEFAULT '389', `login` VARCHAR(100) NOT NULL, `password` VARCHAR(60) NOT NULL, `base_dsn` VARCHAR(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; CREATE TABLE IF NOT EXISTS `ldap_group_roles` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `ldap_group_name` VARCHAR(100) NOT NULL, `role_id` INT(11) NOT NULL, `company_id` INT(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; DROP PROCEDURE IF EXISTS upgrade_onpremise_deployments; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE upgrade_onpremise_deployments() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'onpremise_deployments' AND column_name = 'ssh_port'; IF colName IS NULL THEN ALTER TABLE `onpremise_deployments` ADD COLUMN ssh_port INT NOT NULL DEFAULT 22; END IF; END$$ DELIMITER ; CALL upgrade_onpremise_deployments; DROP PROCEDURE upgrade_onpremise_deployments; DROP PROCEDURE IF EXISTS upgrade_ldap; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE upgrade_ldap() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'apis' AND column_name = 'from_ldap_user'; IF colName IS NULL THEN ALTER TABLE apis ADD COLUMN `from_ldap_user` INT(11) NOT NULL DEFAULT 0; ALTER TABLE settings ADD COLUMN `from_ldap_user` INT(11) NOT NULL DEFAULT 0; ALTER TABLE onpremise_deployments ADD COLUMN `from_ldap_user` INT(11) NOT NULL DEFAULT 0; ALTER TABLE aws_credentials ADD COLUMN `from_ldap_user` INT(11) NOT NULL DEFAULT 0; ALTER TABLE onpremise_credentials ADD COLUMN `from_ldap_user` INT(11) NOT NULL DEFAULT 0; ALTER TABLE deployments ADD COLUMN `from_ldap_user` INT(11) NOT NULL DEFAULT 0; ALTER TABLE openstack_credentials ADD COLUMN `from_ldap_user` INT(11) NOT NULL DEFAULT 0; END IF; END$$ DELIMITER ; CALL upgrade_ldap; DROP PROCEDURE upgrade_ldap; CREATE TABLE IF NOT EXISTS `acls` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `feature_name` VARCHAR(30) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB AUTO_INCREMENT = 15 DEFAULT CHARSET = latin1; REPLACE INTO `acls` (`id`, `feature_name`) VALUES (1, 'Overview'), (2, 'Nodes'), (3, 'Configuration Management'), (4, 'Query Monitor'), (5, 'Performance'), (6, 'Backup'), (7, 'Manage'), (8, 'Alarms'), (9, 'Jobs'), (10, 'Settings'), (11, 'Add Existing Cluster'), (12, 'Create Cluster'), (13, 'Add Load Balancer'), (14, 'Clone'), (15, 'Access All Clusters'), (16, 'Cluster Registrations'), (17, 'Manage AWS'), (18, 'Search'), (19, 'Create Database Node'), (20, 'Developer studio'), (21, 'Custom Advisor'), (22, 'SSL Key Management'), (23, 'MySQL User Management'), (24, 'Operational Reports'), (25, 'Integrations'), (26, 'Web SSH'); CREATE TABLE IF NOT EXISTS `role_acls` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `role_id` INT(11) NOT NULL, `acl_id` INT(11) NOT NULL, `permission` INT(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1; DROP PROCEDURE IF EXISTS update_role_acls; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE update_role_acls() BEGIN DECLARE cnt INT; SELECT count(*) INTO cnt FROM `role_acls`; IF cnt = 0 THEN INSERT INTO `role_acls` (`role_id`, `acl_id`, `permission`) VALUES (2, 1, 17), (2, 2, 17), (2, 3, 17), (2, 4, 17), (2, 5, 1), (2, 6, 17), (2, 7, 17), (2, 8, 33), (2, 9, 33), (2, 10, 33), (2, 11, 16), (2, 12, 16), (2, 13, 16), (2, 14, 16), (2, 15, 1), (2, 16, 17), (2, 17, 17), (2, 18, 1), (2, 19, 16), (2, 20, 1), (3, 1, 17), (3, 2, 17), (3, 3, 17), (3, 4, 17), (3, 5, 1), (3, 6, 17), (3, 7, 17), (3, 8, 33), (3, 9, 33), (3, 10, 33), (3, 11, 16), (3, 12, 16), (3, 13, 16), (3, 14, 16), (3, 15, 2), (3, 16, 17), (3, 17, 17), (3, 18, 1), (2, 23, 1), (3, 23, 1), (2, 24, 1), (3, 24, 1), (2, 25, 1), (3, 25, 2), (2, 26, 1), (3, 26, 2); END IF; END$$ DELIMITER ; CALL update_role_acls; DROP PROCEDURE update_role_acls; DROP PROCEDURE IF EXISTS upgrade_jobs; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE upgrade_jobs() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'jobs' AND column_name = 'from_ldap_user'; IF colName IS NULL THEN DROP TABLE IF EXISTS `jobs`; CREATE TABLE `jobs` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `cluster_id` INT(11) UNSIGNED NOT NULL DEFAULT '0', `cmon_jobid` INT(11) NOT NULL, `job_command` VARCHAR(2000) NOT NULL DEFAULT '0', `cluster_type` VARCHAR(100) NOT NULL DEFAULT '0', `created` DATETIME NOT NULL DEFAULT '2014-01-01 00:00:00', `last_updated` DATETIME NOT NULL DEFAULT '2014-01-01 00:00:00', `status` ENUM ('DEFINED', 'DEQUEUED', 'RUNNING', 'RUNNING_EXT', 'ABORTED', 'FINISHED', 'FAILED', 'DELETED') NOT NULL DEFAULT 'DEFINED', `user_id` INT(11) NOT NULL, `from_ldap_user` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 1; END IF; END$$ DELIMITER ; CALL upgrade_jobs; DROP PROCEDURE upgrade_jobs; -- upgrade settings table 1.2.8 DROP PROCEDURE IF EXISTS upgrade_settings; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE upgrade_settings() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'settings' AND column_name = 'cluster_type'; IF colName IS NULL THEN ALTER TABLE `settings` ADD COLUMN `cluster_type` ENUM ('mysqlcluster', 'replication', 'galera', 'mongodb', 'mysql_single', 'postgresql_single', 'unknown') NOT NULL DEFAULT 'unknown'; INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('InnoDB - Disk I/O', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'galera'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'INNODB_LOG_WRITES,INNODB_DATA_WRITES,INNODB_DATA_READS,INNODB_BACKGROUND_LOG_SYNC,INNODB_DATA_FSYNCS,INNODB_OS_LOG_FSYNCS:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('InnoDB - Disk I/O', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'replication'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'INNODB_LOG_WRITES,INNODB_DATA_WRITES,INNODB_DATA_READS,INNODB_BACKGROUND_LOG_SYNC,INNODB_DATA_FSYNCS,INNODB_OS_LOG_FSYNCS:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('InnoDB - Disk I/O', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mysql_single'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'INNODB_LOG_WRITES,INNODB_DATA_WRITES,INNODB_DATA_READS,INNODB_BACKGROUND_LOG_SYNC,INNODB_DATA_FSYNCS,INNODB_OS_LOG_FSYNCS:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Query Performance', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'galera'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'SLOW_QUERIES,SELECT_FULL_JOIN,SELECT_FULL_RANGE_JOIN,SELECT_RANGE_CHECK,SELECT_SCAN,CREATED_TMP_DISK_TABLES:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Query Performance', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'replication'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'SLOW_QUERIES,SELECT_FULL_JOIN,SELECT_FULL_RANGE_JOIN,SELECT_RANGE_CHECK,SELECT_SCAN,CREATED_TMP_DISK_TABLES:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Query Performance', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mysql_single'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'SLOW_QUERIES,SELECT_FULL_JOIN,SELECT_FULL_RANGE_JOIN,SELECT_RANGE_CHECK,SELECT_SCAN,CREATED_TMP_DISK_TABLES:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Query Performance', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mysqlcluster'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'SLOW_QUERIES,SELECT_FULL_JOIN,SELECT_FULL_RANGE_JOIN,SELECT_RANGE_CHECK,SELECT_SCAN,CREATED_TMP_DISK_TABLES:linear'); /* bytes sent /recv all mysql based clusters */ INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Bytes Sent/Recv', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'galera'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'BYTES_SENT,BYTES_RECEIVED:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Bytes Sent/Recv', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'replication'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'BYTES_SENT,BYTES_RECEIVED:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Bytes Sent/Recv', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mysqlcluster'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'BYTES_SENT,BYTES_RECEIVED:linear'); /* replication specific */ INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Replication Lag', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'replication'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'REPLICATION_LAG:linear'); /*Galera specific*/ INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Galera - Queues', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'galera'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'WSREP_LOCAL_SEND_QUEUE, WSREP_LOCAL_SEND_QUEUE_AVG,WSREP_LOCAL_RECV_QUEUE,WSREP_LOCAL_RECV_QUEUE_AVG:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Galera - Flow Ctrl', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'galera'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'WSREP_LOCAL_CERT_FAILURES, WSREP_LOCAL_BF_ABORTS,WSREP_FLOW_CONTROL_SENT,WSREP_FLOW_CONTROL_RECV:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Galera - Innodb/Flow', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'galera'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'INNODB_BUFFER_POOL_PAGES_DIRTY, INNODB_BUFFER_POOL_PAGES_DATA, INNODB_OS_LOG_FSYNCS, INNODB_DATA_FSYNCS, WSREP_FLOW_CONTROL_SENT,WSREP_FLOW_CONTROL_RECV:logarithmic'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Galera - Replication', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'galera'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'WSREP_REPLICATED_BYTES,WSREP_RECEIVED_BYTES:linear'); /* Mongodb */ INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('WT - Cache', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mongodb'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'wiredTiger.cache.bytes currently in the cache,wiredTiger.cache.tracked dirty bytes in the cache,wiredTiger.cache.maximum bytes configured:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Cursors', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mongodb'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'metrics.cursor.timedOut,metrics.cursor.open.noTimeout,metrics.cursor.open.total:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Asserts', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mongodb'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'asserts.msg,asserts.warning,asserts.regular,asserts.user:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('GlobalLock', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mongodb'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'globalLock.currentQueue.readers,globalLock.currentQueue.writers,globalLock.activeClients.readers,globalLock.activeClients.writers:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Network', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mongodb'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'network.bytesIn,network.bytesOut:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('WT - ConcurrentTransactions', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mongodb'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'wiredTiger.concurrentTransactions.read.available,wiredTiger.concurrentTransactions.write.available,wiredTiger.concurrentTransactions.read.out,wiredTiger.concurrentTransactions.write.out:linear'); END IF; END$$ DELIMITER ; CALL upgrade_settings; DROP PROCEDURE upgrade_settings; DROP PROCEDURE IF EXISTS upgrade_settings_1210; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE upgrade_settings_1210() BEGIN DECLARE colVal TEXT; SELECT name INTO colVal FROM dcps.settings WHERE name = 'Handler' LIMIT 1; IF colVal IS NULL THEN -- 1.2.10 handler dashboard INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Handler', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'galera'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'HANDLER_COMMIT,HANDLER_DELETE,HANDLER_READ_FIRST,HANDLER_READ_KEY,HANDLER_READ_LAST,HANDLER_READ_NEXT,HANDLER_READ_PREV,HANDLER_READ_RND,HANDLER_READ_RND_NEXT,HANDLER_UPDATE,HANDLER_WRITE:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Handler', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'mysql_single'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'HANDLER_COMMIT,HANDLER_DELETE,HANDLER_READ_FIRST,HANDLER_READ_KEY,HANDLER_READ_LAST,HANDLER_READ_NEXT,HANDLER_READ_PREV,HANDLER_READ_RND,HANDLER_READ_RND_NEXT,HANDLER_UPDATE,HANDLER_WRITE:linear'); INSERT INTO `settings` (`name`, `user_id`, `location_id`, `cluster_id`, `selected`, `dash_order`, `rs_name`, `type`, `from_ldap_user`, `cluster_type`) VALUES ('Handler', 1, 1, -1, 0, 0, 'none', 'dashboard', 0, 'replication'); INSERT INTO `settings_items` (`setting_id`, `item`) VALUES (LAST_INSERT_ID(), 'HANDLER_COMMIT,HANDLER_DELETE,HANDLER_READ_FIRST,HANDLER_READ_KEY,HANDLER_READ_LAST,HANDLER_READ_NEXT,HANDLER_READ_PREV,HANDLER_READ_RND,HANDLER_READ_RND_NEXT,HANDLER_UPDATE,HANDLER_WRITE:linear'); END IF; END$$ DELIMITER ; CALL upgrade_settings_1210; DROP PROCEDURE upgrade_settings_1210; DROP PROCEDURE IF EXISTS update_ldap_settings; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE update_ldap_settings() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'ldap_settings' AND column_name = 'user_dn'; IF colName IS NULL THEN ALTER TABLE `ldap_settings` ADD COLUMN `user_dn` VARCHAR(100) DEFAULT NULL; ALTER TABLE `ldap_settings` ADD COLUMN `group_dn` VARCHAR(100) DEFAULT NULL; END IF; END$$ DELIMITER ; CALL update_ldap_settings; DROP PROCEDURE update_ldap_settings; -- -- Increment logins counter for the user -- DROP TRIGGER IF EXISTS `users_update_logins`; DELIMITER $$ CREATE TRIGGER users_update_logins BEFORE UPDATE ON users FOR EACH ROW BEGIN SET NEW.logins = OLD.logins + 1; END $$ DELIMITER ; INSERT INTO `companies` (id, name) VALUES (1, 'Admin') ON DUPLICATE KEY UPDATE name = name; -- INSERT INTO `users` (id,company_id, email, password, name, sa, created) VALUES (1, 1, 'admin@localhost.xyz', '7163017d8e76e4b47ef16ffc5e346be010827adc', 'admin', 1, unix_timestamp(now())) ON DUPLICATE KEY UPDATE created=unix_timestamp(now()); -- -- version 1.2.12 -- CREATE TABLE IF NOT EXISTS `custom_advisors` ( `id` BIGINT(18) UNSIGNED NOT NULL AUTO_INCREMENT, `type` ENUM ('Threshold', 'Health', 'Security', 'Preditions', 'Auto tuning') DEFAULT NULL, `resource` ENUM ('Host', 'Node') DEFAULT NULL, `cluster_id` BIGINT(18) DEFAULT NULL, `node_id` BIGINT(18) DEFAULT NULL, `hostname` VARCHAR(500) DEFAULT NULL, `metric` VARCHAR(255) DEFAULT NULL, `critical` INT(11) DEFAULT '80', `warning` INT(11) DEFAULT '70', `condition` ENUM ('>', '<', '=') DEFAULT '=', `filename` VARCHAR(500) NOT NULL, `descr_title` VARCHAR(255) DEFAULT NULL, `descr_advice` TEXT DEFAULT NULL, `descr_justification` TEXT DEFAULT NULL, `notification_types` VARCHAR(255) DEFAULT NULL, `notification_settings` TEXT DEFAULT NULL, `extra_data` TEXT DEFAULT NULL, `duration` INT(11) DEFAULT '120', PRIMARY KEY (`id`) ) ENGINE = InnoDB AUTO_INCREMENT = 20 DEFAULT CHARSET = utf8; DROP TABLE IF EXISTS `service_configs`; CREATE TABLE IF NOT EXISTS `integrations` ( `id` BIGINT(18) UNSIGNED NOT NULL AUTO_INCREMENT, `is_active` CHAR(1) DEFAULT '1', `company_id` INT(10) DEFAULT NULL, `service_id` VARCHAR(50) NOT NULL, `name` VARCHAR(255) NOT NULL, `config` LONGTEXT DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB AUTO_INCREMENT = 20 DEFAULT CHARSET = utf8; /** * Extended the ACL */ -- -- Table structure for table `roles` -- DROP PROCEDURE IF EXISTS add_column_to_role_table; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE add_column_to_role_table() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'roles' AND column_name = 'role_type'; IF colName IS NULL THEN ALTER TABLE `roles` ADD COLUMN `role_type` CHAR(1) DEFAULT 'u' AFTER `role_name`; END IF; -- Only admin REPLACE INTO user_roles (id, user_id, role_id) VALUES (1, 1, 1); /** Update the data */ # UPDATE `roles` SET role_type = 's' where id = 1; # UPDATE `roles` SET role_type = 'u' where id = 3; # UPDATE `roles` SET role_type = 'a' where id = 2; REPLACE INTO `roles` (`id`, `role_name`, `role_type`) VALUES (1, 'Super Admin', 's'), (2, 'Admin', 'a'), (3, 'User', 'u'); END$$ DELIMITER ; CALL add_column_to_role_table; DROP PROCEDURE add_column_to_role_table; /** * Add column ``token` varchar(255) DEFAULT NULL,` for the clusters table */ DROP PROCEDURE IF EXISTS add_column_to_clusters_table; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE add_column_to_clusters_table() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'clusters' AND column_name = 'token'; IF colName IS NULL THEN ALTER TABLE `clusters` ADD COLUMN `token` VARCHAR(255) DEFAULT NULL AFTER `ip`; END IF; END$$ DELIMITER ; CALL add_column_to_clusters_table; DROP PROCEDURE add_column_to_clusters_table; /** * Extended the ACL */ -- -- Table structure for table `roles` -- DROP PROCEDURE IF EXISTS add_column_to_users_table; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE add_column_to_users_table() BEGIN DECLARE colName TEXT; SELECT column_name INTO colName FROM information_schema.columns WHERE table_schema = 'dcps' AND table_name = 'users' AND column_name = 'timezone'; IF colName IS NULL THEN ALTER TABLE `users` ADD COLUMN `timezone` VARCHAR(100) DEFAULT '' AFTER `name`; END IF; END$$ DELIMITER ; CALL add_column_to_users_table; DROP PROCEDURE add_column_to_users_table; -- -- Extend clusters table bt a new enum type -- DROP PROCEDURE IF EXISTS extend_cluster_type_clus_1609; DELIMITER $$ CREATE DEFINER = CURRENT_USER PROCEDURE extend_cluster_type_clus_1609() BEGIN ALTER TABLE `clusters` CHANGE COLUMN `type` `type` ENUM( 'mysqlcluster', 'replication', 'galera', 'mongodb', 'mysql_single', 'postgresql_single', 'group_replication' ) NOT NULL; END$$ DELIMITER ; CALL extend_cluster_type_clus_1609; DROP PROCEDURE extend_cluster_type_clus_1609;
Java
UTF-8
1,041
2.203125
2
[]
no_license
package edu.ap.bol; import org.restlet.resource.ClientResource; public class BestellingenClient { public static void main(String[] args) { try { ClientResource clientResource = new ClientResource("http://localhost:8087/bestellingen"); String bestelling1 = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"; bestelling1 += "<bestelling naamKlant =\"Jasper Maes2\" adres =\"Schensbossen 10\" datumBestelling =\"23/07/1994\" produktNaam =\"1 TB Harddrive\" hoeveelheid=\"1\"></bestelling>"; System.out.println(bestelling1); clientResource.post(bestelling1); String bestelling2 = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"; bestelling2 += "<bestelling naamKlant =\"Jasper Maes3\" adres =\"Schensbossen 10\" datumBestelling =\"23/07/1994\" produktNaam =\"1 TB Harddrive\" hoeveelheid=\"1\"></bestelling>"; clientResource.post(bestelling2); System.out.println(clientResource.getResponseEntity().getText()); } catch (Exception e) { System.out.print(e.getMessage()); } } }
SQL
UTF-8
457
2.96875
3
[]
no_license
DROP SCHEMA IF EXISTS lead_service; CREATE SCHEMA lead_service; USE lead_service; CREATE TABLE `leads`( id INT AUTO_INCREMENT NOT NULL, `name` VARCHAR(255), email VARCHAR(255), company_name VARCHAR(255), phone_number VARCHAR(255), sales_rep_id INT, PRIMARY KEY(id) ); INSERT INTO `leads` (`name`, email, company_name, phone_number, sales_rep_id) VALUES ('John Nieve', 'johnstark@gmail.com', 'Invernalia', '654874598', 1), ('Baby Yoda', 'babyoda@gmail.com', 'Ajos sa', '654541257', 2);
Java
UTF-8
1,280
2.828125
3
[]
no_license
package qinkai.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Demo02 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String cookieName = cookie.getName(); String cookieValue = cookie.getValue(); System.out.println(cookieName + ":" + cookieValue); } } // 添加cookie Cookie cookie1 = new Cookie("name", "zhangsan"); // setMaxAge: 设置最大有效时间,单位秒 、负值表示当浏览器关闭时cookie失效 默认值-1 cookie1.setMaxAge(60 * 60 * 24 * 7); response.addCookie(cookie1); Cookie cookie2 = new Cookie("age", "18"); response.addCookie(cookie2); response.getWriter().write("请求成功!!!"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Java
UTF-8
659
2.4375
2
[]
no_license
package database_query; import java.util.Hashtable; import java.util.concurrent.Callable; import jpl.Atom; import jpl.PrologException; import jpl.Query; import jpl.Term; public class CustomCallable implements Callable<Term> { private String queryString; public CustomCallable(String queryString) { this.queryString = queryString; } @Override public Term call() throws Exception { Query query = new Query("execute_query(" + queryString + ", Result)"); try { if (query.hasMoreElements()) { return (Term) ((Hashtable) query.nextElement()).get("Result"); } } catch (PrologException e) { e.printStackTrace(); } return null; } }
Java
UTF-8
172
1.671875
2
[]
no_license
package edu.washington.cse.codestats; public class Constant { public static Constant of(final String string) { // TODO Auto-generated method stub return null; } }
Java
UTF-8
2,276
2.53125
3
[]
no_license
package net.perspilling.asset.api; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Size; import java.util.Objects; /** * The representation (DTO) of an asset entity. * * @author Per Spilling */ @ApiModel public class Asset { private Long id; @Size(min = 4, max = 10) @NotEmpty // may not be null or blank @ApiModelProperty(required = true, value = "The serialnumber of the asset.") private String serialNumber; @Length(max = 50) @NotEmpty @ApiModelProperty(required = true, value = "The model name of the asset.") private String modelName; @ApiModelProperty(required = false, value = "The address where the asset is installed.") private Address address; public Asset() { // Jackson deserialization } public Asset(String serialNumber, String modelName, Address address) { this.serialNumber = serialNumber; this.modelName = modelName; this.address = address; } public Asset(Long id, String serialNumber, String modelName, Address address) { this.id = id; this.serialNumber = serialNumber; this.modelName = modelName; this.address = address; } @JsonProperty public Long getId() { return id; } @JsonProperty public String getSerialNumber() { return serialNumber; } @JsonProperty public String getModelName() { return modelName; } @JsonProperty public Address getAddress() { return address; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Asset)) { return false; } final Asset that = (Asset) o; return Objects.equals(this.id, that.id) && Objects.equals(this.serialNumber, that.serialNumber) && Objects.equals(this.modelName, that.modelName); } @Override public int hashCode() { return Objects.hash(id, serialNumber, modelName); } }
Markdown
UTF-8
11,781
2.734375
3
[ "Apache-2.0" ]
permissive
# 附录 孔学新语自序 髫年入学,初课四书;壮岁穷经,终惭三学。虽游心于佛道,探性命之真如;犹输志于宏儒,乐治平之实际。况干戈扰攘,河山之面目全非;世变频仍,文教之精神隳裂。默言遁晦,灭迹何难。众苦煎熬,离群非计。故当夜阑昼午,每与二三子温故而知新。疑古证今,时感二十篇入奴而出主。讲述积久,笔记盈篇。朋辈咐嘱灾梨,自愧见囿窥管。好在宫墙外望,明堂揖让两庑。径道异行,云辇留连一乘。六篇先讲,相期欲尽全文。半部可安,会意何妨片羽。砖陈玉见,同扬洙泗之传薪。讽颂雅言,一任尼山之桂杖。是为序。 时岁次壬寅(一九六二年)孔圣诞辰南怀瑾序于台北寓居 孔学新语发凡 我们作为现代的一个人,既有很沉痛的悲惨遭遇,也有难逢难遇的幸运;使我们生当历史文化空前巨变的潮流中。身当其冲的要负起开继的责任。但是目前所遭遇的种种危难,除了个人身受其苦以外,并不足可怕。眼见我们历史传统的文化思想快要灭绝了,那才是值得震惊和悲哀的事!自从“五四运动”的先后时期,先我们一辈而老去了的青年们,为了寻求救国之路,不惜削足适履,大喊其“打倒孔家店”。虽然人之将死,其言也善,有些人到了晚年,转而讲述儒家的思想,重新提倡孔孟之学,用求内心的悔意,可是已形成了的风气,大有排山倒海之势,根本已无能为力了! 其实,孔家店在四十年前的那个时代,是否应该打倒,平心而论,实在很有问题,也不能尽将责任推向那些大打出手的人物。原因是孔家店开得太久了,经过二千多年的陈腐滥败,许多好东西,都被前古那些店员们弄得霉滥不堪,还要硬说它是好东西,叫大家买来吃,这也是很不合理的事。可是在我们的文化里,原有悠久历史性的老牌宝号,要把它洗测革新一番,本是应该的事,若随便把它打倒,那就万不可以。这是什么原因呢?我有一个简单的譬喻:我们那个老牌宝号的孔家店,他向来是出售米麦五谷等的粮食店,除非你成了仙佛,否则如果我们不吃五谷米粮,就要没命了!固然而包牛排也一样可以吃饱,但是它到底太稀松,不能长日充饥,而且我们也买不起,甚至不客气的说:还吃得不太习惯,常常会患消化不良的毛病。至于说时令不对,新谷已经登场,我们要把本店里的陈霉滥货倒掉,添买新米,那是绝对可以的事。 因些,就可了解孔家店被人打倒是不无原因的: 第一,所讲的义理不对。第二,内容的讲法不合科学。我们举几个例子来说:(1)“三年无改于父之道,可谓孝矣。”几千年来,都把它解释做父母死了,三年以后,还没有改变了父母的旧道路,这样才叫做孝子。那么,问题就来了,如果男盗女娼,他的子女岂不也要实行其旧业三年吗?(2)“无友不如己者。”又解释做交朋友都要交比自己好的,不要交不如自己的人。如果大家都如此,岂不是势利待人吗?其实,几千年来,大家都把这些话解错了,把孔子冤枉得太苦了!所以我现在就不怕挨骂,替他讲个明白,为孔子伸冤。这些毛病出在哪里呢?古人和今人一样,都是把《论语》当做一节一节的格言句读,没有看出它是实实在在首尾连贯的关系,而且每篇都不可以分割,每节都不可以支解。他们的错误,都错在断章取义,使整个义理支离破碎了。本来二十篇《论语》,都已经孔门弟子的悉心编排,都是首尾一贯,条理井然,是一篇完整的文章。因此,大家所讲的第二个问题,认为没有体系,不合科学分类的编排,也是很大的误解。 为什么古人会忽略这一点,一直就误解内容,错了二千多年呢?这也有个原因:因为自汉代独尊儒学以后,士大夫们“学成文武艺,货与帝王家。”的思想,唯一的批发厂家,只有孔家一门,人云亦云,谁也不敢独具异见,否则,不但纱帽儿戴不上,甚至,被士大夫所指责,被社会所唾弃,乃至把戴纱帽的家伙也会玩掉,所以谁都不敢推翻旧说,为孔子伸冤啊!再加以到了明代以后科举考试,必以四书的章句为题,而四书的义解,又必宗朱熹的为是。于是先贤有错,大家就将错就错,一直就错到现在,真是冤上加错! 现在,我们的看法,不但是二十篇《论语》,每篇都条理井然,脉络一贯。而且二十篇的编排,都是首尾呼应,等于一篇天衣无缝的好文章。如果要确切了解我们历史传统文化的思想精神,必须先要了解儒家孔孟之学,和研究孔子学术思想的体系,然后才能触类旁通,自然会把它融和起来了。至于内容方面,历来的讲解,错误之处,屡见不鲜,也须一一加以明辨清楚,使大家能认识孔子之所以被尊为圣人,的确是有其伟大的道理。如果认为我是大胆的狂妄,居然敢推翻几千年来的旧说,那我也只好引用孟子说的:“予岂好辩哉!予不得已也!”何况我的发现,也正因为有历代先贤的启发,加以力学、思辨和体验,才敢如此做为,开创新说。其次,更要郑重声明,我不敢如宋明理学家们的无聊,明明是因佛道两家的启发,才对儒学有所发挥,却为了士大夫社会的地位,反而大骂佛老。我呢?假如这些见解确是对的,事实上,也只是因为我在多年学佛,才悟出其中的道理。为了深感世变的可怕,再不重整孔家店,大家精神上遭遇的危难,恐怕还会有更大的悲哀!所以我才讲述二十年前的一得之见,贡献于诸位后起之秀。希望大家能秉宋代大儒张横渠先生的目标:“为天地立心,为生民立命,为往圣继绝学,为万世开太平。”为今后我们的文化和历史,担承起更重大的责任。我既不想入孔庙吃冷猪头,更不敢自己杜塞学问的根源。 其次,我们要了解传统文化,首先必须要了解儒家的学术思想。要讲儒家的思想,首先便要研究孔孟的学术。要讲孔子的思想学术,必须先要了解《论语》。《论语》是记载孔子的生平讲学、和门弟子们言行的一部书。它虽然像语录一样用简单的文字,记载那些教条式的名言懿行,但都是经过门弟子们的悉心编排,自有它的体系条贯的。自唐以后,经过名儒们的圈点,沿习成风,大家便认为《论语》的章节,就是这种支支节节的形式,随便排列,谁也不敢跳出这传统的范围,重新加以注释,所以就墨守成规,弄得问题丛生了!这种原因,虽然是学者因袭成见,困于师承之所致。但是,最大的责任,还是由于汉、宋诸儒的思想垄断,以致贻误至今! 我们传统的历史文化,自秦汉统一以后,儒家的学术思想,已经独尊天下,生当汉代的大儒们,正当经过战国与秦汉的大变乱之后,文化学术,支离破碎,亟须重加整理。于是汉儒们便极力注重考据、训诂、疏释等的工作,这种学术的风气,就成为汉代儒家学者特有其实的风格,这就是有名的汉学。现在外国人把研究中国文化的学问也统名叫做汉学,这是大有问题的,我们自己要把这个名词所代表的不同意义分清楚。唐代儒者的学风,大体还是因袭汉学,对于章句、训诂、名物等类,更加详证,但对义理并无特别的创见。到了宋代以后,更有理学家的儒者兴起,自谓直承孔孟以后的心传,大讲其心性微妙的义理,这就是宋儒的理学。与汉儒们只讲训诂、疏释的学问,又别有一番面目。从此儒学从汉学的范畴脱颖而出,一直误认讲义理之学便是儒家的主旨,相沿传习,直到明代的儒者,仍然守此藩篱而不变。到了明末清初时代,有几位儒家学者,对于平时静坐而谈心性的理学,深恶痛绝,认为这是坐致亡国的原因,因此便提倡恢复朴学的路线,但求平实治学而不重玄谈,仍然注重考据和训诂的学问,以整治汉学为标榜,这就是清儒的朴学。由此可知儒家的孔孟学术,虽然经汉、唐、宋、明、清的几个时代的变动,治学的方法和路线虽有不同,但是尊崇孔孟,不敢离经叛道而加以新说,这是一仍不变的态度。虽然不是完全把他构成为一宗教,但把孔子温良恭俭让的生平,塑成为一个威严不可侵犯的圣人偶像,致使后生小子,望之却步,实在大有瞒人眼目之嫌,罪过不浅!所以现代人愤愤然奋起要打倒孔家店,使开创二千多年老店的祖宗,也受牵连之过,岂不太冤枉了吗? 现在我们既要重新估价,再来研究《论语》,首先必须了解几个前提。(一)《论语》是孔门弟子们所编记,先贤们几经考据,认为它大多是出于曾子或有子门人的编纂,这个观念比较信实而可靠。(二)但是当孔门弟子编辑此书的时候,对于它的编辑体系,已经经过详密的研究,所以它的条理次序,都是井然不乱的。(三)所以此书不但仅为孔子和孔门弟子们当时的言行录,同时也便是孔子一生开万世宗师的史料,为汉代史家们编录孔子历史资料的渊源。由此可知研究《论语》,也等于直接研究孔子的生平。至于效法先圣,自立立人以至于治平之道,那是当然的本分事。(四)可是古代书册是刻记于竹简上的,所以文字极需简练,后来发明了纸张笔墨,也是以卷幅抄写卷起,但因古代的字体屡经变更,所以一抄再抄,讹误之处,不免有所脱节,因此少数地方,或加重复,或有脱误,或自增删,都是难免的事实。(五)古代相传的《论语》有三种,即《鲁论》二十篇,和《齐论》二十二篇,又在孝景帝的时期,传说鲁恭王坏孔子故宅的墙壁,又得《古文论语》。但《古文论语》和《齐论》,到了汉魏之间,都已逐渐失传,现在所传诵的《论语》,就是《鲁论》二十篇了。(六)至于《论语》的训诂注疏,历汉、唐、宋、明、清诸代,已经有详实的考据,我们不必在此另作画蛇添足的工作。至若极言性命心性的微言,自北宋五大儒的兴起,也已经有一套完整的努力,我们也不必另创新说,再添枝叶。 最后举出我们现在所要讲的,便是要入乎其内,出乎其外的体验,摆脱二千余年的章句训诂的范围,重新来确定它章句训诂的内义。主要的是将经史合参,以《论语》与《春秋》的史迹相融会,看到春秋战国时期政治社会的紊乱面目,以见孔子确立开创教化的历史文化思想的精神;再来比照现代世界上的国际间文化潮流,对于自己民族、国家和历史,确定今后应该要走的路线和方向。因此若能使一般陷于现代社会心理病态的人们,在我们讲的文字言语以外去体会,能够求得一个解脱的答案,建立一种卓然不拔,矗立于风雨艰危中的人生目的和精神,这便是我所要馨香祷祝的了。 岁次壬寅(一九六二年)八月南怀瑾记于台北
C++
UTF-8
1,325
4.03125
4
[]
no_license
/* remove算法会通过移动来覆盖需要删除的元素,但是并不会缩减容器的容量,其返回新的终点位置,但原有的元素位置仍然有效 该程序同时展示了distance的用法 */ #include <iostream> #include <list> #include <iterator> #include <algorithm> using namespace std; template<class T> void print(const std::string& prefix, const T& continer) { cout << prefix << ": "; copy(continer.begin(), continer.end(), ostream_iterator<typename T::value_type>(cout, " ")); cout << endl; } int main() { list<int> col; for(int i = 0; i < 6; ++i) { col.push_back(i); col.push_front(i); } print("pre list:", col); //remove算法返回一个新的终点 list<int>::iterator newend = remove(col.begin(), col.end(), 3); print("after remove:", col); cout << "rigth cout: " << endl; copy(col.begin(), newend, ostream_iterator<int>(cout, " ")); cout << endl; cout << "list size:" << distance(col.begin(), newend) << endl; //真正删除元素的方法,调用容器本身的erase删除区间 col.erase(newend, col.end()); print("after earse:", col); return 0; } 输出:注意最后的4、5 2个元素 pre list:: 5 4 3 2 1 0 0 1 2 3 4 5 after remove:: 5 4 2 1 0 0 1 2 4 5 4 5 rigth cout: 5 4 2 1 0 0 1 2 4 5 list size:10 after earse:: 5 4 2 1 0 0 1 2 4 5
Markdown
UTF-8
7,135
2.890625
3
[]
no_license
# Member/v1 Documentation ## Retrieve a Member Returns a specific Member object. ### URL > GET /member/v1/{id} > GET /member/v1/me ### Parameters <table> <thead> <tr> <th>Name</th> <th>Required?</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>{id}</code></td> <td>Required</td> <td>string</td> <td>The member id. If the member id is <code>me</code> the current authenticated user will be used.</td> </tr> </tbody> </table> ### Example > GET http://localhost/rest/member/v1/123 ```js { "Apt":"String content", "BusinessUnitId":2, "City":"String content", "CreatedDate":"2012-07-16T17:23:34Z", "DateOfBirth":"1980-01-01T08:00:00Z", "Email":"someone@gmail.com", "EnterpriseId":5, "FamilyId":154, "FirstName":"String content", "Image":"String content", "IsActive":true, "LastName":"String content", "LastVisitDate":"2012-07-16T17:23:34Z", "MemberId":123, "MiddleName":"String content", "ModifiedDate":"2012-07-16T17:23:34Z", "ProviderUserKey":"1627aea5-8e0a-4371-9022-9b504344e724", "StartDate":"2012-07-16T17:23:34Z", "State":"IN", "Street":"String content", "UserName":"String content", "Zip":46142 } ``` ## Update a Member Updates a specific Member object. ### URL > POST /member/v1/{id} > POST /member/v1/me _(coming soon)_ ### Parameters <table> <thead> <tr> <th>Name</th> <th>Required?</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>{id}</code></td> <td>Required</td> <td>string</td> <td>The member id. If the member id is <code>me</code> the current authenticated user will be used.</td> </tr> <tr> <td>Apt</td> <td>Optional</td> <td>string</td> <td>The apartment of the member</td> </tr> <tr> <td>City</td> <td>Optional</td> <td>string</td> <td>The city of the member</td> </tr> <tr> <td>DateOfBirth</td> <td>Optional</td> <td>string</td> <td>The date of birth of the member. ISO86 date string format.</td> </tr> <tr> <td>FirstName</td> <td>Optional</td> <td>string</td> <td>The first name of the member.</td> </tr> <tr> <td>Image</td> <td>Optional</td> <td>string</td> <td>A url linking the member image.</td> </tr> <tr> <td>LastName</td> <td>Optional</td> <td>string</td> <td>The last name of the member.</td> </tr> <tr> <td>LastVisitDate</td> <td>Optional</td> <td>string</td> <td>The date that the member visited the church last. ISO86 date string format.</td> </tr> <tr> <td>MiddleName</td> <td>Optional</td> <td>string</td> <td>The middle name of the member.</td> </tr> <tr> <td>StartDate</td> <td>Optional</td> <td>string</td> <td>The date that the member first joined the church. ISO86 date string format.</td> </tr> <tr> <td>State</td> <td>Optional</td> <td>string</td> <td>The state the member resides in.</td> </tr> <tr> <td>Street</td> <td>Optional</td> <td>string</td> <td>The street address of the member.</td> </tr> <tr> <td>Zip</td> <td>Optional</td> <td>string</td> <td>The zip code of the member.</td> </tr> </tbody> </table> ### Example > POST http://localhost/rest/member/v1/123 ```js { "Apt":"String content", "City":"String content", "DateOfBirth":"1980-01-01T08:00:00Z", "FamilyId":154, "FirstName":"String content", "Image":"String content", "LastName":"String content", "LastVisitDate":"2012-07-16T17:23:34Z", "MiddleName":"String content", "StartDate":"2012-07-16T17:23:34Z", "State":"IN", "Street":"String content", "Zip":46142 } ``` ## Retrieve a collection of Members Returns a collection of Member objects. ### URL > GET /member/v1/?index={index}&paging={paging} ### Parameters <table> <thead> <tr> <th>Name</th> <th>Required?</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>{index}</code></td> <td>Required</td> <td>string</td> <td>The page in the data set to be queried.</td> </tr> <tr> <td><code>{paging}</code></td> <td>Required</td> <td>string</td> <td>The number of records to be returned in the page. Max is 100.</td> </tr> </tbody> </table> ### Example > GET http://localhost/rest/member/v1/?index=1&paging=25 ```js { "Entities": [ { "Apt":"String content", "BusinessUnitId":2, "City":"String content", "CreatedDate":"2012-07-16T17:23:34Z", "DateOfBirth":"1980-01-01T08:00:00Z", "Email":"someone@gmail.com", "EnterpriseId":5, "FamilyId":154, "FirstName":"String content", "Image":"String content", "IsActive":true, "LastName":"String content", "LastVisitDate":"2012-07-16T17:23:34Z", "MemberId":123, "MiddleName":"String content", "ModifiedDate":"2012-07-16T17:23:34Z", "ProviderUserKey":"1627aea5-8e0a-4371-9022-9b504344e724", "StartDate":"2012-07-16T17:23:34Z", "State":"IN", "Street":"String content", "UserName":"String content", "Zip":46142 } ], "Index": 1, "Paging": 25, "Total": 1 } ``` ## Change password for a Member Allows a member to change their password. ### URL > POST /member/v1/{id}/changepassword > POST /member/v1/me/changepassword _(coming soon)_ ### Parameters <table> <thead> <tr> <th>Name</th> <th>Required?</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>{id}</code></td> <td>Required</td> <td>string</td> <td>The member id. If the member id is <code>me</code> the current authenticated user will be used.</td> </tr> <tr> <td>oldpassword</td> <td>Required</td> <td>string</td> <td>The current password of the authenticated user.</td> </tr> <tr> <td>newpassword</td> <td>Required</td> <td>string</td> <td>The new password of the authenticated user.</td> </tr> </tbody> </table> ### Example > GET http://localhost/rest/member/v1/123/changepassword ```js { "oldpassword":"String content", "newpassword":"String content" } ```
Java
UTF-8
269
2.359375
2
[]
no_license
package MrWeatherSort; public class LogMessage { static StringBuffer message=new StringBuffer(""); public static StringBuffer getMessage() { return message; } public static void setMessage(String s) { message.append(s+"\n"); } }
Python
UTF-8
5,601
2.71875
3
[]
no_license
""" To override a function in this module, do the following: import mtoa.hooks def setupFilter(filter, aovName=None): if aovName == "Occlusion": filter.aiTranslator.set("guassian") mtoa.hooks.setupFilter = setupFilter There are copies of each function in this module that start with an underscore. This makes it easy to extend the built-in functionality within your override. For example: import mtoa.hooks def getDefaultAOVs(): return _getDefaultAOVs() + [("Occlusion", "float")] mtoa.hooks.getDefaultAOVs = getDefaultAOVs """ import os from posixpath import join def setupFilter(filter, aovName=None): """ Setup a filter that was created by mtoa. filter : pymel.PyNode the newly created filter node aovName : string or None the name of the AOV that the filter will be connected to This function can be used to set the default filter type or set attributes like filter width. Note that if you only want to change the default filter, you can use `registerDefaultTranslator` also found in this module. For example, to set the default to gaussian: registerDefaultTranslator('aiAOVFilter', 'gaussian') """ pass def setupDriver(driver, aovName=None): """ Setup a driver that was created by mtoa. filter : pymel.PyNode the newly created driver node aovName : string or None the name of the AOV that the driver will be connected to This function can be used to set the default driver type or set attributes like compression. Note that if you only want to change the default driver, you can use `registerDefaultTranslator` also found in this module. For example, to set the default to jpg: registerDefaultTranslator('aiAOVDriver', 'jpg') """ pass def setupOptions(options): """ Setup the 'defaultArnoldRenderOptions' node. options : pymel.PyNode the newly created options node Override this function to change defaults on the options node. """ pass def setupDefaultAOVs(opts): """ opts: aovs.AOVInterface used to call addAOV, etc By default, this function calls getDefaultAOVs to get the names and types of AOVs to create. Override this function if getDefaultAOVs does not provide enough control. """ for args in getDefaultAOVs(): opts.addAOV(*args) # save a copy _setupDefaultAOVs = setupDefaultAOVs def getDefaultAOVs(): """ Returns a list of aov (name, type) pairs for setting up the default AOVs in a scene. type can either be a string or integer from `mtoa.aovs.TYPES` """ return [] # save a copy _getDefaultAOVs = getDefaultAOVs def fileTokenScene(path, tokens, **kwargs): import pymel.core as pm if '<Scene>' in path and 'Scene' not in tokens: sceneName = pm.sceneName().namebase if sceneName == '': sceneName = 'untitled' tokens['Scene'] = sceneName _fileTokenScene = fileTokenScene def fileTokenRenderPass(path, tokens, **kwargs): import pymel.core as pm if not kwargs.get('strictAOVs', False) and '<RenderPass>' not in path and 'RenderPass' in tokens: if not os.path.isabs(path): path = join('<RenderPass>', path) else: pm.cmds.warning('[mtoa] Multiple render passes (AOVs) exist, but output path is absolute and without <RenderPass> token: "%s"' % path) return path _fileTokenRenderPass = fileTokenRenderPass def fileTokenCamera(path, tokens, **kwargs): import pymel.core as pm renderable = [c for c in pm.ls(type='camera') if c.renderable.get()] if '<Camera>' not in path and len(renderable) > 1: if os.path.isabs(path): pm.cmds.warning('[mtoa] Multiple renderable cameras exist, but output path is absolute and without <Camera> token: "%s"' % path) else: path = join('<Camera>', path) if '<Camera>' in path and 'Camera' not in tokens: if len(renderable) > 1: if not kwargs['leaveUnmatchedTokens']: raise ValueError("[mtoa] Multiple renderable cameras: you must provide a value for <Camera> token") elif len(renderable) == 1: tokens['Camera'] = renderable[0].getParent().name() else: if not kwargs['leaveUnmatchedTokens']: raise ValueError("[mtoa] No renderable cameras: you must provide a value for <Camera> token") return path _fileTokenCamera = fileTokenCamera def fileTokenRenderLayer(path, tokens, **kwargs): import pymel.core as pm layers = pm.cmds.listConnections('renderLayerManager.renderLayerId', source=False, destination=True) if '<RenderLayer>' not in path and len(layers) > 1: if os.path.isabs(path): pm.cmds.warning('[mtoa] Multiple renderable render layers exist, but output path is absolute and without <RenderLayer> token: "%s"' % path) else: path = join('<RenderLayer>', path) if '<RenderLayer>' in path and 'RenderLayer' not in tokens: tokens['RenderLayer'] = pm.cmds.editRenderLayerGlobals(q=True, currentRenderLayer=True) if tokens.get('RenderLayer', None) == 'defaultRenderLayer': tokens['RenderLayer'] = 'masterLayer' return path _fileTokenRenderLayer = fileTokenRenderLayer def fileTokenVersion(path, tokens, **kwargs): import pymel.core as pm if '<Version>' in path and 'Version' not in tokens: tokens['Version'] = pm.getAttr('defaultRenderGlobals.renderVersion')
Python
UTF-8
493
4.34375
4
[]
no_license
#Range()function: It is a pre-defined function, whose range starts from # 0 to given value(excluding) #ex:- range(10)--->here values from 0 to 9 are generated and stored in an object. x=range(10) print(x) print(type(x)) for p in x: print(p) y=range(10,20) print(y) print(type(y)) for q in y: print(q) z=range(20,30,2) print(z) print(type(z)) for r in z: print(r) w=range(40,30,-1) print(w) print(type(w)) for s in w: print(s)
SQL
UTF-8
99
2.5625
3
[]
no_license
SELECT name, COUNT(NAME) COUNT FROM animal_ins GROUP BY name HAVING COUNT(NAME) > 1 ORDER BY name;
Shell
UTF-8
152
3.09375
3
[]
no_license
#!/usr/bin/env bash #reading from etc passwd cut -d: -f1 /etc/passwd | while IFS= read -r user do echo "$user" # do something with $user done
Shell
UTF-8
16,933
3.046875
3
[]
no_license
#! /bin/bash ## Selamat datang di Soal Mudah ## ##Create Kuriyanto Adi ## ## *Perintah Dasar Linux* ## clear waktu=`date +%H:%M:%S`; ## Soal nomor 1 echo "1. Untuk melihat isi file dalam sebuah direktori dengan perintah ? " echo -n " Jawaban : " read jwb1 if [ ls = $jwb1 ] then nil1=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 2 echo "2. Untuk masuk kedalam direktori dengan perintah ? " echo -n " Jawaban : " read jwb2 if [ cd = $jwb2 ] then nil2=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 3 echo "3. Untuk mengecek posisi di direktori mana dengan perintah ? " echo -n " Jawaban : " read jwb3 if [ pwd = $jwb3 ] then nil3=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 4 echo "4. Untuk mengubah nama file dengan perintah ? " echo -n " Jawaban : " read jwb4 if [ mv = $jwb4 ] then nil4=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 5 echo "5. Untuk mengubah nama folder dengan perintah ? " echo -n " Jawaban : " read jwb5 if [ mv = $jwb5 ] then nil5=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 6 echo "6. Untuk menghapus file dengan perintah ? " echo -n " Jawaban : " read jwb6 if [ rm = $jwb6 ] then nil6=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 7 echo "7. Untuk membuat folder baru dengan perintah ? " echo -n " Jawaban : " read jwb7 if [ mkdir = $jwb7 ] then nil7=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 8 echo "8. Untuk melakukan remote ssh dengan perintah ? " echo -n " Jawaban : " read jwb8 if [ ssh = $jwb8 ] then nil8=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 9 echo "9. Untuk menambah user baru dengan perintah ? " echo -n " Jawaban : " read jwb9 if [ adduser = $jwb9 ] then nil9=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 10 echo "10. Untuk mengecek siapa yang login dengan perintah ? " echo -n " Jawaban : " read jwb10 if [ who = $jwb10 ] then nil10=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 11 echo "11. Untuk mengopy file dengan perintah ? " echo -n " Jawaban : " read jwb11 if [ cp = $jwb11 ] then nil11=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 12 echo "12. Untuk mengarsip file menjadi zip dengan perintah ? " echo -n " Jawaban : " read jwb12 if [ zip = $jwb12 ] then nil12=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 13 echo "13. Untuk membuka file zip dengan perintah ? " echo -n " Jawaban : " read jwb13 if [ unzip = $jwb13 ] then nil13=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 14 echo "14. Untuk mengubah hak akses dengan perintah ? " echo -n " Jawaban : " read jwb14 if [ chmod = $jwb14 ] then nil14=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 15 echo "15. Untuk pemilikan file atau grup dengan perintah ? " echo -n " Jawaban : " read jwb15 if [ chown = $jwb15 ] then nil15=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 16 echo "16. Untuk melihat isi file dalam sebuah direktori dengan banyak format dengan perintah ? " echo -n " Jawaban : " read jwb16 case $jwb16 in "ls -l") nil16=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 17 echo "17. Untuk mencopy direktori dan isinya dengan perintah ? " echo -n " Jawaban : " read jwb17 case $jwb17 in "cp -r") nil17=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 18 echo "18. Untuk menghapus direktori dan isinya dengan perintah ? " echo -n " Jawaban : " read jwb18 case $jwb18 in "rm -rf") nil18=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 19 echo "19. Untuk melihat isi file text dengan perintah ? " echo -n " Jawaban : " read jwb19 case $jwb19 in "cat") nil19=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 20 echo "20. Hapus direktori dengan satu baris perintah. /smk/tkj/ " echo -n " Jawaban : " read jwb20 case $jwb20 in "rm -rf /smk/tkj/") nil20=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; "rm -rf /smk/tkj") nil20=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 21 echo "21. Hapus file dengan satu baris perintah. /smk/tkj/tugas " echo -n " Jawaban : " read jwb21 case $jwb21 in "rm /smk/tkj/tugas") nil21=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 22 echo "22. Untuk membuat folder saya-belajar anda bisa memasukan perintah ?" echo -n " Jawaban : " read jwb22 case $jwb22 in "mkdir saya-belajar") nil22=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 23 echo "23. Untuk membuat folder belajar-bash anda bisa memasukan perintah ?" echo -n " Jawaban : " read jwb23 case $jwb23 in "mkdir belajar-bash") nil23=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 24 echo "24. Untuk mengubah nama file tugas-sekolah menjadi tugas-bahasa dengan perintah" echo -n " Jawaban : " read jwb24 case $jwb24 in "mv tugas-sekolah tugas-bahasa") nil24=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 25 echo "25. Untuk memindah tugas-bash.sh ke folder tugas/sekolah ?" echo -n " Jawaban : " read jwb25 case $jwb25 in "mv tugas-bash.sh tugas/sekolah") nil25=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 26 echo "26. Perintah mengubah hak akses untuk eksekusi tugas-bash.sh bisa di jalankan secara Symbolic ?" echo -n " Jawaban : " read jwb26 case $jwb26 in "chmod +x") nil26=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 27 echo "27. Untuk Melihat isi dalam directory beserta hak akses nya ?" echo -n " Jawaban : " read jwb27 case $jwb27 in "ls -l") nil27=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 28 echo "28. Untuk mengetahui apakah Directory atau file pada Linux ditandakan dengan karakter ?" echo -n " Jawaban : " read jwb28 case $jwb28 in "-") nil28=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 29 echo "29. Perintah Untuk Mematikan Komputer pada Terminal ?" echo -n " Jawaban : " read jwb29 case $jwb29 in "poweroff") nil29=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 30 echo "30. Perintah Membuat File ?" echo -n " Jawaban : " read jwb30 case $jwb30 in "touch") nil30=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 31 echo "31. Perintah untuk melihat tanggal ?" echo -n " Jawaban : " read jwb31 case $jwb31 in "date") nil31=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 32 echo "32. Perintah untuk menjalankan format .bin pada Linux ?" echo -n " Jawaban : " read jwb32 case $jwb32 in "./") nil32=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 33 echo "33. Perintah Untuk membuat group pada Linux ?" echo -n " Jawaban : " read jwb33 case $jwb33 in "addgroup") nil33=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 34 echo "34. Perintah untuk Memberikan HAK AKSES penuh user,group dan other pada file tugas-bash.sh ?" echo -n " Jawaban : " read jwb34 case $jwb34 in "chmod 777") nil34=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 35 echo "35. Perintah untuk melihat isi file secara step by step ?" echo -n " Jawaban : " read jwb35 case $jwb35 in "more") nil35=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 36 echo "36. Perintah untuk menginstall package .deb ?" echo -n " Jawaban : " read jwb36 case $jwb36 in "dpkg -i") nil36=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 37 echo "37. Untuk melihat IP Address ?" echo -n " Jawaban : " read jwb37 case $jwb37 in "ifconfig") nil25=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 38 echo "38. Untuk mengetahui Bash berjalan pada Linux" echo -n " Jawaban : " read jwb38 case $jwb38 in "ps") nil38=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 39 echo "39. Perintah masuk Super User/root ?" echo -n " Jawaban : " read jwb39 case $jwb39 in "sudo su") nil39=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 40 echo "40. Untuk keluar dari super user / root pada terminal ?" echo -n " Jawaban : " read jwb40 case $jwb40 in "exit") nil40=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 41 echo "41. Untuk mengalihkan Kepemilikan file tugas-bash ?" echo -n " Jawaban : " read jwb41 case $jwb41 in "chown") nil41=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 42 echo "42. Untuk memberikan Hak akses penuh pada tugas-bash.sh secara full" echo -n " Jawaban : " read jwb42 case $jwb42 in "chmod 777 tugas-bash.sh") nil42=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 43 echo "43. Perintah untuk mengetahui versi Kernel ?" echo -n " Jawaban : " read jwb43 case $jwb43 in "uname -r") nil43=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 44 echo "44. Letak Posisi untuk mengganti Hostname pada Linux ?" echo -n " Jawaban : " read jwb44 case $jwb44 in "/etc/hostname") nil44=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 45 echo "45. Untuk Membuat groub dengan nama belajar ? " echo -n " Jawaban : " read jwb45 case $jwb45 in "addgroup belajar") nil45=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 46 echo "46. Untuk Mengetahui file atau directory pada Linux ? " echo -n " Jawaban : " read jwb46 case $jwb46 in "ls -l") nil46=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 47 echo "47. Perintah update pada Distro linux Debian beserta Turunan nya ?" echo -n " Jawaban : " read jwb47 if [ "$jwb47" = "apt update" ] || [ "$jwb47" = "apt-get update" ]; then nil47=1 echo "\033[1;32m Jawaban anda benar\033[0m" else echo "\033[1;31m Maaf jawaban anda salah\033[0m" fi echo "" ## Soal nomor 48 echo "48. Perintah Untuk Melihat Proses kinerja Linux " echo -n " Jawaban : " read jwb48 case $jwb48 in "top") nil48=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 49 echo "49. Berikut Editor Bawaan Linux secara Default?" echo -n " Jawaban : " read jwb49 case $jwb49 in "vim") nil49=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac ## Soal nomor 50 echo "50. Untuk Restart (menghidupkan kembali) Komputer ? " echo -n " Jawaban : " read jwb50 case $jwb50 in "reboot") nil50=1 echo "\033[1;32m Jawaban anda benar\033[0m" ;; *) echo "\033[1;31m Maaf jawaban anda salah\033[0m" ;; esac hasil1=$((nil1 + nil2 + nil3 + nil4 + nil5)) hasil2=$((nil6 + nil7 + nil8 + nil9 + nil10 )) hasil3=$((nil11 + nil12 + nil13 + nil14 + nil15 )) hasil4=$((nil16 + nil17 + nil18 + nil19 + nil20 )) hasil5=$((nil21 + nil22 + nil23 + nil24 + nil25 )) hasil6=$((nil26 + nil27 + nil28 + nil29 + nil30 )) hasil7=$((nil31 + nil32 + nil33 + nil34 + nil35 )) hasil8=$((nil36 + nil37 + nil38 + nil39 + nil40 )) hasil9=$((nil41 + nil42 + nil43 + nil44 + nil45 )) hasil10=$((nil46 + nil47 + nil48 + nil49 + nil50 )) hasilA=$(($hasil1 + $hasil2 + $hasil3)) hasilB=$(($hasil4 + $hasil5 + $hasil6)) hasilC=$(($hasil7 + $hasil8 + $hasil9 + $hasil10)) hasil=$(($hasilA + $hasilB + $hasilC)) echo "Waktu di yang di selesaikan: " $waktu echo "Nilai anda dari menjawab \033[1;32mSoal Mudah\033[0m adalah \033[1;32m" $hasil "\033[0m"
JavaScript
UTF-8
8,617
2.578125
3
[ "MIT" ]
permissive
const {escapeshellarg, sprintf, trim, isset, is_string, is_array, is_int, in_array, to_array, array_key_exists, count, array_shift, array_unshift, substr, strpos, strlen, str_replace, preg_match, implode, stripcslashes} = require('../PhpPolyfill'); const forEach = require('lodash/forEach'); const InputArgument = require('../input/InputArgument'); const InputDefinition = require('../input/InputDefinition'); const InputOption = require('../input/InputOption'); class Command { static get defaultName() { //return this.prototype.constructor.name; return null; } constructor(name = null) { this.application = null; this.name = name || this.constructor.getFallbackName() || null; this.processTitle = null; this.aliases = []; this.hidden = false; this.help = ''; this.description = ''; this._ignoreValidationErrors = false; this.applicationDefinitionMerged = false; this.applicationDefinitionMergedWithArgs = false; this.code = null; this.synopsis = []; this.usages = []; this.helperSet = null; this.definition = new InputDefinition(); this.configure(); } static getFallbackName() { //let class = \get_called_class(); //r = new \ReflectionProperty(class, 'fallbackName'); return this.defaultName || null; } ignoreValidationErrors() { this._ignoreValidationErrors = true; } setApplication(application = null) { this.application = application; if (application) { this.setHelperSet(application.getHelperSet()); } else { this.helperSet = null; } } setHelperSet(helperSet) { this.helperSet = helperSet; } getHelperSet() { return this.helperSet; } getApplication() { return this.application; } isEnabled() { return true; } configure() { } /** * Executes the current command + * * This method is not abstract because you can use this class * as a concrete class + In this case, instead of defining the * execute() method, you set the code to execute by passing * a Closure to the setCode() method + * * @return int 0 if everything went fine, or an exit code * * @throws Error When this abstract method is not implemented * * @see setCode() */ execute(input, output) { throw new Error('You must override the execute() method in the concrete command class.'); } async interact (input, output) { } /** * Initializes the command after the input has been bound and before the input * is validated + * * This is mainly useful when a lot of commands extends one main command * where some things need to be initialized based on the input arguments and options + * * @see InputInterface.bind() * @see InputInterface.validate() */ initialize(InputInterface, input, output) { } async run(input, output) { // force the creation of the synopsis before the merge with the app definition this.getSynopsis(true); this.getSynopsis(false); // add the application arguments and options this.mergeApplicationDefinition(); // bind the input against the command specific arguments/options try { input.bind(this.definition); } catch (e) { if (!this._ignoreValidationErrors) { throw e; } } this.initialize(input, output); if (null !== this.processTitle) { process.title = this.processTitle; } if (input.isInteractive()) { await this.interact(input, output); } // The command name argument is often omitted when a command is executed directly with its run() method + // It would fail the validation if we didn't make sure the command argument is present, // since it's required by the application + if (input.hasArgument('command') && null === input.getArgument('command')) { input.setArgument('command', this.getName()); } input.validate(); let statusCode = null; if (this.code) { statusCode = await (this.code)(input, output); } else { statusCode = await this.execute(input, output); if (!is_int(statusCode)) { throw new Error(sprintf('Return value of "%s.execute()" must be of the type int, %s returned.', this.constructor.name, typeof statusCode)); } } return is_int(statusCode) ? statusCode : 0; } setCode(code) { // ES6 const isBindable = func => func.hasOwnProperty('prototype'); if (code.bind) { code.bind(this); } this.code = code; return this; } mergeApplicationDefinition(mergeArgs = true) { if (null === this.application || (true === this.applicationDefinitionMerged && (this.applicationDefinitionMergedWithArgs || !mergeArgs))) { return; } this.definition.addOptions(this.application.getDefinition().getOptions()); this.applicationDefinitionMerged = true; if (mergeArgs) { let currentArguments = this.definition.getArguments(); this.definition.setArguments(this.application.getDefinition().getArguments()); this.definition.addArguments(currentArguments); this.applicationDefinitionMergedWithArgs = true; } } setDefinition(definition) { if (definition instanceof InputDefinition) { this.definition = definition; } else { this.definition.setDefinition(definition); } this.applicationDefinitionMerged = false; return this; } getDefinition() { if (null === this.definition) { throw new Error(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the super constructor.', this.prototype.constructor.name)); } return this.definition; } getNativeDefinition() { return this.getDefinition(); } addArgument(name, mode = null, description = '', fallback = null) { this.definition.addArgument(new InputArgument(name, mode, description, fallback)); return this; } addOption(name, shortcut = null, mode = null, description = '', fallback = null) { this.definition.addOption(new InputOption(name, shortcut, mode, description, fallback)); return this; } setName(name) { this.validateName(name); this.name = name; return this; } setProcessTitle(title) { this.processTitle = title; return this; } getName() { return this.name; } setHidden(hidden) { this.hidden = hidden; return this; } isHidden() { return this.hidden; } setDescription(description) { this.description = description; return this; } getDescription() { return this.description; } setHelp(help) { this.help = help; return this; } getHelp() { return this.help; } getProcessedHelp() { let name = this.name; let isSingleCommand = this.application && this.application.isSingleCommand(); let scriptPath = process.argv[1].replace(process.cwd() + "/", ""); // allow to override this path // for global commands if(this.getApplication().command){ scriptPath = this.getApplication().command } let placeholders = [ '%command.name%', '%command.full_name%', ]; let replacements = [ name, isSingleCommand ? scriptPath : scriptPath + ' ' + name, ]; return str_replace(placeholders, replacements, this.getHelp() || this.getDescription()); } setAliases(aliases) { forEach(aliases, (alias) => { this.validateName(alias); }); this.aliases = aliases; return this; } getAliases() { return this.aliases; } getSynopsis(short = false) { let key = short ? 'short' : 'long'; if (!isset(this.synopsis[key])) { this.synopsis[key] = trim(sprintf('%s %s', this.name, this.definition.getSynopsis(short))); } return this.synopsis[key]; } addUsage(usage) { if (0 !== strpos(usage, this.name)) { usage = sprintf('%s %s', this.name, usage); } this.usages.push(usage); return this; } getUsages() { return this.usages; } getHelper(name) { if (null === this.helperSet) { throw new Error(sprintf('Cannot retrieve helper "%s" because there is no HelperSet defined. Did you forget to add your command to the application or to set the application on the command using the setApplication() method? You can also set the HelperSet directly using the setHelperSet() method.', name)); } return this.helperSet.get(name); } validateName(name) { if (!name || !name.match(/^[^\:]+(\:[^\:]+)*$/)) { throw new Error(sprintf('Command name "%s" is invalid.', name)); } } } module.exports = Command;
Java
UTF-8
824
2.046875
2
[]
no_license
package com.sumy.gamestore.service; import java.time.LocalDate; import java.time.LocalDateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sumy.gamestore.controller.MyPageController; import com.sumy.gamestore.mapper.QuestionUserMapper; import com.sumy.gamestore.model.QuestionList; @Service public class QuestionUserService { @Autowired private QuestionUserMapper questionUserMapper; public int questionInsert(QuestionList question) { question.setQuestionWriteDate(LocalDateTime.now());//문의등록 시간 보여줌 question.setQuestionAnswerYn(0);//문의등록 응답여부 question.setQuestionReadYn(0);//문의등록 확인여부 System.out.println(question); return questionUserMapper.insertQuestion(question); } }
PHP
UTF-8
32,367
2.828125
3
[]
no_license
<?php //Set the view as a new stdClass $view = new stdClass(); //Set up the page's title $view->pageTitle = 'GPS Page'; //Require from the huntListing class require('Models/class.huntListing.php'); //Require from the updateListing class require_once('Models/class.updateListing.php'); //Require the sessions class require_once('Models/class.sessions.php'); //Create a new session $session = new Session(); //Assign a local variable storing the session's id value $view->sessionID = $session->getSession('id'); //Assign a local variable storing the session's username value $view->sessionUsername = $session->getSession('username'); //Assign a local variable storing the session's user status value $view->sessionUserStatus = $session->getSession('status'); //Assign a value for the session's user avatar $view->sessionAvatar = $session->getSession('userAvatar'); //Set up an empty variable for the next clue to be discovered $view->nextClue = ''; //Create a local huntListing instance $view->huntObject = new HuntListing(); //Create a new updateListing instance $view->updateList = new UpdateListing(); //Create a method for displaying the rough location for the next clue $view->nextClueLocation = ''; //Set up a variable for getting a possible latitude session $view->latitude = $session->getSession('latitude'); //Set up a variable for getting a possible longitude session $view->longitude = $session->getSession('longitude'); //Set up a variable for getting a possible accuracy session $view->accuracy = $session->getSession('accuracy'); //Create an array for storing user sessions needed to pinpoint all logged on user locations on the GPS $view->sessionList = array(); //Create a 1st array for storing default path clue related values $view->table1 = array(); //Create a 2nd array for storing alternate path 1 clue related values $view->table2 = array(); //Create a 3rd array for storing alternate path 2 clue related values $view->table3 = array(); //If the "goToGPSPage/submit" button from the huntClues.phtml page has been clicked if (isset($_POST['goToGPSPage'])) { //Set the local hunt ID as a local variable, holding the same value as the posted object's huntID field $localHuntID = $_POST['huntID']; //Call the hunt object's fetchById method by passing it the hunt ID variable's value, then assign to a "huntFound" variable $huntFound = $view->huntObject->fetchById($localHuntID); //Get the return value from the fetchById method, then convert it into a new Hunt instance $hunt = new Hunt($huntFound); //Require from the updateListing class require_once ('Models/class.updateListing.php'); //Create an instance of the updateListing class $updateObject = new UpdateListing(); //Get all updates belonging to the user by calling the userListing class' fetchUpdatesByID method and passing it the user's session ID value $userUpdates = $updateObject->fetchUpdatesByID($view->sessionID); //Create the page's variable for handling the default path's next clue location and give it a default value of clue 1's location $view->nextClueLocation = $hunt->getClue1Location(); //Create the page's variable for handling alternate path 1's next clue location and give it a default value of the path's clue 1's location $view->nextClueLocation2 = ""; //If there is a return value from the hunt object's getAltClue1Location method if ($hunt->getAltClue1Location() != null) { //Assign the value of altClue1Location to the local nextClueLocation2 variable $view->nextClueLocation2 = $hunt->getAltClue1Location(); //If there is a return value from the hunt object's getAltClue2Location method } else if ($hunt->getAltClue2Location() != null) { //Assign the value of altClue2Location to the local nextClueLocation2 variable $view->nextClueLocation2 = $hunt->getAltClue2Location(); //If there is a return value from the hunt object's getAltClue3Location method } else if ($hunt->getAltClue3Location() != null) { //Assign the value of altClue3Location to the local nextClueLocation2 variable $view->nextClueLocation2 = $hunt->getAltClue3Location(); //If there is a return value from the hunt object's getAltClue4Location method } else if ($hunt->getAltClue4Location() != null) { //Assign the value of altClue4Location to the local nextClueLocation2 variable $view->nextClueLocation2 = $hunt->getAltClue4Location(); //If there is a return value from the hunt object's getAltClue5Location method } else if ($hunt->getAltClue5Location() != null) { //Assign the value of altClue5Location to the local nextClueLocation2 variable $view->nextClueLocation2 = $hunt->getAltClue5Location(); //If there is a return value from the hunt object's getAltClue6Location method } else if ($hunt->getAltClue6Location() != null) { //Assign the value of altClue6Location to the local nextClueLocation2 variable $view->nextClueLocation2 = $hunt->getAltClue6Location(); //If there is a return value from the hunt object's getAltClue7Location method } else if ($hunt->getAltClue7Location() != null) { //Assign the value of altClue7Location to the local nextClueLocation2 variable $view->nextClueLocation2 = $hunt->getAltClue7Location(); } //Create the page's variable for handling alternate path 2's next clue location and give it a default value of the path's clue 1's location $view->nextClueLocation3 = ""; //If there is a return value from the hunt object's getAlt2Clue1Location method if ($hunt->getAltClue1Location() != null) { //Assign the value of alt2Clue1Location to the local nextClueLocation3 variable $view->nextClueLocation3 = $hunt->getAlt2Clue1Location(); //If there is a return value from the hunt object's getAlt2Clue2Location method } else if ($hunt->getAltClue2Location() != null) { //Assign the value of alt2Clue2Location to the local nextClueLocation3 variable $view->nextClueLocation3 = $hunt->getAlt2Clue2Location(); //If there is a return value from the hunt object's getAlt2Clue3Location method } else if ($hunt->getAltClue3Location() != null) { //Assign the value of alt2Clue3Location to the local nextClueLocation3 variable $view->nextClueLocation3 = $hunt->getAlt2Clue3Location(); //If there is a return value from the hunt object's getAlt2Clue4Location method } else if ($hunt->getAltClue4Location() != null) { //Assign the value of alt2Clue4Location to the local nextClueLocation3 variable $view->nextClueLocation3 = $hunt->getAlt2Clue4Location(); //If there is a return value from the hunt object's getAlt2Clue5Location method } else if ($hunt->getAltClue5Location() != null) { //Assign the value of alt2Clue5Location to the local nextClueLocation3 variable $view->nextClueLocation3 = $hunt->getAlt2Clue5Location(); //If there is a return value from the hunt object's getAlt2Clue6Location method } else if ($hunt->getAltClue6Location() != null) { //Assign the value of alt2Clue6Location to the local nextClueLocation3 variable $view->nextClueLocation3 = $hunt->getAlt2Clue6Location(); //If there is a return value from the hunt object's getAlt2Clue7Location method } else if ($hunt->getAltClue7Location() != null) { //Assign the value of alt2Clue7Location to the local nextClueLocation3 variable $view->nextClueLocation3 = $hunt->getAlt2Clue7Location(); } //Add the clue 1 number to the table1 table $view->table1[] = "Clue 1"; //Add to the table1 array the value of the hunt's clue 1 $view->table1[] = $hunt->getClue1(); //Add to the table1 array the value of the hunt's clue 1 location $view->table1[] = $hunt->getClue1Location(); //If the default hunt path's clue 2 location is null if ($hunt->getClue2Location() == null) { //Do Nothing } else { //Add the clue 2 number to the table1 array $view->table1[] = "Clue 2"; //Add to the table1 array the value of the hunt's clue 2 $view->table1[] = $hunt->getClue2(); //Add to the table1 array the hunt's clue 2 location $view->table1[] = $hunt->getClue2Location(); } //If the default hunt path's clue 3 location is null if ($hunt->getClue3Location() == null) { //Do Nothing } else { //Add the clue 3 number to the table1 array $view->table1[] = "Clue 3"; //Add to the table1 array the value of the hunt's clue 3 $view->table1[] = $hunt->getClue3(); //Add to the table1 array the hunt's clue 3 location $view->table1[] = $hunt->getClue3Location(); } //If the default hunt path's clue 4 location is null if ($hunt->getClue4Location() == null) { //Do Nothing } else { //Add the clue 4 number to the table1 array $view->table1[] = "Clue 4"; //Add to the table1 array the value of the hunt's clue 4 $view->table1[] = $hunt->getClue4(); //Add to the table1 array the hunt's clue 4 location $view->table1[] = $hunt->getClue4Location(); } //If the default hunt path's clue 5 location is null if ($hunt->getClue5Location() == null) { //Do Nothing } else { //Add the clue 5 number to the table1 array $view->table1[] = "Clue 5"; //Add to the table1 array the value of the hunt's clue 5 $view->table1[] = $hunt->getClue5(); //Add to the table1 array the hunt's clue 5 location $view->table1[] = $hunt->getClue5Location(); } //If the default hunt path's clue 6 location is null if ($hunt->getClue6Location() == null) { //Do Nothing } else { //Add the clue 6 number to the table1 array $view->table1[] = "Clue 6"; //Add to the table1 array the value of the hunt's clue 6 $view->table1[] = $hunt->getClue6(); //Add to the table1 array the hunt's clue 6 location $view->table1[] = $hunt->getClue6Location(); } //If the default hunt path's clue 7 location is null if ($hunt->getClue7Location() == null) { //Do Nothing } else { //Add the clue 7 number to the table1 array $view->table1[] = "Clue 7"; //Add to the table1 array the value of the hunt's clue 7 $view->table1[] = $hunt->getClue7(); //Add to the table1 array the hunt's clue 7 location $view->table1[] = $hunt->getClue7Location(); } //Create the next entry in table1 as End Loop, which acts as a stop and leads to the hunt finish $view->table1[] = "End Loop"; //If the alternate hunt path 1's clue 1 location is null if ($hunt->getAltClue1Location() == null) { //Do Nothing } else { //Add the alt path 1 clue 1 number to the table2 array $view->table2[] = "Alternative Path 1 Clue 1"; //Add to the table2 array the value of the hunt's alt 1 clue 1 $view->table2[] = $hunt->getAltClue1(); //Add to the table2 array the hunt's alt 1 clue 1 location $view->table2[] = $hunt->getAltClue1Location(); } //If the alternate hunt path 1's clue 2 location is null if ($hunt->getAltClue2Location() == null) { //Do Nothing } else { //Add the alt path 1 clue 2 number to the table2 array $view->table2[] = "Alternative Path 1 Clue 2"; //Add to the table2 array the value of the hunt's alt 1 clue 2 $view->table2[] = $hunt->getAltClue2(); //Add to the table2 array the hunt's alt 1 clue 2 location $view->table2[] = $hunt->getAltClue2Location(); } //If the alternate hunt path 1's clue 3 location is null if ($hunt->getAltClue3Location() == null) { //Do Nothing } else { //Add the alt path 1 clue 3 number to the table2 array $view->table2[] = "Alternative Path 1 Clue 3"; //Add to the table2 array the value of the hunt's alt 1 clue 3 $view->table2[] = $hunt->getAltClue3(); //Add to the table2 array the hunt's alt 1 clue 3 location $view->table2[] = $hunt->getAltClue3Location(); } //If the alternate hunt path 1's clue 4 location is null if ($hunt->getAltClue4Location() == null) { //Do Nothing } else { //Add the alt path 1 clue 4 number to the table2 array $view->table2[] = "Alternative Path 1 Clue 4"; //Add to the table2 array the value of the hunt's alt 1 clue 4 $view->table2[] = $hunt->getAltClue4(); //Add to the table2 array the hunt's alt 1 clue 4 location $view->table2[] = $hunt->getAltClue4Location(); } //If the alternate hunt path 1's clue 5 location is null if ($hunt->getAltClue5Location() == null) { //Do Nothing } else { //Add the alt path 1 clue 5 number to the table2 array $view->table2[] = "Alternative Path 1 Clue 5"; //Add to the table2 array the value of the hunt's alt 1 clue 5 $view->table2[] = $hunt->getAltClue5(); //Add to the table2 array the hunt's alt 1 clue 5 location $view->table2[] = $hunt->getAltClue5Location(); } //If the alternate hunt path 1's clue 6 location is null if ($hunt->getAltClue6Location() == null) { //Do Nothing } else { //Add the alt path 1 clue 6 number to the table2 array $view->table2[] = "Alternative Path 1 Clue 6"; //Add to the table2 array the value of the hunt's alt 1 clue 6 $view->table2[] = $hunt->getAltClue6(); //Add to the table2 array the hunt's alt 1 clue 6 location $view->table2[] = $hunt->getAltClue6Location(); } //If the alternate hunt path 1's clue 7 location is null if ($hunt->getAltClue7Location() == null) { //Do Nothing } else { //Add the alt path 1 clue 7 number to the table2 array $view->table2[] = "Alternative Path 1 Clue 7"; //Add to the table2 array the value of the hunt's alt 1 clue 7 $view->table2[] = $hunt->getAltClue7(); //Add to the table2 array the hunt's alt 1 clue 7 location $view->table2[] = $hunt->getAltClue7Location(); } //Create the next entry in table2 as End Loop, which acts as a stop and leads to the hunt finish $view->table2[] = "End Loop"; //If the alternate hunt path 2's clue 3 location is null if ($hunt->getAlt2Clue3Location() == null) { //Do Nothing } else { //Add the alt path 2 clue 1 number to the table3 array $view->table3[] = "Alternative Path 2 Clue 1"; //Add to the table3 array the value of the hunt's alt 2 clue 1 $view->table3[] = $hunt->getAlt2Clue1(); //Add to the table3 array the hunt's alt 2 clue 1 location $view->table3[] = $hunt->getAlt2Clue1Location(); } //If the alternate hunt path 2's clue 2 location is null if ($hunt->getAlt2Clue2Location() == null) { //Do Nothing } else { //Add the alt path 2 clue 2 number to the table3 array $view->table3[] = "Alternative Path 2 Clue 2"; //Add to the table3 array the value of the hunt's alt 2 clue 2 $view->table3[] = $hunt->getAlt2Clue2(); //Add to the table3 array the hunt's alt 2 clue 2 location $view->table3[] = $hunt->getAlt2Clue2Location(); } //If the alternate hunt path 2's clue 3 location is null if ($hunt->getAlt2Clue3Location() == null) { //Do Nothing } else { //Add the alt path 2 clue 3 number to the table3 array $view->table3[] = "Alternative Path 2 Clue 3"; //Add to the table3 array the value of the hunt's alt 2 clue 3 $view->table3[] = $hunt->getAlt2Clue3(); //Add to the table3 array the hunt's alt 2 clue 3 location $view->table3[] = $hunt->getAlt2Clue3Location(); } //If the alternate hunt path 2's clue 4 location is null if ($hunt->getAlt2Clue4Location() == null) { //Do Nothing } else { //Add the alt path 2 clue 4 number to the table3 array $view->table3[] = "Alternative Path 2 Clue 4"; //Add to the table3 array the value of the hunt's alt 2 clue 4 $view->table3[] = $hunt->getAlt2Clue4(); //Add to the table3 array the hunt's alt 2 clue 4 location $view->table3[] = $hunt->getAlt2Clue4Location(); } //If the alternate hunt path 2's clue 5 location is null if ($hunt->getAlt2Clue5Location() == null) { //Do Nothing } else { //Add the alt path 2 clue 5 number to the table3 array $view->table3[] = "Alternative Path 2 Clue 5"; //Add to the table3 array the value of the hunt's alt 2 clue 5 $view->table3[] = $hunt->getAlt2Clue5(); //Add to the table3 array the hunt's alt 2 clue 5 location $view->table3[] = $hunt->getAlt2Clue5Location(); } //If the alternate hunt path 2's clue 6 location is null if ($hunt->getAlt2Clue6Location() == null) { //Do Nothing } else { //Add the alt path 2 clue 6 number to the table3 array $view->table3[] = "Alternative Path 2 Clue 6"; //Add to the table3 array the value of the hunt's alt 2 clue 6 $view->table3[] = $hunt->getAlt2Clue6(); //Add to the table3 array the hunt's alt 2 clue 6 location $view->table3[] = $hunt->getAlt2Clue6Location(); } //If the alternate hunt path 2's clue 7 location is null if ($hunt->getAlt2Clue7Location() == null) { //Do Nothing } else { //Add the alt path 2 clue 7 number to the table3 array $view->table3[] = "Alternative Path 2 Clue 7"; //Add to the table3 array the value of the hunt's alt 2 clue 7 $view->table3[] = $hunt->getAlt2Clue7(); //Add to the table3 array the hunt's alt 2 clue 7 location $view->table3[] = $hunt->getAlt2Clue7Location(); } //Create the next entry in table3 as End Loop, which acts as a stop and leads to the hunt finish $view->table3[] = "End Loop"; //Create an interval value for scrolling through the table entries (3 at a time) to determine if each entry is a clue number, clue, clue location or "End Loop" stop $interval = 0; //Create a ticket value for the 1st table to scroll through each entry in the table $ticket1 = 0; //Create a ticket value for the 2nd table to scroll through each entry in the table $ticket2 = 0; //Create a ticket value for the 3rd table to scroll through each entry in the table $ticket3 = 0; //Create variables for storing clue number values in each table $clueNo = ""; $clueNo2 = ""; $clueNo3 = ""; //Create variables for storing clue values in each table $clue = ""; $clue2 = ""; $clue3 = ""; //Create variables for storing clue location values in each table $clueLoc = ""; $clueLoc2 = ""; $clueLoc3 = ""; //For every entry stored in the table for the default path foreach ($view->table1 as $tab1){ //If the entry value does not equal "End Loop" if ($tab1 != "End Loop") { //If the interval value equals 0 (entry is a clue number) if ($interval == 0) { //Assign the clue number value with the same as the table entry $clueNo = $tab1; //Increment the ticket by one $ticket1 = $ticket1 + 1; //Set the interval value as 1, ready to count the next table entry as a clue $interval = 1; //If the interval value equals 1 (is a clue) } else if ($interval == 1) { //Assign the clue value so that it is the same as the table entry $clue = $tab1; //Increment the ticket value by 1 $ticket1 = $ticket1 + 1; //Set the interval value as 2, ready to count the next table entry as a clue location $interval = 2; //If the interval value is 2 (table entry is a clue location) } else if ($interval == 2) { //Assign the clue location so that it stores the same value as the table entry $clueLoc = $tab1; //For each entry in the userUpdates array foreach ($userUpdates as $update) { //If the update's getUpdateContent value matches the followign String if ($update->getUpdateContent() == "You have found ".$clueNo." of ".$hunt->getHuntName().": ".$clue) { //If the table entry after the current one equals "End Loop" if ($view->table1[($ticket1 + 1)] == "End Loop") { //Set the main clue location as the hunt finish location $view->nextClueLocation = $hunt->getHuntFinishLocation(); //If the next entry in the table is a clue number instead of "End Loop" } else { //Set up the next clue location as the next clue location $view->nextClueLocation = $clueLoc; } } else { //Do Nothing } } //Increment the ticket value by 1 $ticket1 = $ticket1 + 1; //Return the interval value back to 0 $interval = 0; //Set the clue no value back to null $clueNo = ""; //Set the clue value back to null $clue = ""; //Set the clue location value back to null $clueLoc = ""; } //Otherwise, if the current table entry does equal "End Loop" } else if ($tab1 == "End Loop") { //Do Nothing } } //For every entry in the table2 table foreach ($view->table2 as $tab2) { //If the entry value does not equal "End Loop" if ($tab2 != "End Loop") { //If the interval value equals 0 (entry is a clue number) if ($interval == 0) { //Assign the clue number value with the same as the table entry $clueNo2 = $tab2; //Increment the ticket by one $ticket2 = $ticket2 + 1; //Set the interval value as 1, ready to count the next table entry as a clue $interval = 1; //If the interval value equals 1 (is a clue) } else if ($interval == 1) { //Assign the clue value so that it is the same as the table entry $clue2 = $tab2; //Increment the ticket value by 1 $ticket2 = $ticket2 + 1; //Set the interval value as 2, ready to count the next table entry as a clue location $interval = 2; //If the interval value is 2 (table entry is a clue location) } else if ($interval == 2) { //Assign the clue location so that it stores the same value as the table entry $clueLoc2 = $tab2; //For each entry in the userUpdates array foreach ($userUpdates as $update) { //If the update's getUpdateContent value matches the followign String if ($update->getUpdateContent() == "You have found ".$clueNo2." of ".$hunt->getHuntName().": ".$clue2) { //If the table entry after the current one equals "End Loop" if ($view->table2[($ticket2 + 1)] == "End Loop") { //Set the main clue location as the hunt finish location $view->nextClueLocation2 = $hunt->getHuntFinishLocation(); //If the next entry in the table is a clue number instead of "End Loop" } else { //Set up the next clue location as the next clue location $view->nextClueLocation2 = $clueLoc2; } } else { //Do Nothing } } //Increment the ticket value by 1 $ticket2 = $ticket2 + 1; //Return the interval value back to 0 $interval = 0; //Set the clue no value back to null $clueNo2 = ""; //Set the clue value back to null $clue2 = ""; //Set the clue location value back to null $clueLoc2 = ""; } //Otherwise, if the current table entry does equal "End Loop" } else if ($tab2 == "End Loop") { //Do Nothing } } //For every entry in the table3 table foreach ($view->table3 as $tab3) { //If the entry value does not equal "End Loop" if ($tab3 != "End Loop") { //If the interval value equals 0 (entry is a clue number) if ($interval == 0) { //Assign the clue number value with the same as the table entry $clueNo3 = $tab3; //Increment the ticket by one $ticket3 = $ticket3 + 1; //Set the interval value as 1, ready to count the next table entry as a clue $interval = 1; //If the interval value equals 1 (is a clue) } else if ($interval == 1) { //Assign the clue value so that it is the same as the table entry $clue3 = $tab3; //Increment the ticket value by 1 $ticket3 = $ticket3 + 1; //Set the interval value as 2, ready to count the next table entry as a clue location $interval = 2; //If the interval value is 2 (table entry is a clue location) } else if ($interval == 2) { //Assign the clue location so that it stores the same value as the table entry $clueLoc3 = $tab3; //For each entry in the userUpdates array foreach ($userUpdates as $update) { //If the update's getUpdateContent value matches the followign String if ($update->getUpdateContent() == "You have found ".$clueNo3." of ".$hunt->getHuntName().": ".$clue3) { //If the table entry after the current one equals "End Loop" if ($view->table3[($ticket3 + 1)] == "End Loop") { //Set the main clue location as the hunt finish location $view->nextClueLocation3 = $hunt->getHuntFinishLocation(); //If the next entry in the table is a clue number instead of "End Loop" } else { //Set up the next clue location as the next clue location $view->nextClueLocation3 = $clueLoc3; } } else { //Do Nothing } } //Increment the ticket value by 1 $ticket3 = $ticket3 + 1; //Return the interval value back to 0 $interval = 0; //Set the clue no value back to null $clueNo3 = ""; //Set the clue value back to null $clue3 = ""; //Set the clue location value back to null $clueLoc3 = ""; } //Otherwise, if the current table entry does equal "End Loop" } else if ($tab3 == "End Loop") { //Do Nothing } } //Declare a value for storing the next clue location in order to be sent off to a google website for location processing $prepAddr = str_replace(' ','+',$view->nextClueLocation); //call the google website by passing the clue variable in it's URL $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false'); //Initialise the output so that we can extract the latitude and longitude from it $output= json_decode($geocode); //Extract the latitude and set as variable $view->clueLatitude = $output->results[0]->geometry->location->lat; //Extract the longitude and set as variable $view->clueLongitude = $output->results[0]->geometry->location->lng; //Declare a value for storing the next clue location in order to be sent off to a google website for location processing $prepAddr2 = str_replace(' ','+',$view->nextClueLocation2); //call the google website by passing the clue variable in it's URL $geocode2=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr2.'&sensor=false'); //Initialise the output so that we can extract the latitude and longitude from it $output2= json_decode($geocode2); //Extract the latitude and set as variable $view->clueLatitude2 = $output2->results[0]->geometry->location->lat; //Extract the longitude and set as variable $view->clueLongitude2 = $output2->results[0]->geometry->location->lng; //Declare a value for storing the next clue location in order to be sent off to a google website for location processing $prepAddr3 = str_replace(' ','+',$view->nextClueLocation3); //call the google website by passing the clue variable in it's URL $geocode3=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr3.'&sensor=false'); //Initialise the output so that we can extract the latitude and longitude from it $output3= json_decode($geocode3); //Extract the latitude and set as variable $view->clueLatitude3 = $output3->results[0]->geometry->location->lat; //Extract the longitude and set as variable $view->clueLongitude3 = $output3->results[0]->geometry->location->lng; //Create a variable storing the path to the directory where the session files are stored $path = session_save_path(); //If the session path exists if (strpos($path, ";") !== FALSE) { //Define the path variable as such $path = substr($path, strpos($path, ";")+1); } //For each file in the directory that begins with "sess_" (session files) foreach (glob("".$path."\sess_*") as $sessFile) { //Store the file's contents in a string variable $scanSessFile = file_get_contents($sessFile); //If the first two characters equal "id" (if this is an active session) if (substr($scanSessFile, 0, 2 ) === "id") { //Divide the string into an array and store in a "words" variable $words = explode('";', $scanSessFile); //Declare a variable for temporarily storing a username variable $tempUsername = ""; //For each word in the words array foreach ($words as $word) { //If the first 8 characters make up "username" if (substr($word, 0, 8 ) === 'username' ) { //Have the temp username variable store the username value $tempUsername = substr($word, strrpos($word, '"') + 1, strlen($word)); //If the first 8 characters make up "latitude" } else if (substr($word, 0, 8 ) === 'latitude') { //Add the latitude value into the sessionList array $view->sessionList[] = substr($word, strrpos($word, '"') + 1, strlen($word)); //If the first 9 characters make up "longitude" } else if (substr($word, 0, 9 ) === 'longitude') { //Add the longitude calue into the sessionList array $view->sessionList[] = substr($word, strrpos($word, '"') + 1, strlen($word)); //Add the temp username value in the sessionList array $view->sessionList[] = $tempUsername; } } } } } require_once('Views/gpsPage.phtml');
Java
UTF-8
622
2.265625
2
[]
no_license
package com.residencia.dell.services; import com.residencia.dell.entities.Customers; import com.residencia.dell.repositories.CustomersRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CustomerService { @Autowired private CustomersRepository customersRepository; //Create customer public Customers create (Customers customer){ return customersRepository.save(customer); } //Find by ID public Customers findById(Integer id) { return customersRepository.findById(id).get(); } }
Python
UTF-8
219
2.828125
3
[]
no_license
from tkinter import * root=Tk() def hello(): print('hello!') menubar=Menu(root) filememu=Menu(menubar,tearoff=0) filemenu.add_command(label='打开',command=hello) filemenu.add_command(label='保存',command=hello)
Python
UTF-8
600
3.078125
3
[]
no_license
class Solution: def merge(self, nums1, m: int, nums2, n: int) -> None: i = 0 j = 0 end = len(nums1) - 1 # compare items from the end of nums1 and nums2,put max item to the end of nums1 while end >= 0: if j == n or i < m and j < n and nums1[m-i-1] > nums2[n-j-1]: nums1[end] = nums1[m-i-1] i += 1 elif i == m or i < m and j < n and nums1[m-i-1] <= nums2[n-j-1]: nums1[end] = nums2[n - j - 1] j += 1 end -= 1 s1 = set([1,2,3]) s2 = set([1,2]) print(s1 | s2)
Rust
UTF-8
829
3
3
[ "MIT" ]
permissive
use serde::Deserialize; use std::error::Error; use std::process::{Command, Output}; #[derive(Debug, Deserialize)] struct RunFile { cmd: Vec<Cmd>, } #[derive(Debug, Deserialize)] struct Cmd { name: String, bin: String, args: String, } pub fn run(command: &str) -> Result<Output, Box<dyn Error>> { let runfile: RunFile = toml::from_str( include_str!("../../runfiles/example.toml") )?; match runfile.cmd.iter().find(|&c| c.name == command) { Some(cmd) => Ok(Command::new(&cmd.bin) .args(cmd.args.split_whitespace()) .output()?), None => Err(format!("`{}` not found in runfile", command).into()), } } // TODO: // Make tests D: /* #[cfg(test)] mod tests { use super::*; #[test] fn floops_n_bloops() { assert!(true); } } */
C++
UTF-8
1,073
2.5625
3
[]
no_license
#include <string> #include <iostream> #include <vector> #include <map> #include <set> #include <assert.h> #include <algorithm> #include <queue> using namespace std; int main() { int n; cin >> n; vector<long long> a; vector<long long> b; for (int i = 0; i < n; i++) { long long x; cin >> x; a.push_back(x); } sort(a.begin(), a.end()); long long count = 0; long long last = -n * 2; for (int i = 0; i < n; i++) { b.push_back(count); if (a[i] > last + n) { count += n; last = a[i] + n; } else { count += a[i] + n - last; last = a[i] + n; } } for (int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; for (int i = 0; i < n; i++) { cout << b[i] << " "; } cout << endl; // int q; // cin >> q; // for (int i = 0; i < q; i++) { // long long l,r; // cin >> l >> r; // long long res; // cout << res << " "; // } return 0; }
C#
UTF-8
981
2.671875
3
[]
no_license
using IdentityModel; using Microsoft.AspNetCore.Http; using System; namespace Messaging.API.Services { public class IdentityService : IIdentityService { private IHttpContextAccessor _context; public IdentityService(IHttpContextAccessor context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Guid GetUserId() { var idClaim = _context.HttpContext.User.FindFirst(JwtClaimTypes.Subject); return !String.IsNullOrEmpty(idClaim.Value) ? Guid.Parse(idClaim.Value) : throw new ArgumentNullException("User id is null or empty"); } public string GetUserName() { var userNameClaim = _context.HttpContext.User.FindFirst(JwtClaimTypes.PreferredUserName); return !String.IsNullOrEmpty(userNameClaim.Value) ? userNameClaim.Value : throw new ArgumentNullException("Username is null or empty"); } } }
Java
UTF-8
1,254
2.9375
3
[]
no_license
import java.text.SimpleDateFormat; import java.util.Date; public class Match implements Comparable<Match> { Date matchDate; String teamOne; String teamTwo; public Date getMatchDate() { return matchDate; } public void setMatchDate(Date matchDate) { this.matchDate = matchDate; } public String getTeamOne() { return teamOne; } public void setTeamOne(String teamOne) { this.teamOne = teamOne; } public String getTeamTwo() { return teamTwo; } public void setTeamTwo(String teamTwo) { this.teamTwo = teamTwo; } public Match(Date matchDate, String teamOne, String teamTwo) { super(); this.matchDate = matchDate; this.teamOne = teamOne; this.teamTwo = teamTwo; } public int compareTo(Match mat) { if(this.getMatchDate().getTime()==mat.getMatchDate().getTime()) return 0; else if(this.getMatchDate().getTime()>mat.getMatchDate().getTime()) return 1; else return -1; } @Override public String toString() { SimpleDateFormat sdf= new SimpleDateFormat("MM-dd-yyyy"); String s=sdf.format(this.getMatchDate()); String d=("Team 1 "+this.getTeamOne()+"\nTeam 2 "+this.getTeamTwo()+"\nMatch held on "+s); return d; } }
JavaScript
UTF-8
623
3.625
4
[]
no_license
/* 元素和大于target的最短连续子序列 滑动窗口法 每轮循环 都将当前值加到sum上 sum>target 则记录一次最小长度 同时减去左边框 左边框+1 循环判断sum* */ function minSubArrayLen(arr, target) { // 左边框 let i = 0; let sum = 0; let len = arr.length; let flag = false for (let j = 0; j < arr.length; j++) { sum = sum + arr[j]; while (sum >= target) { flag = true len = Math.min(len, j - i + 1); sum = sum - arr[i]; i++; } } return flag?len:0 } console.log(minSubArrayLen([1,2,3,4,5],15))
JavaScript
UTF-8
2,255
3.421875
3
[]
no_license
function checkForm() { // Reset the background colour to white on each of the form elements // The element's ids are name, address, memtype, magrad and agreepar // Use document.getElementById("element-name").style.backgroundColor = "white"; var isFormOK = true; var errorString = "The following fields are incorrect"; // Check if the name field is blank var theElement = document.getElementById('name').value; if (theElement.length == 0) { errorString += '\n* Give your name'; document.getElementById("name").style.backgroundColor = "red"; isFormOK = false; } // Check if the address field is blank // Modify the code used for the name field // Check the magazine options // Get all the 'mag' elements from the first form on the field // Use: document.forms[the-first-one]['the-element-name'] // if (the-first-mag-element-is-not-checked && the-second-mag-element-is-not-checked) { // add to the error string (in the same way as for the name and address fields above) // set the background colour of the magrad element to red // set the validation boolean variable to false (as shown above, for the name element) // } // Check selected membership type is not the default // Get the value of the 'memtype' element using document.getElementById(...).value // if (the value of the memtype elemnent is not the default value of 'x') { // add another error message to the error message string // set the memtype element background colour to red // set the validation boolean variable to false // } // Check the agreed field has been checked // Get the 'agree' element // if (the agree element is not checked) { // add to the error string // set the agree element's backgroun colour to red // set the validation boolean variable to false // } // Check whether the form is valid. If not print the error message to the 'notes' element // if (the form is not OK) // set the notes element's inner HTML to '<pre>' + errorString + '</pre>'; // return the validation boolean } //end checkForm()
Java
UTF-8
2,256
2.375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 Higher Frequency Trading http://www.higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.map.fromdocs; import net.openhft.chronicle.map.ChronicleMapBuilder; import org.junit.Ignore; import org.junit.Test; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.Map; import static org.junit.Assert.assertEquals; /** * Created by peter on 28/02/14. */ public class GettingStartedTest { @Test @Ignore public void testTheCodeInGuide() throws IOException { String tmpdir = System.getProperty("java.io.tmpdir"); Map<String, String> map = ChronicleMapBuilder.of(String.class, String.class) .create(new File(tmpdir + "/shared.map")); map.put("some.json", "missing"); map.get("some.json"); map.put("Hello", "World"); String hi = map.get("Hello"); map.put("Long String", "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"); String json = "{\"menu\": {\n" + " \"id\": \"file\",\n" + " \"value\": \"File\",\n" + " \"popup\": {\n" + " \"menuitem\": [\n" + " {\"value\": \"New\", \"onclick\": \"CreateNew()\"},\n" + " {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n" + " {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n" + " ]\n" + " }\n" + "}}"; map.put("some.json", json); String s2 = map.get("some.json"); assertEquals(json, s2); ((Closeable) map).close(); } }
Java
UTF-8
1,435
2.875
3
[]
no_license
package resources; public class Operation { private String name; private int demand; private CircuitBreaker circuitBreaker; private Dependency[] dependencies; private int dependingOperationCount = 0; public Operation(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDemand() { return demand; } public void setDemand(int demand) { this.demand = demand; } public CircuitBreaker getCircuitBreaker() { return circuitBreaker; } public void setCircuitBreaker(CircuitBreaker circuitBreaker) { this.circuitBreaker = circuitBreaker; } public Dependency[] getDependencies() { return dependencies; } public void setDependencies(Dependency[] dependencies) { this.dependencies = dependencies; } public int getDependingOperationCount() { return dependingOperationCount; } public void setDependingOperationCount(int dependingOperationCount) { this.dependingOperationCount = dependingOperationCount; } public void increaseDependingOperationCount() { this.dependingOperationCount++; } public boolean hasCircuitBreaker() { if (circuitBreaker != null) { return true; } return false; } }
Python
UTF-8
400
3.421875
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- def main(): """ Для целого числа, если в нем больше трех разрядов, используйте пробел, чтобы сгруппировать разряды по 3. """ # Code goes over here. print("{:,}".format(int(input())).replace(',', ' ')) return 0 if __name__ == "__main__": main()
JavaScript
UTF-8
7,114
2.796875
3
[ "MIT" ]
permissive
export const arr = [ { language: "node", title: 'start', code: `npm install --save-dev jest babel-jest /* Add to package.json */ "scripts": { "test": "jest" } # Run your tests npm test -- --watch` },{ language: 'javascript', title: 'enzyme', code: `import React from 'react' import App from './App' import Enzyme, { shallow } from 'enzyme' import Adapter from 'enzyme-adapter-react-16' // install Enzyme Enzyme.configure({ adapter: new Adapter() })` },{ language: 'javascript', title: 'test 2+2', code: `// simple test test('first test', () => { expect(2 + 2).toBe(4); })` },{ language: 'javascript', title: 'describe', code: `describe('My work', () => { test('works', () => { expect(2).toEqual(2) }) })` },{ language: 'javascript', title: 'with enzyme', code: `test('first with enzume', () => { //render App (without Error!) const wrapper = shallow(<App></App>); //DOM in terminal console.log(wrapper.debug()); //wrapper not '' || null || undefinet expect(wrapper).toBeTruthy() })` },{ language: 'javascript', title: 'setup', code: `/** * 17 * Facroty function to create s ShallowWrapper for the App component.l * @function setup * @param {object} props - Component props specific to this setup. * @param {object} state - inimial state for setup. * @returns {shallowWrapper} */ const setup = (props={}, state=null) => { // 19 const wrapper = shallow(<App {...props} />) if (state) wrapper.setState(state) return wrapper }` },{ language: 'javascript', title: 'findByTestAttr', code: `/** * Return ShallowWrapper containing node(s) with the given data-test * @param {ShallowWrapper} wrapper - Enzyme shallow wrapper to seacrch * @param {string} val - Value of data-test attribute for search. * @returns {ShallowWrapper} */ const findByTestAttr = (wraper, val) => { return wraper.find(\`[data-test="$\{val}"]\`) }` },{ language: 'javascript', title: 'find data-test atr', code: ` // 1) ловимо <App /> 2) ловимо [data-test="hello"] 3) к-сть = 1 test('renders without error', () => { const wraper = setup(); const appComponent = findByTestAttr(wraper, 'hello'); expect(appComponent.length).toBe(1); });` },{ language: 'javascript', title: 'state === ?', code: `// провіряєм чи каунтер = 0 test('counter start at 0', () => { const wrapper = setup(); const initialState = wrapper.state('counter'); expect(initialState).toBe(0) })` },{ language: 'javascript', title: 'button', code: `//провірка роботи кнопки test('clicking button increments counter display', () => { const counter = 7; const wrapper = setup(null, { counter }); // знаходимо кнопку, стимулюємо клік, обновляємо const button = findByTestAttr(wrapper, 'my'); button.simulate('click'); wrapper.update(); //знаходимо h1, провіряємо чи є каунтер + 1 const counterDisplay = findByTestAttr(wrapper, 'test'); expect(counterDisplay.text()).toContain(counter + 1) })` },{ language: 'javascript', title: 'setup width defaultProps', code: `const defaultProps = { seccess: false } /** * factorry function to create shallowWrapper for the Jotto * @function setup * @param {object} props - Component props specific to this setup. * @returns {shallowWrapper} */ const setup = (props = {}) => { // 31 for default props const setupProps = { ...defaultProps, ...props } return shallow(<Jotto {...setupProps} />) }` },{ language: 'javascript', title: 'test with props', code: `test('renders no test when success prop is folse', () => { const wrapper = setup({ success: false }) const jottoComponent = findByTestAttr(wrapper, 'jotto-component') expect(jottoComponent.text()).toBe('') }) test('renders non-empty congrats message when success prop is true', () => { const wrapper = setup({ success: true }) const jottoComponent = findByTestAttr(wrapper, 'jotto-component') expect(jottoComponent.text()).not.toBe(0) })` },{ language: 'javascript', title: 'checkProps', code: `import checkPropTypes from 'check-prop-types' /** * 29 prop-types * Check component prop-types for to be undefined. * @function * @param {shallowWrapper} component * @param {string} conformingProps */ export const checkProps = (componet, conformingProps) => { const propError = checkPropTypes( componet.propTypes, conformingProps, 'prop', componet.name) expect(propError).toBeUndefined() }` },{ language: 'javascript', title: 'test for propTypes', code: `test('does not throw warning with expected props', () => { const expectedProps = { success: false } checkProps(Jotto, expectedProps) })` },{ language: 'javascript', title: '--------------------------------------------------------------------------------------------------', code: `` },{ language: 'javascript', title: 'beforeEach', code: `describe('if there are no words guessed', () => { // 39 beforeEach put wrapper in evry test() let wrapper beforeEach(() => { wrapper = setup({ guessedWords: [] }) }) test('renders without error', () => { const component = findByTestAttr(wrapper, 'componet-gues-word') expect(component.length).toBe(1) }) test('renders instructions to guess aword', () => { const instrunctions = findByTestAttr(wrapper, 'guess-instruction') expect(instrunctions.text().length).not.toBe(0) }) })` },{ language: 'javascript', title: 'beforeEach 2', code: `describe('if there are words guessed', () => { let wrapper let guessedWords = [ { guessedWords: 'train', letterMaitchCount: 3 }, { guessedWords: 'agile', letterMaitchCount: 1 }, { guessedWords: 'party', letterMaitchCount: 5 } ] beforeEach(() => { wrapper = setup({ guessedWords }) }) test('correct number of guessed words', () => { const guessedWordNodes = findByTestAttr(wrapper, 'guessed-word') expect(guessedWordNodes.length).toBe(guessedWords.length) }) })` },{ language: 'javascript', title: '-------------------------------------------------------------------------------------------------------', code: `` },{ language: 'javascript', title: 'actions', code: `import { correctGuess, actionTypes } from './' describe('correctGuess', () => { // 48 test actions test('returns an action with type \`CORRECT_GUESS\`', () => { const action = correctGuess() expect(action).toEqual({ type: actionTypes.CORRECT_GUESS }) }) })` },{ language: 'javascript', title: 'reducer', code: `import { actionTypes } from '../actions/index' import successReducer from './successReducer' // 49 50 test reducer test('returns default initial atate of \`false\` when no scton is passed', () => { // console.log(successReducer) const newState = successReducer(undefined, {}) expect(newState).toBe(false) }) test('returns state of true upon receiving an action of type \`CORRECT_GUESS\`', () => { const newState = successReducer(undefined, { type: actionTypes.CORRECT_GUESS }) expect(newState).toBe(true) })` } ]
Shell
UTF-8
1,277
3.71875
4
[]
no_license
set -e # Feel free to change any of the following variables for your app: APP_ROOT=/home/deployer/apps/deploytestp/ CMD="cd $APP_ROOT/current; bundle exec puma -C $APP_ROOT/shared/config/puma.rb -b unix://$APP_ROOT/shared/sockets/puma.sock -e production --control unix://$APP_ROOT/shared/sockets/pumactl.sock --state $APP_ROOT/shared/sockets/puma.state --pidfile $APP_ROOT/shared/pids/puma.pid 2>&1 >> $APP_ROOT/shared/log/puma.log &" CTL="cd $APP_ROOT/current; bundle exec pumactl -S $APP_ROOT/shared/sockets/puma.state" AS_USER=deployer set -u run () { if [ "$(id -un)" = "$AS_USER" ]; then eval $1 else su -c "$1" - $AS_USER fi } case "$1" in start) if [ ! -e "$APP_ROOT/shared/sockets/puma.sock" ] then run "$CMD" exit 1 else echo >&2 "Already running" fi ;; stop) [ -e "$APP_ROOT/shared/sockets/puma.sock" ] && run "$CTL stop" && exit 0 echo >&2 "Not running" ;; force-stop) [ -e "$APP_ROOT/shared/sockets/puma.sock" ] && run "$CTL halt" && exit 0 echo >&2 "Not running" ;; restart|reload) [ -e "$APP_ROOT/shared/sockets/puma.sock" ] && run "$CTL restart" && exit 0 echo >&2 "Couldn't reload, starting '$CMD' instead" run "$CMD" ;; *) echo >&2 "Usage: $0 <start|stop|restart|force-stop>" exit 1 ;; esac
Java
UTF-8
510
2.046875
2
[]
no_license
package com.brotherhui.tcc.order.model.request; import java.util.List; /** * @author xiaohui.c.liu * @create 2018-04-13 3:39 PM */ public class OrderRequest { private Integer amount; private List<OrderItemRequest> items; public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public List<OrderItemRequest> getItems() { return items; } public void setItems(List<OrderItemRequest> items) { this.items = items; } }
Java
UTF-8
2,215
2.390625
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright © 2009 HotPads (admin@hotpads.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.datarouter.model.key.primary; import io.datarouter.model.key.unique.UniqueKey; import io.datarouter.model.serialize.fielder.PrimaryKeyFielder; /** * A primary key is an ordered set of fields that uniquely identify a Databean among others of the same type. It * corresponds to MySQL's primary key or a Memcached key. * * The PrimaryKey defines the hashCode(), equals() and compareTo() methods that distinguish databeans. The user should * generally not override these methods. They are based on the PK fields, in order, and allow java collections to mimic * the behavior of the underlying datastore. For example, adding a Databean to a TreeSet will insert it in the same * order that MySQL inserts it into the database. If the Databean already exists in the set, then calling * treeSet.put(databean) will overwrite the existing Databean in the set, similar to updating the Databean in the * database. * * Having a strongly-typed PrimaryKey defined for each table makes it easier to construct compound primary keys. PK * fields and their ordering is an important design decision for a large database table, and the PK class aims to * support compound primary keys without adding more work down the line for comparison, SQL generation, etc. * * To keep the application portable, avoid relying on the underlying datastore's automatic id generation. Unless you * need incrementing primary keys, it's usually more flexible to generate random IDs or rely on dedicated ID generator. */ public interface PrimaryKey<PK extends PrimaryKey<PK>> extends UniqueKey<PK>, PrimaryKeyFielder<PK>{ }
Java
UTF-8
308
1.75
2
[ "MIT" ]
permissive
package com.alibaba.sentinel.feign.controller; import org.springframework.web.bind.annotation.*; /** * @author Lion Li */ @RestController public class TestController { @PostMapping("/test") public String test(@RequestParam("name") String name) { return "服务提供端::返回值 => " + name; } }
Markdown
UTF-8
593
2.875
3
[]
no_license
## Question 3 React Competency Test Build a react app that calls an api and renders a random beer. You can use create-react-app or gatsby or any other starter template. The api to use is the one you built in Question 2. The requirements for this app are, 1. Display all fields from the api in your UI, 2. Have a “Next” button to fetch a new random beer and display data on the UI, 3. Initial render when there is no beer should show a loading icon, ## How to run 1. run command `yarn install` 2. run command `yarn start` to start application 3. access web browser `http://localhost:3000`
C#
UTF-8
318
3.515625
4
[]
no_license
string[] strNums = {"111","32","33","545","1","" ,"23",null}; var nums = strNums.Where( s => { int result; return !string.IsNullOrEmpty(s) && int.TryParse(s,out result); } ) .Select(s => int.Parse(s)) .OrderBy(n => n); foreach(int num in nums) { Console.WriteLine(num); }
JavaScript
UTF-8
3,020
2.8125
3
[]
no_license
var about = document.getElementById("about"); var contact = document.getElementById("contact"); var contact_item = document.getElementById("contact-item"); var breadcrumbs = document.getElementById("breadcrumbs"); var mob_contact_item = document.getElementById("mob-contact-item"); var mob_contact = document.getElementById("mob-contact"); var mob_about = document.getElementById("mob-about"); var mob_projects = document.getElementById("mob-projects"); var mob_breadcrumbs = document.getElementById("mob-breadcrumbs"); function setTheme() { var today = new Date(); var t = today.getHours(); let root = document.documentElement; if (t > 5 && t < 19) { console.log("🌞") root.style.setProperty('--color', 'black'); root.style.setProperty('--bg-color', 'white'); } else { console.log("🌚") root.style.setProperty('--color', 'white'); root.style.setProperty('--bg-color', 'black'); } } setTheme(); setInterval(setTheme, 60000); function toContact() { breadcrumbs.innerText = "/contact" about.classList.add("hide"); contact.classList.remove("hide"); contact_item.classList.add("active"); } function toHome() { breadcrumbs.innerText = "" about.classList.remove("hide"); contact.classList.add("hide"); contact_item.classList.remove("active"); } function toMobContact() { mob_breadcrumbs.innerText = "/contact" mob_about.classList.add("hide"); mob_projects.classList.add("hide"); mob_contact.classList.remove("hide"); mob_contact_item.classList.add("active") } function toMobHome() { mob_breadcrumbs.innerText = "" mob_about.classList.remove("hide"); mob_projects.classList.remove("hide"); mob_contact.classList.add("hide"); mob_contact_item.classList.remove("active"); } console.log(` ██╗░░░██╗░██████╗███████╗██████╗░░█████╗░███████╗░░██╗██╗███████╗ ██║░░░██║██╔════╝██╔════╝██╔══██╗██╔══██╗╚════██║░██╔╝██║╚════██║ ██║░░░██║╚█████╗░█████╗░░██████╔╝╚██████║░░░░██╔╝██╔╝░██║░░░░██╔╝ ██║░░░██║░╚═══██╗██╔══╝░░██╔══██╗░╚═══██║░░░██╔╝░███████║░░░██╔╝░ ╚██████╔╝██████╔╝███████╗██║░░██║░█████╔╝░░██╔╝░░╚════██║░░██╔╝░░ ░╚═════╝░╚═════╝░╚══════╝╚═╝░░╚═╝░╚════╝░░░╚═╝░░░░░░░░╚═╝░░╚═╝░░░ `)
Shell
UTF-8
676
2.5625
3
[]
no_license
#!/bin/bash # Declare variables for certificate gen CERT_DIR="/usr/local/osmosix/cert" COUNTRY="US" STATE="PA" CITY="Pittsburgh" ORG="REQLAB" ORG_UNIT="Sales" COMMON_NAME="owncloud.threepings.com" # Prepare certificates for HTTPS sudo mkdir -p $CERT_DIR sudo openssl req -nodes -newkey rsa:2048 -keyout $CERT_DIR/private.key -out $CERT_DIR/CSR.csr -subj "/C=$COUNTRY/ST=$STATE/L=$CITY/O=$ORG/OU=$ORG_UNIT/CN=$COMMON_NAME" sudo openssl rsa -in $CERT_DIR/private.key -out $CERT_DIR/vm.cliqr.com.key sudo openssl x509 -in $CERT_DIR/CSR.csr -out $CERT_DIR/vm.cliqr.com.cert -req - signkey $CERT_DIR/vm.cliqr.com.key sudo cp $CERT_DIR/vm.cliqr.com.cert $CERT_DIR/vm.cliqr.com.crt
C++
UTF-8
481
3.75
4
[]
no_license
#include <iostream> using namespace std; /* Ingresar 5 numeros y contar cuantos son pares e impares. */ int main() { int num,cpar,cimpar; int conta=0; cpar=0;cimpar=0; while (conta<5) { cout<< "Ingrese el numero: " cout<<endl; cin>>num; conta++; if (num%2==0) cpar++; else cimpar++; } cout<<"Numeros pares: "<<cpar<<endl; cout<<"Numeros impares: "<<cimpar<<endl; }
Markdown
UTF-8
6,090
3.046875
3
[ "CC0-1.0" ]
permissive
--- title: '为你在 Bash 历史中执行过的每一项命令设置时间和日期' date: 2019-01-24 2:30:11 hidden: true slug: aspmydtljqn categories: [reprint] --- {{< raw >}} <h1><a href="#为你在-bash-历史中执行过的每一项命令设置时间和日期"></a>为你在 Bash 历史中执行过的每一项命令设置时间和日期</h1> <p>在默认情况下,所有通过 Bash 在命令行中执行过的命令都被存储在历史缓存区或者一个叫做 <code>~/.bash_history</code> 的文件里。这意味着系统管理员可以看到系统上用户执行过的命令清单,或者用户可以通过像 <a href="http://www.tecmint.com/history-command-examples/">history 命令</a>这样的选项来看他或她自己的命令历史。</p> <pre><code class="hljs shell"><span class="hljs-meta">$</span><span class="bash"> <span class="hljs-built_in">history</span></span> </code></pre><p><a href="http://www.tecmint.com/wp-content/uploads/2017/01/Linux-History-Command.png"><img src="https://p5.ssl.qhimg.com/t01e06e6469e940e11e.png" alt="Linux History Command"></a></p> <p><em>Linux 历史命令</em></p> <p>从上面 <a href="http://www.tecmint.com/history-command-examples/">history 命令</a>的输出可知,命令被执行的日期和时间并没有显示出来。基本上所有的 Linux 发行版的默认设置都是这样的。</p> <p>在这篇文章里,我们将解释当在 Bash 中执行 <code>history</code> 命令显示每个命令时,如何配置显示时间戳信息。</p> <p>每个命令相关的日期和时间可以记录到历史文件中,用 <code>HISTTIMEFORMAT</code> 环境变量的设置作为命令历史的备注记录。</p> <p>这里有两种可行的方式来达到目的:一种是暂时的效果,一种是永久的效果。</p> <p>要临时设置 <code>HISTTIMEFORMAT</code> 环境变量,在命令行这样输出它:</p> <pre><code class="hljs routeros">$ <span class="hljs-builtin-name">export</span> <span class="hljs-attribute">HISTTIMEFORMAT</span>=<span class="hljs-string">'%F %T'</span> </code></pre><p>在上面的输出命令当中,时间戳格式如下:</p> <p>1、<code>%F</code>-展开为完整日期,即 <code>%Y-%m-%d</code>(年-月-日)。</p> <p>2、<code>%T</code>-展开为时间,即 <code>%H:%M:%S</code>(时:分:秒)。</p> <p>通读 <a href="http://www.tecmint.com/sort-ls-output-by-last-modified-date-and-time/">date 命令</a>的 man 手册来获得更多使用说明:</p> <pre><code class="hljs shell"><span class="hljs-meta">$</span><span class="bash"> man date</span> </code></pre><p>然后如下检查你的命令历史:</p> <pre><code class="hljs shell"><span class="hljs-meta">$</span><span class="bash"> <span class="hljs-built_in">history</span> </span> </code></pre><p><a href="http://www.tecmint.com/wp-content/uploads/2017/01/Set-Date-and-Time-on-Linux-Commands-History.png"><img src="https://p3.ssl.qhimg.com/t010bfab9d8a35cc3af.png" alt="Display Linux Command History with Date and Time"></a></p> <p><em>显示带有日期和时间的 Linux 命令历史。</em></p> <p>(LCTT 译注:注意:这个功能只能用在当 HISTTIMEFORMAT 这个环境变量被设置之后,之后的那些新执行的 bash 命令才会被打上正确的时间戳。在此之前的所有命令,都将会显示成设置 HISTTIMEFORMAT 变量的时间。)</p> <p>然而,如果你想永久地配置该变量,用你最喜欢的编辑器打开文件 <code>~/.bashrc</code>。</p> <pre><code class="hljs shell"><span class="hljs-meta">$</span><span class="bash"> vi ~/.bashrc</span> </code></pre><p>然后在下方添加(用注释将其标记为你自己的配置):</p> <pre><code class="hljs routeros"><span class="hljs-comment"># 我的配置</span> <span class="hljs-builtin-name">export</span> <span class="hljs-attribute">HISTTIMEFORMAT</span>=<span class="hljs-string">'%F %T'</span> </code></pre><p>保存文件并退出,然后,运行下面的命令以便改动当即生效:</p> <pre><code class="hljs shell"><span class="hljs-meta">$</span><span class="bash"> <span class="hljs-built_in">source</span> ~/.bashrc</span> </code></pre><p>就是这些!请通过下方的评论区来与我们分享一些有趣的历史命令的小技巧以及你对这篇文章的想法。</p> <hr> <p>作者简介:</p> <p><a href="https://camo.githubusercontent.com/9bda718a074a10a458a4f2a719822c3e32d74ff1/687474703a2f2f312e67726176617461722e636f6d2f6176617461722f37626164646462633533323937623265386564373031316366343564663063303f733d31323826643d626c616e6b26723d67"><img src="https://p5.ssl.qhimg.com/t01ed9dfa925baac48b.jpg" alt=""></a></p> <p>我是 Ravi Saive,TecMint 的创建者。一个爱在网上分享的技巧和提示的电脑极客和 Linux 专家。我的大多数服务器运行在名为 Linux 的开源平台上。请在 Twitter、 Facebook 和 Google 等上关注我。</p> <hr> <p>via: <a href="http://www.tecmint.com/display-linux-command-history-with-date-and-time/">http://www.tecmint.com/display-linux-command-history-with-date-and-time/</a></p> <p>作者:<a href="http://www.tecmint.com/author/admin/">Ravi Saive</a> 译者:<a href="https://github.com/Hymantin">Hymantin</a> 校对:<a href="https://github.com/wxy">wxy</a></p> <p>本文由 <a href="https://github.com/LCTT/TranslateProject">LCTT</a> 原创编译,<a href="https://linux.cn/">Linux中国</a> 荣誉推出</p> {{< /raw >}} # 版权声明 本文资源来源互联网,仅供学习研究使用,版权归该资源的合法拥有者所有, 本文仅用于学习、研究和交流目的。转载请注明出处、完整链接以及原作者。 原作者若认为本站侵犯了您的版权,请联系我们,我们会立即删除! ## 原文标题 为你在 Bash 历史中执行过的每一项命令设置时间和日期 ## 原文链接 [https://www.zcfy.cc/article/set-date-and-time-for-each-command-you-execute-in-bash-history](https://www.zcfy.cc/article/set-date-and-time-for-each-command-you-execute-in-bash-history)
Java
UTF-8
23,814
1.867188
2
[]
no_license
package com.superdata.pm.activity.project.plan; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.suda.pm.ui.R; import com.superdata.pm.common.BaseActivity; import com.superdata.pm.config.InterfaceConfig; import com.superdata.pm.entity.entityplanpackage; import com.superdata.pm.service.SDHttpClient; import com.superdata.pm.view.AbstractSpinerAdapter.IOnItemSelectListener; import com.superdata.pm.view.CustemSpinerAdapter; import com.superdata.pm.view.SDProgressDialog; import com.superdata.pm.view.SpinerPopWindow; import com.superdata.pm.view.XListView; import com.superdata.pm.view.XListView.IXListViewListener; /** * 项目--》项目管理--》项目详细--》项目计划(工作包) * * @author kw * */ public class ProjectPlanPackageActivity extends BaseActivity implements IXListViewListener,OnClickListener { private ImageView btnBack; private TextView top_title; // 费用管理条目 private XListView listView; // 获取的是第几页的数据 private int pageNum = 1; // 获取的这页的数量 private int pageSize = 10; // Adapter里面放的List, private List<entityplanpackage> listplanpack = new ArrayList<entityplanpackage>(); // 临时的List,用于加载更多 的逻辑处理 private List<entityplanpackage> listplanpack1 = new ArrayList<entityplanpackage>(); private SDProgressDialog sdDialog; // 标识是否加载更多 private boolean flag = true; private boolean isLastPage = false; private MyAdapter adapter; private String id; entityplanpackage epp; SDHttpClient sdClient; String url = InterfaceConfig.PROJECT_Plan_Package_URL; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: listView.setAdapter(adapter); if (sdDialog.isShow()) { sdDialog.cancel(); } adapter.notifyDataSetChanged(); if (sdDialog.isShow()) { sdDialog.cancel(); } break; case 2: flag = true; listView.setAdapter(adapter); listView.setSelection(listplanpack.size() - pageSize); adapter.notifyDataSetChanged();// 数据变化刷新 if (sdDialog.isShow()) sdDialog.cancel(); onLoad(); break; case 3: onLoad(); Toast.makeText(getApplicationContext(), "已全部加载完成", Toast.LENGTH_SHORT).show(); break; case 5: Toast.makeText(getApplicationContext(), "暂无网络", 1).show(); if (sdDialog.isShow()) { sdDialog.cancel(); } break; case 6: Toast.makeText(getApplicationContext(), "暂时无法成功获取", 1).show(); if (sdDialog.isShow()) { sdDialog.cancel(); } break; default: break; } super.handleMessage(msg); } }; private void onLoad() { listView.stopRefresh(); listView.stopLoadMore(); listView.setRefreshTime(new Date().toLocaleString()); } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.projectplan_package); initView();//初始化视图 initData(); } public void initData(){ top_title.setText("工作包"); initdata(id, pageNum + "", pageSize + "", 1 + ""); } private void initdata(String projectId, String pageNum, String pageSize, String kind) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("projectId", projectId)); params.add(new BasicNameValuePair("pageNum", pageNum)); params.add(new BasicNameValuePair("pageSize", pageSize)); params.add(new BasicNameValuePair("kind", kind)); new MyTask().execute(params); } class MyTask extends AsyncTask<List<NameValuePair>, Integer, String> { @Override protected void onPreExecute() { if (pageNum == 1) { sdDialog = new com.superdata.pm.view.SDProgressDialog( ProjectPlanPackageActivity.this); sdDialog.show(); } super.onPreExecute(); } @Override protected String doInBackground(List<NameValuePair>... params) { String aa = null; sdClient = new SDHttpClient(); try { aa = sdClient.post_session(url, params[0]); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return aa; } DecimalFormat df = new DecimalFormat("#.##"); @Override protected void onPostExecute(String result) { if (result != null) { try { JSONObject jRoot = new JSONObject(result); JSONObject jaresultList1 = jRoot .getJSONObject("resultData"); JSONArray jaresultList = jaresultList1 .getJSONArray("resultList"); int totalSize = jaresultList1.getInt("totalSize"); if (totalSize >= pageNum * pageSize) { isLastPage = false; } else { isLastPage = true; } listplanpack1.clear(); for (int i = 0; i < jaresultList.length(); i++) { String name = (jaresultList.getJSONObject(i) .get("name")).equals(null) ? "" + i : (String) jaresultList.getJSONObject(i).get( "name"); String packagestartdata = (jaresultList .getJSONObject(i).get("startDate")) .equals(null) ? "" : ((String) jaresultList.getJSONObject(i).get( "startDate")).substring(0, 10); String packageenddata = (jaresultList.getJSONObject(i) .get("endDate")).equals(null) ? "" : ((String) jaresultList.getJSONObject(i).get( "endDate")).substring(0, 10); String lasttime = (jaresultList.getJSONObject(i) .get("lastTime")).equals(null) ? 0 + "" : df.format(jaresultList.getJSONObject(i) .get("lastTime")) + "天"; String empName = ((jaresultList.getJSONObject(i) .get("empName")).equals(null)) ? "" : (String) jaresultList.getJSONObject(i).get( "empName"); Integer id = (Integer) (((jaresultList.getJSONObject(i) .get("id")).equals(null)) ? 1 : jaresultList .getJSONObject(i).get("id")); Integer projectId = (Integer) (((jaresultList .getJSONObject(i).get("projectId")) .equals(null)) ? 1 : jaresultList .getJSONObject(i).get("projectId")); String projectName = ((jaresultList.getJSONObject(i) .get("projectName")).equals(null)) ? "" : (String) jaresultList.getJSONObject(i).get( "projectName"); entityplanpackage epp = new entityplanpackage(name, packagestartdata, packageenddata, lasttime, empName, projectId, projectName, id); listplanpack1.add(epp); } } catch (JSONException e) { e.printStackTrace(); } } Message msg = new Message(); // 加载更多 时 if (!flag) { listplanpack.addAll(listplanpack1); listplanpack1.clear(); adapter = new MyAdapter(); msg.what = 2; } else { // 第一次 // 重新加载全部的 listplanpack.clear(); listplanpack.addAll(listplanpack1); adapter = new MyAdapter(); msg.what = 1; } if (sdDialog.isShow()) sdDialog.cancel(); handler.sendMessage(msg); super.onPostExecute(result); } } public void initView(){ top_title = (TextView) findViewById(R.id.tv_top_title); btnBack = (ImageView) findViewById(R.id.ll_top_title); id = getIntent().getExtras().getString("projectId"); sdDialog = new SDProgressDialog(this); btnBack.setOnClickListener(this); listView = (XListView) findViewById(R.id.lv_projectplan_package); listView.setOnItemClickListener(new ProjectPlanListener()); listView.setCacheColorHint(0); listView.setPullLoadEnable(true); listView.setXListViewListener(this); listView.setHeaderDividersEnabled(false); listView.setFooterDividersEnabled(false); } private class ProjectPlanListener implements OnItemClickListener{ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ProjectPlanPackageActivity.this, ProjectPlanTaskActivity.class); intent.putExtra("PACKAGEID", listplanpack.get(position - 1) .getId()); intent.putExtra("PROJECTID", listplanpack.get(position - 1) .getProjectId()); intent.putExtra("PROJECTNAME", listplanpack.get(position - 1) .getProjectName()); startActivity(intent); } } /*// 返回按钮 private ImageView back; // 费用管理条目 private XListView listView; // 获取的是第几页的数据 private int page = 1; // 获取的这页的数量 private int pagesize = 7; // Adapter里面放的List, private List<entityplanpackage> listplanpack = new ArrayList<entityplanpackage>(); // 临时的List,用于加载更多 的逻辑处理 private List<entityplanpackage> listplanpack1 = new ArrayList<entityplanpackage>(); private com.superdata.pm.view.SDProgressDialog sdDialog; // 标识是否加载更多 private boolean flag = true; private boolean isLastPage = false; private MyAdapter adapter; private TextView top_title; // 存的是项目 Map<Integer, List<String>> map = new HashMap<Integer, List<String>>(); private ArrayList<String> list; private CustemSpinerAdapter mAdapter; private SpinerPopWindow mSpinerPopWindow; private TextView proplanpack_projectby_items; private ImageView proplanpack_projectby_iv; private String id; private List<String> nameList = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.projectplan_package); init();// 初始化 initTopSelect(); // 点击返回 back = (ImageView) findViewById(R.id.proplanpack_iv_back); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 回退 onBackPressed(); } }); } private void initTopSelect() { mAdapter = new CustemSpinerAdapter(this); proplanpack_projectby_iv = (ImageView) this .findViewById(R.id.proplanpack_projectby_iv); proplanpack_projectby_items = (TextView) this .findViewById(R.id.proplanpack_projectby_items); proplanpack_projectby_iv.setOnClickListener(listener); mAdapter = new CustemSpinerAdapter(this); mSpinerPopWindow = new SpinerPopWindow(this); mSpinerPopWindow.setItemListener(this); intitData(); } public void intitData() { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pageNum", 1 + "")); params.add(new BasicNameValuePair("pageSize", 100 + "")); new MyTask1().execute(params); } class MyTask1 extends AsyncTask<List<NameValuePair>, Integer, String> { String url = InterfaceConfig.PROJECT_LIST_URL1; @Override protected void onPreExecute() { sdDialog = new com.superdata.pm.view.SDProgressDialog( ProjectPlanPackageActivity.this); sdDialog.show(); super.onPreExecute(); } @Override protected String doInBackground(List<NameValuePair>... params) { String json = null; try { json = new SDHttpClient().post_session(url, params[0]); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return json; } @Override protected void onPostExecute(String result) { if (result != null) { try { JSONObject jRoot = new JSONObject(result); // list = new ArrayList<HashMap<String,Object>>(); JSONArray resultList = jRoot.getJSONArray("resultList"); for (int i = 0; i < resultList.length(); i++) { String name = (String) (resultList.getJSONObject(i) .get("name"));// 项目名称 Integer id = (Integer) (resultList.getJSONObject(i) .get("id"));// 项目id list = new ArrayList<String>(); list.add(id + ""); list.add(name); map.put(i, list); } } catch (JSONException e) { Message msg = new Message(); msg.what = 6; handler.handleMessage(msg); e.printStackTrace(); } Message msg = new Message(); msg.what = 7; handler.handleMessage(msg); } else { Message msg = new Message(); msg.what = 5; handler.handleMessage(msg); } } } OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.proplanpack_projectby_iv: showSpinWindow(); break; default: break; } } }; @Override public void onItemClick(int pos) { proplanpack_projectby_items.setText(nameList.get(pos)); id = map.get(pos).get(0); initData(); page = 1; isLastPage = false; } private void showSpinWindow() { mSpinerPopWindow.setWidth(proplanpack_projectby_items.getWidth()); mSpinerPopWindow.showAsDropDown(proplanpack_projectby_items); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: listView.setAdapter(adapter); if (sdDialog.isShow()) { sdDialog.cancel(); } adapter.notifyDataSetChanged(); if (sdDialog.isShow()) { sdDialog.cancel(); } break; case 2: flag = true; listView.setAdapter(adapter); listView.setSelection(listplanpack.size() - pagesize); adapter.notifyDataSetChanged();// 数据变化刷新 if (sdDialog.isShow()) sdDialog.cancel(); onLoad(); break; case 3: onLoad(); Toast.makeText(getApplicationContext(), "已全部加载完成", Toast.LENGTH_SHORT).show(); break; case 5: Toast.makeText(getApplicationContext(), "暂无网络", 1).show(); if (sdDialog.isShow()) { sdDialog.cancel(); } break; case 6: Toast.makeText(getApplicationContext(), "暂时无法成功获取", 1).show(); if (sdDialog.isShow()) { sdDialog.cancel(); } break; case 7: if (sdDialog.isShow()) { sdDialog.cancel(); } for (int i = 0; i < map.size(); i++) { nameList.add(map.get(i).get(1)); } proplanpack_projectby_items.setText(nameList.get(0)); id = map.get(0).get(0); proplanpack_projectby_iv.setOnClickListener(listener); mAdapter.refreshData(nameList, 0); mSpinerPopWindow.setAdatper(mAdapter); // 获取数据 initData(); break; default: break; } super.handleMessage(msg); } }; private void onLoad() { listView.stopRefresh(); listView.stopLoadMore(); listView.setRefreshTime(new Date().toLocaleString()); } private void initData() { initdata(id, page + "", pagesize + "", 1 + ""); } private void initdata(String projectId, String page, String size, String kind) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("projectId", projectId)); params.add(new BasicNameValuePair("pageNum", page)); params.add(new BasicNameValuePair("pageSize", size)); params.add(new BasicNameValuePair("kind", kind)); new MyTask().execute(params); } // http://localhost:8080/pm/taskInterface/queryTask.do // String url ="http://192.168.0.117:8080/pm/taskInterface/queryTask.do"; String url = InterfaceConfig.PROJECT_Plan_Package_URL; class MyTask extends AsyncTask<List<NameValuePair>, Integer, String> { @Override protected void onPreExecute() { if (page == 1) { sdDialog = new com.superdata.pm.view.SDProgressDialog( ProjectPlanPackageActivity.this); sdDialog.show(); } super.onPreExecute(); } @Override protected String doInBackground(List<NameValuePair>... params) { String aa = null; try { aa = new SDHttpClient().post_session(url, params[0]); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return aa; } @Override protected void onPostExecute(String result) { if (result != null) { try { JSONObject jRoot = new JSONObject(result); JSONObject jaresultList1 = jRoot .getJSONObject("resultData"); JSONArray jaresultList = jaresultList1 .getJSONArray("resultList"); int totalSize = jaresultList1.getInt("totalSize"); if (totalSize >= page * pagesize) { isLastPage = false; } else { isLastPage = true; } listplanpack1.clear(); for (int i = 0; i < jaresultList.length(); i++) { String name = (jaresultList.getJSONObject(i) .get("name")).equals(null) ? "工作包名没有" + i : (String) jaresultList.getJSONObject(i).get( "name"); String packagestartdata = (jaresultList .getJSONObject(i).get("startDate")) .equals(null) ? "2014-01-01" : ((String) jaresultList.getJSONObject(i).get( "startDate")).substring(0, 10); String packageenddata = (jaresultList.getJSONObject(i) .get("endDate")).equals(null) ? "2014-03-03" : ((String) jaresultList.getJSONObject(i).get( "endDate")).substring(0, 10); String lasttime = (jaresultList.getJSONObject(i) .get("lastTime")).equals(null) ? 0 + "" : String.valueOf(jaresultList.getJSONObject(i) .get("lastTime")) + "天"; String empName = ((jaresultList.getJSONObject(i) .get("empName")).equals(null)) ? "负责人没有" : (String) jaresultList.getJSONObject(i).get( "empName"); Integer id = (Integer) (((jaresultList.getJSONObject(i) .get("id")).equals(null)) ? 1 : jaresultList .getJSONObject(i).get("id")); Integer projectId = (Integer) (((jaresultList .getJSONObject(i).get("projectId")) .equals(null)) ? 1 : jaresultList .getJSONObject(i).get("projectId")); String projectName = ((jaresultList.getJSONObject(i) .get("projectName")).equals(null)) ? "无所属项目" : (String) jaresultList.getJSONObject(i).get( "projectName"); entityplanpackage epp = new entityplanpackage(name, packagestartdata, packageenddata, lasttime, empName, projectId, projectName, id); listplanpack1.add(epp); } } catch (JSONException e) { e.printStackTrace(); } } Message msg = new Message(); // 加载更多 时 if (!flag) { listplanpack.addAll(listplanpack1); listplanpack1.clear(); adapter = new MyAdapter(); msg.what = 2; } else { // 第一次 // 重新加载全部的 listplanpack.clear(); listplanpack.addAll(listplanpack1); adapter = new MyAdapter(); msg.what = 1; } if (sdDialog.isShow()) sdDialog.cancel(); handler.sendMessage(msg); super.onPostExecute(result); } } // 初始化数据的方法 public void init() { listView = (com.superdata.pm.view.XListView) findViewById(R.id.lv_projectplan_package);// 初始化listview listView.setCacheColorHint(0); listView.setPullLoadEnable(true); listView.setXListViewListener(this); listView.setHeaderDividersEnabled(false); listView.setFooterDividersEnabled(false); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ProjectPlanPackageActivity.this, ProjectPlanTaskActivity.class); intent.putExtra("PACKAGEID", listplanpack.get(position - 1) .getId()); intent.putExtra("PROJECTID", listplanpack.get(position - 1) .getProjectId()); intent.putExtra("PROJECTNAME", listplanpack.get(position - 1) .getProjectName()); startActivity(intent); } }); }*/ @Override public void onRefresh() { pageNum = 1; initdata(id, 1 + "", pageSize + "", 1 + ""); onLoad(); } @Override public void onLoadMore() { if (!isLastPage) { if (flag) { flag = false; ++pageNum; initdata(id, pageNum + "", pageSize + "", 1 + ""); } } else { handler.sendEmptyMessage(3); } } @Override public void onClick(View v) { if(v == btnBack){ onBackPressed(); } } /** * 自定义适配器 * * @author Administrator * */ class MyAdapter extends BaseAdapter { @Override public int getCount() { // TODO Auto-generated method stub return listplanpack.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return listplanpack.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder; if (convertView == null) { holder = new Holder(); convertView = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.projectplan_package_item, null); holder.package_name = (TextView) convertView .findViewById(R.id.tv_cb_projectplan_package_name); holder.package_startdata = (TextView) convertView .findViewById(R.id.tv_cb_projectplan_package_startdata); holder.package_enddata = (TextView) convertView .findViewById(R.id.tv_cb_projectplan_package_enddata); holder.package_duration = (TextView) convertView .findViewById(R.id.tv_cb_projectplan_package_duration); holder.package_person = (TextView) convertView .findViewById(R.id.tv_cb_projectplan_package_person); holder.projectby = (TextView) convertView .findViewById(R.id.tv_cb_projectplan_package_projectby); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } holder.package_name.setText(listplanpack.get(position) .getPackagename()); holder.package_startdata.setText(listplanpack.get(position) .getPackagestartdata()); holder.package_enddata.setText(listplanpack.get(position) .getPackageenddata()); holder.package_duration.setText(listplanpack.get(position) .getPackageduration()); holder.package_person.setText(listplanpack.get(position) .getPackageheader()); holder.projectby.setText(listplanpack.get(position) .getProjectName()); return convertView; } class Holder { TextView package_name; // 工作包名称 TextView package_startdata; // 工作包开始时间 TextView package_enddata; // 工作包结束时间 TextView package_duration; // 工作包持续时间 TextView package_person; // 工作包负责人 TextView projectby;// 所属项目 } } }
Java
UTF-8
521
2.109375
2
[]
no_license
package org.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.pojo.Classes; import org.springframework.stereotype.Repository; @Repository public class ClassesDao { @Resource private SessionFactory sf; public Session set() { return sf.getCurrentSession(); } public List<Classes> selectAllClasses(String sql) { return set().createSQLQuery(sql).addEntity(Classes.class).list(); } }
C#
UTF-8
1,073
2.921875
3
[]
no_license
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using CustomerApp.Model; namespace CustomerApp.Models { public class CustomerViewModel { public long Id { get; set; } [Required] [DisplayName("Name")] public string Name { get; set; } [Required] [DisplayName("Surname")] public string Surname { get; set; } [DisplayName("Phone number")] [DataType(DataType.PhoneNumber)] public string TelephoneNumber { get; set; } [Required] [DisplayName("Address")] public string Address { get; set; } public CustomerViewModel() { } public CustomerViewModel(Customer customer) { if (customer != null) { this.Id = customer.Id; this.Name = customer.Name; this.Surname = customer.Surname; this.TelephoneNumber = customer.TelephoneNumber; this.Address = customer.Address; } } } }
C++
UTF-8
7,776
2.546875
3
[ "MIT" ]
permissive
#include "../include/json_generator.hpp" #include "../../grammar/include/grammar.hpp" #include "../../grammar/include/nonterminal.hpp" #include "../../grammar/include/production.hpp" #include "../../grammar/include/token.hpp" #include "../../grammar/include/nonterminal.hpp" #include "../../table/include/state.hpp" #include "../../table/include/table.hpp" #include <iostream> #include <stdexcept> using namespace asparserations; using namespace grammar; using namespace table; using namespace codegen; JSON_Generator::JSON_Generator(const Table& table, bool pretty_print, bool debug, const std::string& tab) : m_table(table), m_grammar(table.grammar()), m_pretty_print(pretty_print), m_indent_depth(0), m_debug(debug), m_tab(tab) { m_generate(); } const std::string& JSON_Generator::code() const {return m_code;} void JSON_Generator::m_break_and_indent() { if(m_indent_depth > 10) { std::cout << m_code << std::endl; throw std::runtime_error("Int underflow"); } if(m_pretty_print) { m_code += "\n"; for(unsigned int i = 0; i < m_indent_depth; ++i) { m_code += m_tab; } } } void JSON_Generator::m_generate() { m_code += "{"; ++m_indent_depth; m_break_and_indent(); m_code += "\"grammar\" : "; m_generate_grammar(m_grammar); m_code += ","; m_break_and_indent(); m_code += "\"table\" : "; m_generate_table(m_table); --m_indent_depth; m_break_and_indent(); m_code += "}"; } void JSON_Generator::m_generate_token(const Token& token) { m_break_and_indent(); m_code += "\"" + token.name() + "\""; } void JSON_Generator::m_generate_nonterminal(const Nonterminal& n) { m_code += "\"" + n.name() + "\" : {"; ++m_indent_depth; bool needs_comma = false; for(auto& production : n.productions()) { if(needs_comma) { m_code += ","; } else { needs_comma = true; } m_break_and_indent(); m_code += "\"" + production.name() + "\" : ["; ++m_indent_depth; bool needs_comma2 = false; for(const Symbol* const symbol : production.symbols()) { if(needs_comma2) { m_code += ","; } else { needs_comma2 = true; } m_break_and_indent(); m_code += "{"; ++m_indent_depth; m_break_and_indent(); m_code += "\"name\" : \"" + symbol->name() + "\","; m_break_and_indent(); m_code += "\"isToken\" : " + std::string((symbol->is_token() ? "true" : "false")); --m_indent_depth; m_break_and_indent(); m_code += "}"; } --m_indent_depth; m_break_and_indent(); m_code += "]"; } --m_indent_depth; m_break_and_indent(); m_code += "}"; } void JSON_Generator::m_generate_grammar(const Grammar& grammar) { m_code += "{"; ++m_indent_depth; m_break_and_indent(); // Tokens m_code += "\"tokens\" : ["; ++m_indent_depth; m_generate_token(grammar.end()); for(const Token* token : grammar.tokens()) { m_code += ","; m_generate_token(*token); } --m_indent_depth; m_break_and_indent(); m_code += "],"; m_break_and_indent(); // Nonterminals m_code += "\"nonterminals\" : {"; ++m_indent_depth; m_break_and_indent(); m_generate_nonterminal(grammar.accept()); for(const Nonterminal* nonterminal : grammar.nonterminals()) { m_code += ","; m_break_and_indent(); m_generate_nonterminal(*nonterminal); } --m_indent_depth; m_break_and_indent(); m_code += "}"; --m_indent_depth; m_break_and_indent(); m_code += "}"; } void JSON_Generator::m_generate_actions( const std::map<std::reference_wrapper<const Token>, std::pair<const State*, std::set<std::reference_wrapper<const Production>>>>& actions) { m_code += "{"; ++m_indent_depth; bool needs_comma = false; for(auto& action : actions) { if(needs_comma) { m_code += ","; } else { needs_comma = true; } m_break_and_indent(); m_code += "\"" + action.first.get().name() + "\" : {"; ++m_indent_depth; m_break_and_indent(); m_code += "\"shift\" : " + (action.second.first == nullptr ? "null" : std::to_string(action.second.first->index())) + ","; m_break_and_indent(); m_code += "\"reductions\" : ["; ++m_indent_depth; bool needs_comma2 = false; for(auto& production : action.second.second) { if(needs_comma2) { m_code += ","; } else { needs_comma2 = true; } m_break_and_indent(); m_code += "{"; ++m_indent_depth; m_break_and_indent(); m_code += "\"nonterminal\" : \"" + production.get().nonterminal().name() + "\","; m_break_and_indent(); m_code += "\"production\" : \"" + production.get().name() + "\""; --m_indent_depth; m_break_and_indent(); m_code += "}"; } --m_indent_depth; m_break_and_indent(); m_code += "]"; --m_indent_depth; m_break_and_indent(); m_code += "}"; } --m_indent_depth; m_break_and_indent(); m_code += "}"; } void JSON_Generator::m_generate_gotos( const std::map<std::reference_wrapper<const Nonterminal>,const State*>& gotos ) { m_code += "{"; ++m_indent_depth; bool needs_comma = false; for(auto& go_to : gotos) { if(needs_comma) { m_code += ","; } else { needs_comma = true; } m_break_and_indent(); m_code += "\"" + go_to.first.get().name() + "\" : " + std::to_string(go_to.second->index()); } --m_indent_depth; m_break_and_indent(); m_code += "}"; } void JSON_Generator::m_generate_item_set(const Item_Set& item_set) { m_code += "["; ++m_indent_depth; bool needs_comma = false; for(const Item& item : item_set.items()) { if(needs_comma) { m_code += ","; } else { needs_comma = true; } m_break_and_indent(); m_code += "{"; ++m_indent_depth; m_break_and_indent(); m_code += "\"production\" : {"; ++m_indent_depth; m_break_and_indent(); m_code += "\"nonterminal\" : \"" + item.production.nonterminal().name() + "\","; m_break_and_indent(); m_code += "\"production\" : \"" + item.production.name() + "\""; --m_indent_depth; m_break_and_indent(); m_code += "},"; m_break_and_indent(); m_code += "\"marker\" : " + std::to_string(item.marker) + ","; m_break_and_indent(); m_code += "\"lookahead\" : \"" + item.lookahead.name() + "\""; --m_indent_depth; m_break_and_indent(); m_code += "}"; } --m_indent_depth; m_break_and_indent(); m_code += "]"; } void JSON_Generator::m_generate_state(const State& state, const Item_Set* item_set) { m_code += "{"; ++m_indent_depth; m_break_and_indent(); m_code += "\"index\" : " + std::to_string(state.index()) + ","; m_break_and_indent(); m_code += "\"actions\" : "; m_generate_actions(state.actions()); m_code += ","; m_break_and_indent(); m_code += "\"gotos\" : "; m_generate_gotos(state.gotos()); m_code += ","; m_break_and_indent(); m_code += "\"itemSet\" : "; if(item_set == nullptr) { m_code += "null"; } else { m_generate_item_set(*item_set); } --m_indent_depth; m_break_and_indent(); m_code += "}"; }; void JSON_Generator::m_generate_table(const Table& table) { m_code += "["; ++m_indent_depth; bool insert_comma = false; for(auto& pair : table.item_set_state_pairs()) { if(insert_comma) { m_code += ","; } else { insert_comma = true; } m_break_and_indent(); if(m_debug) { m_generate_state(*pair.second, pair.first); } else { m_generate_state(*pair.second, nullptr); } } --m_indent_depth; m_break_and_indent(); m_code += "]"; }
C
UTF-8
3,436
2.984375
3
[]
no_license
// bmp.c #include "bmp.h" // THIS CODE WAS TAKEN FROM HERE: // https://stackoverflow.com/a/2654860 // I DID NOT WRITE IT MYSELF #include <stdint.h> #include <stdlib.h> #include <string.h> void bmp_write ( char const* fname, struct bmp bmp ) { uint32_t h = bmp.height; uint32_t w = bmp.width; FILE *f; int padding_per_row = w%4 ? 4-w%4 : 0; int filesize = 54 + 3*w*h + padding_per_row * h; //w is your image width, h is image height, both int unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0}; unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0}; unsigned char bmppad[3] = {0,0,0}; bmpfileheader[ 2] = (unsigned char)(filesize ); bmpfileheader[ 3] = (unsigned char)(filesize>> 8); bmpfileheader[ 4] = (unsigned char)(filesize>>16); bmpfileheader[ 5] = (unsigned char)(filesize>>24); bmpinfoheader[ 4] = (unsigned char)(w ); bmpinfoheader[ 5] = (unsigned char)(w>> 8); bmpinfoheader[ 6] = (unsigned char)(w>>16); bmpinfoheader[ 7] = (unsigned char)(w>>24); bmpinfoheader[ 8] = (unsigned char)(h ); bmpinfoheader[ 9] = (unsigned char)(h>> 8); bmpinfoheader[10] = (unsigned char)(h>>16); bmpinfoheader[11] = (unsigned char)(h>>24); f = fopen(fname,"wb"); fwrite(bmpfileheader,1,14,f); fwrite(bmpinfoheader,1,40,f); unsigned char *img = (unsigned char *)malloc(3*w*h); memset(img,0,3*w*h); for (int j=0; j<h; j++) { for (int i=0; i<w; i++) { int x = i; int y = (h-1)-j; uint8_t r = bmp.data[j*w+i].r; uint8_t g = bmp.data[j*w+i].g; uint8_t b = bmp.data[j*w+i].b; img[(x+y*w)*3+2] = (unsigned char)(r); img[(x+y*w)*3+1] = (unsigned char)(g); img[(x+y*w)*3+0] = (unsigned char)(b); } } for(int y = h; y--;) { fwrite(img+(w*y*3), 3, w, f); if (w % 4 != 0) { int extra = 4 - w%4; fwrite(bmppad, 1, extra, f); } } free(img); fclose(f); } struct bmp bmp_read(FILE *f) { unsigned char fileheader[14] = {}; unsigned char info[40] = {}; fread(fileheader,1,14,f); fread(info,1,40,f); uint32_t size = ((uint32_t)fileheader[2] << 0) | ((uint32_t)fileheader[3] << 8) | ((uint32_t)fileheader[4] << 16) | ((uint32_t)fileheader[5] << 24); uint32_t width = ((uint32_t)info[4] << 0) | ((uint32_t)info[5] << 8) | ((uint32_t)info[6] << 16) | ((uint32_t)info[7] << 24); uint32_t height = ((uint32_t)info[8] << 0) | ((uint32_t)info[9] << 8) | ((uint32_t)info[10] << 16) | ((uint32_t)info[11] << 24); struct rgb* result_data = malloc(width * height * sizeof(struct rgb)); uint32_t data_size = size - 54; // file size minus header size uint8_t* data = malloc(data_size); fread(data, 1, data_size, f); int k = 0; int q = 0; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { result_data[k++] = (struct rgb){ .r = data[q+2], .g = data[q+1], .b = data[q+0], }; q += 3; } // round up to multiple of 4 if (q % 4 != 0) { q += 4 - q % 4; } } free(data); return (struct bmp){ .width = width, .height = height, .data = result_data, }; } struct bmp bmp_make(int width, int height) { size_t data_size = width * height * sizeof(struct rgb); struct rgb* data = malloc(data_size); memset(data, 0, data_size); return (struct bmp){ .width = width, .height = height, .data = data }; }
Java
UTF-8
11,812
2.03125
2
[]
no_license
package com.ood.myorange.service.impl; import com.amazonaws.AmazonServiceException; import com.amazonaws.HttpMethod; import com.amazonaws.SdkClientException; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.*; import com.fasterxml.jackson.core.JsonProcessingException; import com.ood.myorange.auth.ICurrentAccount; import com.ood.myorange.config.storage.S3Configuration; import com.ood.myorange.config.storage.StorageType; import com.ood.myorange.dto.FileUploadDto; import com.ood.myorange.dto.response.PreSignedUrlResponse; import com.ood.myorange.exception.ForbiddenException; import com.ood.myorange.exception.InternalServerError; import com.ood.myorange.pojo.OriginalFile; import com.ood.myorange.pojo.User; import com.ood.myorange.service.*; import com.ood.myorange.util.NamingUtil; import com.ood.myorange.util.StorageConfigUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * Created by Guancheng Lai */ @Service @Slf4j public class UploadServiceImpl implements UploadService { @Autowired ICurrentAccount currentAccount; @Autowired FileService fileService; @Autowired UserService userService; @Override @Transactional public PreSignedUrlResponse getPreSignedUrl(FileUploadDto fileUploadDto) throws JsonProcessingException { int configId = currentAccount.getUserInfo().getSourceId(); // check used size User user = userService.getUserById(currentAccount.getUserInfo().getId()); if (user.getMemorySize() < user.getUsedSize() + fileUploadDto.getSize()) { throw new ForbiddenException("you are running out of space"); } userService.increaseUsedSize(user.getId(), user.getUsedSize() + fileUploadDto.getSize()); // Check duplicate boolean originalFileExist = fileService.checkOriginFileExist( fileUploadDto,configId ); if (originalFileExist) { PreSignedUrlResponse preSignedUrlResponse = new PreSignedUrlResponse(); OriginalFile of = fileService.InsertOrUpdateOriginFile( fileUploadDto,configId ); fileService.addUserFile( fileUploadDto,of.getOriginId() ); return preSignedUrlResponse; } PreSignedUrlResponse preSignedUrlResponse; StorageType storageType = StorageConfigUtil.getStorageConfigurationType( configId ); switch (storageType) { case AWS : S3Configuration s3Configuration = (S3Configuration) StorageConfigUtil.getStorageConfiguration( configId ); preSignedUrlResponse = AWSUpload( s3Configuration, NamingUtil.generateOriginFileId(fileUploadDto.getMD5(),String.valueOf( fileUploadDto.getSize())), fileUploadDto.getFileName() ); break; case AZURE : // TODO preSignedUrlResponse = new PreSignedUrlResponse(); preSignedUrlResponse.setUploadUrl( "TODO.AZURE/FINISHED.UPLOAD" ); break; case LOCAL : // TODO preSignedUrlResponse = new PreSignedUrlResponse(); preSignedUrlResponse.setUploadUrl( "TODO.LOCAL/FINISHED.UPLOAD" ); break; default: throw new InternalError( "Unknown storage type:" + storageType ); } return preSignedUrlResponse; } @Override @Transactional public void uploadFinished(FileUploadDto fileUploadDto) throws JsonProcessingException { int configId = currentAccount.getUserInfo().getSourceId(); StorageType storageType = StorageConfigUtil.getStorageConfigurationType( configId ); switch (storageType) { case AWS: try { S3Configuration s3Configuration = (S3Configuration) StorageConfigUtil.getStorageConfiguration( configId ); AmazonS3 s3Client = (AmazonS3) StorageConfigUtil.getStorageClient( StorageType.AWS ); if (s3Client == null) { log.error( "NEED ATTENTION! StorageUtil has a NULL AWS S3 Client." ); StorageConfigUtil.insertStorageConfig( configId,"AWS", s3Configuration); s3Client = (AmazonS3) StorageConfigUtil.getStorageClient( StorageType.AWS ); } if (!s3Client.doesBucketExistV2( fileUploadDto.getUploadKey() )) { throw new InternalServerError( "Could not found the temp bucket, upload failed." ); } S3Object s3Object = s3Client.getObject( fileUploadDto.getUploadKey(),fileUploadDto.getFileName() ); s3Client.copyObject( fileUploadDto.getUploadKey(), fileUploadDto.getFileName(), s3Configuration.getAwsBucketName(), NamingUtil.generateOriginFileId( fileUploadDto.getMD5(),String.valueOf( fileUploadDto.getSize() ) ) ); ObjectListing objectListing = s3Client.listObjects(fileUploadDto.getUploadKey()); while (true) { Iterator<S3ObjectSummary> objIter = objectListing.getObjectSummaries().iterator(); while (objIter.hasNext()) { s3Client.deleteObject(fileUploadDto.getUploadKey(), objIter.next().getKey()); } // If the bucket contains many objects, the listObjects() call // might not return all of the objects in the first listing. Check to // see whether the listing was truncated. If so, retrieve the next page of objects // and delete them. if (objectListing.isTruncated()) { objectListing = s3Client.listNextBatchOfObjects(objectListing); } else { break; } } s3Client.deleteBucket( fileUploadDto.getUploadKey() ); } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); log.info("Failed to validate the AWS S3 Credential"); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); log.info("Failed to validate the AWS S3 Credential"); } break; case AZURE: // TODO break; case LOCAL: // TODO break; default: throw new InternalServerError( "Invalid storage type: " + storageType ); } OriginalFile of = fileService.InsertOrUpdateOriginFile( fileUploadDto,configId ); fileService.addUserFile( fileUploadDto,of.getOriginId() ); } private PreSignedUrlResponse AWSUpload(S3Configuration s3Configuration, String fileObjectName, String fileRealName) { PreSignedUrlResponse preSignedUrlResponse = new PreSignedUrlResponse(); try { AmazonS3 s3Client = (AmazonS3) StorageConfigUtil.getStorageClient( StorageType.AWS ); try { S3Object s3Object = s3Client.getObject( s3Configuration.getAwsBucketName(),fileObjectName ); } catch (AmazonS3Exception e) { log.info( "File Already exist" ); } String tempBucketName = AWSCreateTempBucket( s3Client,fileObjectName ); String preSignedURL = AWSGenerateURL( s3Client,tempBucketName,fileObjectName,fileRealName ); log.info("AWS Upload Pre-Signed URL has been generated: " + preSignedURL ); preSignedUrlResponse.setUploadUrl( preSignedURL ); preSignedUrlResponse.setUploadKey( tempBucketName ); } catch ( AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); System.out.println( "Failed to generate pre-signed URL" ); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); System.out.println( "Failed to generate pre-signed URL" ); } return preSignedUrlResponse; } private String AWSCreateTempBucket(AmazonS3 s3Client, String fileObjectName) { String tempBucketName = "my-orange-" + fileObjectName.substring( 0,32 ).toLowerCase() + "-" + System.currentTimeMillis(); while (s3Client.doesBucketExistV2( tempBucketName )) { tempBucketName = "my-orange-" + fileObjectName.substring( 0,32 ).toLowerCase() + "-" + System.currentTimeMillis(); log.info( tempBucketName + ", size = " + tempBucketName.length() ); } List<CORSRule.AllowedMethods> ruleAM = new ArrayList<CORSRule.AllowedMethods>(); ruleAM.add(CORSRule.AllowedMethods.PUT); CORSRule rule = new CORSRule().withId("CORSRule").withAllowedMethods(ruleAM) .withAllowedOrigins( Arrays.asList("*")).withMaxAgeSeconds(3000) .withExposedHeaders(Arrays.asList("x-amz-server-side-encryption")); List<CORSRule> rules = new ArrayList<CORSRule>(); rules.add( rule ); // Add the rules to a new CORS configuration. BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration(); configuration.setRules(rules); try { Bucket tempBucketForUpload = s3Client.createBucket( tempBucketName ); s3Client.setBucketCrossOriginConfiguration( tempBucketName, configuration ); } catch (AmazonS3Exception e) { e.printStackTrace(); } return tempBucketName; } private String AWSGenerateURL(AmazonS3 s3Client, String tempBucketName, String fileObjectName, String fileRealName) { // Set the pre-signed URL to expire after 60 seconds. java.util.Date expiration = new java.util.Date(); long expTimeMillis = expiration.getTime(); // expTimeMillis += 1000 * 60 * 60; // one hour // expTimeMillis += 1000 * 60 * 60 * 24 ; // one day expTimeMillis += 1000 * 60 * 60 * 24 * 7; // one week expiration.setTime(expTimeMillis); // GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(storageConfigDto.getAwsBucketName(), fileObjectName) // .withMethod( HttpMethod.PUT) // .withExpiration(expiration); GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(tempBucketName, fileRealName) .withMethod( HttpMethod.PUT ) .withExpiration(expiration); return s3Client.generatePresignedUrl(generatePresignedUrlRequest).toString(); } }
Python
UTF-8
839
3.359375
3
[ "Apache-2.0" ]
permissive
class Solution: def __first_match(self, s, p, i, j): return s[i] == p[j] or p[j] == '.' def isMatch(self, s: str, p: str) -> bool: s_len = len(s) p_len = len(p) dp = [[False for _ in range(p_len + 1)] for _ in range(s_len + 1)] dp[0][0] = True for j in range(2, p_len + 1): dp[0][j] = (p[j - 1] == '*' and dp[0][j - 2]) for i in range(s_len): for j in range(p_len): if p[j] == '*': if dp[i + 1][j - 1]: dp[i + 1][j + 1] = True else: dp[i + 1][j + 1] = self.__first_match(s, p, i, j - 1) and dp[i][j + 1] else: dp[i + 1][j + 1] = self.__first_match(s, p, i, j) and dp[i][j] return dp[s_len][p_len]
Java
UTF-8
601
1.789063
2
[ "Apache-2.0" ]
permissive
package com.mongodb.hadoop.examples.sensors; import com.mongodb.hadoop.util.*; import org.apache.commons.logging.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.util.*; import org.bson.*; public class Sensors extends MongoTool{ private static final Log log = LogFactory.getLog( MongoTool.class ); String _jobName = "Sensors Aggregation"; public static void main( final String[] pArgs ) throws Exception{ Configuration conf = new Configuration(); System.exit( ToolRunner.run( conf, new Sensors(), pArgs )); } }
C#
UTF-8
13,998
2.734375
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Linq; using FluentAssertions; using RentalData; using RentalData.Models; using RentalServices; using Microsoft.EntityFrameworkCore; using Moq; using NUnit.Framework; namespace UnitTests.Services { [TestFixture] class GuitarServiceShould { [Test] public void Add_New_Guitar_To_Db() { var mockDbSet = new Mock<DbSet<Guitar>>(); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var svc = new GuitarService(mockContext.Object); svc.Add(new Guitar()); mockContext.Verify(a => a.Add(It.IsAny<Guitar>()), Times.Once); mockContext.Verify(s => s.SaveChanges(), Times.Once); } [Test] public void Get_Guitars_By_Id() { var guitars = new List<Guitar>() { new Guitar { Id = 1, Name = "Fender Appender" }, new Guitar { Id = 2, Name = "Bass with Face" }, new Guitar { Id = 3, Name = "Acoustic Guitar" } }.AsQueryable(); var mockDbSet = new Mock<DbSet<Guitar>>(); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Provider).Returns(guitars.Provider); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Expression).Returns(guitars.Expression); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.ElementType).Returns(guitars.ElementType); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.GetEnumerator()).Returns(guitars.GetEnumerator); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var service = new GuitarService(mockContext.Object); var guitar = service.Get(2); guitar.Name.Should().Be("Bass with Face"); } [Test] public void Get_Guitars_By_Type() { var guitars = new List<Guitar>() { new Guitar { Id = 1, Name = "Fender Appender", Type = "Electric" }, new Guitar { Id = 4, Name = "Bobby Gibson", Type = "Electric" }, new Guitar { Id = 3, Name = "Acoustic Guitar", Type = "Acoustic" } }.AsQueryable(); var mockDbSet = new Mock<DbSet<Guitar>>(); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Provider).Returns(guitars.Provider); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Expression).Returns(guitars.Expression); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.ElementType).Returns(guitars.ElementType); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.GetEnumerator()).Returns(guitars.GetEnumerator); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var service = new GuitarService(mockContext.Object); var queryResults = service.GetByType("Electric"); queryResults.Should().HaveCount(2); queryResults.Should().Contain(g => g.Name == "Fender Appender"); queryResults.Should().Contain(g => g.Name == "Bobby Gibson"); } [Test] public void Get_Guitars_By_Style() { var guitars = new List<Guitar>() { new Guitar { Id = 1, Name = "Fender Appender", Type = "Electric", Style = "Lagoon Blue" }, new Guitar { Id = 4, Name = "Bobby Gibson", Type = "Electric", Style = "Lagoon Blue" }, new Guitar { Id = 3, Name = "Acoustic Guitar", Type = "Acoustic", Style = "Lagoon Blue" } }.AsQueryable(); var mockDbSet = new Mock<DbSet<Guitar>>(); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Provider).Returns(guitars.Provider); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Expression).Returns(guitars.Expression); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.ElementType).Returns(guitars.ElementType); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.GetEnumerator()).Returns(guitars.GetEnumerator); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var service = new GuitarService(mockContext.Object); var queryResults = service.GetByStyle("Lagoon Blue"); queryResults.Should().HaveCount(3); queryResults.Should().Contain(g => g.Name == "Fender Appender"); queryResults.Should().Contain(g => g.Name == "Bobby Gibson"); queryResults.Should().Contain(g => g.Name == "Acoustic Guitar"); } [Test] public void Get_Guitars_By_NumberStrings() { var guitars = new List<Guitar>() { new Guitar { Id = 1, Name = "Fender Appender", Type = "Electric", NumberOfStrings = 6 }, new Guitar { Id = 4, Name = "Bobby Gibson", Type = "Electric", NumberOfStrings = 7 }, new Guitar { Id = 3, Name = "Acoustic Guitar", Type = "Acoustic", NumberOfStrings = 6 } }.AsQueryable(); var mockDbSet = new Mock<DbSet<Guitar>>(); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Provider).Returns(guitars.Provider); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Expression).Returns(guitars.Expression); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.ElementType).Returns(guitars.ElementType); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.GetEnumerator()).Returns(guitars.GetEnumerator); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var service = new GuitarService(mockContext.Object); var queryResults = service.GetByNumberStrings(6); queryResults.Should().HaveCount(2); queryResults.Should().Contain(g => g.Name == "Fender Appender"); queryResults.Should().Contain(g => g.Name == "Acoustic Guitar"); } [Test] public void Get_Guitars_By_NumberStrings_Range() { var guitars = new List<Guitar>() { new Guitar { Id = 1, Name = "Fender Appender", Type = "Electric", NumberOfStrings = 6 }, new Guitar { Id = 4, Name = "Bobby Gibson", Type = "Electric", NumberOfStrings = 7 }, new Guitar { Id = 3, Name = "Acoustic Guitar", Type = "Acoustic", NumberOfStrings = 6 }, new Guitar { Id = 2, Name = "Bass with Face", Type = "Bass", NumberOfStrings = 4 } }.AsQueryable(); var mockDbSet = new Mock<DbSet<Guitar>>(); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Provider).Returns(guitars.Provider); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Expression).Returns(guitars.Expression); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.ElementType).Returns(guitars.ElementType); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.GetEnumerator()).Returns(guitars.GetEnumerator); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var service = new GuitarService(mockContext.Object); var queryResults = service.GetByNumberStrings(4, 6); queryResults.Should().HaveCount(3); queryResults.Should().Contain(g => g.Name == "Fender Appender"); queryResults.Should().Contain(g => g.Name == "Acoustic Guitar"); queryResults.Should().Contain(g => g.Name == "Bass with Face"); } [Test] public void Get_Type() { var guitars = new List<Guitar>() { new Guitar { Id = 1, Name = "Fender Appender", Type = "Electric", Style = "Lagoon Blue" }, new Guitar { Id = 4, Name = "Pinky", Type = "Electric", Style = "Pink" }, new Guitar { Id = 3, Name = "Acoustic Guitar", Type = "Acoustic", Style = "Lagoon Blue" } }.AsQueryable(); var mockDbSet = new Mock<DbSet<Guitar>>(); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Provider).Returns(guitars.Provider); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Expression).Returns(guitars.Expression); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.ElementType).Returns(guitars.ElementType); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.GetEnumerator()).Returns(guitars.GetEnumerator); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var service = new GuitarService(mockContext.Object); var style = service.GetType(1); style.Should().Be("Electric"); } [Test] public void Get_NumberOfStrings() { var guitars = new List<Guitar>() { new Guitar { Id = 1, Name = "Fender Appender", Type = "Electric", Style = "Lagoon Blue", NumberOfStrings = 6 }, new Guitar { Id = 4, Name = "Pinky", Type = "Electric", Style = "Pink", NumberOfStrings = 5 }, new Guitar { Id = 3, Name = "Acoustic Guitar", Type = "Acoustic", Style = "Lagoon Blue", NumberOfStrings = 6 } }.AsQueryable(); var mockDbSet = new Mock<DbSet<Guitar>>(); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Provider).Returns(guitars.Provider); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Expression).Returns(guitars.Expression); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.ElementType).Returns(guitars.ElementType); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.GetEnumerator()).Returns(guitars.GetEnumerator); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var service = new GuitarService(mockContext.Object); var style = service.GetNumberStrings(4); style.Should().Be(5); } [Test] public void Get_Style() { var guitars = new List<Guitar>() { new Guitar { Id = 1, Name = "Fender Appender", Type = "Electric", Style = "Lagoon Blue" }, new Guitar { Id = 4, Name = "Pinky", Type = "Electric", Style = "Pink" }, new Guitar { Id = 3, Name = "Acoustic Guitar", Type = "Acoustic", Style = "Lagoon Blue" } }.AsQueryable(); var mockDbSet = new Mock<DbSet<Guitar>>(); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Provider).Returns(guitars.Provider); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.Expression).Returns(guitars.Expression); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.ElementType).Returns(guitars.ElementType); mockDbSet.As<IQueryable<Guitar>>().Setup(p => p.GetEnumerator()).Returns(guitars.GetEnumerator); var mockContext = new Mock<RentalContext>(); mockContext.Setup(g => g.Guitars).Returns(mockDbSet.Object); var service = new GuitarService(mockContext.Object); var style = service.GetStyle(4); style.Should().Be("Pink"); } } }
Markdown
UTF-8
1,510
3.3125
3
[]
no_license
## input组件 包含了 - input输入框 - radio单选项 - select下拉框 - textarea文本域 组件接受多个参数: - type(optional): 组件类型,包括textarea、select、radio,默认为text - label(optional):label项,显示在input之前 - value(require):值 - name(optional):name选项 - options:在`type`等于`select`或`radio`时为必须项。 - placeholder(optional):原生属性 - required(optional):原生属性,是否必填 ### Usage 使用方法 上手即用,对不同类型的input,需绑定不同事件来监听值的改变。 ``` html <template> <v-input v-for="data in inputData" :key="data.name" v-bind="data" @input=data.value = $event @selectChange=data.vaule = $evnet @radioChange=data.value = $event> </template> <script> data() { return { inputData: [ { label: '姓名', value: '', name: 'realName', placeholder: '请输入你的姓名' }, { label: '公司性质', value: 'default', name: 'companyType', type: 'select', options: [ { label: '请输入公司类型', value: 'default', disabled: true }, { label: 'A类公司', value: 'a' }, { label: 'B类公司', value: 'b' } ] } ] } } </script> ```
Markdown
UTF-8
2,208
3.65625
4
[]
no_license
# Root to Leaf Paths ## Easy <div class="problem-statement"> <p></p><p><span style="font-size:18px">Given a Binary Tree of size N, you need to find&nbsp;all the possible paths&nbsp;from root node to all the leaf&nbsp;node's of the binary tree.</span></p> <p><span style="font-size:18px"><strong>Example 1:</strong></span></p> <pre><span style="font-size:18px"><strong>Input:</strong> 1 / \ 2 3 <strong>Output: </strong>1 2&nbsp;#1 3&nbsp;# <strong>Explanation: </strong> All possible paths: 1-&gt;2 1-&gt;3 </span> </pre> <p dir="ltr"><strong><span style="font-size:18px">Example 2:</span></strong></p> <pre><span style="font-size:18px"><strong>Input: &nbsp; </strong>10 &nbsp; / \ &nbsp; 20 30 &nbsp; / \ &nbsp; 40 60<strong> Output: </strong>10 20 40 #10 20 60 #10 30 # </span> </pre> <p dir="ltr"><span style="font-size:18px"><strong>Your Task:</strong><br> Your task is to complete the function&nbsp;<strong>Paths()</strong>&nbsp;that takes the root node as an argument and return all the possible path. (All the path are printed '#' separated by the driver's code.)</span></p> <p dir="ltr"><strong><span style="font-size:18px">Note:&nbsp;</span></strong><span style="font-size:18px">The return type<br> <strong>cpp:&nbsp;</strong>vector<br> <strong>java:&nbsp;</strong>ArrayList&gt;<br> <strong>python:&nbsp;</strong>list of list</span></p> <p><span style="font-size:18px"><strong>Expected Time Complexity:&nbsp;</strong>O(N).<br> <strong>Expected Auxiliary Space:&nbsp;</strong>O(H).</span><br> <span style="font-size:18px"><strong>Note:&nbsp;</strong>H is the height of the tree.</span></p> <p><span style="font-size:18px"><strong>Constraints:</strong><br> 1&lt;=N&lt;=10<sup>3</sup></span></p> <p><strong>Note:&nbsp;</strong>The <strong>Input/Ouput</strong> format and <strong>Example</strong> given, are used for the system's internal purpose, and should be used by a user for <strong>Expected Output</strong> only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.</p> <p></p> </div>
Java
UTF-8
235
1.59375
2
[]
no_license
package com.webosmotic.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.webosmotic.entity.ProductSummary; public interface ProductSummaryRepository extends JpaRepository<ProductSummary, Long>{ }
PHP
UTF-8
548
2.75
3
[ "MIT" ]
permissive
<?php $target_dir = "uploads/"; $target_file = $target_dir. basename($_FILES["fileToUpload"]["name"]); while (file_exists($target_file)) { $target_file = substr($target_file,0,strrpos($target_file,".",-1))."0".substr($target_file,strrpos($target_file,".",-1)); } if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "http://".$_SERVER['HTTP_HOST'].substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'],"/",-1))."/".$target_file; } else { echo "Sorry, there was an error uploading your file."; } ?>
TypeScript
UTF-8
1,573
2.921875
3
[]
no_license
import { Component, OnInit, OnDestroy } from '@angular/core'; import { interval, Subscription, Observable } from 'rxjs'; import { map, filter } from 'rxjs/operators'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit, OnDestroy { private obsSubscripion: Subscription; constructor() { } ngOnInit() { // this.obsSubscripion = interval(1000).subscribe( // count => { // console.log(count); // } // ); const customeInterval = Observable.create((observer) => { let count = 0; setInterval(() => { observer.next(count) count++; if(count == 5){ observer.complete();} if(count === 6){ observer.error('Oops! the counter is up to 3...') } }, 1000); }); /** it can take 3 paramters * 1-the method to process * 2- the error * 3- the complete subscribtion */ /** it can handel error in subscription */ /** the filter() and map() are called operators from rxjs */ this.obsSubscripion = customeInterval.pipe( filter(data => { return data > 0}) ,map((data: number) => { return 'Round ' + (data + 1)})) .subscribe(data => { console.log(data); }, error => {console.log( error)}, () => {console.log('completed!')} ); } /** we need destroy method because observable is running all of the time for the program is running */ ngOnDestroy(){ this.obsSubscripion.unsubscribe(); } }
Java
UTF-8
9,645
2.203125
2
[]
no_license
package com.appirio.service.member.manager; import com.appirio.service.member.api.ExternalLinkURL; import com.appirio.service.member.api.MemberExternalLink; import com.appirio.service.member.api.MemberExternalLinkData; import com.appirio.service.member.api.MemberProfile; import com.appirio.service.member.dao.MemberExternalLinksDAO; import com.appirio.service.member.dao.MemberProfileDAO; import com.appirio.supply.Messages; import com.appirio.supply.SupplyException; import com.appirio.supply.ValidationException; import com.appirio.tech.core.auth.AuthUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.InvocationTargetException; import java.security.NoSuchAlgorithmException; import java.util.*; /** * Manager for Member external links * * Created by rakeshrecharla on 10/19/15. */ public class MemberExternalLinksManager { /** * Logger for the class */ private Logger logger = LoggerFactory.getLogger(MemberExternalLinksManager.class); /** * DAO for Member external links */ private MemberExternalLinksDAO memberExternalLinksDAO; /** * DAO for Member profile */ private MemberProfileDAO memberProfileDAO; /** * Constructor to initialize DAOs for member external accounts and member profile * @param memberExternalLinksDAO Member external accounts DAO * @param memberProfileDAO Member profile DAO */ public MemberExternalLinksManager(MemberExternalLinksDAO memberExternalLinksDAO, MemberProfileDAO memberProfileDAO) { this.memberExternalLinksDAO = memberExternalLinksDAO; this.memberProfileDAO = memberProfileDAO; } /** * Get MD5 hash * @param txt String text * @return Hash * @throws NoSuchAlgorithmException Exception for no such algorithm */ public static String getHash(String txt) throws NoSuchAlgorithmException { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(txt.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } /** * Get member external links * @param handle Handle of the user * @return MemberExternalLinkData list */ public List<MemberExternalLinkData> getMemberExternalLinks(String handle) throws SupplyException { MemberProfile memberProfile = memberProfileDAO.validateHandle(handle, null, true); Map<String, MemberExternalLinkData> linksDataMap = new HashMap<String, MemberExternalLinkData>(); List<MemberExternalLink> memberExternalLinkList = memberExternalLinksDAO.getMemberExternalLinks( memberProfile.getUserId()); List<MemberExternalLinkData> memberExternalLinkDataList = memberExternalLinksDAO.getMemberExternalLinksData( memberProfile.getUserId()); logger.debug("Total external links : " + memberExternalLinkList.size()); logger.debug("Total external links data : " + memberExternalLinkDataList.size()); for (MemberExternalLinkData memberExternalLinkData : memberExternalLinkDataList) { linksDataMap.put(memberExternalLinkData.getKey(), memberExternalLinkData); } List<MemberExternalLinkData> memberExternalLinkNewDataList = new ArrayList<MemberExternalLinkData>(); for (int linksIndex = 0; linksIndex < memberExternalLinkList.size(); linksIndex++) { MemberExternalLink memberExternalLink = memberExternalLinkList.get(linksIndex); if (!memberExternalLink.getIsDeleted()) { MemberExternalLinkData memberExternalLinkData; String key = memberExternalLink.getKey(); if (linksDataMap.containsKey(key)) { memberExternalLinkData = linksDataMap.get(key); memberExternalLinkData.setHandle(memberProfile.getHandle()); } else { memberExternalLinkData = new MemberExternalLinkData(); memberExternalLinkData.setUserId(memberProfile.getUserId()); memberExternalLinkData.setKey(key); memberExternalLinkData.setHandle(memberProfile.getHandle()); } memberExternalLinkData.setUrl(memberExternalLink.getUrl()); memberExternalLinkData.setSynchronizedAt(memberExternalLink.getSynchronizedAt()); memberExternalLinkNewDataList.add(memberExternalLinkData); } } return memberExternalLinkNewDataList; } /** * Validate external link URL * @param externalLinkURL External link URL * @throws IllegalAccessException Exception for illegal access * @throws InvocationTargetException Exception for invocation target * @throws InstantiationException Exception for instantiation * @throws SupplyException Exception for supply * @throws NoSuchMethodException Exception for no such method */ private void validateExternalLinkUrl(ExternalLinkURL externalLinkURL) throws IllegalAccessException, InvocationTargetException, InstantiationException, SupplyException, NoSuchMethodException { List<String> validationMessages = externalLinkURL.validate(); if (validationMessages != null && validationMessages.size() > 0) { String concatMessage = ""; for (String msg : validationMessages) { concatMessage += msg + " | "; } ValidationException validationException = new ValidationException(concatMessage); validationException.setValidationMessages(validationMessages); throw validationException; } } /** * Create member external link * @param handle Handle of the user * @param authUser Authentication user * @param externalLinkURL External link URL * @return Member External link data list * @throws SupplyException Exception for Supply * @throws NoSuchAlgorithmException Exception for no such algorithm */ public MemberExternalLink createMemberExternalLink(String handle, AuthUser authUser, ExternalLinkURL externalLinkURL) throws SupplyException, NoSuchAlgorithmException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { MemberProfile memberProfile = memberProfileDAO.validateHandle(handle, authUser, false); validateExternalLinkUrl(externalLinkURL); MemberExternalLink memberExternalLink = new MemberExternalLink(); memberExternalLink.setUserId(memberProfile.getUserId()); memberExternalLink.setUrl(externalLinkURL.getUrl()); if (externalLinkURL.getUrl() != null) { String url = memberExternalLink.getUrl(); String key = memberProfile.getUserId() + ":" + url.replaceFirst("http://", "").replaceFirst("https://", ""); logger.debug("key : " + key); memberExternalLink.setKey(getHash(key)); } memberExternalLink.setSynchronizedAt(0L); memberExternalLink.setIsDeleted(false); memberExternalLink.setHasErrored(false); memberExternalLink.setCreatedAt(new Date()); memberExternalLink.setUpdatedAt(new Date()); MemberExternalLink existingMemberExternalLink = memberExternalLinksDAO.getMemberExternalLink( memberProfile.getUserId(), memberExternalLink.getKey()); if (existingMemberExternalLink != null && existingMemberExternalLink.getIsDeleted() == false) { throw new SupplyException(String.format(Messages.EXTERNAL_LINK_URL_ALREADY_EXISTS, memberExternalLink.getUrl(), memberProfile.getHandle()), HttpServletResponse.SC_BAD_REQUEST); } memberExternalLinksDAO.updateMemberExternalLink(memberExternalLink); return memberExternalLinksDAO.getMemberExternalLink(memberProfile.getUserId(), memberExternalLink.getKey()); } /** * Delete member external link * @param handle Handle of the user * @param key Key * @param authUser Authentication user * @return MemberExternalLinkData list * @throws SupplyException Exception for supply */ public MemberExternalLink deleteMemberExternalLink(String handle, String key, AuthUser authUser) throws SupplyException { MemberProfile memberProfile = memberProfileDAO.validateHandle(handle, authUser, false); MemberExternalLink memberExternalLink = memberExternalLinksDAO.getMemberExternalLink(memberProfile.getUserId(), key); if (memberExternalLink == null || memberExternalLink.getIsDeleted() == true) { throw new SupplyException(String.format(Messages.EXTERNAL_LINK_KEY_NOT_FOUND, key, memberProfile.getHandle()), HttpServletResponse.SC_NOT_FOUND); } memberExternalLink.setIsDeleted(true); memberExternalLinksDAO.updateMemberExternalLink(memberExternalLink); return memberExternalLinksDAO.getMemberExternalLink(memberProfile.getUserId(), key); } }
Python
UTF-8
431
3.296875
3
[]
no_license
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(11,GPIO.OUT) servo1 = GPIO.PWM(11,50) # note. pin 11 will output 50hz pulse servo1.start(0) time.sleep(2) duty = 2 while duty <=12: servo1.ChangeDutyCycle(duty) time.sleep(1) duty = duty + 1 time.sleep(2) print ("turning back 90 degrees") servo1.ChangeDutyCycle(7) time.sleep(1) servo1.ChangeDutyCycle(0) servo1.stop() GPIO.cleanup()