identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/zenas001/bankMaster/blob/master/server/src/main/java/com/zenas/WebConfiguration.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
bankMaster
|
zenas001
|
Java
|
Code
| 104
| 510
|
package com.zenas;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author Kevin Zou (kevinz@weghst.com)
*/
@Configuration
@RestController
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Value("classpath:/ui/index.html")
private Resource indexHtml;
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new CharacterEncodingFilter("UTF-8", true);
return filter;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/ui/");
}
@Bean
public ServletRegistrationBean apiV1ServletBean(WebApplicationContext wac) {
DispatcherServlet servlet = new DispatcherServlet(wac);
ServletRegistrationBean bean = new ServletRegistrationBean(servlet, "/api/v1/*");
bean.setName("api-v1");
return bean;
}
@RequestMapping("/")
public Object index() {
return ResponseEntity.ok().body(indexHtml);
}
}
| 16,228
|
https://github.com/Kautenja/CBOE-emulator/blob/master/docs/search/variables_e.js
|
Github Open Source
|
Open Source
|
MIT
| null |
CBOE-emulator
|
Kautenja
|
JavaScript
|
Code
| 6
| 225
|
var searchData=
[
['reason_507',['reason',['../struct_order_entry_1_1_messages_1_1_logout_response.html#a4e8ceaa80363d12e0aaaae84d8f8ba56',1,'OrderEntry::Messages::LogoutResponse']]],
['root_508',['root',['../struct_data_feed_1_1_l_o_b_1_1_limit_tree.html#aa5d78bfbf4d2d89b4a4a7e5a79d69d5b',1,'DataFeed::LOB::LimitTree::root()'],['../struct_order_entry_1_1_l_o_b_1_1_limit_tree.html#a3ac3b0e3e5575a95b3ed35325cdc1dbd',1,'OrderEntry::LOB::LimitTree::root()']]]
];
| 10,767
|
https://github.com/ADCPD/cma/blob/master/src/Cma/CmaBundle/Resources/views/Default/Certificat/index.html.twig
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
cma
|
ADCPD
|
Twig
|
Code
| 120
| 523
|
{% extends 'CmaBundle:Administrator:index.html.twig' %}
{% block body -%}
<div class="row-fluid">
<div class="span12" style="margin-top: 5%;">
<div class="span12">
<section class="panel"><header class="panel-heading">
Liste des slides :
</header>
<div class="row-fluid text-small">
<a href="{{path('certificat_add')}}">
<button type="button" class="btn btn-info"><i class="icon-plus-sign"></i> Ajouter une certificat</button>
</a>
<div class="pull-out m-t-small">
<table class="table table-striped b-t text-small">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
<th>Tag</th>
<th>Certificat</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entity in certficat%}
<tr>
<td>{{ entity.id }}</td>
<td>{{ entity.title }}</td>
<td>{{ entity.description }}</td>
<td>
<img src="{{ asset(entity.getWebPath()) }}" width="100px"/></td>
<td>
<a href="{{ path('certificat_edit', { 'id': entity.id }) }}">
<button type="button"><i class="fa fa-pencil-square-o red"></i>modifier</button>
</a>
<a href="{{ path('certificat_drop', { 'id': entity.id }) }}">
<button type="button"><i class="fa fa-times"></i>effacer</button>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
</div>
</div>
</div>
{% endblock %}
| 10,665
|
https://github.com/cts-randrid/WurmAssistant3/blob/master/src/Common/Essentials/Extensions/DotNet/TimeSpanExtensions.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
WurmAssistant3
|
cts-randrid
|
C#
|
Code
| 302
| 957
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AldursLab.Essentials.Extensions.DotNet
{
public static class TimeSpanExtensions
{
public static TimeSpan StripMilliseconds(this TimeSpan timeSpan)
{
return new TimeSpan(timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
}
/// <summary>
/// Multiplies by an integer value.
/// </summary>
public static TimeSpan Multiply(this TimeSpan multiplicand, int multiplier)
{
return TimeSpan.FromTicks(multiplicand.Ticks * multiplier);
}
/// <summary>
/// Multiplies by a double value.
/// </summary>
public static TimeSpan Multiply(this TimeSpan multiplicand, double multiplier)
{
return TimeSpan.FromTicks((long)(multiplicand.Ticks * multiplier));
}
/// <summary>
/// Converts timespan to string similar to: "9d", "3d 22h", "18h", "3h 22m", "22m"
/// </summary>
/// <param name="timespan"></param>
/// <param name="resolution"></param>
/// <returns></returns>
public static string ToStringCompact(this TimeSpan timespan, CompactResolution resolution = CompactResolution.Seconds)
{
//todo unit test
switch (resolution)
{
case CompactResolution.Seconds:
return ToStringCompactSecondsResolution(timespan);
case CompactResolution.Minutes:
return ToStringCompactMinutesResolution(timespan);
default:
Debug.Fail("unexpected CompactResolution " + resolution);
return ToStringCompactSecondsResolution(timespan);
}
}
static string ToStringCompactSecondsResolution(TimeSpan timespan)
{
double totalMinutes = timespan.TotalMinutes;
if (totalMinutes < 0)
{
return "unsupported";
}
else if (totalMinutes < 10)
{
return timespan.ToString("m'm 's's'");
}
else if (totalMinutes < 1 * 60)
{
return timespan.ToString("m'm'");
}
else if (totalMinutes < 6 * 60)
{
return timespan.ToString("h'h 'm'm'");
}
else if (totalMinutes < 24 * 60)
{
return timespan.ToString("h'h'");
}
else if (totalMinutes < 144 * 60)
{
return timespan.ToString("d'd 'h'h'");
}
else
{
return timespan.ToString("d'd'");
}
}
static string ToStringCompactMinutesResolution(TimeSpan timespan)
{
double totalMinutes = timespan.TotalMinutes;
if (totalMinutes < 0)
{
return "unsupported";
}
else if (totalMinutes < 1 * 60)
{
return timespan.ToString("m'm'");
}
else if (totalMinutes < 6 * 60)
{
return timespan.ToString("h'h 'm'm'");
}
else if (totalMinutes < 24 * 60)
{
return timespan.ToString("h'h'");
}
else if (totalMinutes < 144 * 60)
{
return timespan.ToString("d'd 'h'h'");
}
else
{
return timespan.ToString("d'd'");
}
}
}
public enum CompactResolution
{
Seconds = 0,
Minutes
}
}
| 31,653
|
https://github.com/instructure/lti_codeshare_engine/blob/master/app/assets/javascripts/lti_codeshare_engine/app.js
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
lti_codeshare_engine
|
instructure
|
JavaScript
|
Code
| 166
| 650
|
App = Ember.Application.create();
App.Router.map(function() {
this.route('index', { path: '/' });
this.route('embed', { path: '/embed' });
});
App.IndexController = Ember.Controller.extend({
needs: ['embed'],
actions: {
verify: function() {
var _this = this;
var postUrl = Ember.ENV['root_path'] + 'api/create_entry_from_url';
this.set('error', null);
this.set('entry', null);
ic.ajax({
type: "POST",
url: postUrl,
data: { url: this.get('url') }
}).then(
function(result) {
_this.set('entry', Em.Object.create(result));
},
function(result) {
var errorMessage = result.jqXHR.responseJSON.error;
_this.set('error', errorMessage);
}
);
},
reset: function() {
this.set('error', null);
this.set('entry', null);
this.set('url', null);
},
embed: function() {
var _this = this;
var embedUrl = Ember.ENV.root_path + 'embed';
ic.ajax({
type: "POST",
url: embedUrl,
data: { launch_params: Ember.ENV.launch_params, uuid: this.get('entry.uuid') }
}).then(
function(result) {
window.location = result.redirect_url;
},
function(result) {
var embedObject = Ember.Object.create(result.jqXHR.responseJSON);
_this.get('controllers.embed').set('model', embedObject);
_this.transitionToRoute('embed');
}
);
}
}
});
App.IndexRoute = Ember.Route.extend({});
App.EmbedController = Ember.ObjectController.extend({
embedCode: function() {
return '<iframe src="' + this.get('url') + '" frameborder="0" style="position: absolute; height: 100%; overflow: hidden; width:100%;" height="100%" width="100%" allowfullscreen></iframe>';
}.property('model')
});
App.EmbedRoute = Ember.Route.extend({
setupController: function(controller, model) {
if (Ember.isEmpty(controller.get('model'))) {
this.transitionTo('index');
}
}
});
| 39,195
|
https://github.com/andoriyu/material-design-icons-rs/blob/master/src/materialicons/image/icon_panorama_horizontal_select.rs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
material-design-icons-rs
|
andoriyu
|
Rust
|
Code
| 113
| 620
|
pub struct IconPanoramaHorizontalSelect {
props: crate::Props,
}
impl yew::Component for IconPanoramaHorizontalSelect {
type Properties = crate::Props;
type Message = ();
fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self
{
Self { props }
}
fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender
{
true
}
fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender
{
false
}
fn view(&self) -> yew::prelude::Html
{
yew::prelude::html! {
<svg
class=self.props.class.unwrap_or("")
width=self.props.size.unwrap_or(24).to_string()
height=self.props.size.unwrap_or(24).to_string()
viewBox="0 0 24 24"
fill=self.props.fill.unwrap_or("none")
stroke=self.props.color.unwrap_or("currentColor")
stroke-width=self.props.stroke_width.unwrap_or(2).to_string()
stroke-linecap=self.props.stroke_linecap.unwrap_or("round")
stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round")
>
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M21.43 4c-.1 0-.2.02-.31.06C18.18 5.16 15.09 5.7 12 5.7s-6.18-.55-9.12-1.64C2.77 4.02 2.66 4 2.57 4c-.34 0-.57.23-.57.63v14.75c0 .39.23.62.57.62.1 0 .2-.02.31-.06 2.94-1.1 6.03-1.64 9.12-1.64s6.18.55 9.12 1.64c.11.04.21.06.31.06.33 0 .57-.23.57-.63V4.63c0-.4-.24-.63-.57-.63z"/></svg>
</svg>
}
}
}
| 34,228
|
https://github.com/GabrielGhe/Connect4/blob/master/ConnectFourClient/src/cs543/project1/connectfour/C4ContentCardLayout.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Connect4
|
GabrielGhe
|
Java
|
Code
| 1,142
| 3,438
|
package cs543.project1.connectfour;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import cs543.project1.connectfour.C4BoardPanel.GameType;
/**
* This is the Card Layout which will contain Panels to which will be rotated as
* the user play or interact with the menu.
*
* @author Natacha Gabbamonte
* @author Gabriel Gheorghian
* @author Mark Scerbo
*
*/
public class C4ContentCardLayout implements Observer {
private C4Menu menu;
private JPanel content;
private C4Model model;
private C4ScorePanel score;
private C4GamePanel gamePanel = null;
private final static String INPUTPANEL = "Input";
private final static String GAMEPANEL = "Game";
private final static String SCOREPANEL = "Score";
/**
*
* Constructor creating the card layout and populating the panels to be used
* with in the GUI.
*
* @param menu
* handle to the menu
* @throws UnknownHostException
* @throws IOException
*/
public C4ContentCardLayout(C4Menu menu) throws UnknownHostException,
IOException {
this.menu = menu;
CardLayout card = new CardLayout(25, 25);
content = new JPanel(card);
content.setPreferredSize(new Dimension(500, 500));
model = new C4Model();
model.addObserver(this);
C4InputPanel inputPanel = new C4InputPanel(this);
score = new C4ScorePanel();
content.add(inputPanel, INPUTPANEL);
content.add(score, SCOREPANEL);
}
/**
* This will activate the game play for the client to start playing.
*
* @param ipNumber
* (to be used to connect to the server)
* @throws UnknownHostException
* @throws IOException
*/
public void startGame(String ipNumber) throws UnknownHostException,
IOException {
gamePanel = new C4GamePanel(ipNumber, model);
content.add(gamePanel, GAMEPANEL);
((CardLayout) content.getLayout()).show(content, GAMEPANEL);
menu.enableNewGame();
requestFocusForPanel();
}
public void requestFocusForPanel() {
gamePanel.requestFocusForPanel();
}
/**
* Will rotate the panels in the CardLayout
*
* @param panel
* (the panel to be displayed)
* @throws IOException
*/
public void changePanel(String panel, GameType gameType) throws IOException {
if (panel.equals(GAMEPANEL)) {
gamePanel.getBoardPanel().forfeit(gameType);
} else {
((CardLayout) content.getLayout()).show(content, panel);
}
}
/**
* Returns the content panel.
*
* @return The content panel.
*/
public Container getConnectFourContent() {
return content;
}
private Timer t = null;
/**
* updates the display
*/
@Override
public void update(Observable o, Object arg) {
if (model.getGameIsOver()) {
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
score.setScore();
try {
changePanel(SCOREPANEL, null);
score.requestFocusForPanel();
} catch (IOException e) {
model.setMessage("An error has occured: "
+ e.getMessage());
}
t.cancel();
}
}, 1000);
} else {
if (gamePanel != null) {
((CardLayout) content.getLayout()).show(content, GAMEPANEL);
}
}
}
/**
* Inner class to create the panel to be displayed in the card layout during
* Game play
*
* @author Natacha Gabbamonte
* @author Gabriel Gheorghian
* @author Mark Scerbo
*/
private class C4GamePanel extends JPanel implements Observer {
private static final long serialVersionUID = 5636939329643138282L;
private C4BoardPanel board;
private C4Model model;
JLabel message;
/**
* Constructor in creating the C4GamePanel
*
* @param ipNumber
* (the ip address for the server connection)
* @param model
* :handle to the model
* @throws UnknownHostException
* @throws IOException
*/
public C4GamePanel(String ipNumber, C4Model model)
throws UnknownHostException, IOException {
setLayout(new GridBagLayout());
this.model = model;
model.addObserver((Observer) this);
JLabel heading = new JLabel("Connect Four", JLabel.CENTER);
heading.setFont(new Font("Arial", Font.PLAIN, 25));
message = new JLabel("Error message will go here!", JLabel.CENTER);
board = new C4BoardPanel(model, ipNumber);
board.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(heading, makeConstraints(0, 0, 1, 1, .2, .2));
add(message, makeConstraints(0, 1, 1, 1, .2, .2));
add(board, makeConstraints(0, 2, 1, 1, 1, 1));
}
public void requestFocusForPanel() {
board.requestFocusForPanel();
}
/**
* Returns the board.
*
* @return current board
*/
public C4BoardPanel getBoardPanel() {
return board;
}
/**
* Updates the message stating state of play
*/
@Override
public void update(Observable o, Object arg) {
message.setText(model.getMessage());
}
}
/**
* This is the panel to display player's score. This may be displayed in
* several locations.
*
* @author Natacha Gabbamonte
* @author Gabriel Gheorghian
* @author Mark Scerbo
*
*/
private class C4ScorePanel extends JPanel {
private static final long serialVersionUID = -3115017397824719761L;
JLabel winL;
JLabel lossL;
JLabel drawL;
JLabel winner;
JButton yesButton;
JButton noButton;
JLabel question;
String[] winners = new String[] { "IT'S A DRAW", "PLAYER ONE WON!",
"PLAYER TWO WON!" };
String[] questions = new String[] { "Would you like to play again?",
"Would you like to start a new Multiplayer game?",
"Would you like to start a new Singleplayer game?" };
/**
* Constructor to the Score panel populates variables and proccess them.
*/
public C4ScorePanel() {
setLayout(new GridBagLayout());
winL = new JLabel("", JLabel.CENTER);
lossL = new JLabel("", JLabel.CENTER);
drawL = new JLabel("", JLabel.CENTER);
winner = new JLabel("", JLabel.CENTER);
winner.setFont(new Font("Times New Roman", Font.BOLD, 20));
question = new JLabel(" ", JLabel.CENTER);
yesButton = new JButton("Yes");
yesButton.addActionListener(new ActionListener() {
/**
* updates the content
*/
@Override
public void actionPerformed(ActionEvent e) {
menu.enableNewGame();
try {
gamePanel.getBoardPanel().playerWantsToPlayAgain();
} catch (IOException e1) {
model.setMessage("An error has occured: "
+ e1.getMessage());
((CardLayout) content.getLayout())
.show(content, "GAME");
}
}
});
noButton = new JButton("No");
noButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
gamePanel.getBoardPanel().playerDoesntWantToPlayAgain();
} catch (IOException e1) {
model.setMessage("An error has occured: "
+ e1.getMessage());
((CardLayout) content.getLayout())
.show(content, "GAME");
}
System.exit(0);
}
});
// Adds a keyboard listener to listen for Y or N.
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
char key = e.getKeyChar();
switch (key) {
case 'y':
case 'Y':
yesButton.doClick();
break;
case 'n':
case 'N':
noButton.doClick();
break;
}
}
});
JLabel gameOverLabel = new JLabel("Game Over", JLabel.CENTER);
gameOverLabel.setFont(new Font("Times New Roman", Font.BOLD, 25));
add(gameOverLabel, makeConstraints(0, 0, 2, 1, 0.2, 0.2));
add(winner, makeConstraints(0, 1, 2, 1, 0.2, 0.2));
add(winL, makeConstraints(0, 2, 2, 1, 0.2, 0.2));
add(lossL, makeConstraints(0, 3, 2, 1, 0.2, 0.2));
add(drawL, makeConstraints(0, 4, 2, 1, 0.2, 0.2));
add(question, makeConstraints(0, 5, 2, 1, 0.2, 0.2));
add(yesButton, makeConstraints(0, 6, 1, 1, 0.2, 0.2));
add(noButton, makeConstraints(1, 6, 1, 1, 0.2, 0.2));
}
/**
* This arranges the text to be displayed on the score panel
*/
public void setScore() {
menu.disableNewGame();
winner.setText(winners[model.getWinner()]);
question.setText(questions[model.getGameOverMessage()]);
winL.setText("Player one's Wins: " + model.getWins());
lossL.setText("Player two's Wins: " + model.getLosses());
drawL.setText("Draws: " + model.getDraws());
if (model.isNextIsNewGame()) {
model.setNextIsNewGame(false);
model.setGameOverMessage(0);
model.resetStats();
}
}
public void requestFocusForPanel() {
this.requestFocusInWindow();
}
}
/**
* sets constraints based on the values sent in
*
* @param gridx
* x coordinates
* @param gridy
* y coordinates
* @param gridwidth
* number of columns to go across
* @param gridheight
* number of rows to go across
* @param weightx
* weight of the component in the x direction
* @param weighty
* weight of the component in the y direction
* @return constraints (the constraints to be added to a component
*/
public static GridBagConstraints makeConstraints(int gridx, int gridy,
int gridwidth, int gridheight, double weightx, double weighty) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridheight = gridheight;
constraints.gridwidth = gridwidth;
constraints.gridx = gridx;
constraints.gridy = gridy;
constraints.weightx = weightx;
constraints.weighty = weighty;
// Default for all the components.
constraints.insets = new Insets(1, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
return constraints;
}
}
| 25,125
|
https://github.com/JasperBouwman/TPort/blob/master/src/com/spaceman/tport/commands/tport/tag/Create.java
|
Github Open Source
|
Open Source
|
MIT
| null |
TPort
|
JasperBouwman
|
Java
|
Code
| 119
| 503
|
package com.spaceman.tport.commands.tport.tag;
import com.spaceman.tport.commandHander.ArgumentType;
import com.spaceman.tport.commandHander.EmptyCommand;
import com.spaceman.tport.commandHander.SubCommand;
import com.spaceman.tport.commands.tport.Tag;
import org.bukkit.entity.Player;
import static com.spaceman.tport.fancyMessage.TextComponent.textComponent;
import static com.spaceman.tport.fancyMessage.colorTheme.ColorTheme.ColorType.infoColor;
import static com.spaceman.tport.fancyMessage.colorTheme.ColorTheme.sendErrorTheme;
import static com.spaceman.tport.fancyMessage.colorTheme.ColorTheme.sendSuccessTheme;
public class Create extends SubCommand {
private final EmptyCommand emptyTag;
public Create() {
emptyTag = new EmptyCommand();
emptyTag.setCommandName("tag", ArgumentType.REQUIRED);
emptyTag.setCommandDescription(textComponent("This command is used to create your own tag", infoColor));
emptyTag.setPermissions("TPort.tag.create", "TPort.admin.tag");
addAction(emptyTag);
}
@Override
public void run(String[] args, Player player) {
// tport tag create <tag>
if (!emptyTag.hasPermissionToRun(player, true)) {
return;
}
if (args.length == 3) {
String tag = Tag.getTag(args[2]);
if (tag != null) {
sendErrorTheme(player, "Tag %s already exist", tag);
return;
}
Tag.createTag(args[2]);
sendSuccessTheme(player, "Successfully created the tag %s", args[2]);
} else {
sendErrorTheme(player, "Usage: %s", "/tport tag create <tag>");
}
}
}
| 21,318
|
https://github.com/wdhif/daily-coding-problem/blob/master/14.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
daily-coding-problem
|
wdhif
|
Python
|
Code
| 130
| 334
|
#!/usr/bin/env python3
"""
The area of a circle is defined as πr². Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x2 + y2 = r2.
"""
import unittest
import math
import random
def generate_points(radius):
x = random.randint(-radius, radius)
y = random.randint(-radius, radius)
return x, y
def in_circle(x, y, radius):
distance = math.sqrt(x ** 2 + y ** 2)
if distance < radius:
return True
return False
def compute_pi():
points_in_circle = 0
points_in_square = 0
radius = 200
for i in range(250000):
x, y = generate_points(radius)
if in_circle(x, y, radius):
points_in_circle += 1
points_in_square += 1
return 4 * (points_in_circle / points_in_square)
class Test(unittest.TestCase):
def test(self):
accuracy = (compute_pi() / math.pi) * 100
self.assertGreater(accuracy, 99)
if __name__ == '__main__':
unittest.main()
| 9,716
|
https://github.com/ConnectBox/wifi-test-framework/blob/master/scripts/downloader.py
|
Github Open Source
|
Open Source
|
MIT
| null |
wifi-test-framework
|
ConnectBox
|
Python
|
Code
| 829
| 2,967
|
#!/usr/bin/env python3
import argparse
from collections import Counter, OrderedDict
import logging
import math
import pathlib
import time
import socket
import sys
import random
import urllib.request
import unittest
# 1GB/sec
UNLIMITED_SPEED = 1000000000
#
TIMESLICE_SECS = 0.01
BYTES_TO_READ = 1024
LOGGER = logging.getLogger("downloader")
class TokenBucket(object):
"""Derived from Alec Thomas' ActiveState Code Recipe
https://code.activestate.com/recipes/511490-implementation-of-the-token-bucket-algorithm/
"""
def __init__(self,
capacity,
initial_tokens,
refill_amount_per_interval,
refill_interval_secs):
# Initial token count == capacity, for arguments sake
self.capacity = int(capacity)
self.initial_tokens = initial_tokens
self._tokens = max(self.capacity, float(initial_tokens))
self.refill_amount_per_interval = float(refill_amount_per_interval)
self.refill_interval_secs = float(refill_interval_secs)
self.last_refill_time = time.time()
def reset(self):
self._tokens = self.initial_tokens
self.last_refill_time = time.time()
def consume(self, tokens_requested):
# Can only consume whole numbers of tokens
assert isinstance(tokens_requested, int)
# Can only offer whole numbers of tokens
available_tokens = math.floor(self.available_tokens())
if tokens_requested > available_tokens:
self._tokens -= available_tokens
return available_tokens
self._tokens -= tokens_requested
return tokens_requested
def available_tokens(self):
if self._tokens < self.capacity:
now = time.time()
if (now - self.last_refill_time) >= self.refill_interval_secs:
# Only do refills until we hit a complete refill period
elapsed_interval_count = \
(now - self.last_refill_time) / self.refill_interval_secs
new_tokens = \
self.refill_amount_per_interval * elapsed_interval_count
# print("ROPI", self.refill_amount_per_interval, "eic",
# elapsed_interval_count, "New tokens: ", new_tokens)
self._tokens = min(self.capacity, self._tokens + new_tokens)
# print("Tokens now:", self._tokens)
self.last_refill_time = now
return self._tokens
class OrderedCounter(OrderedDict, Counter):
"Counter that remembers the order elements are first encountered"
def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, OrderedDict(self))
def __reduce__(self):
return self.__class__, (OrderedDict(self),)
class Downloader(object):
def __init__(self, url, rate_bps):
self.first_timestamp = int(time.time())
self.last_timestamp = int(time.time())
self.url = url
self.rate_bps = rate_bps
self.recvd_bytes_at_timestamp = OrderedCounter()
# bucket is refilled every TIMESLICE_SECS with the
# data rate at rate/sec * 1/TIMESLICE_SECS
self.download_quota = TokenBucket(
self.rate_bps, 0, self.rate_bps * TIMESLICE_SECS, TIMESLICE_SECS)
self.test_identifier = "{0}_{1}".format(socket.getfqdn(),
random.randint(0, pow(2, 24)))
# Populated in run()
self.remote_site = None
def service_once(self):
now_secs = int(time.time())
if now_secs > self.last_timestamp:
LOGGER.info("%s - %s received bytes: %s",
self.last_timestamp,
self.test_identifier,
self.recvd_bytes_at_timestamp[self.last_timestamp])
max_bytes_to_read = self.download_quota.consume(BYTES_TO_READ)
if max_bytes_to_read > 0:
newly_read = self.remote_site.read(max_bytes_to_read)
self.recvd_bytes_at_timestamp[now_secs] += len(newly_read)
self.last_timestamp = now_secs
return len(newly_read)
return 0
def run(self):
self.remote_site = urllib.request.urlopen(self.url)
# Reset the counter when the URL has actually been opened otherwise
# we accrue tokens while the connection is being established
self.download_quota.reset()
# XXX what happens if this is over a slow link?
while self.remote_site.length > 0:
bytes_read = self.service_once()
if bytes_read == 0:
time.sleep(TIMESLICE_SECS)
def report(self, stats_fd):
LOGGER.debug("Writing stats to %s", stats_fd.name)
if self.recvd_bytes_at_timestamp[self.last_timestamp] == 0:
# It was a zero-byte read at the end... discard
del self.recvd_bytes_at_timestamp[self.last_timestamp]
self.last_timestamp -= 1
# Even if we We always have at least 1 second
elapsed_secs = 1 + self.last_timestamp - self.first_timestamp
recvd_bytes_total = sum(
self.recvd_bytes_at_timestamp.values())
LOGGER.info("Received %s bytes in %s secs at %s bytes per sec",
recvd_bytes_total,
elapsed_secs,
int(recvd_bytes_total/elapsed_secs))
stats_fd.write("#client_test_id,timestamp,bytes_per_sec\n")
for timestamp, byte_count in self.recvd_bytes_at_timestamp.items():
stats_fd.write("{0},{1:d},{2:d}\n".format(
self.test_identifier,
timestamp,
byte_count))
def main():
parser = argparse.ArgumentParser()
# 250000 bytes/sec = 2Mbit/sec = max 480p
parser.add_argument(
"-b", "--bps",
type=int,
default=UNLIMITED_SPEED,
help="the speed of the connection bytes per sec (default: unlimited)")
parser.add_argument(
"-d", "--output-file-dir",
default="/tmp",
help="the base directory used for storage of test measurements. "
"- implies no storage and print results to stdout. "
"(default: /tmp)")
parser.add_argument(
"-s", "--sleep",
type=int,
default=0,
help="the number of seconds to sleep before starting the test")
parser.add_argument(
"-v", "--verbose",
action="store_true"
)
parser.add_argument(
"url",
help="the url to download")
args = parser.parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig()
if args.sleep:
LOGGER.debug("Sleeping for %s seconds before starting test",
args.sleep)
time.sleep(args.sleep)
else:
LOGGER.debug("Starting test immediately (no sleeping)")
dler = Downloader(args.url, args.bps)
dler.run()
# The default output file requires the test id, which is only available
# once the test has run, so we process these arguments late.
if args.output_file_dir == "-":
stats_fd = sys.stdout
else:
output_path = pathlib.Path(args.output_file_dir,
"{0}.csv".format(dler.test_identifier))
stats_fd = open(str(output_path), "w")
dler.report(stats_fd)
class TokenBucketTestCase(unittest.TestCase):
def testDryBucket(self):
tb = TokenBucket(0, 0, 0, 0)
tokens = tb.consume(0)
self.assertEqual(tokens, 0)
# Wait, to demonstrate it doesn't refill
time.sleep(1)
tokens = tb.consume(0)
self.assertEqual(tokens, 0)
def testZeroCapacityBucket(self):
tb = TokenBucket(0, 0, 1, 1)
tokens = tb.consume(1)
self.assertEqual(tokens, 0)
# Wait, to demonstrate it doesn't refill
time.sleep(1)
tokens = tb.consume(0)
self.assertEqual(tokens, 0)
def testIntegerRefill(self):
one_per_sec = TokenBucket(1, 1, 1, 1)
tokens = one_per_sec.consume(1)
self.assertEqual(tokens, 1)
# refill (1 token per second)
time.sleep(1)
tokens = one_per_sec.consume(1)
self.assertEqual(tokens, 1)
def testFulfilPartialRequest(self):
one_per_sec = TokenBucket(1, 1, 1, 1)
tokens = one_per_sec.consume(2)
self.assertEqual(tokens, 1)
# refill (1 token per second)
time.sleep(1)
tokens = one_per_sec.consume(2)
self.assertEqual(tokens, 1)
def testFloatRefillRate(self):
half_per_sec = TokenBucket(1, 1, 0.5, 1)
# Consume initial capacity
tokens = half_per_sec.consume(1)
self.assertEqual(tokens, 1)
# Confirm empty
tokens = half_per_sec.consume(1)
self.assertEqual(tokens, 0)
# wait for a second for a refill
time.sleep(1)
tokens = half_per_sec.consume(1)
# Can only distribute whole numbers of tokens
self.assertEqual(tokens, 0)
# Wait for a second so we have an integer number of tokens available
time.sleep(1)
tokens = half_per_sec.consume(1)
self.assertEqual(tokens, 1)
def testGT1secRefillRate(self):
two_per_two_secs = TokenBucket(2, 2, 2, 2)
# Consume initial capacity
tokens = two_per_two_secs.consume(2)
self.assertEqual(tokens, 2)
# Confirm empty
tokens = two_per_two_secs.consume(1)
self.assertEqual(tokens, 0)
# wait for a second
time.sleep(1)
# Confirm still empty (2 sec refill period)
tokens = two_per_two_secs.consume(1)
self.assertEqual(tokens, 0)
# wait for a second
time.sleep(1)
# Confirm refill
tokens = two_per_two_secs.consume(2)
self.assertEqual(tokens, 2)
if __name__ == "__main__":
main()
| 32,277
|
https://github.com/toanleviet95/tweetme/blob/master/app/assets/javascripts/script.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
tweetme
|
toanleviet95
|
JavaScript
|
Code
| 41
| 266
|
$(document).ready(function(){
$('#your_mind').keydown(function(){
var length = $(this).val().length;
var number = 140 - length;
$('#character_number').text(number);
if(number < 0){
$("#btn_tweet").css('opacity','0.3').css('cursor','default');
$('#character_number').css('color','red');
}else{
$("#btn_tweet").css('opacity','1').css('cursor','pointer');
$('#character_number').css('color','black');
}
});
$('#your_mind').select(function(){
$(this).keyup(function(){
var length = $(this).val().length;
var number = 140 - length;
$('#character_number').text(number);
$("#btn_tweet").css('opacity','1').css('cursor','pointer');
$('#character_number').css('color','black');
});
});
});
| 50,459
|
https://github.com/ekapujiw2002/deco/blob/master/setup.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
deco
|
ekapujiw2002
|
Python
|
Code
| 26
| 103
|
#!/usr/bin/env python
from distutils.core import setup
setup(
name = "deco",
version = "0.6.3",
description = "A decorator for concurrency",
packages = ["deco"],
author='Alex Sherman',
author_email='asherman1024@gmail.com',
url='https://github.com/alex-sherman/deco')
| 31,129
|
https://github.com/stanislavulrych/FreeCAD-Reporting/blob/master/report.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
FreeCAD-Reporting
|
stanislavulrych
|
Python
|
Code
| 1,281
| 5,236
|
import FreeCAD
import FreeCADGui
import string
import json
from FreeCAD import Units
from pivy import coin
from report_utils.resource_utils import uiPath
from report_utils.resource_utils import iconPath
from report_utils import logger
from sql import freecad_sql_parser
from sql.sql_parser import SqlStatementValidationError
from sql.sql_grammar import ParseError
from PySide2.QtWidgets import QTableWidgetItem
from PySide2.QtWidgets import QPlainTextEdit
from PySide2.QtWidgets import QGroupBox
from PySide2.QtWidgets import QLineEdit
from PySide2.QtWidgets import QFormLayout
from PySide2.QtWidgets import QPushButton
from PySide2.QtWidgets import QCheckBox
SQL_PARSER = freecad_sql_parser.newParser()
COLUMN_NAMES = list(string.ascii_uppercase)
def statementsToDict(reportStatements):
statements = []
for reportStatement in reportStatements:
statements.append({
'header': reportStatement.header,
'plainTextStatement': reportStatement.plainTextStatement,
'skipRowsAfter': reportStatement.skipRowsAfter,
'skipColumnNames': reportStatement.skipColumnNames,
'printResultInBold': reportStatement.printResultInBold
})
return {
'statements': statements
}
def dictToStatements(statementDict):
reportStatements = []
for statement in statementDict['statements']:
reportStatement = ReportStatement(statement['header'],
statement['plainTextStatement'], statement['skipRowsAfter'],
statement['skipColumnNames'], statement['printResultInBold'])
reportStatements.append(reportStatement)
return reportStatements
def nextColumnName(actualColumnName):
if actualColumnName is None:
return COLUMN_NAMES[0]
nextIndex = COLUMN_NAMES.index(actualColumnName) + 1
if nextIndex >= len(COLUMN_NAMES):
nextIndex -= len(COLUMN_NAMES)
return COLUMN_NAMES[nextIndex]
def lineRange(startColumn, endColumn, lineNumber):
return cellRange(startColumn, lineNumber, endColumn, lineNumber)
def cellRange(startColumn, startLine, endColumn, endLine):
return '%s%s:%s%s' % (startColumn, startLine, endColumn, endLine)
def buildCellName(columnName, lineNumber):
return '%s%s' % (columnName, lineNumber)
def literalText(text):
return "'%s" % (text)
class ReportSpreadsheet(object):
def __init__(self, spreadsheet):
self.spreadsheet = spreadsheet
self.lineNumber = 1
self.maxColumn = None
def clearAll(self):
self.spreadsheet.clearAll()
def printHeader(self, header, numberOfColumns):
spreadsheet = self.spreadsheet
if header is None or header == '':
return
headerCell = 'A%s' % (self.lineNumber)
self.setCellValue(headerCell, header)
spreadsheet.setStyle(headerCell, 'bold|underline', 'add')
if numberOfColumns > 1:
lastColumnCell = COLUMN_NAMES[numberOfColumns - 1]
spreadsheet.mergeCells(
lineRange('A', lastColumnCell, self.lineNumber))
self.lineNumber += 1
self.updateMaxColumn('A')
self.clearLine(self.lineNumber)
def printColumnLabels(self, columnLabels):
spreadsheet = self.spreadsheet
columnName = None
for columnLabel in columnLabels:
columnName = nextColumnName(columnName)
cellName = buildCellName(columnName, self.lineNumber)
self.setCellValue(cellName, columnLabel)
spreadsheet.setStyle(
lineRange('A', columnName, self.lineNumber), 'bold', 'add')
self.lineNumber += 1
self.updateMaxColumn(columnName)
self.clearLine(self.lineNumber)
def printRows(self, rows, skipRowsAfter=False, printResultInBold=False):
lineNumberBefore = self.lineNumber
columnName = 'A'
for row in rows:
columnName = None
for column in row:
columnName = nextColumnName(columnName)
cellName = buildCellName(columnName, self.lineNumber)
self.setCellValue(cellName, column)
self.lineNumber += 1
if printResultInBold:
self.spreadsheet.setStyle(
cellRange('A', lineNumberBefore, columnName, self.lineNumber), 'bold', 'add')
self.clearLine(self.lineNumber)
if not skipRowsAfter:
self.clearLine(self.lineNumber + 1)
self.clearLine(self.lineNumber + 2)
self.lineNumber += 2
self.updateMaxColumn(columnName)
def setCellValue(self, cell, value):
if value is None:
convertedValue = ''
elif isinstance(value, Units.Quantity):
convertedValue = value.UserString
else:
convertedValue = str(value)
convertedValue = literalText(convertedValue)
logger.debug('set %s to %s for %s',
(cell, convertedValue, self.spreadsheet))
self.spreadsheet.set(cell, convertedValue)
def recompute(self):
self.spreadsheet.recompute()
def updateMaxColumn(self, columnName):
if self.maxColumn is None:
self.maxColumn = columnName
else:
actualIndex = COLUMN_NAMES.index(self.maxColumn)
columnIndex = COLUMN_NAMES.index(columnName)
if actualIndex < columnIndex:
self.maxColumn = columnName
def clearUnusedCells(self, column, line):
if line is not None and line > self.lineNumber:
for lineNumberToDelete in range(line, self.lineNumber, -1):
self.clearLine(lineNumberToDelete)
if column is not None:
columnIndex = COLUMN_NAMES.index(column)
maxColumnIndex = COLUMN_NAMES.index(self.maxColumn)
if columnIndex > maxColumnIndex:
for columnIndexToDelete in range(columnIndex, maxColumnIndex, -1):
self.clearColumn(COLUMN_NAMES[columnIndexToDelete], line)
def clearLine(self, lineNumberToDelete):
logger.debug('Clear line %s', (lineNumberToDelete))
column = None
while column is None or column != self.maxColumn:
column = nextColumnName(column)
cellName = buildCellName(column, lineNumberToDelete)
logger.debug(' Clear cell %s', (cellName))
self.spreadsheet.clear(cellName)
def clearColumn(self, columnToDelete, maxLineNumber):
logger.debug('Clear column %s', (columnToDelete))
for lineNumber in range(1, maxLineNumber):
cellName = buildCellName(columnToDelete, lineNumber + 1)
logger.debug(' Clear cell %s', (cellName))
self.spreadsheet.clear(cellName)
class ReportEntryWidget(QGroupBox):
def __init__(self, header, statement, skipRowsAfter, skipColumnNames, printResultInBold, panel, index, hasError):
super().__init__()
self.panel = panel
self.index = index
self.headerEdit = QLineEdit(header)
self.statementEdit = QPlainTextEdit(statement)
self.skipRowsAfterEdit = QCheckBox('Skip Empty Rows After Statement')
self.skipColumnNamesEdit = QCheckBox('Skip Column Names')
self.printResultInBoldEdit = QCheckBox('Print Result in bold')
self.removeButton = QPushButton('Remove')
self.skipRowsAfterEdit.setChecked(skipRowsAfter)
self.skipColumnNamesEdit.setChecked(skipColumnNames)
self.printResultInBoldEdit.setChecked(printResultInBold)
self.removeButton.clicked.connect(self.remove)
if hasError:
self.statementEdit.setStyleSheet('background-color: #f5dbd9;')
self.initUi()
def initUi(self):
self.layout = QFormLayout()
self.layout.addRow('Header', self.headerEdit)
self.layout.addRow('Statement', self.statementEdit)
self.layout.addRow(' ', self.skipColumnNamesEdit)
self.layout.addRow(' ', self.skipRowsAfterEdit)
self.layout.addRow(' ', self.printResultInBoldEdit)
self.layout.addRow(' ', self.removeButton)
self.setLayout(self.layout)
def getHeader(self):
return self.headerEdit.text()
def getPlainTextStatement(self):
return self.statementEdit.toPlainText()
def shouldSkipColumnNames(self):
return self.skipColumnNamesEdit.isChecked()
def shouldSkipRowsAfter(self):
return self.skipRowsAfterEdit.isChecked()
def shouldPrintResultInBold(self):
return self.printResultInBoldEdit.isChecked()
def remove(self):
self.panel.removeRow(self)
class ReportConfigPanel():
def __init__(self, report, freecadObject):
self.report = report
self.freecadObject = freecadObject
self.entries = []
self.form = FreeCADGui.PySideUic.loadUi(uiPath('report_config.ui'))
self.form.Title.setText('%s Config' % (freecadObject.Label))
self.scrollAreaWidget = self.form.ScrollArea.widget()
self.form.AddStatementButton.clicked.connect(
self.addRow)
self.setupRows()
def setupRows(self):
for statement in self.report.statements:
self.addRow(statement.header, statement.plainTextStatement,
statement.skipRowsAfter, statement.skipColumnNames, statement.printResultInBold, statement.parserError)
def addRow(self, header=None, statement=None, skipRowsAfter=False, skipColumnNames=False, printResultInBold=False, hasError=False):
widget = ReportEntryWidget(header, statement, skipRowsAfter,
skipColumnNames, printResultInBold, self, len(self.entries), hasError)
self.entries.append(widget)
self.scrollAreaWidget.layout().addWidget(widget)
def removeRow(self, widget):
self.entries.pop(widget.index)
layoutItem = self.scrollAreaWidget.layout().takeAt(widget.index)
layoutItem.widget().deleteLater()
def accept(self):
self.saveIntoConfig()
FreeCADGui.Control.closeDialog()
self.report.execute(self.freecadObject)
def reject(self):
FreeCADGui.Control.closeDialog()
def saveIntoConfig(self):
self.report.statements.clear()
for entry in self.entries:
reportStatement = ReportStatement(
entry.getHeader(), entry.getPlainTextStatement(), entry.shouldSkipRowsAfter(), entry.shouldSkipColumnNames(), entry.shouldPrintResultInBold())
self.report.statements.append(reportStatement)
class ReportStatement(object):
def __init__(self, header, plainTextStatement, skipRowsAfter=False, skipColumnNames=False, printResultInBold=False):
self.header = header
self.plainTextStatement = plainTextStatement
self.skipRowsAfter = skipRowsAfter
self.skipColumnNames = skipColumnNames
self.printResultInBold = printResultInBold
self.parserError = False
try:
self.statement = SQL_PARSER.parse(plainTextStatement)
except (SqlStatementValidationError, ParseError):
self.parserError = True
self.statement = None
import logging
logging.exception('')
logger.debug('parsed statement %s', (plainTextStatement))
logger.debug('to %s', (self.statement))
def execute(self):
if self.parserError:
return [['The statement has some errors. Check console for further details']]
return self.statement.execute()
def getColumnNames(self):
if self.parserError:
return ['Error']
return self.statement.getColumnNames()
def serializeState(self):
return ['VERSION:1', self.header, self.plainTextStatement, self.skipRowsAfter, self.skipColumnNames, self.printResultInBold]
@staticmethod
def deserializeState(state):
if state[0] == 'VERSION:1':
return ReportStatement(state[1], state[2], state[3], state[4], state[5])
else:
stateItems = len(state)
if stateItems == 2:
return ReportStatement(state[0], state[1])
if stateItems == 5:
return ReportStatement(state[0], state[1], state[2], state[3], state[4])
return ReportStatement(state[0], state[1], state[3], state[4], state[5])
class Report():
def __init__(self, obj, fileObject=None):
obj.Proxy = self
self.setProperties(obj)
self.statements = [
# ReportStatement, ...
]
self.maxColumn = None
self.maxLine = None
def setProperties(self, obj):
pl = obj.PropertiesList
if not 'Result' in pl:
obj.addProperty("App::PropertyLink", "Result", "Settings",
"The spreadsheet to print the results to")
if not 'SkipComputing' in pl:
obj.addProperty("App::PropertyBool", "SkipComputing", "Settings",
"When true no calculation of this report is performed, even when the document gets recomputed").SkipComputing = False
def onDocumentRestored(self, obj):
self.setProperties(obj)
def execute(self, fp):
if fp.SkipComputing:
return
if not fp.Result:
FreeCAD.Console.PrintError(
'No spreadsheet attached to %s. Could not recompute result' % (fp.Label))
spreadsheet = ReportSpreadsheet(fp.Result)
lineNumber = 1
for statement in self.statements:
columnNames = statement.getColumnNames()
spreadsheet.printHeader(statement.header, len(columnNames))
if not statement.skipColumnNames:
spreadsheet.printColumnLabels(columnNames)
rows = statement.execute()
spreadsheet.printRows(
rows, statement.skipRowsAfter, statement.printResultInBold)
spreadsheet.clearUnusedCells(self.maxColumn, self.maxLine)
self.maxColumn = spreadsheet.maxColumn
self.maxLine = spreadsheet.lineNumber
spreadsheet.recompute()
def exportJson(self, fileObject):
try:
jsonDict = statementsToDict(self.statements)
json.dump(jsonDict, fileObject, sort_keys=True,
indent=4, ensure_ascii=False)
finally:
fileObject.close()
def importJson(self, fileObject):
try:
jsonDict = json.load(fileObject, encoding='utf-8')
self.statements = dictToStatements(jsonDict)
finally:
fileObject.close()
def exportXLS(self, selected_file):
try:
import xlsxwriter
except:
FreeCAD.Console.PrintError("It looks like 'xlsxwriter' could not be found on your system. Please see https://xlsxwriter.readthedocs.io/getting_started.html how to install it.")
return
try:
workbook = xlsxwriter.Workbook(selected_file)
boldFormat = workbook.add_format({'bold': True})
fmts = {}
def _get_format(unit):
if not unit in fmts:
fmts[unit] = workbook.add_format({'num_format': '#.??\\ \\' + unit})
return fmts[unit]
for statement in self.statements:
worksheet = workbook.add_worksheet(statement.header)
lineNumber = 1
if not statement.skipColumnNames:
columnName = None
for columnLabel in statement.getColumnNames():
columnName = nextColumnName(columnName)
cellName = buildCellName(columnName, lineNumber)
worksheet.write_string(cellName, columnLabel, boldFormat)
lineNumber += 1
rows = statement.execute()
for row in rows:
columnName = None
for value in row:
columnName = nextColumnName(columnName)
cellName = buildCellName(columnName, lineNumber)
fmt = None
if isinstance(value, Units.Quantity):
un = value.getUserPreferred()
worksheet.write(cellName, value.Value/un[1], _get_format(un[2]))
elif value is None:
worksheet.write_string(cellName, '')
else:
worksheet.write_string(cellName, str(value))
lineNumber += 1
finally:
workbook.close()
def __getstate__(self):
state = ['VERSION:1']
state.append([statement.serializeState()
for statement in self.statements])
state.append(self.maxColumn)
state.append(self.maxLine)
return state
def __setstate__(self, state):
if state[0] == 'VERSION:1':
savedStatements = state[1]
self.maxColumn = state[2]
self.maxLine = state[3]
self.statements = [ReportStatement.deserializeState(
serializedState) for serializedState in savedStatements]
else:
self.statements = [ReportStatement.deserializeState(
serializedState) for serializedState in state]
self.maxColumn = None
self.maxLine = None
return None
class ViewProviderReport():
def __init__(self, vobj):
vobj.Proxy = self
def attach(self, vobj):
self.ViewObject = vobj
self.Object = vobj.Object
self.report = self.Object.Proxy
self.coinNode = coin.SoGroup()
vobj.addDisplayMode(self.coinNode, "Standard")
def onChanged(self, vp, prop):
pass
def doubleClicked(self, vobj):
return self.setEdit(vobj, 0)
def setEdit(self, vobj, mode):
if mode == 0:
panel = ReportConfigPanel(self.report, self.Object)
FreeCADGui.Control.showDialog(panel)
return True
return False
def unsetEdit(self, vobj, mode):
# FreeCADGui.Control.closeDialog()
return False
def getIcon(self):
return iconPath("Workbench.svg")
def claimChildren(self):
return [self.Object.Result]
def getDisplayModes(self, obj):
return ["Standard"]
def getDefaultDisplayMode(self):
return "Standard"
def updateData(self, fp, prop):
pass
def __getstate__(self):
return None
def __setstate__(self, state):
return None
def createReport(fileObject=None):
import Spreadsheet
reportObject = FreeCAD.ActiveDocument.addObject(
"App::FeaturePython", "Report")
report = Report(reportObject)
if fileObject is not None:
report.importJson(fileObject)
result = FreeCAD.ActiveDocument.addObject("Spreadsheet::Sheet", "Result")
reportObject.Result = result
ViewProviderReport(reportObject.ViewObject)
if __name__ == "__main__":
if FreeCAD.ActiveDocument is None:
print('Create a document to continue.')
else:
createReport()
| 46,365
|
https://github.com/liulinjie1990823/ArchitectureDemo/blob/master/lib-image-loader/src/main/java/com/llj/lib/image/loader/core/ImageConfig.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
ArchitectureDemo
|
liulinjie1990823
|
Java
|
Code
| 49
| 128
|
package com.llj.lib.image.loader.core;
/**
* describe 不写是傻逼
*
* @author liulinjie
* @date 2020/4/11 10:18 PM
*/
public class ImageConfig {
public static final int FRESCO_ENGINE = 0;
public static final int GLIDE_ENGINE = 1;
public static final int PICASSO_ENGINE = 2;
public static final int DEFAULT_ENGINE = FRESCO_ENGINE;
}
| 50,178
|
https://github.com/joseocampo/samples/blob/master/framework/wcf/Extensibility/DataContract/Surrogate/CS/Service/Service.cs
|
Github Open Source
|
Open Source
|
CC-BY-4.0, MIT
| 2,022
|
samples
|
joseocampo
|
C#
|
Code
| 169
| 476
|
// Copyright (c) Microsoft Corporation. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace Microsoft.Samples.DCSurrogate
{
// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.Samples.DCSurrogate")]
[AllowNonSerializableTypes]
public interface IPersonnelDataService
{
[OperationContract]
void AddEmployee(Employee employee);
[OperationContract]
Employee GetEmployee(string name);
}
// This is the Employee (outer) type used in the sample.
[DataContract(Namespace = "http://Microsoft.Samples.DCSurrogate")]
public class Employee
{
[DataMember]
public DateTime dateHired;
[DataMember]
public Decimal salary;
[DataMember]
public Person person;
}
// This is the Person (inner) type used in the sample.
// Consider this a legacy type without DataContract or Serializable, so it cannot be serialized as is.
public class Person
{
public string firstName;
public string lastName;
public int age;
public Person() { }
}
// Service class which implements the service contract.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PersonnelDataService : IPersonnelDataService
{
Dictionary<string, Employee> employees = new Dictionary<string,Employee>();
public void AddEmployee(Employee employee)
{
employees.Add(employee.person.firstName, employee);
}
public Employee GetEmployee(string name)
{
Employee employee;
if (employees.TryGetValue(name, out employee))
return employee;
else
return null;
}
}
}
| 5,715
|
https://github.com/b3cat/react-spectrum/blob/master/.github/actions/comment/index.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
react-spectrum
|
b3cat
|
JavaScript
|
Code
| 56
| 246
|
const core = require('@actions/core');
const github = require('@actions/github');
const octokit = new github.GitHub(process.env.GITHUB_TOKEN);
run();
async function run() {
try {
let {data: prs} = await octokit.repos.listPullRequestsAssociatedWithCommit({
...github.context.repo,
commit_sha: github.context.sha
});
if (!prs || !prs.length) {
return;
}
await octokit.issues.createComment({
...github.context.repo,
issue_number: prs[0].number,
body: `Build successful! [View the storybook](https://reactspectrum.blob.core.windows.net/reactspectrum/${github.context.sha}/index.html)`
});
} catch (error) {
core.setFailed(error.message);
}
}
| 28,568
|
https://github.com/Bvdldf/ABP/blob/master/include/Zend/Gdata/Contacts/PaxHeader/Query.php
|
Github Open Source
|
Open Source
|
PHP-3.0, Apache-2.0, ECL-2.0
| null |
ABP
|
Bvdldf
|
PHP
|
Code
| 4
| 26
|
29 mtime=1556801615.12834084
24 SCHILY.fflags=extent
| 12,778
|
https://github.com/gmoralesc24/SpringXD/blob/master/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/container/XDContainer.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
SpringXD
|
gmoralesc24
|
Java
|
Code
| 651
| 2,086
|
/*
* Copyright 2013 the original author or authors.
*
* 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 org.springframework.xd.dirt.container;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.RollingFileAppender;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.Assert;
import org.springframework.xd.dirt.server.options.XDPropertyKeys;
/**
* @author Mark Fisher
* @author Jennifer Hickey
* @author David Turanski
* @author Ilayaperumal Gopinathan
*/
public class XDContainer implements SmartLifecycle {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final Log logger = LogFactory.getLog(XDContainer.class);
private volatile ApplicationContext launcherContext;
/**
* Base location for XD config files. Chosen so as not to collide with user provided content.
*/
public static final String XD_CONFIG_ROOT = "META-INF/spring-xd/";
/**
* Where container related config files reside.
*/
public static final String XD_INTERNAL_CONFIG_ROOT = XD_CONFIG_ROOT + "internal/";
private static final String CORE_CONFIG = XD_INTERNAL_CONFIG_ROOT + "container.xml";
// TODO: consider moving to a file: location pattern within $XD_HOME
private static final String PLUGIN_CONFIGS = "classpath*:" + XD_CONFIG_ROOT + "plugins/*.xml";
private static final String LOG4J_FILE_APPENDER = "file";
private volatile AbstractApplicationContext context;
private final String id;
private String hostName;
private String ipAddress;
private volatile String jvmName;
private volatile boolean containerRunning;
/**
* Creates a container with a given id
*
* @param id the id
*/
public XDContainer(String id) {
this.id = id;
}
/**
* Default constructor generates a random id
*/
public XDContainer() {
this.id = UUID.randomUUID().toString();
}
public String getId() {
return (this.context != null) ? this.context.getId() : "";
}
public String getHostName() {
try {
this.hostName = InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException uhe) {
this.hostName = "unknown";
}
return this.hostName;
}
public String getIpAddress() {
try {
this.ipAddress = InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException uhe) {
this.ipAddress = "unknown";
}
return this.ipAddress;
}
public String getJvmName() {
synchronized (this) {
if (this.jvmName == null) {
this.jvmName = ManagementFactory.getRuntimeMXBean().getName();
}
}
return this.jvmName;
}
@Override
public int getPhase() {
return 0;
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public boolean isRunning() {
return this.context != null;
}
private boolean isContainerRunning() {
return containerRunning;
}
public void setLauncherContext(ApplicationContext context) {
this.launcherContext = context;
}
public ApplicationContext getApplicationContext() {
return this.context;
}
@Override
public void start() {
this.context = new ClassPathXmlApplicationContext(new String[] { CORE_CONFIG, PLUGIN_CONFIGS }, false);
context.setId(this.id);
updateLoggerFilename();
Assert.notNull(launcherContext, "no Container launcher ApplicationContext has been set");
ApplicationContext globalContext = launcherContext.getParent();
Assert.notNull(globalContext, "no global context has been set");
context.setParent(globalContext);
context.registerShutdownHook();
context.refresh();
this.containerRunning = true;
context.publishEvent(new ContainerStartedEvent(this));
if (logger.isInfoEnabled()) {
logger.info("started container: " + context.getId());
}
}
@Override
public void stop() {
if (this.context != null && isContainerRunning()) {
this.containerRunning = false;
// Publish the container stopped event before the context is closed.
this.context.publishEvent(new ContainerStoppedEvent(this));
this.context.close();
((ConfigurableApplicationContext) context.getParent()).close();
if (logger.isInfoEnabled()) {
final String message = "Stopped container: " + this.jvmName;
final StringBuilder sb = new StringBuilder(LINE_SEPARATOR);
sb.append(StringUtils.rightPad("", message.length(), "-")).append(LINE_SEPARATOR).append(message).append(
LINE_SEPARATOR).append(StringUtils.rightPad("", message.length(), "-")).append(LINE_SEPARATOR);
logger.info(sb.toString());
}
}
}
@Override
public void stop(Runnable callback) {
this.stop();
callback.run();
}
public void addListener(ApplicationListener<?> listener) {
Assert.state(this.context != null, "context is not initialized");
this.context.addApplicationListener(listener);
}
/**
* Update container log appender file name with container id
*/
private void updateLoggerFilename() {
Appender appender = Logger.getRootLogger().getAppender(LOG4J_FILE_APPENDER);
if (appender instanceof RollingFileAppender) {
String xdHome = context.getEnvironment().getProperty(XDPropertyKeys.XD_HOME);
((RollingFileAppender) appender).setFile(new File(xdHome).getAbsolutePath()
+ "/logs/container-" + this.getId() + ".log");
((RollingFileAppender) appender).activateOptions();
}
}
public int getJmxPort() {
return Integer.valueOf(this.context.getEnvironment().getProperty(XDPropertyKeys.XD_JMX_PORT));
}
public boolean isJmxEnabled() {
return Boolean.valueOf(this.context.getEnvironment().getProperty(XDPropertyKeys.XD_JMX_ENABLED));
}
public String getPropertyValue(String key) {
return this.context.getEnvironment().getProperty(key);
}
}
| 29,616
|
https://github.com/jjdelvalle/gradcafe_analysis/blob/master/app/parse_html.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
gradcafe_analysis
|
jjdelvalle
|
Python
|
Code
| 918
| 2,916
|
from bs4 import BeautifulSoup
import datetime, time
from IPython.core.debugger import Pdb
import sys, re
import os.path
from collections import Counter
import seaborn as sns
import matplotlib.pyplot as plt
import pandas
PROGS = [
('Computer Engineering', 'Electrical and Computer Engineering'),
('Computer Enginnerin', 'Electrical and Computer Engineering'),
('Electrical', 'Electrical and Computer Engineering'),
('ECE', 'Electrical and Computer Engineering'),
('Computer Sc', 'Computer Science'),
('Computer Sc', 'Computer Science'),
('Computer Sicen', 'Computer Science'),
('Computer Sien', 'Computer Science'),
('Computer S Cience', 'Computer Science'),
('Computer,', 'Computer Science'),
('Computers,', 'Computer Science'),
('ComputerScience', 'Computer Science'),
('Human Computer Interaction', 'Human Computer Interaction'),
('Human-Computer Interaction', 'Human Computer Interaction'),
('Human-computer Interaction', 'Human Computer Interaction'),
('software engineering', 'Software Engineering'),
('Embedded', 'Electrical and Computer Engineering'),
('Computer Eng', 'Electrical and Computer Engineering'),
('Computer Vision', 'Computer Science')]
# ('computer graphics', 'Game Development'),
# ('computer gam', 'Game Development'),
# ('Computer Systems', 'Computer Systems Engineering'),
# ('Computer And Systems', 'Computer Systems Engineering'),
# ('Computer & Systems', 'Computer Systems Engineering'),
# ('Information Technology', 'IT'),
# ('Communication', 'Computers and Communication'),
# ('Computer Network', 'Computer Networking'),
# ('Computer And Computational Sciences', 'Computer And Computational Sciences'),
# ('Computer Music', 'Computer Music'),
# ('Computer Control And Automation', 'Computer Control And Automation'),
# ('Computer Aided Mechanical Engineering', 'CAME'),
# ('Computer Art', 'Computer Art'),
# ('Computer Animation', 'Computer Art'),
# ('composition and computer technologies', 'Computer Art'),
# ('computer forensics', 'Computer Art')]
DEGREE = [
(' MFA', 'MFA'),
(' M Eng', 'MEng'),
(' MEng', 'MEng'),
(' M.Eng', 'MEng'),
(' Masters', 'MS'),
(' PhD', 'PhD'),
(' MBA', 'MBA'),
(' Other', 'Other'),
(' EdD', 'Other'),
]
STATUS = {
'A': 'American',
'U': 'International with US Degree',
'I': 'International',
'O': 'Other',
}
COLLEGES = [
('Stanford', 'Stanford'),
('MIT', 'MIT'),
('CMU', 'CMU'),
('Cornell', 'Cornell')
]
errlog = {'major': [], 'gpa': [], 'general': [], 'subject': []}
def process(index, col):
global err
inst, major, degree, season, status, date_add, date_add_ts, comment = None, None, None, None, None, None, None, None
if len(col) != 6:
return []
try:
inst = col[0].text.strip()
except:
print("Couldn't retrieve institution")
try:
major = None
progtext = col[1].text.strip()
if not ',' in progtext:
print('no comma')
errlog['major'].append((index, col))
else:
parts = progtext.split(',')
major = parts[0].strip()
progtext = ' '.join(parts[1:])
for p, nam in PROGS:
if p.lower() in major.lower():
major = nam
break
degree = None
for (d, deg) in DEGREE:
if d in progtext:
degree = deg
break
if not degree:
degree = 'Other'
season = None
mat = re.search('\([SF][012][0-9]\)', progtext)
if mat:
season = mat.group()[1:-1]
else:
mat = re.search('\(\?\)', progtext)
if mat:
season = None
except NameError as e:
print(e)
except:
print("Unexpected error:", sys.exc_info()[0])
try:
extra = col[2].find(class_='extinfo')
gpafin, grev, grem, grew, new_gre, sub = None, None, None, None, None, None
if extra:
gre_text = extra.text.strip()
gpa = re.search('Undergrad GPA: ((?:[0-9]\.[0-9]{1,2})|(?:n/a))', gre_text)
general = re.search('GRE General \(V/Q/W\): ((?:1[0-9]{2}/1[0-9]{2}/(?:(?:[0-6]\.[0-9]{2})|(?:99\.99)|(?:56\.00)))|(?:n/a))', gre_text)
new_gref = True
subject = re.search('GRE Subject: ((?:[2-9][0-9]0)|(?:n/a))', gre_text)
if gpa:
gpa = gpa.groups(1)[0]
if not gpa == 'n/a':
try:
gpafin = float(gpa)
except:
print("Couldn't convert gpa to float")
else:
errlog['gpa'].append((index, gre_text))
if not general:
general = re.search('GRE General \(V/Q/W\): ((?:[2-8][0-9]0/[2-8][0-9]0/(?:(?:[0-6]\.[0-9]{2})|(?:99\.99)|(?:56\.00)))|(?:n/a))', gre_text)
new_gref = False
if general:
general = general.groups(1)[0]
if not general == 'n/a':
try:
greparts = general.split('/')
if greparts[2] == '99.99' or greparts[2] == '0.00' or greparts[2] == '56.00':
grew = None
else:
grew = float(greparts[2])
grev = int(greparts[0])
grem = int(greparts[1])
new_gre = new_gref
if new_gref and (grev > 170 or grev < 130 or grem > 170 or grem < 130 or (grew and (grew < 0 or grew > 6))):
errlog['general'].append((index, gre_text))
grew, grem, grev, new_gre = None, None, None, None
elif not new_gref and (grev > 800 or grev < 200 or grem > 800 or grem < 200 or (grew and (grew < 0 or grew > 6))):
errlog['general'].append((index, gre_text))
grew, grem, grev, new_gre = None, None, None, None
except Exception as e:
print(e)
else:
errlog['general'].append((index, gre_text))
if subject:
subject = subject.groups(1)[0]
if not subject == 'n/a':
sub = int(subject)
else:
errlog['subject'].append((index, gre_text))
extra.extract()
decision = col[2].text.strip()
try:
decisionfin, method, decdate, decdate_ts = None, None, None, None
(decisionfin, method, decdate) = re.search('((?:Accepted)|(?:Rejected)|(?:Wait listed)|(?:Other)|(?:Interview))? ?via ?((?:E-[mM]ail)|(?:Website)|(?:Phone)|(?:Other)|(?:Postal Service)|(?:POST)|(?:Unknown))? ?on ?([0-9]{1,2} [A-Z][a-z]{2} [0-9]{4})?' , decision).groups()
if method and method == 'E-Mail':
method = 'E-mail'
if method and method=='Unknown':
method = 'Other'
if method and method=='POST':
method = 'Postal Service'
if decdate:
try:
decdate_date = datetime.datetime.strptime(decdate, '%d %b %Y')
decdate_ts = decdate_date.strftime('%s')
decdate = decdate_date.strftime('%d-%m-%Y')
except Exception as e:
decdate_date, decdate_ts, decdate = None, None, None
except Exception as e:
print("Couldn't assign method of reporting")
except Exception as e:
print("Extra information error")
try:
statustxt = col[3].text.strip()
if statustxt in STATUS:
status = STATUS[statustxt]
else:
status = None
except:
print("Couldn't retrieve status")
try:
date_addtxt = col[4].text.strip()
date_add_date = datetime.datetime.strptime(date_addtxt, '%d %b %Y')
date_add_ts = date_add_date.strftime('%s')
date_add = date_add_date.strftime('%d-%m-%Y')
except:
print("Couldn't retrieve date_add")
try:
comment = col[5].text.strip()
except:
print("Couldn't retrieve the comment")
res = [inst, major, degree, season, decisionfin, method, decdate, decdate_ts, gpafin, grev, grem, grew, new_gre, sub, status, date_add, date_add_ts, comment]
return res
if __name__ == '__main__':
args = sys.argv
if len(args) < 4:
exit()
if not args[-1].isdigit():
exit()
path = args[1]
title = args[2]
n_pages = int(args[3])
data = []
for page in range(1, n_pages):
if not os.path.isfile('{0}/{1}.html'.format(path, page)):
print("Page {0} not found.".format(page))
continue
with open('{0}/{1}.html'.format(path, page), 'r') as f:
soup = BeautifulSoup(f.read(), features="html.parser")
tables = soup.findAll('table', class_='submission-table')
for tab in tables:
rows = tab.findAll('tr')
for row in rows[1:]:
cols = row.findAll('td')
pro = process(page, cols)
if len(pro) > 0:
data.append(pro)
if page % 10 == 0:
print("Processed 10 more pages (page {0})".format(page))
df = pandas.DataFrame(data)
df.columns = ['institution', 'major', 'degree', 'season', 'decisionfin', 'method', 'decdate', 'decdate_ts', 'gpafin', 'grev', 'grem', 'grew', 'new_gre', 'sub', 'status', 'date_add', 'date_add_ts', 'comment']
df.to_csv("data/{0}.csv".format(title))
| 12,525
|
https://github.com/RonimaxTeam/maui/blob/master/src/Core/src/Layouts/ILayoutManager.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
maui
|
RonimaxTeam
|
C#
|
Code
| 19
| 63
|
using Microsoft.Maui;
namespace Microsoft.Maui.Layouts
{
public interface ILayoutManager
{
Size Measure(double widthConstraint, double heightConstraint);
void ArrangeChildren(Rectangle childBounds);
}
}
| 19,303
|
https://github.com/Rinat-Suleymanov/cat-framework/blob/master/src/main/java/ru/cg/cat_framework/framework/configurator/InjectRandomValueObjectConfigurator.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
cat-framework
|
Rinat-Suleymanov
|
Java
|
Code
| 55
| 224
|
package ru.cg.cat_framework.framework.configurator;
import java.lang.reflect.Field;
import lombok.SneakyThrows;
import org.fluttercode.datafactory.impl.DataFactory;
import ru.cg.cat_framework.framework.annnotation.InjectRandomName;
/**
* @author Rinat Suleymanov
*/
public class InjectRandomValueObjectConfigurator implements ObjectConfigurator {
private DataFactory factory = new DataFactory();
@SneakyThrows
@Override
public void configure(Object object) {
Class<?> type = object.getClass();
for (Field field : type.getDeclaredFields()) {
if (field.isAnnotationPresent(InjectRandomName.class)) {
field.setAccessible(true);
field.set(object, factory.getName());
}
}
}
}
| 6,118
|
https://github.com/bootstrap-vue/bootstrap-vue/blob/master/src/mixins/listen-on-document.spec.js
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
bootstrap-vue
|
bootstrap-vue
|
JavaScript
|
Code
| 207
| 1,062
|
import { mount } from '@vue/test-utils'
import { listenOnDocumentMixin } from './listen-on-document'
describe('mixins/listen-on-document', () => {
it('works', async () => {
const spyClick1 = jest.fn()
const spyClick2 = jest.fn()
const spyFocusin = jest.fn()
const TestComponent = {
mixins: [listenOnDocumentMixin],
props: {
offClickOne: {
type: Boolean,
default: false
}
},
mounted() {
this.listenOnDocument('click', spyClick1)
this.listenOnDocument('focusin', spyFocusin)
this.listenOnDocument('click', spyClick2)
},
watch: {
offClickOne(newValue) {
if (newValue) {
this.listenOffDocument('click', spyClick1)
}
}
},
render(h) {
return h('div', this.$slots.default)
}
}
const App = {
components: { TestComponent },
props: {
offClickOne: {
type: Boolean,
default: false
},
destroy: {
type: Boolean,
default: false
}
},
render(h) {
const props = {
offClickOne: this.offClickOne
}
return h('div', [
h('span', ''),
h('input', { type: 'text' }),
this.destroy ? h() : h(TestComponent, { props }, 'test-component')
])
}
}
const wrapper = mount(App, {
attachTo: document.body,
propsData: {
destroy: false
}
})
expect(wrapper.vm).toBeDefined()
expect(wrapper.text()).toEqual('test-component')
expect(spyClick1).not.toHaveBeenCalled()
expect(spyClick2).not.toHaveBeenCalled()
expect(spyFocusin).not.toHaveBeenCalled()
const $span = wrapper.find('span')
expect($span.exists()).toBe(true)
const $input = wrapper.find('input')
expect($input.exists()).toBe(true)
await $input.trigger('focusin')
expect(spyClick1).not.toHaveBeenCalled()
expect(spyClick2).not.toHaveBeenCalled()
expect(spyFocusin).toHaveBeenCalledTimes(1)
await $span.trigger('click')
expect(spyClick1).toHaveBeenCalledTimes(1)
expect(spyClick2).toHaveBeenCalledTimes(1)
expect(spyFocusin).toHaveBeenCalledTimes(1)
await wrapper.setProps({ offClickOne: true })
await $span.trigger('click')
expect(spyClick1).toHaveBeenCalledTimes(1)
expect(spyClick2).toHaveBeenCalledTimes(2)
expect(spyFocusin).toHaveBeenCalledTimes(1)
await $input.trigger('focusin')
expect(spyClick1).toHaveBeenCalledTimes(1)
expect(spyClick2).toHaveBeenCalledTimes(2)
expect(spyFocusin).toHaveBeenCalledTimes(2)
await wrapper.setProps({ destroy: true })
expect(spyClick1).toHaveBeenCalledTimes(1)
expect(spyClick2).toHaveBeenCalledTimes(2)
expect(spyFocusin).toHaveBeenCalledTimes(2)
await $input.trigger('focusin')
expect(spyClick1).toHaveBeenCalledTimes(1)
expect(spyClick2).toHaveBeenCalledTimes(2)
expect(spyFocusin).toHaveBeenCalledTimes(2)
await $span.trigger('click')
expect(spyClick1).toHaveBeenCalledTimes(1)
expect(spyClick2).toHaveBeenCalledTimes(2)
expect(spyFocusin).toHaveBeenCalledTimes(2)
wrapper.destroy()
})
})
| 37,666
|
https://github.com/WEB3-Devs-Poland/web-page/blob/master/src/theme/ThemeProvider.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
web-page
|
WEB3-Devs-Poland
|
TypeScript
|
Code
| 114
| 300
|
import { createContext, useState } from 'react';
import * as SC from 'styled-components';
import GlobalStyle from './GlobalStyle';
import darkTheme from './theme.dark';
import lightTheme from './theme.light';
type ThemeType = 'light' | 'dark';
export type ThemeStateContextType = {
currentTheme: ThemeType;
changeTheme: () => void;
};
export const ThemeStateContext = createContext<ThemeStateContextType | null>(null);
interface Props {
children: React.ReactNode;
}
const ThemeProvider = ({ children }: Props) => {
const [currentTheme, setCurrentTheme] = useState<ThemeType>('light');
const changeTheme = () => {
const theme: ThemeType = currentTheme === 'light' ? 'dark' : 'light';
setCurrentTheme(theme);
};
return (
<ThemeStateContext.Provider value={{ currentTheme, changeTheme }}>
<SC.ThemeProvider theme={currentTheme === 'light' ? lightTheme : darkTheme}>
{children}
<GlobalStyle />
</SC.ThemeProvider>
</ThemeStateContext.Provider>
);
};
export default ThemeProvider;
| 20,328
|
https://github.com/malloch/chronoviz/blob/master/Classes/Analysis Plugins/PluginManager.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
chronoviz
|
malloch
|
Objective-C
|
Code
| 64
| 321
|
//
// PluginManager.h
// Annotation
//
// Created by Adam Fouse on 9/23/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@class PluginScript;
@class AnnotationDataAnalysisPlugin;
@class PluginDataSource;
@interface PluginManager : NSObject {
NSMutableArray *plugins;
NSMutableArray *pluginNames;
NSMutableArray *pluginScripts;
NSArray *pluginDirectories;
NSMutableDictionary *pluginDataSources;
NSPipe *pipe;
NSFileHandle *pipeReadHandle;
NSString *tempDirectory;
}
+(NSString*)userPluginsDirectory;
+(void)openUserPluginsDirectory;
+(PluginManager*)defaultPluginManager;
-(void)reloadPlugins;
-(NSArray*)plugins;
-(void)runPlugin:(id)sender;
-(PluginDataSource*)dataSourceForPlugin:(AnnotationDataAnalysisPlugin*)plugin;
-(NSArray*)pluginScripts;
-(void)addPluginScript:(PluginScript*)script;
-(void)deletePluginScript:(PluginScript*)script;
-(void)saveScripts;
-(void)saveScript:(PluginScript*)script;
@end
| 50,639
|
https://github.com/Yankee24/Alink/blob/master/core/src/main/java/com/alibaba/alink/operator/batch/source/ParquetSourceBatchOp.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Alink
|
Yankee24
|
Java
|
Code
| 256
| 1,338
|
package com.alibaba.alink.operator.batch.source;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.io.RichInputFormat;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.core.fs.FileInputSplit;
import org.apache.flink.core.fs.Path;
import org.apache.flink.core.io.InputSplit;
import org.apache.flink.ml.api.misc.param.Params;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;
import com.alibaba.alink.common.MLEnvironmentFactory;
import com.alibaba.alink.common.annotation.NameCn;
import com.alibaba.alink.common.io.annotations.AnnotationUtils;
import com.alibaba.alink.common.io.filesystem.AkUtils;
import com.alibaba.alink.common.io.filesystem.AkUtils.FileProcFunction;
import com.alibaba.alink.common.io.filesystem.BaseFileSystem;
import com.alibaba.alink.common.io.filesystem.FilePath;
import com.alibaba.alink.common.io.parquet.ParquetClassLoaderFactory;
import com.alibaba.alink.common.io.parquet.ParquetReaderFactory;
import com.alibaba.alink.common.io.plugin.wrapper.RichInputFormatGenericWithClassLoader;
import com.alibaba.alink.common.utils.DataSetConversionUtil;
import com.alibaba.alink.operator.batch.BatchOperator;
import com.alibaba.alink.params.io.ParquetSourceParams;
import java.io.IOException;
import java.util.List;
@NameCn("parquet文件读入")
public class ParquetSourceBatchOp extends BaseSourceBatchOp <ParquetSourceBatchOp>
implements ParquetSourceParams <ParquetSourceBatchOp> {
public ParquetSourceBatchOp() {
this(new Params());
}
private final ParquetClassLoaderFactory factory;
public ParquetSourceBatchOp(Params params) {
super(AnnotationUtils.annotatedName(ParquetSourceBatchOp.class), params);
factory = new ParquetClassLoaderFactory("0.11.0");
}
@Override
protected Table initializeDataSource() {
if (getPartitions() == null) {
Tuple2 <RichInputFormat <Row, FileInputSplit>, TableSchema> sourceFunction = factory
.createParquetSourceFactory()
.createParquetSourceFunction(getParams());
RichInputFormat <Row, InputSplit> inputFormat
= new RichInputFormatGenericWithClassLoader <>(factory, sourceFunction.f0);
DataSet data = MLEnvironmentFactory
.get(getMLEnvironmentId())
.getExecutionEnvironment()
.createInput(inputFormat, new RowTypeInfo(sourceFunction.f1.getFieldTypes()));
return DataSetConversionUtil.toTable(getMLEnvironmentId(), data, sourceFunction.f1);
}
FilePath filePath = getFilePath();
BatchOperator <?> selected;
TableSchema schema;
try {
selected = AkUtils.selectPartitionBatchOp(getMLEnvironmentId(), filePath, getPartitions());
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
final String[] colNames = selected.getColNames();
final ParquetClassLoaderFactory localFactory = factory;
DataSet data = selected.getDataSet()
.rebalance()
.flatMap(new FlatMapFunction <Row, Row>() {
@Override
public void flatMap(Row value, Collector <Row> out) throws Exception {
Path path = filePath.getPath();
for (int i = 0; i < value.getArity(); ++i) {
path = new Path(path, String.format("%s=%s", colNames[i], String.valueOf(value.getField(i))));
}
AkUtils.getFromFolderForEach(
new FilePath(path, filePath.getFileSystem()),
new FileProcFunction <FilePath, Boolean>() {
@Override
public Boolean apply(FilePath filePath) throws IOException {
ParquetReaderFactory reader = localFactory.createParquetReaderFactory();
reader.open(filePath);
while (!reader.reachedEnd()) {
out.collect(reader.nextRecord());
}
reader.close();
return true;
}
});
}
});
schema = localFactory.createParquetReaderFactory().getTableSchemaFromParquetFile(filePath);
return DataSetConversionUtil.toTable(getMLEnvironmentId(), data, schema);
}
}
| 24,059
|
https://github.com/winoutt/winoutt-django/blob/master/frontend/src/components/user/UserMutualConnections.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
winoutt-django
|
winoutt
|
Vue
|
Code
| 94
| 394
|
<template lang="pug">
.user-mutualConnections
.d-flex.align-items-center.cursor-pointer(@click.prevent="openModal()" v-if="user.end_user.mutual_connections_count")
Icon.icon-connections.mr-1(name="connections")
.count.mr-1.text-secondary.text-truncate(
:style="fontSize ? `font-size: ${fontSize}rem` : ''"
) {{ Humanize.count(user.end_user.mutual_connections_count) }} {{ mutualConnectionsText }}
</template>
<script lang="ts">
import Vue from 'vue'
import ConnectionRequest from '../../Request/ConnectionRequest'
import Icon from '../Icon.vue'
export default Vue.extend({
props: ['user', 'fontSize'],
components: {
Icon
},
computed: {
mutualConnectionsText () {
const text = 'mutual connection'
return this.user.end_user.mutual_connections_count > 1 ? `${text}s` : text
}
},
methods: {
openModal () {
ConnectionRequest.mutuals(this.user)
}
}
})
</script>
<style lang="sass" scoped>
@import '../../assets/sass/variables'
.user-mutualConnections
min-height: 17px
.count
font-size: 0.75rem
.icon-connections
width: 14px
height: 15px
fill: $secondary
</style>
| 3,505
|
https://github.com/alkisg/glo/blob/master/modules/webapp/components/SymbolScope.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
glo
|
alkisg
|
Vue
|
Code
| 295
| 1,114
|
<template lang="pug">
.symbol-scope(:class="darkmode ? 'darkmode': ''")
div.scope-name
span Όνομα εμβέλειας:
span.name {{ scope.name }}
div
.constants(v-if="constants && constants.length")
.title Σταθερες:
.grid
.cv-display(v-for="constant in constants")
.name {{ constant.name }}
.type {{ constant.type }}
.value {{ constant.value }}
.variables(v-if="variables && variables.length")
.title Μεταβλητες:
.grid
.cv-display(v-for="variable in variables")
.name {{ variable.name }}
.type {{ variable.type }}
.value.table(v-if="Array.isArray(variable.value)" @click="selectArray(variable)") Προβολή
.value(v-else-if="variable.value !== undefined") {{ variable.value }}
.value.no-value(v-else)
Popup(
v-if="selectedArray"
@close="closePopup"
:title="`Προβολή πίνακα ${selectedArray.name}`"
:darkmode="darkmode"
)
ArrayView(
:array="selectedArray.value"
:dimensionLength="selectedArray.dimensionLength"
:darkmode="darkmode"
)
</template>
<style lang="stylus" scoped>
.symbol-scope
background white
padding 20px 12px
border-left 1px solid rgba(65,65,65,0.5)
overflow-y scroll
.scope-name
margin-bottom 20px
.name
font-weight bold
.grid
display grid
grid-template-columns 1fr 1fr
grid-template-rows 1fr
grid-gap 20px 25px
margin 7px 0 30px 0
.cv-display
border 1px solid rgba(65,65,65,0.5)
border-radius 10px
text-align center
font-size 15px
display flex
flex-direction column
.name
font-weight bold
.value.no-value
background #eee
height 100%
.value.table
color #007bff
cursor pointer
text-decoration underline
> *
padding calc(20px / 2)
&:not(:last-child)
border-bottom 1px solid rgba(65,65,65,0.5)
&:first-child
border-top-left-radius @border-radius
border-top-right-radius @border-radius
&:last-child
border-bottom-left-radius @border-radius
border-bottom-right-radius @border-radius
&.darkmode
background black
color #f8f8ff
.cv-display
border 1px solid rgba(190,190,190,0.5)
.value.no-value
background #3d3d3d
</style>
<script lang="ts">
import { SymbolScope } from '@glossa-glo/symbol';
import { Component, Vue, Prop, Watch } from 'nuxt-property-decorator';
import { AST } from '@glossa-glo/ast';
import Popup from './Popup.vue';
import ArrayView from './ArrayView.vue';
interface Symbol {
name: string;
type: string;
value: string|undefined;
dimensionLength: number[]|undefined;
}
@Component({
components: {
Popup,
ArrayView
}
})
export default class SymbolScopeComponent extends Vue {
@Prop() scope!: SymbolScope
@Prop() node!: AST;
@Prop() darkmode!: boolean;
closePopup() {
this.selectedArray = null;
}
selectedArray: Symbol|null = null;
selectArray(arr: Symbol) {
this.selectedArray = arr;
}
constants: Symbol[] = [];
variables: Symbol[] = [];
@Watch('node', {
immediate: true,
})
changeVariables() {
const variablesAndConstants = this.scope.getVariablesAndConstants();
this.constants = variablesAndConstants.filter(vc => vc.isConstant);
this.variables = variablesAndConstants.filter(vc => !vc.isConstant);
}
}
</script>
| 3,111
|
https://github.com/philippschmalen/Alternative-ESG-data-codebase/blob/master/src/data/google_trends.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Alternative-ESG-data-codebase
|
philippschmalen
|
Python
|
Code
| 988
| 2,952
|
"""
Extract data from Google trends with the pytrends package
Methods take one keyword, call pytrends and return processed data as CSV or dataframe
Main functions
(1) get_related_queries_pipeline: Returns dataframe of trending searches for a given topic
(2) get_interest_over_time: Returns CSV with interest over time for specified keywords
"""
import pandas as pd
import numpy as np
import logging
from datetime import datetime
from random import randint
from pytrends.request import TrendReq
from .utils_data import list_batch, df_to_csv, sleep_countdown
# ----------------------------------------------------------
# Google trends: Create session
# ----------------------------------------------------------
def create_pytrends_session():
"""Create pytrends TrendReq() session on which .build_payload() can be called."""
pytrends_session = TrendReq()
return pytrends_session
# ----------------------------------------------------------
# Google trends: related queries
# ----------------------------------------------------------
def get_related_queries(pytrends_session, keyword_list, cat=0, geo=""):
"""Returns a dictionary with a dataframe for each keyword
Calls pytrend's related_queries()
Args:
pytrends_session (object): TrendReq() session of pytrend
keyword_list (list): Used as input for query and passed to TrendReq().build_payload()
cat (int): see https://github.com/pat310/google-trends-api/wiki/Google-Trends-Categories
geo (str): Geolocation like US, UK
Returns:
Dictionary: Dict with dataframes with related query results
"""
assert isinstance(
keyword_list, list
), f"keyword_list should be string. Instead of type {type(keyword_list)}"
df_related_queries = pd.DataFrame()
try:
pytrends_session.build_payload(keyword_list, cat=cat, geo=geo)
df_related_queries = pytrends_session.related_queries()
logging.info(f"Query succeeded for {*keyword_list ,}")
except Exception as e:
logging.error(f"Query not unsuccessful due to {e}. Return empty DataFrame.")
return df_related_queries
def process_related_query_response(response, kw, geo, ranking):
"""Helper function for unpack_related_queries_response()"""
try:
df = response[kw][ranking]
df[["keyword", "ranking", "geo", "query_timestamp"]] = [
kw,
ranking,
geo,
datetime.now(),
]
return df
except Exception:
logging.info(f"Append empty dataframe for {ranking}: {kw}")
return pd.DataFrame(
columns=["query", "value", "keyword", "ranking", "geo", "query_timestamp"]
)
def unpack_related_queries_response(response):
"""Unpack response from dictionary and create one dataframe for each ranking and each keyword"""
assert isinstance(response, dict), "Empty response. Try again."
ranking = [*response[[*response][0]]]
keywords = [*response]
return response, ranking, keywords
def create_related_queries_dataframe(
response, rankings, keywords, geo_description="global"
):
"""Returns a single dataframe of related queries for a list of keywords
and each ranking (either 'top' or 'rising')
"""
df_list = []
for r in rankings:
for kw in keywords:
df_list.append(
process_related_query_response(
response, kw=kw, ranking=r, geo=geo_description
)
)
return pd.concat(df_list)
# ---------------------------------------------------
# MAIN QUERY FUNCTION
# ---------------------------------------------------
def get_related_queries_pipeline(
pytrends_session, keyword_list, cat=0, geo="", geo_description="global"
):
"""Returns all response data for pytrend's .related_queries() in a single dataframe
Example usage:
pytrends_session = create_pytrends_session()
df = get_related_queries_pipeline(pytrends_session, keyword_list=['pizza', 'lufthansa'])
"""
response = get_related_queries(
pytrends_session=pytrends_session, keyword_list=keyword_list, cat=cat, geo=geo
) #
response, rankings, keywords = unpack_related_queries_response(response=response)
df_trends = create_related_queries_dataframe(
response=response,
rankings=rankings,
keywords=keywords,
geo_description=geo_description,
)
return df_trends
# ----------------------------------------------------------
# Google trends: Interest over time
# ----------------------------------------------------------
def process_interest_over_time(
df_query_result, keywords, date_index=None, query_length=261
):
"""Process query results
* check for empty response --> create df with 0s if empty
* drop isPartial rows and column
* transpose dataframe to wide format (keywords//search interest)
Args:
df_query_result (pd.DataFrame): dataframe containing query result (could be empty)
date_index (pd.Series): series with date form a basic query to construct df for empty reponses
Returns:
Dataframe: contains query results in long format
(rows: keywords, columns: search interest over time)
"""
# non-empty df
if df_query_result.shape[0] != 0:
# reset_index to preserve date information, drop isPartial column
df_query_result_processed = df_query_result.reset_index().drop(
["isPartial"], axis=1
)
df_query_result_long = pd.melt(
df_query_result_processed,
id_vars=["date"],
var_name="keyword",
value_name="search_interest",
)
# long format (date, keyword, search interest)
return df_query_result_long
# empty df: no search result for any keyword
else:
keywords = keywords.to_list()
logging.info(
f"""process_interest_over_time() handles empty dataframe for {keywords}"""
)
# create empty df with 0s
query_length = len(date_index)
df_zeros = pd.DataFrame(
np.zeros((query_length * len(keywords), 3)),
columns=["date", "keyword", "search_interest"],
)
# replace 0s with keywords
df_zeros["keyword"] = np.repeat(keywords, query_length)
# replace 0s with dates
df_zeros["date"] = pd.concat(
[date_index for i in range(len(keywords))], axis=0, ignore_index=True
)
return df_zeros
def query_interest_over_time(keywords, date_index=None, timeframe="today 5-y"):
"""Forward keywords to Google Trends API and process results into long format
Args:
keywords (list): list of keywords, with maximum length 5
Returns:
DataFrame: Search interest per keyword, preprocessed by process_interest_over_time()
"""
# init pytrends
pt = create_pytrends_session()
pt.build_payload(kw_list=keywords, timeframe=timeframe)
# load search interest over time
df_query_result_raw = pt.interest_over_time()
# preprocess query results
df_query_result_processed = process_interest_over_time(
df_query_result_raw, keywords, date_index
)
return df_query_result_processed
def get_query_date_index(timeframe="today 5-y"):
"""Queries Google trends to have a valid index for query results that returned an empty dataframe
Args:
timeframe (string):
Returns:
pd.Series: date index of Google trend's interest_over_time()
"""
# init pytrends with query that ALWAYS works
pt = create_pytrends_session()
pt.build_payload(kw_list=["pizza", "lufthansa"], timeframe=timeframe)
df = pt.interest_over_time()
# set date as column
df = df.rename_axis("date").reset_index()
return df.date
# ---------------------------------------------------
# MAIN QUERY FUNCTION
# ---------------------------------------------------
def get_interest_over_time(
keyword_list,
filepath,
filepath_failed,
timeframe="today 5-y",
max_retries=3,
timeout=10,
):
"""Main function to query Google Trend's interest_over_time() function.
It respects the query's requirements like
* max. 5 keywords per query, handled by list_batch()
* a basic date index for queries returning empty dataframe
* randomized timeout to not bust rate limits
Error handling:
* retry after query error with increased timeout
* when a query fails after retries, related keywords are stored in csv in filepath_failed.
Args:
keyword_list (list): strings used for the google trends query
filepath (string): csv to store successful query results
filepath_failed (string): csv to store unsuccessful keywords
max_retries (int): how often retry
timeout (int): time to wait in seconds btw. queries
timeframe (string): Defaults to last 5yrs, 'today 5-y',
other values: 'all', Specific dates, 'YYYY-MM-DD YYYY-MM-DD',
Returns:
None: Writes dataframe to csv
"""
# get basic date index for empty responses
date_index = get_query_date_index(timeframe=timeframe)
# divide list into batches of max 5 elements (requirement from Gtrends)
kw_batches = list_batch(lst=keyword_list, n=5)
for i, kw_batch in enumerate(kw_batches):
# retry until max_retries reached
for attempt in range(max_retries):
# random int from range around timeout
timeout_randomized = randint(timeout - 3, timeout + 3)
try:
df = query_interest_over_time(
kw_batch, date_index=date_index, timeframe=timeframe
)
except Exception as e:
logging.error(
f"query_interest_over_time() failed in get_interest_over_time with: {e}"
)
timeout += 3 # increase timetout to be safe
sleep_countdown(timeout_randomized, print_step=2)
# query was successful: store results, sleep
else:
logging.info(
f"{i+1}/{len(list(kw_batches))} get_interest_over_time() query successful"
)
df_to_csv(df, filepath=filepath)
if i < len(kw_batches) - 1:
logging.info(f"Sleep {timeout_randomized}s")
sleep_countdown(timeout_randomized)
break
# max_retries reached: store index of unsuccessful query
else:
df_to_csv(pd.DataFrame(kw_batch), filepath=filepath_failed)
logging.warning(f"{kw_batch} appended to unsuccessful_queries")
| 22,919
|
https://github.com/clawpack/pyclaw/blob/master/src/pyclaw/util.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,023
|
pyclaw
|
clawpack
|
Python
|
Code
| 2,833
| 7,544
|
#!/usr/bin/env python
# encoding: utf-8
r"""
Pyclaw utility methods
"""
from __future__ import absolute_import
from __future__ import print_function
import time
import os
import sys
import subprocess
import logging
import tempfile
import inspect
import warnings
import numpy as np
import contextlib
from six.moves import zip
LOGGING_LEVELS = {0:logging.CRITICAL,
1:logging.ERROR,
2:logging.WARNING,
3:logging.INFO,
4:logging.DEBUG}
def add_parent_doc(parent):
"""add parent documentation for a class"""
return """
**Parent Class Documentation:**
""" + parent.__doc__
def run_serialized(fun):
""" Decorates a function to only run serially, even if called in parallel.
In a parallel communicator, the first process will run while the remaining processes
block on a barrier. In a serial run, the function will be called directly.
This currently assumes the global communicator is PETSc.COMM_WORLD, but is easily
generalized.
"""
try:
from petsc4py import PETSc
is_parallel = True
except ImportError:
is_parallel = False
if is_parallel:
rank = PETSc.COMM_WORLD.getRank()
if rank == 0:
def serial_fun(*args, **kwargs):
fun(*args, **kwargs)
PETSc.COMM_WORLD.Barrier()
else:
def serial_fun(*args, **kwargs):
PETSc.COMM_WORLD.Barrier()
else:
def serial_fun(*args, **kwargs):
fun(*args, **kwargs)
return serial_fun
@run_serialized
def inplace_build(working_dir, warn=True):
"""Build missing extension modules with an in-place build. This is a convenience
function for PyClaw applications that rely on custom extension modules. In its default
mode, this function emits warnings indicating its actions.
This function is safe to execute in parallel, it will only run on the 0 zero process while
the other processes block.
"""
if warn:
warnings.warn("missing extension modules")
warnings.warn("running python setup.py build_ext -i in %s" % working_dir)
subprocess.check_call('python setup.py build_ext -i', shell=True, cwd=working_dir)
if warn:
warnings.warn("successfully executed python setup.py build_ext -i in %s" % working_dir)
def run_app_from_main(application,setplot=None):
r"""
Runs an application from pyclaw/examples/, automatically parsing command line keyword
arguments (key=value) as parameters to the application, with positional
arguments being passed to PETSc (if it is enabled).
Perhaps we should take the PETSc approach of having a database of PyClaw
options that can be queried for options on specific objects within the
PyClaw runtime instead of front-loading everything through the application
main...
"""
# Arguments to the PyClaw should be keyword based, positional arguments
# will be passed to PETSc
petsc_args, pyclaw_kwargs = _info_from_argv(sys.argv)
if 'use_petsc' in pyclaw_kwargs and pyclaw_kwargs['use_petsc']:
import petsc4py
petsc_args = [arg.replace('--','-') for arg in sys.argv[1:] if '=' not in arg]
petsc4py.init(petsc_args)
from clawpack import petclaw as pyclaw
else:
from clawpack import pyclaw
if sys.version_info >= (2, 7):
app_kwargs = {key: value for key, value in pyclaw_kwargs.items()
if not key in ('htmlplot','iplot')}
else:
# the above fails with Python < 2.7, so write it out...
app_kwargs = {}
for key,value in pyclaw_kwargs.items():
if key not in ('htmlplot','iplot'):
app_kwargs[key] = value
claw=application(**app_kwargs)
# Solve
status = claw.run()
# Plot results
htmlplot = pyclaw_kwargs.get('htmlplot',False)
iplot = pyclaw_kwargs.get('iplot',False)
outdir = pyclaw_kwargs.get('outdir','./_output')
if htmlplot:
if setplot is not None:
pyclaw.plot.html_plot(outdir=outdir,setplot=setplot)
else:
pyclaw.plot.html_plot(outdir=outdir)
if iplot:
if setplot is not None:
pyclaw.plot.interactive_plot(outdir=outdir,setplot=setplot)
else:
pyclaw.plot.interactive_plot(outdir=outdir)
return claw
class VerifyError(Exception):
pass
def gen_variants(application, verifier, kernel_languages=('Fortran',), disable_petsc=False, **kwargs):
r"""
Generator of runnable variants of a test application given a verifier
Given an application, a script for verifying its output, and a
list of kernel languages to try, generates all possible variants of the
application to try by taking a product of the available kernel_languages and
(petclaw/pyclaw). For many applications, this will generate 4 variants:
the product of the two main kernel languages ('Fortran' and 'Python'), against
the the two parallel modes (petclaw and pyclaw).
For more information on how the verifier function should be implemented,
see util.test_app for a description, and util.check_diff for an example.
All unrecognized keyword arguments are passed through to the application.
"""
arg_dicts = build_variant_arg_dicts(kernel_languages, disable_petsc)
for test_kwargs in arg_dicts:
test_kwargs.update(kwargs)
try:
test_name = application.__module__
except:
test_name = inspect.getmodule(application)
if 'solver_type' in test_kwargs:
solver_info = 'solver_type={solver_type!s}, '
else:
solver_info = ''
test = lambda: test_app(application, verifier, test_kwargs)
test.description = '%s(%s)' % (test_name, str(kwargs))
yield test
return
def build_variant_arg_dicts(kernel_languages=('Fortran',), disable_petsc=False):
import itertools
# test petsc4py only if it is available
use_petsc_opts = (False,)
if not disable_petsc:
try:
import petsc4py
use_petsc_opts=(True,False)
except ImportError:
pass # petsc starts disabled
opt_names = 'use_petsc','kernel_language'
opt_product = itertools.product(use_petsc_opts,kernel_languages)
arg_dicts = [dict(list(zip(opt_names,argset))) for argset in opt_product]
return arg_dicts
def test_app_variants(application, verifier, kernel_languages, **kwargs):
arg_dicts = build_variant_arg_dicts(kernel_languages)
for test_kwargs in arg_dicts:
test_kwargs.update(kwargs)
test_app(application, verifier, test_kwargs)
return
def test_app(application, verifier, kwargs):
r"""
Test the output of a given application against its verifier method.
This function performs the following two function calls::
output = application(**kwargs)
check_values = verifier(output)
The verifier method should return None if the output is correct, otherwise
it should return an indexed sequence of three items::
0 - expected value
1 - test value
2 - string describing the tolerance type (abs/rel) and value.
This information is used to present descriptive help if an error is detected.
For an example verifier method, see util.check_diff
"""
print(kwargs)
if 'use_petsc' in kwargs and not kwargs['use_petsc']:
try:
# don't duplicate serial test runs
from petsc4py import PETSc
rank = PETSc.COMM_WORLD.getRank()
if rank != 0:
return
except ImportError as e:
pass
claw = application(**kwargs)
claw.run()
check_values = verifier(claw)
if check_values is not None:
err = \
"""%s
********************************************************************************
verification function
%s
args : %s
norm of expected data: %s
norm of test data : %s
test error : %s
%s
********************************************************************************
""" % \
(inspect.getsourcefile(application),
inspect.getsource(verifier),
kwargs,
check_values[0],
check_values[1],
check_values[2],
check_values[3])
raise VerifyError(err)
return
def check_diff(expected, test, **kwargs):
r"""
Checks the difference between expected and test values, return None if ok
This function expects either the keyword argument 'abstol' or 'reltol'.
"""
if 'delta' in kwargs:
d = np.prod(kwargs['delta'])
else:
d = 1.0
err_norm = d*np.linalg.norm(expected - test)
expected_norm = d*np.linalg.norm(expected)
test_norm = d*np.linalg.norm(test)
if 'abstol' in kwargs:
if err_norm < kwargs['abstol']: return None
else: return (expected_norm, test_norm, err_norm,
'abstol : %s' % kwargs['abstol'])
elif 'reltol' in kwargs:
if err_norm/expected_norm < kwargs['reltol']: return None
else: return (expected_norm, test_norm, err_norm,
'reltol : %s' % kwargs['reltol'])
else:
raise Exception('Incorrect use of check_diff verifier, specify tol!')
def check_solutions_are_same(sol_a,sol_b):
assert len(sol_a.states) == len(sol_b.states)
assert sol_a.t == sol_b.t
for state in sol_a.states:
for ref_state in sol_b.states:
if ref_state.patch.patch_index == state.patch.patch_index:
break
# Required state attributes
assert np.linalg.norm(state.q - ref_state.q) < 1.e-6 # Not sure why this can be so large
if ref_state.aux is not None:
assert np.linalg.norm(state.aux - ref_state.aux) < 1.e-16
for attr in ['t', 'num_eqn', 'num_aux']:
assert getattr(state,attr) == getattr(ref_state,attr)
# Optional state attributes
for attr in ['patch_index', 'level']:
if hasattr(ref_state,attr):
assert getattr(state,attr) == getattr(ref_state,attr)
patch = state.patch
ref_patch = ref_state.patch
# Required patch attributes
for attr in ['patch_index', 'level']:
assert getattr(patch,attr) == getattr(ref_patch,attr)
dims = patch.dimensions
ref_dims = ref_patch.dimensions
for dim, ref_dim in zip(dims,ref_dims):
# Required dim attributes
for attr in ['num_cells','lower','delta']:
assert getattr(dim,attr) == getattr(ref_dim,attr)
# Optional dim attributes
for attr in ['units','on_lower_boundary','on_upper_boundary']:
if hasattr(ref_dim,attr):
assert getattr(dim,attr) == getattr(ref_dim,attr)
# ============================================================================
# F2PY Utility Functions
# ============================================================================
def compile_library(source_list,module_name,interface_functions=[],
local_path='./',library_path='./',f2py_flags='',
FC=None,FFLAGS=None,recompile=False,clean=False):
r"""
Compiles and wraps fortran source into a callable module in python.
This function uses f2py to create an interface from python to the fortran
sources in source_list. The source_list can either be a list of names
of source files in which case compile_library will search for the file in
local_path and then in library_path. If a path is given, the file will be
checked to see if it exists, if not it will look for the file in the above
resolution order. If any source file is not found, an IOException is
raised.
The list interface_functions allows the user to specify which fortran
functions are actually available to python. The interface functions are
assumed to be in the file with their name, i.e. claw1 is located in
'claw1.f95' or 'claw1.f'.
The interface from fortran may be different than the original function
call in fortran so the user should make sure to check the automatically
created doc string for the fortran module for proper use.
Source files will not be recompiled if they have not been changed.
One set of options of note is for enabling OpenMP, it requires the usual
fortran flags but the OpenMP library also must be compiled in, this is
done with the flag -lgomp. The call to compile_library would then be:
compile_library(src,module_name,f2py_flags='-lgomp',FFLAGS='-fopenmp')
For complete optimization use:
FFLAGS='-O3 -fopenmp -funroll-loops -finline-functions -fdefault-real-8'
:Input:
- *source_list* - (list of strings) List of source files, if these are
just names of the source files, i.e. 'bc1.f' then they will be searched
for in the default source resolution order, if an explicit path is
given, i.e. './bc1.f', then the function will use that source if it can
find it.
- *module_name* - (string) Name of the resulting module
- *interface_functions* - (list of strings) List of function names to
provide access to, if empty, all functions are accessible to python.
Defaults to [].
- *local_path* - (string) The base path for source resolution, defaults
to './'.
- *library_path* - (string) The library path for source resolution,
defaults to './'.
- *f2py_flags* - (string) f2py flags to be passed
- *FC* - (string) Override the environment variable FC and use it to
compile, note that this does not replace the compiler that f2py uses,
only the object file compilation (functions that do not have
interfaces)
- *FFLAGS* - (string) Override the environment variable FFLAGS and pass
them to the fortran compiler
- *recompile* - (bool) Force recompilation of the library, defaults to
False
- *clean* - (bool) Force a clean build of all source files
"""
# Setup logger
logger = logging.getLogger('f2py')
temp_file = tempfile.TemporaryFile()
logger.info('Compiling %s' % module_name)
# Force recompile if the clean flag is set
if clean:
recompile = True
# Expand local_path and library_path
local_path = os.path.expandvars(local_path)
local_path = os.path.expanduser(local_path)
library_path = os.path.expandvars(library_path)
library_path = os.path.expanduser(library_path)
# Fetch environment variables we need for compilation
if FC is None:
if 'FC' in os.environ:
FC = os.environ['FC']
else:
FC = 'gfortran'
if FFLAGS is None:
if 'FFLAGS' in os.environ:
FFLAGS = os.environ['FFLAGS']
else:
FFLAGS = ''
# Create the list of paths to sources
path_list = []
for source in source_list:
# Check to see if the source looks like a path, i.e. it contains the
# os.path.sep character
if source.find(os.path.sep) >= 0:
source = os.path.expandvars(source)
source = os.path.expanduser(source)
# This is a path, check to see if it's valid
if os.path.exists(source):
path_list.append(source)
continue
# Otherwise, take the last part of the path and try searching for
# it in the resolution order
source = os.path.split(source)
# Search for the source file in local_path and then library_path
if os.path.exists(os.path.join(local_path,source)):
path_list.append(os.path.join(local_path,source))
continue
elif os.path.exists(os.path.join(library_path,source)):
path_list.append(os.path.join(library_path,source))
continue
else:
raise IOError('Could not find source file %s' % source)
# Compile each of the source files if the object files are not present or
# if the modification date of the source file is newer than the object
# file's creation date
object_list = []
src_list = []
for path in path_list:
object_path = os.path.join(os.path.split(path)[0],
'.'.join((os.path.split(path)[1].split('.')[:-1][0],'o')))
# Check to see if this path contains one of the interface functions
if os.path.split(path)[1].split('.')[:-1][0] in interface_functions:
src_list.append(path)
continue
# If there are no interface functions specified, then all source files
# must be included in the f2py call
elif len(interface_functions) == 0:
src_list.append(path)
continue
if os.path.exists(object_path) and not clean:
# Check to see if the modification date of the source file is
# greater than the object file
if os.path.getmtime(object_path) > os.path.getmtime(path):
object_list.append(object_path)
continue
# Compile the source file into the object file
command = '%s %s -c %s -o %s' % (FC,FFLAGS,path,object_path)
logger.debug(command)
subprocess.call(command,shell=True,stdout=temp_file)
object_list.append(object_path)
# Check to see if recompile is needed
if not recompile:
module_path = os.path.join('.','.'.join((module_name,'so')))
if os.path.exists(module_path):
for src in src_list:
if os.path.getmtime(module_path) < os.path.getmtime(src):
recompile = True
break
for obj in object_list:
if os.path.getmtime(module_path) < os.path.getmtime(obj):
recompile = True
break
else:
recompile = True
if recompile:
# Wrap the object files into a python module
f2py_command = "f2py -c"
# Add standard compiler flags
f2py_command = ' '.join((f2py_command,f2py_flags))
f2py_command = ' '.join((f2py_command,"--f90flags='%s'" % FFLAGS))
# Add module names
f2py_command = ' '.join((f2py_command,'-m %s' % module_name))
# Add source files
f2py_command = ' '.join((f2py_command,' '.join(src_list)))
# Add object files
f2py_command = ' '.join((f2py_command,' '.join(object_list)))
# Add interface functions
if len(interface_functions) > 0:
f2py_command = ' '.join( (f2py_command,'only:') )
for interface in interface_functions:
f2py_command = ' '.join( (f2py_command,interface) )
f2py_command = ''.join( (f2py_command,' :') )
logger.debug(f2py_command)
status = subprocess.call(f2py_command,shell=True,stdout=temp_file)
if status == 0:
logger.info("Module %s compiled" % module_name)
else:
logger.info("Module %s failed to compile with code %s" % (module_name,status))
sys.exit(13)
else:
logger.info("Module %s is up to date." % module_name)
temp_file.seek(0)
logger.debug(temp_file.read())
temp_file.close()
def construct_function_handle(path,function_name=None):
r"""
Constructs a function handle from the file at path.
This function will attempt to construct a function handle from the python
file at path.
:Input:
- *path* - (string) Path to the file containing the function
- *function_name* - (string) Name of the function defined in the file
that the handle will point to. Defaults to the same name as the file
without the extension.
:Output:
- (func) Function handle to the constructed function, None if this has
failed.
"""
# Determine the resulting function_name
if function_name is None:
function_name = path.split('/')[-1].split('.')[0]
full_path = os.path.abspath(path)
if os.path.exists(full_path):
suffix = path.split('.')[-1]
# This is a python file and we just need to read it and map it
if suffix in ['py']:
exec(compile(open(full_path).read(), full_path, 'exec'),globals())
return eval('%s' % function_name)
else:
raise Exception("Invalid file type for function handle.")
else:
raise Exception("Invalid file path %s" % path)
#---------------------------------------------------------
def read_data_line(inputfile,num_entries=1,data_type=float):
#---------------------------------------------------------
r"""
Read data a single line from an input file
Reads one line from an input file and returns an array of values
inputfile: a file pointer to an open file object
num_entries: number of entries that should be read, defaults to only 1
type: Type of the values to be read in, they all must be the same type
This function will return either a single value or an array of values
depending on if num_entries > 1
"""
l = []
while l==[]: # skip over blank lines
line = inputfile.readline()
if line == '':
raise IOError('*** Reached EOF in file %s' % inputfile.name)
l = line.split()
if num_entries == 1: # This is a convenience for calling functions
return data_type(l[0])
val = np.empty(num_entries,data_type)
if num_entries > len(l):
print('Error in read_data_line: num_entries = ', num_entries)
print(' is larger than length of l = ',l)
val = [data_type(entry) for entry in l[:num_entries]]
return val
#----------------------------------------
def convert_fort_double_to_float(number):
#----------------------------------------
r"""
Converts a fortran format double to a float
Converts a fortran format double to a python float.
number: is a string representation of the double. Number should
be of the form "1.0d0"
"""
a = number.split('d')
return float(a[0])*10**float(a[1])
#-----------------------------
def current_time(addtz=False):
#-----------------------------
# determine current time and reformat:
time1 = time.asctime()
year = time1[-5:]
day = time1[:-14]
hour = time1[-13:-5]
current_time = day + year + ' at ' + hour
if addtz:
current_time = current_time + ' ' + time.tzname[time.daylight]
return current_time
def _method_info_from_argv(argv=None):
"""Command-line -> method call arg processing.
- positional args:
a b -> method('a', 'b')
- intifying args:
a 123 -> method('a', 123)
- json loading args:
a '["pi", 3.14, null]' -> method('a', ['pi', 3.14, None])
- keyword args:
a foo=bar -> method('a', foo='bar')
- using more of the above
1234 'extras=["r2"]' -> method(1234, extras=["r2"])
@param argv {list} Command line arg list. Defaults to `sys.argv`.
@returns (<method-name>, <args>, <kwargs>)
"""
import json
if argv is None:
argv = sys.argv
method_name, arg_strs = argv[1], argv[2:]
args = []
kwargs = {}
for s in arg_strs:
if s.count('=') == 1:
key, value = s.split('=', 1)
else:
key, value = None, s
try:
value = json.loads(value)
except ValueError:
pass
if value=='True': value=True
if value.lower()=='false': value=False
if key:
kwargs[key] = value
else:
args.append(value)
return method_name, args, kwargs
def _info_from_argv(argv=None):
"""Command-line -> method call arg processing.
- positional args:
a b -> method('a', 'b')
- intifying args:
a 123 -> method('a', 123)
- json loading args:
a '["pi", 3.14, null]' -> method('a', ['pi', 3.14, None])
- keyword args:
a foo=bar -> method('a', foo='bar')
- using more of the above
1234 'extras=["r2"]' -> method(1234, extras=["r2"])
@param argv {list} Command line arg list. Defaults to `sys.argv`.
@returns (<method-name>, <args>, <kwargs>)
"""
import json
if argv is None:
argv = sys.argv
arg_strs = argv[1:]
args = []
kwargs = {}
for s in arg_strs:
if s.count('=') == 1:
key, value = s.split('=', 1)
else:
key, value = None, s
try:
value = json.loads(value)
except ValueError:
pass
if value=='True': value=True
if value=='False': value=False
if key:
kwargs[key] = value
else:
args.append(value)
return args, kwargs
def _arguments_str_from_dictionary(options):
"""
Convert method options passed as a dictionary to a str object
having the form of the method arguments
"""
option_string = ""
for k in options:
if isinstance(options[k], str):
option_string += k+"='"+str(options[k])+"',"
else:
option_string += k+"="+str(options[k])+","
option_string = option_string.strip(',')
return option_string
#-----------------------------
class FrameCounter:
#-----------------------------
r"""
Simple frame counter
Simple frame counter to keep track of current frame number. This can
also be used to keep multiple runs frames separated by having multiple
counters at once.
Initializes to 0
"""
def __init__(self):
self.__frame = 0
def __repr__(self):
return str(self.__frame)
def increment(self):
r"""
Increment the counter by one
"""
self.__frame += 1
def set_counter(self,new_frame_num):
r"""
Set the counter to new_frame_num
"""
self.__frame = new_frame_num
def get_counter(self):
r"""
Get the current frame number
"""
return self.__frame
def reset_counter(self):
r"""
Reset the counter to 0
"""
self.__frame = 0
| 34,060
|
https://github.com/mindbender1/json-schema/blob/master/core/src/main/java/org/everit/json/schema/internal/URIReferenceFormatValidator.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
json-schema
|
mindbender1
|
Java
|
Code
| 64
| 206
|
package org.everit.json.schema.internal;
import static java.lang.String.format;
import java.net.URI;
import java.net.URISyntaxException;
import java8.util.Optional;
import org.everit.json.schema.FormatValidator;
public class URIReferenceFormatValidator extends AFormatValidator {
@Override public Optional<String> validate(String subject) {
try {
new URI(subject);
return Optional.empty();
} catch (URISyntaxException e) {
return failure(subject);
}
}
protected Optional<String> failure(String subject) {
return Optional.of(format("[%s] is not a valid URI reference", subject));
}
@Override public String formatName() {
return "uri-reference";
}
}
| 3,452
|
https://github.com/lagXkjy/yoga/blob/master/fc/src/main/java/com/fc/crm/service/impl/OrderServiceImpl.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
yoga
|
lagXkjy
|
Java
|
Code
| 145
| 888
|
package com.fc.crm.service.impl;
import com.fc.business.service.MemberBaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.fc.crm.dao.OrderDao;
import com.fc.crm.domain.OrderDO;
import com.fc.crm.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.fc.common.utils.PageUtils;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderDao orderDao;
@Autowired
private MemberBaseInfoService memberBaseInfoService;
@Override
public OrderDO get(Integer id){
return orderDao.get(id);
}
@Override
public List<OrderDO> list(Map<String, Object> map){
Map<String, String> yesMap = memberBaseInfoService.queryNameByCode("yes_no");
Map<String, String> payTypeMap = memberBaseInfoService.queryNameByCode("payment_type");
Map<String, String> payModeMap = memberBaseInfoService.queryNameByCode("payment_mode");
Map<String, String> sendMap = memberBaseInfoService.queryNameByCode("send_type");
Map<String, String> campusMap = memberBaseInfoService.queryNameByCode("schedule_campus");
Map<String, String> courseMap = memberBaseInfoService.queryNameByCode("consultingCourse_type");
List<OrderDO> list = orderDao.list(map);
list.forEach(p->{
p.setInitialTraining(p.getInitialTraining()==null?p.getInitialTraining():yesMap.get(p.getInitialTraining()));
p.setPaymentType(p.getPaymentType()==null?p.getPaymentType():payTypeMap.get(p.getPaymentType()));
p.setPaymentMode(p.getPaymentMode()==null?p.getPaymentMode():payModeMap.get(p.getPaymentMode()));
p.setBook(p.getBook()==null?p.getBook():sendMap.get(p.getBook()));
p.setClothes(p.getClothes()==null?p.getClothes():sendMap.get(p.getClothes()));
p.setScheduleCampus(p.getScheduleCampus()==null?p.getScheduleCampus():campusMap.get(p.getScheduleCampus()));
p.setEnrollmentCourse(p.getEnrollmentCourse()==null?p.getEnrollmentCourse():courseMap.get(p.getEnrollmentCourse()));
});
return list;
}
@Override
public List<Map<String, Object>> findDatas(Map<String, Object> map){
List<Map<String, Object>> list = orderDao.findDatas(map);
return list;
}
@Override
public int save(OrderDO order){
return orderDao.save(order);
}
@Override
public int update(OrderDO order){
return orderDao.update(order);
}
@Override
public int remove(Integer id){
return orderDao.remove(id);
}
@Override
public int batchRemove(Integer[] ids){
return orderDao.batchRemove(ids);
}
}
| 30,870
|
https://github.com/JHPDEVS/CheckMate-vue-laravel/blob/master/resources/js/Jetstream/NavLink.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
CheckMate-vue-laravel
|
JHPDEVS
|
Vue
|
Code
| 57
| 237
|
<template>
<inertia-link :href="href" :class="classes">
<slot></slot>
</inertia-link>
</template>
<script>
export default {
props: ['href', 'active'],
computed: {
classes() {
return this.active
? 'inline-flex items-center font-semibold px-1 pt-1 border-b-4 border-primary-content-400 text-sm font-medium leading-5 text-primary-content focus:outline-none focus:border-primary-content-700 transition'
: 'inline-flex items-center font-semibold px-1 pt-1 border-b-4 border-transparent text-sm font-medium leading-5 text-gray-400 hover:text-primary-content hover:border-primary-content focus:outline-none focus:text-primary-content-700 focus:border-primary-content transition'
}
}
}
</script>
| 35,156
|
https://github.com/northern/transmit-server/blob/master/src/app/Query/TemplateQuery.js
|
Github Open Source
|
Open Source
|
MIT
| null |
transmit-server
|
northern
|
JavaScript
|
Code
| 66
| 175
|
import Response from '../Response'
import AppError from '../Error/AppError'
import AbstractQuery from './AbstractQuery'
export default class TemplateQuery extends AbstractQuery {
setTemplateService(templateService) {
this.templateService = templateService
}
getById(templateId) {
const response = new Response()
try {
const template = this.templateService.getById(templateId)
response.template = template
}
catch(e) {
if (e instanceof AppError) {
response.status = Response.ERROR
response.message = e.message
}
else {
throw e
}
}
return response
}
}
| 21,978
|
https://github.com/fuzctc/PyAutoApiRoute/blob/master/sanic/app.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
PyAutoApiRoute
|
fuzctc
|
Python
|
Code
| 84
| 305
|
# !/usr/bin/python
# -*- coding:utf-8 -*-
# Author: Zhichang Fu
# Created Time: 2018-12-14 14:12:31
'''
BEGIN
function:
sanic app
return:
code:0 success
END
'''
from sanic import Sanic
import argparse
import sys
sys.path.append("..")
from base import config, route
parser = argparse.ArgumentParser()
parser.add_argument("--port", help="app running port", type=int, default=8080)
parser.add_argument("--workers", help="app running port", type=int, default=1)
parse_args = parser.parse_args()
app = Sanic("App")
route_path = "./resources"
route_list = route(
route_path, resources_name="resources", route_prefix="sanic/")
for item in route_list:
app.add_route(item[1].as_view(), item[0])
if __name__ == "__main__":
app.run(
host="0.0.0.0",
port=int(parse_args.port),
debug=config.DEBUG,
workers=int(parse_args.workers))
| 42,168
|
https://github.com/qiaw99/SS2020/blob/master/SWT/_U11/Grader.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
SS2020
|
qiaw99
|
Java
|
Code
| 113
| 213
|
package grading;
/**
* Grader for university courses.
*
* So far, this grader can only handle courses with two exams which follow an
* 40-60 point distribution.
*
* @author fzieris
* @version 0.5
*/
public class Grader {
public enum Grade {
A, B, C, D, F
}
/**
* Calculates the grade for a student given his/her points in the exams.
*
* @param firstExam
* Points in the first exam
* @param secondExam
* Points in the second exam
* @return The grade based on the well-known rules
*/
public static Grade grade(int firstExam, int secondExam) {
/** Not actual content; only for documentation */
return null;
}
}
| 42,736
|
https://github.com/microsoftgraph/msgraph-beta-sdk-php/blob/master/src/Generated/Models/AppIdentity.php
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
msgraph-beta-sdk-php
|
microsoftgraph
|
PHP
|
Code
| 807
| 2,171
|
<?php
namespace Microsoft\Graph\Beta\Generated\Models;
use Microsoft\Kiota\Abstractions\Serialization\AdditionalDataHolder;
use Microsoft\Kiota\Abstractions\Serialization\Parsable;
use Microsoft\Kiota\Abstractions\Serialization\ParseNode;
use Microsoft\Kiota\Abstractions\Serialization\SerializationWriter;
use Microsoft\Kiota\Abstractions\Store\BackedModel;
use Microsoft\Kiota\Abstractions\Store\BackingStore;
use Microsoft\Kiota\Abstractions\Store\BackingStoreFactorySingleton;
class AppIdentity implements AdditionalDataHolder, BackedModel, Parsable
{
/**
* @var BackingStore $backingStore Stores model information.
*/
private BackingStore $backingStore;
/**
* Instantiates a new appIdentity and sets the default values.
*/
public function __construct() {
$this->backingStore = BackingStoreFactorySingleton::getInstance()->createBackingStore();
$this->setAdditionalData([]);
}
/**
* Creates a new instance of the appropriate class based on discriminator value
* @param ParseNode $parseNode The parse node to use to read the discriminator value and create the object
* @return AppIdentity
*/
public static function createFromDiscriminatorValue(ParseNode $parseNode): AppIdentity {
return new AppIdentity();
}
/**
* Gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
* @return array<string, mixed>|null
*/
public function getAdditionalData(): ?array {
$val = $this->getBackingStore()->get('additionalData');
if (is_null($val) || is_array($val)) {
/** @var array<string, mixed>|null $val */
return $val;
}
throw new \UnexpectedValueException("Invalid type found in backing store for 'additionalData'");
}
/**
* Gets the appId property value. Refers to the unique identifier representing Application Id in the Azure Active Directory.
* @return string|null
*/
public function getAppId(): ?string {
$val = $this->getBackingStore()->get('appId');
if (is_null($val) || is_string($val)) {
return $val;
}
throw new \UnexpectedValueException("Invalid type found in backing store for 'appId'");
}
/**
* Gets the backingStore property value. Stores model information.
* @return BackingStore
*/
public function getBackingStore(): BackingStore {
return $this->backingStore;
}
/**
* Gets the displayName property value. Refers to the Application Name displayed in the Azure Portal.
* @return string|null
*/
public function getDisplayName(): ?string {
$val = $this->getBackingStore()->get('displayName');
if (is_null($val) || is_string($val)) {
return $val;
}
throw new \UnexpectedValueException("Invalid type found in backing store for 'displayName'");
}
/**
* The deserialization information for the current model
* @return array<string, callable(ParseNode): void>
*/
public function getFieldDeserializers(): array {
$o = $this;
return [
'appId' => fn(ParseNode $n) => $o->setAppId($n->getStringValue()),
'displayName' => fn(ParseNode $n) => $o->setDisplayName($n->getStringValue()),
'@odata.type' => fn(ParseNode $n) => $o->setOdataType($n->getStringValue()),
'servicePrincipalId' => fn(ParseNode $n) => $o->setServicePrincipalId($n->getStringValue()),
'servicePrincipalName' => fn(ParseNode $n) => $o->setServicePrincipalName($n->getStringValue()),
];
}
/**
* Gets the @odata.type property value. The OdataType property
* @return string|null
*/
public function getOdataType(): ?string {
$val = $this->getBackingStore()->get('odataType');
if (is_null($val) || is_string($val)) {
return $val;
}
throw new \UnexpectedValueException("Invalid type found in backing store for 'odataType'");
}
/**
* Gets the servicePrincipalId property value. Refers to the unique identifier indicating Service Principal Id in Azure Active Directory for the corresponding App.
* @return string|null
*/
public function getServicePrincipalId(): ?string {
$val = $this->getBackingStore()->get('servicePrincipalId');
if (is_null($val) || is_string($val)) {
return $val;
}
throw new \UnexpectedValueException("Invalid type found in backing store for 'servicePrincipalId'");
}
/**
* Gets the servicePrincipalName property value. Refers to the Service Principal Name is the Application name in the tenant.
* @return string|null
*/
public function getServicePrincipalName(): ?string {
$val = $this->getBackingStore()->get('servicePrincipalName');
if (is_null($val) || is_string($val)) {
return $val;
}
throw new \UnexpectedValueException("Invalid type found in backing store for 'servicePrincipalName'");
}
/**
* Serializes information the current object
* @param SerializationWriter $writer Serialization writer to use to serialize this model
*/
public function serialize(SerializationWriter $writer): void {
$writer->writeStringValue('appId', $this->getAppId());
$writer->writeStringValue('displayName', $this->getDisplayName());
$writer->writeStringValue('@odata.type', $this->getOdataType());
$writer->writeStringValue('servicePrincipalId', $this->getServicePrincipalId());
$writer->writeStringValue('servicePrincipalName', $this->getServicePrincipalName());
$writer->writeAdditionalData($this->getAdditionalData());
}
/**
* Sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
* @param array<string,mixed> $value Value to set for the additionalData property.
*/
public function setAdditionalData(?array $value): void {
$this->getBackingStore()->set('additionalData', $value);
}
/**
* Sets the appId property value. Refers to the unique identifier representing Application Id in the Azure Active Directory.
* @param string|null $value Value to set for the appId property.
*/
public function setAppId(?string $value): void {
$this->getBackingStore()->set('appId', $value);
}
/**
* Sets the backingStore property value. Stores model information.
* @param BackingStore $value Value to set for the backingStore property.
*/
public function setBackingStore(BackingStore $value): void {
$this->backingStore = $value;
}
/**
* Sets the displayName property value. Refers to the Application Name displayed in the Azure Portal.
* @param string|null $value Value to set for the displayName property.
*/
public function setDisplayName(?string $value): void {
$this->getBackingStore()->set('displayName', $value);
}
/**
* Sets the @odata.type property value. The OdataType property
* @param string|null $value Value to set for the @odata.type property.
*/
public function setOdataType(?string $value): void {
$this->getBackingStore()->set('odataType', $value);
}
/**
* Sets the servicePrincipalId property value. Refers to the unique identifier indicating Service Principal Id in Azure Active Directory for the corresponding App.
* @param string|null $value Value to set for the servicePrincipalId property.
*/
public function setServicePrincipalId(?string $value): void {
$this->getBackingStore()->set('servicePrincipalId', $value);
}
/**
* Sets the servicePrincipalName property value. Refers to the Service Principal Name is the Application name in the tenant.
* @param string|null $value Value to set for the servicePrincipalName property.
*/
public function setServicePrincipalName(?string $value): void {
$this->getBackingStore()->set('servicePrincipalName', $value);
}
}
| 16,881
|
https://github.com/GentlemanBrewing/ADCLibraries-MCP3424/blob/master/ADCPi/demo-logvoltage.py
|
Github Open Source
|
Open Source
|
MIT
| null |
ADCLibraries-MCP3424
|
GentlemanBrewing
|
Python
|
Code
| 157
| 488
|
#!/usr/bin/python3
from ABE_ADCPi import ADCPi
from ABE_helpers import ABEHelpers
import datetime
import time
"""
================================================
ABElectronics ADC Pi 8-Channel ADC data-logger demo
Version 1.0 Created 29/02/2015
Requires python 3 smbus to be installed
run with: python3 demo-read_voltage.py
================================================
Initialise the ADC device using the default addresses and sample rate, change
this value if you have changed the address selection jumpers
Sample rate can be 12,14, 16 or 18
"""
i2c_helper = ABEHelpers()
bus = i2c_helper.get_smbus()
adc = ADCPi(bus, 0x68, 0x69, 18)
def writetofile(texttowrtite):
f = open('adclog.txt', 'a')
f.write(str(datetime.datetime.now()) + " " + texttowrtite)
f.closed
while (True):
# read from adc channels and write to the log file
writetofile("Channel 1: %02f\n" % adc.read_voltage(1))
writetofile("Channel 2: %02f\n" % adc.read_voltage(2))
writetofile("Channel 3: %02f\n" % adc.read_voltage(3))
writetofile("Channel 4: %02f\n" % adc.read_voltage(4))
writetofile("Channel 5: %02f\n" % adc.read_voltage(5))
writetofile("Channel 6: %02f\n" % adc.read_voltage(6))
writetofile("Channel 7: %02f\n" % adc.read_voltage(7))
writetofile("Channel 8: %02f\n" % adc.read_voltage(8))
# wait 1 second before reading the pins again
time.sleep(1)
| 37,048
|
https://github.com/KarpelesLab/static-opus/blob/master/opus/inc-src-opus-multistream.go
|
Github Open Source
|
Open Source
|
MIT
| null |
static-opus
|
KarpelesLab
|
Go
|
Code
| 8
| 35
|
package opus
/*
#include <opus-1.3.1/src/opus_multistream.c>
*/
import "C"
| 15,910
|
https://github.com/apereo/dotnet-cas-client-redis/blob/master/src/DotNetCasClient.Redis/Properties/AutoGeneratedAssemblyInfo.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
dotnet-cas-client-redis
|
apereo
|
C#
|
Code
| 64
| 240
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Cake.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Reflection;
[assembly: AssemblyTitle("Apereo .NET CAS Client Redis backed Proxy/Service Ticket Managers")]
[assembly: AssemblyDescription("Redis backed Proxy/Service Ticket Managers for the Apereo .NET CAS Client.")]
[assembly: AssemblyCompany("Apereo Foundation")]
[assembly: AssemblyProduct("Apereo .NET CAS Client Redis backed Proxy/Service Ticket Managers")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0-alpha.2+Branch.develop.Sha.6f93f4f5e80c8082cf151ff392a0c9cc4bdecaa7")]
[assembly: AssemblyCopyright("Copyright (c) 2007-2019 Apereo. All rights reserved.")]
| 4,890
|
https://github.com/denisoed/Arial-gym/blob/master/dev/Blocks/Pages/About-us/features/features.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
Arial-gym
|
denisoed
|
Sass
|
Code
| 50
| 186
|
.features
padding: 50px 0
&__container
+container()
&__list
width: 100%
display: flex
justify-content: space-around
align-items: center
flex-wrap: wrap
.features-item
display: flex
flex-direction: column
align-items: center
margin: 15px 0
&__icon
font-size: 52px
color: $accent
margin-bottom: 15px
&__total
color: $white
font-size: 32px
font-family: $Segoe-black
margin-bottom: 15px
&__title
color: $white
font-size: 22px
font-family: $Segoe-bold
| 45,335
|
https://github.com/lorenchorley/StrangeIoC-Updated/blob/master/Assets/scripts/StrangeIoC/dispatcher/eventdispatcher/impl/TmEvent.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
StrangeIoC-Updated
|
lorenchorley
|
C#
|
Code
| 201
| 422
|
/*
* Copyright 2013 ThirdMotion, Inc.
*
* 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.
*/
/**
* @class strange.extensions.dispatcher.eventdispatcher.impl.TmEvent
*
* The standard Event object for IEventDispatcher.
*
* The TmEvent has three proeprties:
* <ul>
* <li>type - The key for the event trigger</li>
* <li>target - The Dispatcher that fired the event</li>
* <li>data - An arbitrary payload</li>
* </ul>
*/
using strange.extensions.dispatcher.eventdispatcher.api;
namespace strange.extensions.dispatcher.eventdispatcher.impl {
public class TmEvent : IEvent {
public object type { get; set; }
public IEventDispatcher target { get; set; }
public object data { get; set; }
/// Construct a TmEvent
public TmEvent(object type, IEventDispatcher target, object data) {
this.type = type;
this.target = target;
this.data = data;
}
}
}
| 27,173
|
https://github.com/godoggyo/AutoWordle/blob/master/UserWordle.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
AutoWordle
|
godoggyo
|
Python
|
Code
| 14
| 40
|
import _gamefunc as ws
class UserWordle():
word = None
def __init__(self) -> None:
ws.establishWordPool
| 17,642
|
https://github.com/HeartCommunity/uiKit/blob/master/packages/people-and-teams/profilecard/src/styled/constants.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
uiKit
|
HeartCommunity
|
JavaScript
|
Code
| 129
| 401
|
// @flow
import { colors, themed } from '@findable/theme';
export const bgColor = themed({
light: colors.N0,
dark: colors.DN50,
});
export const headerBgColor = themed({
light: colors.B500,
dark: colors.B100,
});
export const headerBgColorDisabledUser = themed({
light: colors.N30,
dark: colors.B100,
});
export const headerTextColor = themed({
light: colors.N0,
dark: colors.N0,
});
export const headerTextColorInactive = themed({
light: colors.N800,
dark: colors.N0,
});
export const appLabelBgColor = themed({
light: colors.N20,
dark: colors.N20,
});
export const appLabelTextColor = themed({
light: colors.N500,
dark: colors.N500,
});
export const labelTextColor = themed({
light: colors.N800,
dark: colors.DN900,
});
export const labelIconColor = themed({
light: colors.N60,
dark: colors.DN100,
});
export const errorIconColor = themed({
light: colors.N90,
dark: colors.DN90,
});
export const errorTitleColor = themed({
light: colors.N800,
dark: colors.DN800,
});
export const errorTextColor = themed({
light: colors.N90,
dark: colors.DN90,
});
| 21,586
|
https://github.com/Ariken6/localdairy/blob/master/public/mysite/code/model/Event.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,016
|
localdairy
|
Ariken6
|
PHP
|
Code
| 125
| 415
|
<?php
/**
* Created by PhpStorm.
* User: haochen
* Date: 8/6/2016
* Time: 4:45 PM
*/
//TODO think about if this class is needed or everything should go on group
class Event extends DataObject
{
private static $db = array(
'Title' => 'Varchar(200)',
'Reoccurring' => 'Boolean',
'Date' => 'SS_DateTime',
'DayOfTheWeek' => 'enum("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday", "Wednesday")'
);
private static $has_many = array(
'Groups' => 'Group'
);
public function getCMSFields()
{
$fields = parent::getCMSFields();
$fields->addFieldsToTab('Root.Main', array(
TextField::create('Title', 'Event Name'),
CheckboxField::create('Reoccurring', 'Reoccurring'),
$dateTimeField = DatetimeField::create('Date', 'Date'),
DropdownField::create('DayOfTheWeek', 'Day of the week')->setDescription('Only applies if Reoccurring is true'),
GridField::create('Groups', 'Groups', Group::get(), GridFieldConfig_RelationEditor::create()->addComponent(new GridFieldSortableRows('Sort')))
));
$dateTimeField->getDateField()->setConfig('showcalendar', true);
return $fields;
}
}
class EventModelAdmin extends ModelAdmin
{
private static $managed_models = array('Event');
private static $url_segment = 'event-admin';
private static $menu_title = 'Events';
}
| 9,899
|
https://github.com/OmArMouNir/interactive-spaces/blob/master/interactivespaces-master/src/main/java/interactivespaces/master/server/services/ControllerRepository.java
|
Github Open Source
|
Open Source
|
ECL-2.0, Apache-2.0
| 2,016
|
interactive-spaces
|
OmArMouNir
|
Java
|
Code
| 459
| 859
|
/*
* Copyright (C) 2012 Google Inc.
*
* 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 interactivespaces.master.server.services;
import interactivespaces.domain.basic.SpaceController;
import java.util.List;
/**
* A repository which stores information about controllers.
*
* @author Keith M. Hughes
*/
public interface ControllerRepository {
/**
* Create a new controller.
*
* <p>
* The controller will be assigned a UUID.
*
* @return The new controller instance. It will not be saved in the
* repository.
*/
SpaceController newSpaceController();
/**
* Create a new controller from a template.
*
* <p>
* The controller will be assigned a UUID.
*
* @param template
* the template controller whose values will be copied in.
*
* @return The new controller instance. It will not be saved in the
* repository.
*/
SpaceController newSpaceController(SpaceController template);
/**
* Create a new controller from a template object with a specified UUID.
*
* @param uuid
* the UUID to give to the controller
* @param template
* the template controller whose values will be copied in.
*
* @return The new controller instance. It will not be saved in the
* repository.
*/
SpaceController newSpaceController(String uuid, SpaceController template);
/**
* Get all controllers in the repository.
*
* @return Get all controllers in the repository.
*/
List<SpaceController> getAllSpaceControllers();
/**
* Get a controller by its ID.
*
* @param id
* The id of the desired controller.
*
* @return The controller with the given id or {@code null} if no such
* controller.
*/
SpaceController getSpaceControllerById(String id);
/**
* Get a controller by its UUID.
*
* @param uuid
* The UUID of the desired controller.
*
* @return The controller with the given UUID or {@code null} if no such
* controller.
*/
SpaceController getSpaceControllerByUuid(String uuid);
/**
* Save a controller in the repository.
*
* <p>
* Is used both to save a new controller into the repository for the first
* time or to update edits to the controller.
*
* @param controller
* The controller to save.
*
* @return The persisted controller. use this one going forward.
*/
SpaceController saveSpaceController(SpaceController controller);
/**
* Delete a controller in the repository.
*
* @param controller
* The controller to delete.
*
* @return
*/
void deleteSpaceController(SpaceController controller);
}
| 4,687
|
https://github.com/marclayson/Algorithms-CSharp-Translation/blob/master/Programming =++ Algorithms C#/Chapter 6/6.3.7. Побуквено превеждане/Translat.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
Algorithms-CSharp-Translation
|
marclayson
|
C#
|
Code
| 441
| 1,512
|
using System;
class Translat
{
/* Максимален брой съответствия между букви */
const int MAXN = 40;
/* Максимална дължина на дума за превод */
const int MAXTL = 200;
/* Брой съответствия */
const uint n = 38;
/* Дума за превод */
static string str1 = "101001010";
struct transType {
public string st1;
public string st2;
};
static transType[] transf = new transType[MAXN];
static uint[] translation = new uint[MAXTL];
static uint pN, total = 0;
/* В примера се използва Морзовата азбука: 0 е точка, а 1-та е тире */
static void initLanguage()
{
transf[0].st1 = "А";
transf[0].st2 = "01";
transf[1].st1 = "Б";
transf[1].st2 = "1000";
transf[2].st1 = "В";
transf[2].st2 = "011";
transf[3].st1 = "Г";
transf[3].st2 = "110";
transf[4].st1 = "Д";
transf[4].st2 = "100";
transf[5].st1 = "Е";
transf[5].st2 = "0";
transf[6].st1 = "Ж";
transf[6].st2 = "0001";
transf[7].st1 = "З";
transf[7].st2 = "1100";
transf[8].st1 = "И";
transf[8].st2 = "00";
transf[9].st1 = "Й";
transf[9].st2 = "0111";
transf[10].st1 = "К";
transf[10].st2 = "101";
transf[11].st1 = "Л";
transf[11].st2 = "0100";
transf[12].st1 = "М";
transf[12].st2 = "11";
transf[13].st1 = "Н";
transf[13].st2 = "10";
transf[14].st1 = "О";
transf[14].st2 = "111";
transf[15].st1 = "П";
transf[15].st2 = "0110";
transf[16].st1 = "Р";
transf[16].st2 = "010";
transf[17].st1 = "С";
transf[17].st2 = "000";
transf[18].st1 = "Т";
transf[18].st2 = "1";
transf[19].st1 = "У";
transf[19].st2 = "001";
transf[20].st1 = "Ф";
transf[20].st2 = "0010";
transf[21].st1 = "Х";
transf[21].st2 = "0000";
transf[22].st1 = "Ц";
transf[22].st2 = "1010";
transf[23].st1 = "Ч";
transf[23].st2 = "1110";
transf[24].st1 = "Ш";
transf[24].st2 = "1111";
transf[25].st1 = "Щ";
transf[25].st2 = "1101";
transf[26].st1 = "Ю";
transf[26].st2 = "0011";
transf[27].st1 = "Я";
transf[27].st2 = "0101";
transf[28].st1 = "1";
transf[28].st2 = "01111";
transf[29].st1 = "2";
transf[29].st2 = "00111";
transf[30].st1 = "3";
transf[30].st2 = "00011";
transf[31].st1 = "4";
transf[31].st2 = "00001";
transf[32].st1 = "5";
transf[32].st2 = "00000";
transf[33].st1 = "6";
transf[33].st2 = "10000";
transf[34].st1 = "7";
transf[34].st2 = "11000";
transf[35].st1 = "8";
transf[35].st2 = "11100";
transf[36].st1 = "9";
transf[36].st2 = "11110";
transf[37].st1 = "0";
transf[37].st2 = "11111";
}
/* Отпечатва превод */
static void printTranslation()
{
uint i;
total++;
for (i = 0; i < pN; i++)
Console.Write("{0}", transf[translation[i]].st1);
Console.WriteLine();
}
/* Намира следваща буква */
static void nextLetter(int count)
{
uint i, k;
if (count == str1.Length)
{
printTranslation();
return;
}
for (k = 0; k < n; k++)
{
uint len = (uint)transf[k].st2.Length;
for (i = 0; i < len; i++)
if ((int)i>=transf[k].st2.Length || (int)(i+count)>=str1.Length ||
str1[(int)(i + count)] != transf[k].st2[(int)i])
break;
if (i == len)
{
translation[pN++] = k;
nextLetter(count + transf[k].st2.Length);
pN--;
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Списък от всички възможни преводи: ");
initLanguage();
pN = 0;
nextLetter(0);
Console.WriteLine("Общ брой различни преводи: {0} ", total);
}
}
| 22,350
|
https://github.com/sam-cms/fetch/blob/master/fetch/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
fetch
|
sam-cms
|
Python
|
Code
| 10
| 22
|
name = "fetch"
__all__ = ['fetch','info']
from fetch import *
| 6,845
|
https://github.com/twilson63/nifty-generators/blob/master/rails_generators/nifty_nested_scaffold/templates/actions/new.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
nifty-generators
|
twilson63
|
Ruby
|
Code
| 31
| 94
|
def new
@<%= singular_name %> = @<%= parent_singular_name %>.<%= plural_name %>.build
respond_to do |wants|
wants.html
<%- if options[:ajaxify] %>
wants.js { render :action => "dialog" }
<%- end %>
end
end
| 35,231
|
https://github.com/vitorbertti/event-registration/blob/master/resources/js/react/pages/Events/components/BatchesEdit.js
|
Github Open Source
|
Open Source
|
MIT
| null |
event-registration
|
vitorbertti
|
JavaScript
|
Code
| 338
| 1,324
|
import React, { useState, useEffect, useCallback } from 'react'
import api from '../../../services/api'
function ChildComponent(props) {
const batch = props.data;
const index = props.index;
const [name, setName] = useState('');
const [quantity, setQuantity] = useState('');
const [price, setPrice] = useState('');
useEffect(() => {
if(batch !== ''){
setName(batch.name);
setQuantity(batch.quantity);
setPrice(batch.price);
}else {
setName('');
setQuantity('');
setPrice('');
}
}, []);
useEffect(() => {
updateFieldChanged(index);
}, [name, quantity, price]);
function updateFieldChanged (index) {
let newBatch = [...props.batchesList];
newBatch[index].name = name;
newBatch[index].quantity = quantity;
newBatch[index].price = price;
props.setBatches(newBatch);
}
async function remove(e) {
e.preventDefault();
const response = await api.get(`/batch/${batch.id}`);
if(response.data.length){
await api.delete(`/batches/${batch.id}`);
}
props.listBatches();
}
return (
<div id='batches'>
<div className="row" key={batch.id}>
<div className="form-group col-md-5">
<label>Name</label>
<input type="text" required className="form-control" name="name" onChange={e => setName(e.target.value)} value={name} />
</div>
<div className="form-group col-md-3">
<label>Quantity</label>
<input type="text" required className="form-control" name="quantity" onChange={e => setQuantity(e.target.value)} value={quantity} />
</div>
<div className="form-group col-md-3">
<label>Price</label>
<input type="text" required className="form-control" name="price" onChange={e => setPrice(e.target.value)} value={price}/>
</div>
<div className="form-group col-md-1">
<label>Remove</label>
<button className="btn btn-sm btn-danger" data-toggle="tooltip" title="Delete" onClick={e => remove(e)}>
<svg className="bi bi-trash-fill" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M2.5 1a1 1 0 00-1 1v1a1 1 0 001 1H3v9a2 2 0 002 2h6a2 2 0 002-2V4h.5a1 1 0 001-1V2a1 1 0 00-1-1H10a1 1 0 00-1-1H7a1 1 0 00-1 1H2.5zm3 4a.5.5 0 01.5.5v7a.5.5 0 01-1 0v-7a.5.5 0 01.5-.5zM8 5a.5.5 0 01.5.5v7a.5.5 0 01-1 0v-7A.5.5 0 018 5zm3 .5a.5.5 0 00-1 0v7a.5.5 0 001 0v-7z" clipRule="evenodd"/>
</svg>
</button>
</div>
</div>
</div>
)
}
export default function BatchesEdit(props) {
const eventId = props.data;
const [batches, setBatches] = useState([]);
useEffect(() => {
listBatches();
}, []);
useEffect(() => {
props.setBatches(batches);
}, [batches]);
async function listBatches(){
const response = await api.get(`/batches/${eventId}`);
setBatches(response.data);
}
function addBatch(e) {
e.preventDefault();
let id = batches.length + 1;
let newBatch = {
id,
name: '',
quantity: '',
price: ''
}
setBatches([...batches, newBatch]);
}
return (
<div className="tab-pane fade" id="batches" role="tabpanel" aria-labelledby="batches-tab">
<fieldset className="form-group">
{batches.length ? batches.map((batch, index) => (
<ChildComponent key={batch.id} data={batch} setBatches={setBatches} batchesList={batches} index={index} listBatches={listBatches}/>
)) :
<div id='batches'></div>
}
</fieldset>
<button className="btn btn-outline-primary" onClick={e => addBatch(e)}>Add Batch</button>
</div>
)
}
| 26,694
|
https://github.com/dangdangdotcom/cymbal/blob/master/cymbal-portal/src/main/java/com/dangdang/cymbal/web/object/converter/ConfigConverter.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
cymbal
|
dangdangdotcom
|
Java
|
Code
| 47
| 175
|
package com.dangdang.cymbal.web.object.converter;
import com.dangdang.cymbal.domain.po.Config;
import com.dangdang.cymbal.web.object.dto.ConfigDTO;
import org.springframework.stereotype.Component;
/**
* Converter for redis config PO and DTO.
*
* @auther GeZhen
*/
@Component
public class ConfigConverter extends BaseConverter<Config, ConfigDTO> {
@Override
void poToDto(Config config, ConfigDTO configDTO) {
}
@Override
void dtoToPo(ConfigDTO configDTO, Config config) {
}
}
| 41,310
|
https://github.com/isabella232/helix-harmonicabsorber-reports/blob/master/report_00015_2021-02-09T16-11-33.973Z/max-potential-fid/comparison/histogram/2_vs_3.gnuplot
|
Github Open Source
|
Open Source
|
W3C, Apache-2.0
| 2,021
|
helix-harmonicabsorber-reports
|
isabella232
|
Gnuplot
|
Code
| 84
| 299
|
reset
$pagesCachedNoadtech <<EOF
273.6492529524727 68
0 8
820.9477588574181 4
547.2985059049454 19
1094.5970118098908 1
EOF
$pagesCachedNoadtechNomedia <<EOF
273.6492529524727 79
547.2985059049454 12
0 9
EOF
set key outside below
set boxwidth 273.6492529524727
set xrange [111:1086.0000000000002]
set yrange [0:100]
set trange [0:100]
set style fill transparent solid 0.5 noborder
set parametric
set terminal svg size 640, 500 enhanced background rgb 'white'
set output "report_00015_2021-02-09T16-11-33.973Z/max-potential-fid/comparison/histogram/2_vs_3.svg"
plot $pagesCachedNoadtech title "pages+cached+noadtech" with boxes, \
$pagesCachedNoadtechNomedia title "pages+cached+noadtech+nomedia" with boxes, \
130,t title "score p10=130", \
250,t title "score median=250"
reset
| 10,843
|
https://github.com/demigod19892012/jenkin_test/blob/master/sourcecode/api/bdsapi/app/Http/Controllers/Admin/Auth/AdminAuthController.php
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
jenkin_test
|
demigod19892012
|
PHP
|
Code
| 176
| 506
|
<?php
/**
* Created by PhpStorm.
* User: quocviet
* Date: 9/10/15
* Time: 10:47 PM
*/
namespace App\Http\Controllers\Admin\Auth;
use App\Http\Controllers\Base;
use ResponseHelper;
use App;
use App\Model;
use Config;
use App\Model\Table\UserTable;
use Illuminate\Http\Request;
use Auth;
class AdminAuthController extends Base\BaseController{
/*
|--------------------------------------------------------------------------
| Admin Auth Controller
|--------------------------------------------------------------------------
|
| This controller handle the request that require to get authentication from administrator user
|
*/
protected $tblUser = null;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->tblUser = new UserTable();
}
/**
* API to sign into the admin account
* @httpStatusCode_401: If authentication data is wrong, this exception will be fired
* @return mixed
*/
protected function signIn(Request $request){
$email = $request->input('email');
$password = $request->input('password');
$admin = $this->tblUser->authentication($email, $password);
return ResponseHelper::json(null, $admin->toAuthenticationArray(), trans('message.admin_sign_in_success'));
}
/**
* API to sign out from administrator account
* @httpStatusCode_401: If the access token is wrong, this exception will be fired
* @return mixed
*/
protected function signOut(Request $request){
$logoutResult = Auth::user()->logout();
if($logoutResult){
return ResponseHelper::json(null, array('result' => true), trans('message.admin_sign_out_success'));
}
else{
return ResponseHelper::json(null, array('result' => false), trans('message.admin_sign_out_failure'));
}
}
}
| 44,442
|
https://github.com/neelkamath/omni-chat-web/blob/master/src/components/registration-page/RegistrationPage.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
omni-chat-web
|
neelkamath
|
TypeScript
|
Code
| 59
| 178
|
import React, { ReactElement } from 'react';
import { Divider, Row } from 'antd';
import HomeLayout from '../HomeLayout';
import SignUpSection from './SignUpSection';
import ResendEmailAddressVerificationCodeSection from './ResendEmailAddressVerificationCodeSection';
import VerifyYourEmailAddressSection from './VerifyYourEmailAddressSection';
export default function RegistrationPage(): ReactElement {
return (
<HomeLayout>
<Row gutter={16} style={{ padding: 16 }}>
<SignUpSection />
<Divider />
<VerifyYourEmailAddressSection />
<Divider />
<ResendEmailAddressVerificationCodeSection />
</Row>
</HomeLayout>
);
}
| 33,488
|
https://github.com/Proteanindustries/gaphor/blob/master/gaphor/UML/interactions/executionspecification.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
gaphor
|
Proteanindustries
|
Python
|
Code
| 394
| 1,388
|
"""An ExecutionSpecification is defined by a white recrange overlaying the
lifeline.
,----------.
| lifeline |
`----------'
| --- Lifeline
,+. -- ExecutionOccurrenceSpecification
| | -- ExecutionSpecification
`+' -- ExecutionOccurrentSpecification
|
ExecutionOccurrenceSpecification.covered <--> Lifeline.coveredBy
ExecutionOccurrenceSpecification.execution <--> ExecutionSpecification.execution
TODO:ExecutionSpecification is abstract. Should use either
ActionExecutionSpecification or BehaviorExecutionSpecification.
What's the difference?
Stick with BehaviorExecutionSpecification, since it has a [0..1] relation to
behavior, whereas ActionExecutionSpecification has a [1] relation to action.
"""
import ast
from gaphas import Handle
from gaphas.connector import LinePort, Position
from gaphas.constraint import constraint
from gaphas.geometry import Rectangle, distance_rectangle_point
from gaphas.solver import WEAK
from gaphor import UML
from gaphor.core.modeling import Presentation
from gaphor.diagram.presentation import HandlePositionUpdate, postload_connect
from gaphor.diagram.shapes import Box, draw_border
from gaphor.diagram.support import represents
@represents(UML.ExecutionSpecification)
@represents(UML.BehaviorExecutionSpecification)
class ExecutionSpecificationItem(
Presentation[UML.ExecutionSpecification], HandlePositionUpdate
):
"""Representation of interaction execution specification."""
def __init__(self, diagram, id=None):
super().__init__(diagram, id=id)
self._connections = diagram.connections
self.bar_width = 12
ht, hb = Handle(), Handle()
ht.connectable = True
self._handles = [ht, hb]
self.watch_handle(ht)
self.watch_handle(hb)
self._connections.add_constraint(self, constraint(vertical=(ht.pos, hb.pos)))
r = self.bar_width / 2
nw = Position(-r, 0, strength=WEAK)
ne = Position(r, 0, strength=WEAK)
se = Position(r, 0, strength=WEAK)
sw = Position(-r, 0, strength=WEAK)
for c in (
constraint(horizontal=(nw, ht.pos)),
constraint(horizontal=(ne, ht.pos)),
constraint(horizontal=(sw, hb.pos)),
constraint(horizontal=(se, hb.pos)),
constraint(vertical=(nw, ht.pos), delta=r),
constraint(vertical=(ne, ht.pos), delta=-r),
constraint(vertical=(sw, hb.pos), delta=r),
constraint(vertical=(se, hb.pos), delta=-r),
):
self._connections.add_constraint(self, c)
self._ports = [LinePort(nw, sw), LinePort(ne, se)]
self.shape = Box(
style={"background-color": (1.0, 1.0, 1.0, 1.0)}, draw=draw_border
)
def handles(self):
return self._handles
def ports(self):
return self._ports
@property
def top(self):
return self._handles[0]
@property
def bottom(self):
return self._handles[1]
def dimensions(self):
d = self.bar_width
pt, pb = (h.pos for h in self._handles)
return Rectangle(pt.x - d / 2, pt.y, d, y1=pb.y)
def draw(self, context):
self.shape.draw(context, self.dimensions())
def point(self, x, y):
return distance_rectangle_point(self.dimensions(), (x, y))
def save(self, save_func):
def save_connection(name, handle):
c = self._connections.get_connection(handle)
if c:
save_func(name, c.connected)
points = [tuple(map(float, h.pos)) for h in self._handles]
save_func("matrix", tuple(self.matrix))
save_func("points", points)
save_connection("head-connection", self._handles[0])
super().save(save_func)
def load(self, name, value):
if name == "points":
points = ast.literal_eval(value)
for h, p in zip(self._handles, points):
h.pos = p
elif name == "head-connection":
self._load_head_connection = value
else:
super().load(name, value)
if name == "points":
# Fix ports, so connections are made properly
pl, pr = self._ports
ht, hb = self._handles
r = self.bar_width / 2
pl.start.y = pr.start.y = ht.pos.y
pl.end.y = pr.end.y = hb.pos.y
pl.start.x = pl.end.x = ht.pos.x - r
pr.start.x = pr.end.x = ht.pos.x + r
def postload(self):
if hasattr(self, "_load_head_connection"):
postload_connect(self, self._handles[0], self._load_head_connection)
del self._load_head_connection
super().postload()
| 25,502
|
https://github.com/TheRake66/Cody-PHP/blob/master/bases/base_projet/.kernel/js/communication/http.js
|
Github Open Source
|
Open Source
|
MIT
| null |
Cody-PHP
|
TheRake66
|
JavaScript
|
Code
| 264
| 618
|
/**
* Librairie de communication via le protocole HTTP(S).
*
* @author Thibault Bustos (TheRake66)
* @version 1.0
* @category Framework source
* @license MIT License
* @copyright © 2022 - Thibault BUSTOS (TheRake66)
*/
export default class Http {
/**
* @type {string} Les méthodes d'envoi.
*/
static METHOD_GET = 'GET';
static METHOD_POST = 'POST';
static METHOD_PUT = 'PUT';
static METHOD_DELETE = 'DELETE';
static METHOD_PATCH = 'PATCH';
/**
* Exécute une requête AJAX.
*
* @param {string} url URL à requêter.
* @param {function} success Fonction anonyme appeler lors d'une réponse correcte.
* @param {function} failed Fonction anonyme appeler lors d'une réponse incorrecte.
* @param {function} expired Fonction anonyme appeler lorsque la requête expire.
* @param {string} method Type de requête.
* @param {string} params Corps de la requête.
* @param {Number} timeout Temps d'attente avant expiration de la requête.
* @param {boolean} asynchronous Si la requête s'exécute en asynchrone.
* @returns {void}
*/
static send(url, success = null, failed = null, expired = null, method = Http.METHOD_GET, params = {}, timeout = 0, asynchronous = true) {
let xhr = new XMLHttpRequest();
if (method === Http.METHOD_GET &&
params !== null &&
Object.keys(params).length !== 0) {
url += '?' + (new URLSearchParams(params)).toString();
}
xhr.open(method, url, asynchronous);
if (timeout) xhr.timeout = timeout;
if (expired) xhr.ontimeout = expired;
if (failed) xhr.onerror = failed;
if (success) {
xhr.onload = () => {
success(xhr.response);
}
}
if (method !== Http.METHOD_GET) {
let frm = new FormData();
for (let name in params) {
let value = params[name];
frm.append(name, value);
}
xhr.send(frm);
} else {
xhr.send();
}
}
}
| 20,862
|
https://github.com/Ascend/modelzoo/blob/master/built-in/PyTorch/Official/cv/image_object_detection/Faster_Mask_RCNN_for_PyTorch_Dynamic_Shape/detectron2/modeling/proposal_generator/proposal_utils.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
modelzoo
|
Ascend
|
Python
|
Code
| 716
| 2,157
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
import logging
import math
from typing import List, Tuple
import torch
from detectron2.layers import batched_nms, cat
from detectron2.structures import Boxes, Instances
logger = logging.getLogger(__name__)
def find_top_rpn_proposals(
proposals: List[torch.Tensor],
pred_objectness_logits: List[torch.Tensor],
image_sizes: List[Tuple[int, int]],
nms_thresh: float,
pre_nms_topk: int,
post_nms_topk: int,
min_box_size: float,
training: bool,
):
"""
For each feature map, select the `pre_nms_topk` highest scoring proposals,
apply NMS, clip proposals, and remove small boxes. Return the `post_nms_topk`
highest scoring proposals among all the feature maps for each image.
Args:
proposals (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A, 4).
All proposal predictions on the feature maps.
pred_objectness_logits (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A).
image_sizes (list[tuple]): sizes (h, w) for each image
nms_thresh (float): IoU threshold to use for NMS
pre_nms_topk (int): number of top k scoring proposals to keep before applying NMS.
When RPN is run on multiple feature maps (as in FPN) this number is per
feature map.
post_nms_topk (int): number of top k scoring proposals to keep after applying NMS.
When RPN is run on multiple feature maps (as in FPN) this number is total,
over all feature maps.
min_box_size (float): minimum proposal box side length in pixels (absolute units
wrt input images).
training (bool): True if proposals are to be used in training, otherwise False.
This arg exists only to support a legacy bug; look for the "NB: Legacy bug ..."
comment.
Returns:
list[Instances]: list of N Instances. The i-th Instances
stores post_nms_topk object proposals for image i, sorted by their
objectness score in descending order.
"""
num_images = len(image_sizes)
device = proposals[0].device
topk_scores_list = [] # #lvl Tensor, each of shape N x topk
topk_proposals_list = []
level_ids_list = [] # #lvl Tensor, each of shape (topk,)
batch_idx = torch.arange(num_images, device=device)
for level_id, (proposals_i, logits_i) in enumerate(zip(proposals, pred_objectness_logits)):
Hi_Wi_A = logits_i.shape[1]
num_proposals_i = min(pre_nms_topk, Hi_Wi_A)
topk_scores_i, topk_idx = torch.topk(logits_i, num_proposals_i, dim=1)
topk_proposals_i = proposals_i[batch_idx[:, None].long(),
topk_idx.long()] # N x topk x 4
topk_proposals_list.append(topk_proposals_i)
topk_scores_list.append(topk_scores_i)
level_ids_list.append(
torch.full((num_proposals_i,), level_id,
dtype=torch.int32, device=device))
results: List[Instances] = []
for n, image_size in enumerate(image_sizes):
level_keep_list = []
level_boxes_list = []
level_scores_per_img = []
for level in range(len(topk_proposals_list)):
topk_proposals = topk_proposals_list[level]
topk_scores = topk_scores_list[level]
level_ids = level_ids_list[level]
boxes = Boxes(topk_proposals[n])
scores_per_img = topk_scores[n]
lvl = level_ids
if not training:
valid_mask = torch.isfinite(boxes.tensor).all(dim=1) & torch.isfinite(scores_per_img.float())
if not valid_mask.all():
boxes = boxes[valid_mask]
scores_per_img = scores_per_img[valid_mask]
lvl = lvl[valid_mask]
if scores_per_img.dtype != torch.float32:
scores_per_img = scores_per_img.to(torch.float32)
keep_mask = batched_nms(boxes.tensor,
scores_per_img, lvl, nms_thresh)
level_keep_list.append(keep_mask)
level_boxes_list.append(boxes)
level_scores_per_img.append(scores_per_img)
keep_mask = cat(level_keep_list, dim=0)
boxes = Boxes.cat(level_boxes_list)
scores_per_img = cat(level_scores_per_img, dim=0)
scores_per_img = scores_per_img * keep_mask.float()
topk_scores_i, indice = torch.topk(scores_per_img, post_nms_topk)
res = Instances(image_size)
res.proposal_boxes = boxes[indice.long()]
res.objectness_logits = topk_scores_i
results.append(res)
return results
def add_ground_truth_to_proposals(gt_boxes, proposals):
"""
Call `add_ground_truth_to_proposals_single_image` for all images.
Args:
gt_boxes(list[Boxes]): list of N elements. Element i is a Boxes
representing the gound-truth for image i.
proposals (list[Instances]): list of N elements. Element i is a Instances
representing the proposals for image i.
Returns:
list[Instances]: list of N Instances. Each is the proposals for the image,
with field "proposal_boxes" and "objectness_logits".
"""
assert gt_boxes is not None
assert len(proposals) == len(gt_boxes)
if len(proposals) == 0:
return proposals
return [
add_ground_truth_to_proposals_single_image(gt_boxes_i, proposals_i)
for gt_boxes_i, proposals_i in zip(gt_boxes, proposals)
]
def add_ground_truth_to_proposals_single_image(gt_boxes, proposals):
"""
Augment `proposals` with ground-truth boxes from `gt_boxes`.
Args:
Same as `add_ground_truth_to_proposals`, but with gt_boxes and proposals
per image.
Returns:
Same as `add_ground_truth_to_proposals`, but for only one image.
"""
device = proposals.objectness_logits.device
gt_logit_value = math.log((1.0 - 1e-10) / (1 - (1.0 - 1e-10)))
gt_logits = gt_logit_value * torch.ones(len(gt_boxes), device=device)
# Concatenating gt_boxes with proposals requires them to have the same fields
gt_proposal = Instances(proposals.image_size)
gt_proposal.proposal_boxes = gt_boxes
gt_proposal.objectness_logits = gt_logits
new_proposals = Instances.cat([proposals, gt_proposal])
return new_proposals
| 50,071
|
https://github.com/JetBrains/kotlin/blob/master/compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/typeParameters.kt
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, Apache-2.0
| 2,023
|
kotlin
|
JetBrains
|
Kotlin
|
Code
| 70
| 164
|
interface List<out T : Any> {
operator fun get(index: Int): T
infix fun concat(other: List<T>): List<T>
}
typealias StringList = List<out String>
typealias AnyList = List<*>
abstract class AbstractList<out T : Any> : List<T>
class SomeList : AbstractList<Int>() {
override fun get(index: Int): Int = 42
override fun concat(other: List<Int>): List<Int> = this
}
fun <From, To> copyNotNull(from: List<From>, to: List<To>) where From : To, To : Any {
}
| 29,062
|
https://github.com/RanaV25/AssessGo/blob/master/src/main/java/com/assessgo/frontend/util/css/Position.java
|
Github Open Source
|
Open Source
|
Unlicense
| null |
AssessGo
|
RanaV25
|
Java
|
Code
| 27
| 90
|
package com.assessgo.frontend.util.css;
public enum Position {
ABSOLUTE("absolute"), FIXED("fixed"), RELATIVE("relative");
private String value;
Position(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
| 10,248
|
https://github.com/robindirksen1/freek.dev/blob/master/app/Http/ViewComposers/LazyViewComposer.php
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
freek.dev
|
robindirksen1
|
PHP
|
Code
| 54
| 205
|
<?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
class LazyViewComposer
{
public function compose(View $view)
{
$view->with('usesInternetExplorer', $this->usesInternetExplorer());
}
private function usesInternetExplorer(): bool
{
if (app()->runningInConsole()) {
return false;
}
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (preg_match('~MSIE|Internet Explorer~i', $userAgent)) {
return true;
}
if (strpos($userAgent, 'Trident/7.0; rv:11.0') !== false) {
return true;
}
return false;
}
}
| 10,384
|
https://github.com/menucha-de/Shared.REST/blob/master/src/main/java/havis/net/rest/shared/NetService.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Shared.REST
|
menucha-de
|
Java
|
Code
| 130
| 544
|
package havis.net.rest.shared;
import havis.net.rest.shared.data.Uri;
import java.net.URI;
import java.net.URISyntaxException;
import javax.annotation.security.PermitAll;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("net")
public class NetService extends Resource {
@PUT
@Path("uri/complex")
@PermitAll
@Consumes({ MediaType.TEXT_PLAIN })
@Produces({ MediaType.APPLICATION_JSON })
public Uri parseUri(String uri) throws URISyntaxException {
URI javaURI = new URI(uri);
Uri gwtUri = new Uri(javaURI.getScheme(), javaURI.getSchemeSpecificPart(), javaURI.getAuthority(), javaURI.getUserInfo(), javaURI.getHost(),
javaURI.getPort(), javaURI.getPath(), javaURI.getQuery(), javaURI.getRawQuery(), javaURI.getFragment());
return gwtUri;
}
@PUT
@Path("uri/plain")
@PermitAll
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.TEXT_PLAIN })
public String printUri(Uri uri) throws URISyntaxException {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()).toString();
}
@GET
@Path("hostname")
@PermitAll
@Produces({ MediaType.TEXT_PLAIN })
public String getHostname() {
String hostname = System.getenv("HOSTNAME");
if (hostname != null) {
int index = hostname.indexOf('-');
return index > 0 ? hostname.substring(0, index) : hostname;
}
return "";
}
}
| 19,576
|
https://github.com/Cubix92/statistics-module/blob/master/module/Statistics/test/Application/Command/StatisticsCommandTest.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
statistics-module
|
Cubix92
|
PHP
|
Code
| 202
| 1,133
|
<?php
declare(strict_types=1);
namespace StatisticsTest\Application\Command;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Statistics\Application\Command\BannerNotFoundException;
use Statistics\Application\Command\CreateStatisticsCommand;
use Statistics\Application\Command\CreateStatisticsHandler;
use Statistics\Domain\Exception\StatisticsDuplicateException;
use Statistics\Domain\Model\Banner;
use Statistics\Domain\Model\Statistics;
use Statistics\Domain\Repository\BannerRepositoryInterface;
use Statistics\Domain\Repository\StatisticsRepositoryInterface;
class StatisticsCommandTest extends TestCase
{
const BANNER_ID = 101;
const CLICKS = 500;
const UNIQUE_CLICKS = 300;
const IMPRESSIONS = 2000;
const UNIQUE_IMPRESSIONS = 1000;
/** @var BannerRepositoryInterface $bannerRepository */
private $bannerRepository;
/** @var StatisticsRepositoryInterface $statisticsRepository */
private $statisticsRepository;
protected function setUp()
{
parent::setUp();
$this->bannerRepository = $this->prophesize(BannerRepositoryInterface::class);
$this->statisticsRepository = $this->prophesize(StatisticsRepositoryInterface::class);
}
public function testCreateStatisticsCommandExecutesProperly()
{
/** @var Banner $banner */
$banner = $this->prophesize(Banner::class)->reveal();
$this->bannerRepository->findOneByOrigin(Argument::type('integer'))
->willReturn($banner)
->shouldBeCalled();
$this->statisticsRepository->findOneByBannerOriginAndDate(Argument::type('integer'), Argument::type(\DateTime::class))
->willReturn(null)
->shouldBeCalled();
$this->statisticsRepository->save(Argument::type(Statistics::class))
->shouldBeCalled();
$createStatisticsCommand = new CreateStatisticsCommand(
new \DateTime(),
self::BANNER_ID,
self::CLICKS,
self::UNIQUE_CLICKS,
self::IMPRESSIONS,
self::UNIQUE_IMPRESSIONS
);
$createStatisticsHandler = new CreateStatisticsHandler(
$this->statisticsRepository->reveal(),
$this->bannerRepository->reveal()
);
$createStatisticsHandler->handle($createStatisticsCommand);
}
public function testExceptionIsThrownWhenCreateStatisticsWithNonExistedBanner()
{
$now = new \DateTime();
/** @var Statistics $statistics */
$statistics = $this->prophesize(Statistics::class)->reveal();
$this->statisticsRepository->findOneByBannerOriginAndDate(Argument::type('integer'), Argument::type(\DateTime::class))
->willReturn($statistics)
->shouldBeCalled();
$this->expectException(StatisticsDuplicateException::class);
$this->expectExceptionMessage("On {$now->format('Y-m-d')} statistics were added and cannot be overwritten.");
$createStatisticsCommand = new CreateStatisticsCommand(
new \DateTime(),
self::BANNER_ID,
self::CLICKS,
self::UNIQUE_CLICKS,
self::IMPRESSIONS,
self::UNIQUE_IMPRESSIONS
);
$createStatisticsHandler = new CreateStatisticsHandler(
$this->statisticsRepository->reveal(),
$this->bannerRepository->reveal()
);
$createStatisticsHandler->handle($createStatisticsCommand);
}
public function testExceptionIsThrownWhenCreateStatisticsWithDuplicateDate()
{
$this->bannerRepository->findOneByOrigin(Argument::type('integer'))
->willReturn(null)
->shouldBeCalled();
$this->statisticsRepository->findOneByBannerOriginAndDate(Argument::type('integer'), Argument::type(\DateTime::class))
->willReturn(null)
->shouldBeCalled();
$this->expectException(BannerNotFoundException::class);
$createStatisticsCommand = new CreateStatisticsCommand(
new \DateTime(),
self::BANNER_ID,
self::CLICKS,
self::UNIQUE_CLICKS,
self::IMPRESSIONS,
self::UNIQUE_IMPRESSIONS
);
$createStatisticsHandler = new CreateStatisticsHandler(
$this->statisticsRepository->reveal(),
$this->bannerRepository->reveal()
);
$createStatisticsHandler->handle($createStatisticsCommand);
}
}
| 7,729
|
https://github.com/tdurieux/smartbugs-wild/blob/master/contracts/0xe0b8fce1183e31c995b40460e6cb6712fa929f59.sol
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
smartbugs-wild
|
tdurieux
|
Solidity
|
Code
| 68
| 151
|
contract AmIOnTheFork {
bool public forked = false;
address constant darkDAO = 0x304a554a310c7e546dfe434669c62820b7d83490;
// Check the fork condition during creation of the contract.
// This function should be called between block 1920000 and 1930000.
// After that the status will be locked in.
function update() {
if (block.number >= 1920000 && block.number <= 1930000) {
forked = darkDAO.balance < 3600000 ether;
}
}
function() {
throw;
}
}
| 40,364
|
https://github.com/AndiAkbar09/penggajian/blob/master/routes/web.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
penggajian
|
AndiAkbar09
|
PHP
|
Code
| 111
| 1,168
|
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::group(['prefix'=>'penggajian'],function(){
//Home
Route::get('home', 'Penggajian\HomeController@index')->name('penggajians.home');
//Data Pegawai
Route::get('data-pegawai', 'Penggajian\EmployeeController@index')->name('penggajians.pegawai');
Route::get('tambah/data-pegawai', 'Penggajian\EmployeeController@create')->name('penggajians.pegawai.buat');
Route::post('simpan/data-pegawai', 'Penggajian\EmployeeController@store')->name('penggajians.pegawai.simpan');
Route::delete('hapus/data-pegawai{employee}', 'Penggajian\EmployeeController@destroy')->name('penggajians.pegawai.hapus');
Route::get('lihat/data-pegawai{employee}', 'Penggajian\EmployeeController@show')->name('penggajians.pegawai.lihat');
Route::patch('update/data-pegawai{employee}', 'Penggajian\EmployeeController@update')->name('penggajians.pegawai.update');
Route::get('edit/data-pegawai{employee}', 'Penggajian\EmployeeController@edit')->name('penggajians.pegawai.edit');
//Data Hadir
Route::get('absensi', 'Penggajian\TypeController@index')->name('absensi');
Route::get('tambah/absensi', 'Penggajian\TypeController@create')->name('tambah.absensi');
Route::post('simpan/absensi', 'Penggajian\TypeController@store')->name('simpan.absensi');
Route::delete('hapus/absensi{type}', 'Penggajian\TypeController@destroy')->name('hapus.absensi');
Route::get('edit/absensi{type}', 'Penggajian\TypeController@edit')->name('edit.absensi');
Route::patch('update/absensi{type}', 'Penggajian\TypeController@update')->name('update.absensi');
//Price
Route::get('price','Penggajian\PriceController@index')->name('price');
Route::get('tambah/price','Penggajian\PriceController@create')->name('tambah.price');
Route::post('simpan/price','Penggajian\PriceController@store')->name('simpan.price');
Route::get('edit/price{price}','Penggajian\PriceController@edit')->name('edit.price');
Route::delete('hapus/price{price}','Penggajian\PriceController@destroy')->name('hapus.price');
Route::patch('update/price{price}','Penggajian\PriceController@update')->name('update.price');
Route::get('lihat/price{price}','Penggajian\PriceController@show')->name('lihat.price');
//Payment
Route::get('payment','Penggajian\PaymentController@index')->name('payment');
Route::get('tambah/payment','Penggajian\PaymentController@create')->name('tambah.payment');
Route::post('simpan/payment','Penggajian\PaymentController@store')->name('simpan.payment');
Route::get('edit/payment{payment}','Penggajian\PaymentController@edit')->name('edit.payment');
Route::patch('update/payment{payment}','Penggajian\PaymentController@update')->name('update.payment');
Route::get('lihat/payment{payment}','Penggajian\PaymentController@show')->name('lihat.payment');
Route::delete('hapus/payment{payment}','Penggajian\PaymentController@destroy')->name('hapus.payment');
// SMS
Route::get('create/sms', 'SmsController@create')->name('create.sms');
Route::post('send/sms', 'SmsController@send')->name('send.sms');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
| 18,105
|
https://github.com/william-keller/hacker-rank/blob/master/algorithms/warmup/diagonal-difference/Solution.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
hacker-rank
|
william-keller
|
Java
|
Code
| 81
| 259
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[][] = new int[n][n];
for(int a_i=0; a_i < n; a_i++){
for(int a_j=0; a_j < n; a_j++){
a[a_i][a_j] = in.nextInt();
}
}
int primaryDiagonalSum = 0;
int secondaryDiagonalSum = 0;
for (int i = 0; i < n; i++) {
primaryDiagonalSum += a[i][i];
secondaryDiagonalSum += a[i][n-i-1];
}
System.out.println(Math.abs(primaryDiagonalSum - secondaryDiagonalSum));
}
}
| 27,907
|
https://github.com/sanjeevan/nanoinvoice/blob/master/nano/static/src/sass/vendor/_facebox.scss
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
nanoinvoice
|
sanjeevan
|
SCSS
|
Code
| 96
| 359
|
#facebox {
position: absolute;
top: 0;
left: 0;
z-index: 100;
text-align: left;
}
#facebox .popup{
position:relative;
}
#facebox .content-wrapper {
@include box-sizing(border-box);
width: 100%;
display:table;
}
#facebox .close{
position:absolute;
top:5px;
right:5px;
padding:2px;
}
#facebox .close img{
opacity:0.3;
}
#facebox .close:hover img{
opacity:1.0;
}
#facebox .loading {
text-align: center;
}
#facebox .image {
text-align: center;
}
#facebox_overlay {
position: fixed;
top: 0px;
left: 0px;
height:100%;
width:100%;
}
.facebox_hide {
z-index:-100;
}
.facebox_overlayBG {
z-index: 99;
@include background-image( radial-gradient(rgba(0, 0, 0, 0.3) 1%, rgba(0, 0, 0, 0.624) 100%) );
height: 100%;
overflow: hidden;
pointer-events: none;
position: absolute;
}
| 36,721
|
https://github.com/vvmnnnkv/PyGrid/blob/master/apps/node/src/deploy.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
PyGrid
|
vvmnnnkv
|
Python
|
Code
| 19
| 64
|
import os
import sys
# Add dependencies in EFS to python-path
sys.path.append(os.environ.get("MOUNT_PATH"))
from app import create_lambda_app
app = create_lambda_app(node_id="bob")
| 44,336
|
https://github.com/salar-fs/deriv-com/blob/master/src/pages/trader-tools/_style.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
deriv-com
|
salar-fs
|
JavaScript
|
Code
| 902
| 3,085
|
import styled, { css } from 'styled-components'
import { Form } from 'formik'
import { Flex, SectionContainer } from 'components/containers'
import { Header, Text, Dropdown } from 'components/elements'
import { Button, LinkButton } from 'components/form'
import device from 'themes/device'
export const StyledText = styled(Text)`
@media ${device.tabletL} {
font-size: 16px;
}
`
export const StyledSection = styled(SectionContainer)`
position: relative;
padding: 3rem 0;
`
export const SectionHeader = styled(Header)`
@media ${device.tabletL} {
font-size: 32px;
}
`
export const SectionSubtitle = styled(Text)`
width: 79.2rem;
margin: auto;
margin-bottom: 4rem;
font-size: 16px;
@media ${device.tablet} {
width: unset;
padding: 0 16px;
}
`
export const SwapTabSelector = styled(Flex)`
padding: 2.4rem 4rem;
width: 35rem;
height: 8.4rem;
border-radius: 4px;
border: solid 1px rgba(51, 51, 51, 0.1);
justify-content: center;
flex-direction: column;
cursor: pointer;
${(props) =>
props.active
? css`
box-shadow: 0 16px 20px 0 rgba(0, 0, 0, 0.05), 0 0 20px 0 rgba(0, 0, 0, 0.05);
border: unset;
${Text} {
font-weight: bold;
}
`
: css`
box-shadow: unset;
${Text} {
font-weight: unset;
}
`}
@media ${device.mobileL} {
width: 164px;
padding: 12px 24px;
}
`
export const ContentContainer = styled(Flex)`
@media ${device.laptopM} {
flex-direction: column;
}
`
export const FormWrapper = styled(Flex)`
margin-right: 4.8rem;
max-height: 705px;
width: unset;
@media ${device.laptopM} {
padding: 0 16px;
margin-bottom: 6rem;
margin-right: 0;
}
`
export const SwapFormWrapper = styled(FormWrapper)`
max-height: 580px;
margin-top: 40px;
@media ${device.tabletL} {
margin-top: 0;
}
`
export const CalculatorForm = styled(Form)`
background-color: #ffffff;
border-radius: 10px;
box-sizing: border-box;
box-shadow: 0 16px 20px 0 rgba(0, 0, 0, 0.05), 0 0 20px 0 rgba(0, 0, 0, 0.05);
width: 48.6rem;
@media ${device.mobileL} {
width: 328px;
margin-bottom: 20px;
}
`
export const CalculatorHeader = styled.div`
border-radius: 8px 8px 0 0;
padding: 2.4rem;
background-color: var(--color-blue-4);
`
export const CalculatorLabel = styled.label`
font-size: var(--text-size-xs);
font-weight: 300;
display: block;
margin-bottom: 1.4rem;
@media ${device.mobileL} {
font-size: 14px;
}
`
export const CalculatorOutputContainer = styled(Flex)`
position: relative;
border-radius: 5px;
box-sizing: border-box;
height: 7.5rem;
border: 1.5px solid var(--color-blue-5);
background-color: white;
`
export const CalculatorOutputField = styled(Flex)`
width: 80%;
white-space: nowrap;
resize: none;
background-color: white;
justify-content: flex-start;
height: 95%;
border: 0;
padding: 2.2rem;
font-size: 2.4rem;
font-weight: 500;
color: var(--color-blue-5);
overflow-x: auto;
overflow-y: hidden;
-webkit-text-fill-color: var(--color-blue-5);
opacity: 1;
-webkit-opacity: 1;
margin: 1px;
@media ${device.tabletL} {
font-size: 18px;
}
@media ${device.mobileL} {
padding-top: 2.4rem;
font-size: 16px;
}
&::-webkit-scrollbar {
width: 0;
background: transparent; /* Chrome/Safari/Webkit */
}
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE 10+ */
`
export const CalculatorOutputSymbol = styled.label`
margin: 1px;
pointer-events: none;
color: var(--color-blue-5);
font-weight: bold;
font-size: 2.4rem;
padding: 2.2rem;
@media ${device.tabletL} {
font-size: 18px;
}
@media ${device.mobileL} {
font-size: 16px;
padding-top: 2.4rem;
}
`
export const CalculatorBody = styled.div`
padding: 2.4rem;
/* stylelint-disable property-no-vendor-prefix */
ul::-webkit-scrollbar {
width: 12px;
}
ul::-webkit-scrollbar-thumb {
border: 4px solid rgba(0, 0, 0, 0);
background-clip: padding-box;
-webkit-border-radius: 7px;
border-radius: 7px;
background-color: var(--color-grey-32);
-webkit-box-shadow: inset -1px -1px 0 rgba(0, 0, 0, 0.05),
inset 1px 1px 0 rgba(0, 0, 0, 0.05);
box-shadow: inset -1px -1px 0 rgba(0, 0, 0, 0.05), inset 1px 1px 0 rgba(0, 0, 0, 0.05);
}
ul::-webkit-scrollbar-corner {
background-color: transparent;
}
`
export const CalculatorTabItem = styled.div`
height: 72px;
width: 21rem;
border-radius: 1rem;
padding: 2rem;
border: solid 1px rgba(51, 51, 51, 0.1);
display: flex;
justify-content: center;
flex-direction: column;
cursor: pointer;
${(props) =>
props.active
? css`
pointer-events: none;
border: 1.5px solid var(--color-blue-5);
${Text} {
font-weight: bold;
}
`
: css`
box-shadow: unset;
${Text} {
font-weight: unset;
}
`}
@media ${device.mobileL} {
width: 140px;
}
${StyledText} {
@media ${device.mobileL} {
font-size: 14px;
}
}
`
export const CalculatorDropdown = styled(Dropdown)`
margin-bottom: 3.6rem;
`
export const InputGroup = styled.div`
position: relative;
width: 100%;
margin: 2.4rem 0;
`
export const ActionSection = styled(Flex)`
margin-top: 3rem;
justify-content: center;
`
export const SwapActionSection = styled(Flex)`
padding: 0 2rem 2rem 2rem;
justify-content: center;
`
export const CalculateButton = styled(Button)`
width: 100%;
@media ${device.mobileL} {
font-size: 14px;
}
`
export const RightContent = styled.div`
display: block;
max-width: 69rem;
margin: 0;
@media ${device.laptopM} {
margin: auto;
}
`
export const RightContentHeader = styled(Header)`
line-height: 1.25;
@media ${device.mobileL} {
font-size: 24px;
}
`
export const TextWrapper = styled.div`
@media ${device.tabletM} {
padding: 0 16px;
}
`
export const ImageWrapper = styled.div`
padding-left: 16px;
max-width: 650px;
@media ${device.laptop} {
padding-left: 0;
}
`
export const FormulaText = styled.div`
background-color: #f9fafc;
padding: 1.6rem;
font-size: 14px;
line-height: 2;
`
export const StyledOl = styled.ol`
list-style: decimal;
font-weight: bold;
margin-left: 20px;
span {
font-weight: 300;
}
`
export const BottomContent = styled(Flex)`
max-width: 100%;
align-items: center;
margin-bottom: 7.2rem;
font-size: 1.6rem;
text-align: center;
padding: 0 16px;
`
export const BottomText = styled(StyledText)`
width: 120rem;
@media ${device.laptopL} {
width: auto;
}
@media ${device.tabletL} {
font-size: 16px;
}
`
// export const RightContentHeaderP = styled.div`
// font-size: 16px;
// font-weight: normal;
// font-stretch: normal;
// font-style: normal;
// line-height: 1.5;
// letter-spacing: normal;
// text-align: center;
// color: #333333;
// margin-bottom: 40px;
// @media ${device.mobileL} {
// margin-bottom: 16px;
// }
// `
export const LinkWrapper = styled(Flex)`
padding: 2rem 2rem 1rem;
width: 100%;
justify-content: center;
@media (max-width: 1420px) {
top: 480px;
}
@media ${device.laptop} {
top: 350px;
flex-direction: column-reverse;
}
@media ${device.tabletL} {
top: 236px;
}
@media ${device.tablet} {
position: unset;
top: unset;
justify-content: start;
margin-top: 12.8px;
padding: 0;
}
`
export const StyledLinkButton = styled(LinkButton)`
padding: 1.2rem 1.5rem;
font-size: 14px;
max-height: 4rem;
height: 100%;
margin-right: 0.8rem;
@media ${device.laptop} {
padding: 1.5rem 1.6rem;
height: 42px;
white-space: nowrap;
display: block;
max-height: 40px;
:nth-child(2) {
margin-bottom: 16px;
}
}
:active {
outline: none;
border: none;
}
:focus {
outline: 0;
}
`
| 39,690
|
https://github.com/makbash/ngmatkit-es6/blob/master/app/src/modules/signin/Module.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ngmatkit-es6
|
makbash
|
JavaScript
|
Code
| 229
| 678
|
// Load the custom app ES6 modules
'use strict';
import angular from 'angular';
// Define the AngularJS 'home' module
export default angular
.module("signin", ['ngMaterial'])
.component('signin', {
templateUrl: './src/modules/signin/signin.html',
controller: function ($scope, $rootScope, $sce, $location, AuthenticationService) {
console.log('signin controller');
const vm = this;
vm.signin = signin;
// reset signin status
AuthenticationService.Logout();
function signin() {
vm.loading = true;
AuthenticationService.Signin(vm.fields, function (res) {
vm.response = { type: null, text: null };
if (res === true) {
vm.response.type = 'success';
vm.response.text = $sce.trustAsHtml('Hesabınız başaryla doğrulandı. Anasayfa\'ya yönlendiriliyorsunuz.');
setTimeout(() => {
$scope.$apply(() => {
$location.path('/home');
})
vm.loading = false;
}, 3000);
} else {
vm.response.type = 'danger';
vm.loading = false;
vm.response.text = 'unknown error';
if (res.status === false) {
if (res.data.name == 'MongoError') {
let errText = res.data.name + ' : ' + res.data.errmsg;
vm.response.text = $sce.trustAsHtml(errText);
} else if (res.data.name == 'ValidationError') {
let errText = '';
vm.response.type = 'warning';
$rootScope.loop(res.data.errors, function (item, key) {
errText += item.name + ' : ' + item.message + '<br>';
});
vm.response.text = $sce.trustAsHtml(errText);
}
else {
$rootScope.loop(res.data, function (item, key) {
if (typeof (item) === 'string') {
let errText = key + ' : ' + item;
vm.response.text = $sce.trustAsHtml(errText);
} else {
let errText = '';
$rootScope.loop(item, function (citem, ckey) {
errText += ckey + ' : ' + citem + '<br>';
});
vm.response.text = $sce.trustAsHtml(errText);
}
});
}
}
}
});
}
}
});
| 35,754
|
https://github.com/imrafaelmerino/json-values/blob/master/src/main/java/jsonvalues/OpFilterObjKeys.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
json-values
|
imrafaelmerino
|
Java
|
Code
| 195
| 708
|
package jsonvalues;
import io.vavr.Tuple2;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
final class OpFilterObjKeys {
static JsObj filterAll(JsObj json,
final JsPath startingPath,
final BiPredicate<? super JsPath, ? super JsValue> predicate
) {
for (final Tuple2<String, JsValue> next : json) {
final JsPath headPath = startingPath.key(next._1);
if (predicate.negate()
.test(headPath,
next._2
)) {
json = json.delete(next._1);
}
else if (next._2.isObj())
json = json.set(next._1,
filterAll(next._2.toJsObj(),
headPath,
predicate
)
);
else if (next._2.isArray())
json = json.set(next._1,
OpFilterArrKeys.filterAll(next._2.toJsArray(),
headPath,
predicate
)
);
}
return json;
}
static JsObj filter(JsObj json,
final BiPredicate<? super String, ? super JsValue> predicate) {
for (final Tuple2<String, JsValue> next : json) {
if (predicate.negate()
.test(next._1,
next._2
)) {
json = json.delete(next._1);
}
}
return json;
}
static JsObj filterAll(JsObj json,
final Predicate<? super String> predicate) {
for (final Tuple2<String, JsValue> next : json) {
if (predicate.negate()
.test(next._1)) {
json = json.delete(next._1);
}
else if (next._2.isObj())
json = json.set(next._1,
filterAll(next._2.toJsObj(),
predicate
)
);
else if (next._2.isArray())
json = json.set(next._1,
OpFilterArrKeys.filterAll(next._2.toJsArray(),
predicate
)
);
}
return json;
}
static JsObj filter(JsObj json,
final Predicate<? super String> predicate) {
for (final Tuple2<String, JsValue> next : json) {
if (predicate.negate()
.test(next._1
)) {
json = json.delete(next._1);
}
}
return json;
}
}
| 30,115
|
https://github.com/henlo-birb/lovepotion/blob/master/platform/switch/source/modules/joystick.cpp
|
Github Open Source
|
Open Source
|
0BSD
| 2,021
|
lovepotion
|
henlo-birb
|
C++
|
Code
| 124
| 516
|
#include "modules/joystick/joystick.h"
#include "modules/timer/timer.h"
using namespace love;
static constexpr size_t MAX_GAMEPADS = 4;
Joystick::VibrationThread::VibrationThread(VibrationPool* pool) : pool(pool), finish(false)
{
this->threadName = "VibrationPool";
}
Joystick::VibrationThread::~VibrationThread()
{}
void Joystick::VibrationThread::ThreadFunction()
{
while (!this->finish)
{
this->pool->Update();
svcSleepThread(5000000);
}
}
void Joystick::VibrationThread::SetFinish()
{
this->finish = true;
}
Joystick::Joystick() : pool(nullptr), poolThread(nullptr)
{
this->pool = new VibrationPool();
this->poolThread = new VibrationThread(pool);
this->poolThread->Start();
}
Joystick::~Joystick()
{
this->poolThread->SetFinish();
this->poolThread->Wait();
delete this->poolThread;
delete this->pool;
}
size_t Joystick::GetActiveControllerCount()
{
size_t active = 0;
for (size_t index = 0; index < MAX_GAMEPADS; index++)
{
HidNpadIdType id = static_cast<HidNpadIdType>(HidNpadIdType_No1 + index);
uint32_t styleSet = hidGetNpadStyleSet(id);
/* check for handheld */
if (styleSet == 0)
styleSet = hidGetNpadStyleSet(HidNpadIdType_Handheld);
if (styleSet != 0)
active++;
}
return active;
}
bool Joystick::AddVibration(Gamepad* gamepad, size_t id)
{
return this->pool->AssignGamepad(gamepad, id);
}
| 11,740
|
https://github.com/ahanafi/travelly/blob/master/application/models/Product_model.php
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-unknown-license-reference
| 2,018
|
travelly
|
ahanafi
|
PHP
|
Code
| 151
| 550
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product_model extends CI_Model {
protected $table = "produk";
public function all($limit = NULL)
{
if ($limit != NULL) {
$sql = $this->db->limit($limit)->get($this->table);
} else {
$sql = $this->db->get($this->table);
}
return $sql->result();
}
public function insert($data)
{
$insert = $this->db->insert($this->table, $data);
return ($insert == TRUE) ? TRUE : FALSE;
}
public function findById($id)
{
$sql = $this->db->get_where($this->table, ['id' => $id]);
return $sql->row();
}
public function getBySlug($slug)
{
$this->db->where("slug", $slug);
$sql = $this->db->get($this->table);
return $sql->row();
}
public function update($id, $data)
{
$this->db->where('id', $id);
$update = $this->db->update($this->table, $data);
return ($update == TRUE) ? TRUE : FALSE;
}
public function delete($id)
{
$this->db->where('id', $id);
$delete = $this->db->delete($this->table);
return ($delete == TRUE) ? TRUE : FALSE;
}
public function search($keyword)
{
//$keyword = $this->db->escape($keyword);
$this->db->like('produk', $keyword)->or_like('konten', $keyword);
$sql = $this->db->get($this->table);
//$sq; = $this->db->last_query();
return $sql->result();
}
}
/* End of file Profile_model.php */
/* Location: ./application/models/Profile_model.php */
| 3,095
|
https://github.com/PeterQu007/pidhomes3/blob/master/partials-twig/components/pid-map.twig
|
Github Open Source
|
Open Source
|
MIT
| null |
pidhomes3
|
PeterQu007
|
Twig
|
Code
| 63
| 233
|
{# {{ dump(pid_map_locations) }} #}
{% block pid_map %}
{% if show_map %}
<img src="{{pid_map_image}}" style="display:none"></img>
<div id="listing-map" class="acf-map" style="text-align:left; padding: 0 2px">
{% for location in pid_map_locations %}
<div style="display:inline-block; padding: 0 2px" class="marker" data-lat="{{ location.map_location.lat }}" data-lng="{{location.map_location.lng}}">
<h5 style="display:inline-block; padding: 0 2px; margin: 0"><a href="{{ location.nav_link }}">{{ location.map_location_label }}</a></h5>
{{location.location_name}}
</div>
{% endfor %}
</div>
{% endif %}
{% endblock %}
| 18,452
|
https://github.com/ReactExpert918/Laravel-3geniusMarketing/blob/master/public/assets/templates/tmp2/front/sass/_layout/_footer.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Laravel-3geniusMarketing
|
ReactExpert918
|
SCSS
|
Code
| 243
| 814
|
/*Footer-Section Starts Here*/
.footer-top {
border-bottom: 1px solid #271c3e;
}
.footer-widget {
.widget-header {
position: relative;
.title {
margin-bottom: 27px;
text-transform: capitalize;
margin-top: 0;
@include breakpoint(sm) {
margin-top: -5px;
}
@include breakpoint(lg) {
margin-bottom: 47px;
}
}
&::after {
@extend %pa;
width: 45px;
height: 1px;
background: $theme-four;
bottom: -18px;
left: 0;
}
}
&.widget-about {
.logo {
margin-bottom: 50px;
}
.content {
opacity: .9;
p {
margin-bottom: 11px;
}
.addr {
margin-bottom: -13px;
>li {
@extend %flex;
margin-bottom: 5px;
.icon {
width: 40px;
font-size: 24px;
margin-top: 4px;
i {
color: $theme-four;
}
}
ul {
width: calc(100% - 40px);
li {
padding: 0;
}
}
}
}
}
}
&.widget-links {
ul {
margin-bottom: -13px;
li {
@extend %flex;
&::before {
content: "\f111";
font-family: "Font Awesome 5 Free";
font-weight: 600;
color: $theme-four;
left: 0;
font-size: 8px;
align-items: flex-start;
width: 18px;
}
a {
opacity: .9;
width: calc(100% - 18px);
}
&:hover {
a {
opacity: 1;
padding-left: 3px;
}
}
}
}
}
&.widget-post {
ul {
margin-bottom: -13px;
li {
margin-bottom: 5px;
.sub-title {
margin-top: 4px;
font-size: 16px;
font-weight: 400;
font-family: $body;
margin-bottom: 10px;
a {
color: $white-color;
text-transform: none;
}
}
a {
color: $theme-four;
text-transform: uppercase;
}
}
@include breakpoint(lg) {
li {
margin-bottom: 15px;
}
}
}
}
margin-bottom: 50px;
}
.mb-50-none {
margin-bottom: -50px;
}
.footer-bottom {
padding: 27px 0;
}
footer {
overflow: hidden;
position: relative;
}
.footer-bottom {
* {
position: relative;
z-index: 9;
}
}
| 21,190
|
https://github.com/iconara/aws-doc-sdk-examples/blob/master/javav2/usecases/creating_photo_analyzer_async/src/main/java/com/example/photo/AnalyzePhotos.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
aws-doc-sdk-examples
|
iconara
|
Java
|
Code
| 193
| 704
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.photo;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionAsyncClient;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.services.rekognition.model.*;
@Component
public class AnalyzePhotos {
public ArrayList DetectLabels(byte[] bytes, String key) {
Region region = Region.US_EAST_2;
RekognitionAsyncClient rekAsyncClient = RekognitionAsyncClient.builder()
.credentialsProvider(EnvironmentVariableCredentialsProvider.create())
.region(region)
.build();
try {
final AtomicReference<ArrayList<WorkItem>> reference = new AtomicReference<>();
SdkBytes sourceBytes = SdkBytes.fromByteArray(bytes);
// Create an Image object for the source image.
Image souImage = Image.builder()
.bytes(sourceBytes)
.build();
DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder()
.image(souImage)
.maxLabels(10)
.build();
CompletableFuture<DetectLabelsResponse> futureGet = rekAsyncClient.detectLabels(detectLabelsRequest);
futureGet.whenComplete((resp, err) -> {
try {
if (resp != null) {
List<Label> labels = resp.labels();
System.out.println("Detected labels for the given photo");
ArrayList list = new ArrayList<WorkItem>();
WorkItem item ;
for (Label label: labels) {
item = new WorkItem();
item.setKey(key); // identifies the photo
item.setConfidence(label.confidence().toString());
item.setName(label.name());
list.add(item);
}
reference.set(list);
} else {
err.printStackTrace();
}
} finally {
// Only close the client when you are completely done with it
rekAsyncClient.close();
}
});
futureGet.join();
// Use the AtomicReference object to return the ArrayList<WorkItem> collection.
return reference.get();
} catch (RekognitionException e) {
System.out.println(e.getMessage());
System.exit(1);
}
return null ;
}
}
| 41,151
|
https://github.com/opuslogica/oli_comments/blob/master/README.rdoc
|
Github Open Source
|
Open Source
|
MIT
| null |
oli_comments
|
opuslogica
|
RDoc
|
Code
| 209
| 415
|
# Oli Comments
Oli Comments provides an easy-to-configure commenting system.
## Installation
Add this line to your application's Gemfile:
gem 'oli_comments'
And then execute:
$ bundle install
Once you have bundled it, you should run the installation generator:
$ rails g oli_comments:install
Migrate
$ rake db:migrate
## Usage
Once installed, configure important stuff in
`config/initializers/oli_comments.rb` #not implemented yet
This gem uses cancan for permissions on who can comment/reply. Define permissions in your own ability model.
This gem also requires a @current_member object when someone is logged in.
1. Add 'commentable' to any model to which you would like to add comments.
class Recipe < ActiveRecord::Base
commentable
...
...
end
2. Implement 'commenters' on that model to return an array of members who should be notified in case someone posts a comment.
class Recipe
commentable
...
def commenters
[self.member]
end
...
end
3. Add the comments to the view of the commentable object:
= render 'comments/comments', commentable: @myobj
## Todo:
1. Add config for member image method
2. Add CanCan to engine
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| 40,447
|
https://github.com/mgaidamak/cinema/blob/master/hall/src/main/kotlin/org/mgaidamak/dao/cinema/DbCinemaRepo.kt
|
Github Open Source
|
Open Source
|
MIT
| null |
cinema
|
mgaidamak
|
Kotlin
|
Code
| 302
| 902
|
package org.mgaidamak.dao.cinema
import org.mgaidamak.dao.Cinema
import org.mgaidamak.dao.DbRepo
import org.mgaidamak.dao.Page
import java.sql.DriverManager
import java.sql.ResultSet
import java.util.Properties
/**
* Production ready repository on PostgreSQL
*/
class DbCinemaRepo(url: String,
props: Properties = Properties()): DbRepo<Cinema>(url, props), ICinemaRepo {
override fun form(rs: ResultSet) = Cinema(rs)
override fun createCinema(cinema: Cinema): Cinema? {
val sql = """INSERT INTO cinema (name, city, address, timezone)
VALUES (?, ?, ?, ?) RETURNING id, name, city, address, timezone"""
return try {
DriverManager.getConnection(url, props).use { connection ->
connection.prepareStatement(sql).use { ps ->
ps.setString(1, cinema.name)
ps.setString(2, cinema.city)
ps.setString(3, cinema.address)
ps.setString(4, cinema.timezone)
ps.executeQuery().use { rs ->
if (rs.next()) form(rs) else null
}
}
}
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
private fun getCinemas(page: Page, sort: List<String>): Collection<Cinema> {
val sql = "SELECT id, name, city, address, timezone FROM cinema LIMIT ? OFFSET ?"
return try {
DriverManager.getConnection(url, props).use { connection ->
connection.prepareStatement(sql).use { ps ->
ps.setInt(1, page.limit)
ps.setInt(2, page.offset)
ps.executeQuery().use { it.collect(emptyList()) }
}
}
} catch (e: Exception) {
println(e)
emptyList()
}
}
override fun getCinemas(city: String?, page: Page, sort: List<String>): Collection<Cinema> {
if (city == null) return getCinemas(page, sort)
val sql = """SELECT id, name, city, address, timezone FROM cinema
WHERE city ILIKE '%' || ? || '%'
LIMIT ? OFFSET ?"""
return try {
DriverManager.getConnection(url, props).use { connection ->
connection.prepareStatement(sql).use { ps ->
ps.setString(1, city)
ps.setInt(2, page.limit)
ps.setInt(3, page.offset)
ps.executeQuery().use { it.collect(emptyList()) }
}
}
} catch (e: Exception) {
println(e)
emptyList()
}
}
override fun getCinemaById(id: Int): Cinema? {
val sql = "SELECT id, name, city, address, timezone FROM cinema WHERE id = ?"
return single(id, sql)
}
override fun deleteCinemaById(id: Int): Cinema? {
val sql = "DELETE FROM cinema WHERE id = ? RETURNING id, name, city, address, timezone"
return single(id, sql)
}
override fun clear() = clear("DELETE FROM cinema")
override fun total() = total("SELECT COUNT(*) FROM cinema")
}
| 28,963
|
https://github.com/HappyPorch/uSplit/blob/master/src/Endzone.uSplit/Commands/StopExperiment.cs
|
Github Open Source
|
Open Source
|
Unlicense
| 2,018
|
uSplit
|
HappyPorch
|
C#
|
Code
| 100
| 327
|
using System.Threading.Tasks;
using Endzone.uSplit.GoogleApi;
using Endzone.uSplit.Models;
namespace Endzone.uSplit.Commands
{
public class StopExperiment : GoogleApiCommand<Experiment>
{
private readonly string _googleExperimentId;
public StopExperiment(AnalyticsAccount config, string googleExperimentId) : base(config)
{
_googleExperimentId = googleExperimentId;
}
public override async Task<Experiment> ExecuteAsync()
{
var service = await GetAnalyticsService();
var googleExperimentRequest = service.Management.Experiments.Get(account, _googleExperimentId);
var googleExperiment = await googleExperimentRequest.ExecuteAsync();
googleExperiment.Status = "ENDED";
var request = service.Management.Experiments.Patch(account, googleExperiment);
var experiment = await request.ExecuteAsync();
var parsedExperiment = new Experiment(experiment);
//update cache
var experiments = await new GetCachedExperiments().ExecuteAsync();
var index = experiments.FindIndex(e => e.Id == experiment.Id);
if (index >= 0)
{
experiments[index] = parsedExperiment;
}
return parsedExperiment;
}
}
}
| 50,210
|
https://github.com/Manchester-Central/2022-Rapid-React/blob/master/src/main/java/frc/robot/commands/DriveOverTime.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
2022-Rapid-React
|
Manchester-Central
|
Java
|
Code
| 185
| 480
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import edu.wpi.first.wpilibj.RobotController;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.SwerveDrive;
public class DriveOverTime extends CommandBase {
long m_startTimeMs;
SwerveDrive m_drive;
float m_x, m_y, m_theta;
int m_timeMs;
/** Creates a new DriveOverTime. */
public DriveOverTime(SwerveDrive drive, float x, float y, float theta, int timeMs) {
// Use addRequirements() here to declare subsystem dependencies.
addRequirements(drive);
m_drive = drive;
m_x = x;
m_y = y;
m_theta = theta;
m_timeMs = timeMs;
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
m_startTimeMs = RobotController.getFPGATime() / 1000;
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
m_drive.moveFieldRelative(m_x, m_y, m_theta);
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
long currentTimeMs = RobotController.getFPGATime() / 1000;
return currentTimeMs > m_startTimeMs + m_timeMs;
}
}
| 8,242
|
https://github.com/log2timeline/plaso/blob/master/tests/formatters/yaml_formatters_file.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
plaso
|
log2timeline
|
Python
|
Code
| 182
| 1,052
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the YAML-based formatters file."""
import io
import unittest
from plaso.formatters import yaml_formatters_file
from plaso.lib import errors
from tests import test_lib as shared_test_lib
class YAMLFormattersFileTest(shared_test_lib.BaseTestCase):
"""Tests for the YAML-based formatters file."""
# pylint: disable=protected-access
_FORMATTERS_YAML = {
'type': 'conditional',
'data_type': 'test:fs:stat',
'message': [
'{display_name}',
'Type: {file_entry_type}',
'({unallocated})'],
'short_message': [
'{filename}'],
'short_source': 'SOURCE',
'source': 'My Custom Log Source'}
def testReadFormatterDefinition(self):
"""Tests the _ReadFormatterDefinition function."""
test_formatters_file = yaml_formatters_file.YAMLFormattersFile()
formatter = test_formatters_file._ReadFormatterDefinition(
self._FORMATTERS_YAML)
self.assertIsNotNone(formatter)
self.assertEqual(formatter.data_type, 'test:fs:stat')
with self.assertRaises(errors.ParseError):
test_formatters_file._ReadFormatterDefinition({})
with self.assertRaises(errors.ParseError):
test_formatters_file._ReadFormatterDefinition({'type': 'bogus'})
with self.assertRaises(errors.ParseError):
test_formatters_file._ReadFormatterDefinition({'type': 'conditional'})
with self.assertRaises(errors.ParseError):
test_formatters_file._ReadFormatterDefinition({
'type': 'conditional',
'data_type': 'test:fs:stat'})
with self.assertRaises(errors.ParseError):
test_formatters_file._ReadFormatterDefinition({
'type': 'conditional',
'data_type': 'test:fs:stat',
'message': [
'{display_name}',
'Type: {file_entry_type}',
'({unallocated})']})
with self.assertRaises(errors.ParseError):
test_formatters_file._ReadFormatterDefinition({
'type': 'conditional',
'data_type': 'test:fs:stat',
'message': [
'{display_name}',
'Type: {file_entry_type}',
'({unallocated})']})
with self.assertRaises(errors.ParseError):
test_formatters_file._ReadFormatterDefinition({'bogus': 'error'})
def testReadFromFileObject(self):
"""Tests the _ReadFromFileObject function."""
test_file_path = self._GetTestFilePath(['formatters', 'format_test.yaml'])
self._SkipIfPathNotExists(test_file_path)
test_formatters_file = yaml_formatters_file.YAMLFormattersFile()
with io.open(test_file_path, 'r', encoding='utf-8') as file_object:
formatters = list(test_formatters_file._ReadFromFileObject(file_object))
self.assertEqual(len(formatters), 2)
def testReadFromFile(self):
"""Tests the ReadFromFile function."""
test_file_path = self._GetTestFilePath(['formatters', 'format_test.yaml'])
self._SkipIfPathNotExists(test_file_path)
test_formatters_file = yaml_formatters_file.YAMLFormattersFile()
formatters = list(test_formatters_file.ReadFromFile(test_file_path))
self.assertEqual(len(formatters), 2)
self.assertEqual(formatters[0].data_type, 'test:event')
self.assertEqual(formatters[1].data_type, 'test:fs:stat')
if __name__ == '__main__':
unittest.main()
| 18,613
|
https://github.com/nvander/incubator-rya/blob/master/extras/rya.geo/src/test/java/mvm/rya/geo/GeoRyaTypeResolverTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
incubator-rya
|
nvander
|
Java
|
Code
| 52
| 225
|
package mvm.rya.geo;
import mvm.rya.api.domain.RyaType;
import org.junit.Assert;
import org.junit.Test;
public class GeoRyaTypeResolverTest
{
private final GeoRyaTypeResolver resolver = new GeoRyaTypeResolver();
@Test
public void testSerialization_andBack() throws Exception
{
String latLon = "20.00,30.00";
RyaType orig = new RyaType(RyaGeoSchema.GEOPOINT, latLon);
byte[] bytes = resolver.serialize(orig);
RyaType copy = resolver.deserialize(bytes);
Assert.assertEquals(latLon, copy.getData());
Assert.assertEquals(orig, copy);
Assert.assertEquals(RyaGeoSchema.GEOPOINT, copy.getDataType());
}
}
| 37,391
|
https://github.com/rhinoSp/LibOkHttp/blob/master/libOkHttp/src/main/java/com/rhino/http/SSLUtils.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
LibOkHttp
|
rhinoSp
|
Java
|
Code
| 148
| 575
|
package com.rhino.http;
import android.annotation.SuppressLint;
import com.rhino.log.LogUtils;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SSLUtils {
private static final String TAG = SSLUtils.class.getSimpleName();
private SSLUtils() {
}
@SuppressLint("TrulyRandom")
public static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory sSLSocketFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, new TrustManager[]{new TrustAllManager()}, new SecureRandom());
sSLSocketFactory = sc.getSocketFactory();
} catch (Exception e) {
LogUtils.d(TAG, e.toString());
}
return sSLSocketFactory;
}
public static class TrustAllManager implements X509TrustManager {
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
LogUtils.d(TAG, "authType = " + authType);
}
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
LogUtils.d(TAG, "authType = " + authType);
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
public static class TrustAllHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String requestedHost, SSLSession remoteServerSession) {
return requestedHost.equalsIgnoreCase(remoteServerSession.getPeerHost());
}
}
}
| 14,316
|
https://github.com/NARUTONBM/ReserveClassroom/blob/master/App/src/main/java/com/naruto/reserveclassroom/activity/PostReservationActivity.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ReserveClassroom
|
NARUTONBM
|
Java
|
Code
| 1,336
| 7,078
|
package com.naruto.reserveclassroom.activity;
/*
* Created by NARUTO on 2016/11/10.
*/
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.naruto.reserveclassroom.R;
import com.naruto.reserveclassroom.db.dao.ContactsDao;
import com.naruto.reserveclassroom.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.TimePicker;
public class PostReservationActivity extends AppCompatActivity {
@Bind(R.id.tv_rese_roomNo)
TextView tv_rese_roomNo;
@Bind(R.id.et_manager_contact)
EditText et_manager_contact;
@Bind(R.id.et_reserver_contact)
EditText et_reserver_contact;
@Bind(R.id.tv_rese_time)
TextView tv_rese_time;
@Bind(R.id.tv_rese_time_present)
TextView tv_rese_time_present;
@Bind(R.id.bt_time_choose)
Button bt_time_choose;
@Bind(R.id.cb_use_multimedia)
CheckBox cb_use_multimedia;
@Bind(R.id.et_rese_reason)
EditText et_rese_reason;
@Bind(R.id.cb_agree_commitment)
CheckBox cb_agree_commitment;
@Bind(R.id.bt_read_commitment)
Button bt_read_commitment;
@Bind(R.id.bt_submit_reservation)
Button bt_submit_reservation;
@Bind(R.id.tv_rese_date)
TextView tv_rese_date;
private Context mContext;
private List<ContactsDao.Contacts> mContactsForManager, mContactsForReserver;
private ListView listView;
private PopupWindow popupWindow;
private int bt_choose_clicked = 0;
private String mStartH;
private String mStartM;
private String mReseTime;
private String mCurrentdate;
private String mCurrentDateWeek;
private List<Integer> mAvaiTSList;
private String mRoomNo;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postreservation);
ButterKnife.bind(this);
mContext = this;
initUI();
initData();
}
/**
* 初始化界面
*/
private void initUI() {
ButterKnife.bind(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("提交申请");
listView = new ListView(this);
listView.setDividerHeight(0);
listView.setBackgroundResource(R.mipmap.listview_background);
}
/**
* 初始化数据
*/
private void initData() {
// 拿到ReserveClassRoomActivity传过来的数据(申请的教室号、日期),并将之设置给textview
String date = getIntent().getStringExtra("date");
mRoomNo = getIntent().getStringExtra("roomNo");
mAvaiTSList = getIntent().getIntegerArrayListExtra("avaiTime");
tv_rese_date.setText(date);
tv_rese_roomNo.setText(mRoomNo + "教室借用申请");
ContactsDao contactsDao = ContactsDao.getInstance(mContext);
mContactsForManager = contactsDao.getContacts(0);
mContactsForReserver = contactsDao.getContacts(1);
String[] split = date.split(" ");
mCurrentdate = split[0];
mCurrentDateWeek = split[1];
}
@OnClick({R.id.bt_time_choose, R.id.bt_read_commitment, R.id.bt_submit_reservation})
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_time_choose:
// 使屏幕变暗
makeWindowDark();
// 展示时间选择器
showTimePicker();
break;
case R.id.bt_read_commitment:
// 跳转到一个页面展示承诺书
break;
case R.id.bt_submit_reservation:
// 获取输入框的信息,并对输入的信息进行校验
List<String> inputResult = provideInputInfo();
// 提交申请
submitReservation(inputResult);
break;
/*case R.id.ib_manager_down_arrow:
// 弹出负责人的下拉选择联系人
showPopupWindow(R.id.ib_manager_down_arrow, et_manager_contact);
break;
case R.id.ib_reserver_down_arrow:
// 弹出联系人的下拉选择联系人
showPopupWindow(R.id.ib_reserver_down_arrow, et_reserver_contact);
break;*/
default:
break;
}
}
/**
* 展示自定义的时间选择器
*/
private void showTimePicker() {
bt_choose_clicked ++;
TimePicker timePicker = new TimePicker(this, TimePicker.HOUR_24);
if (bt_choose_clicked % 2 == 1) {
// 奇数次点击设置开始时间
if (mCurrentDateWeek.equals("星期六") || mCurrentDateWeek.equals("星期六")) {
// 周末开始时间至少在8点之后
timePicker.setRangeStart(8, 0);
} else {
// 工作日开始时间至少在18点之后
timePicker.setRangeStart(18, 0);
}
// 最晚要在20点之前开始使用
timePicker.setRangeEnd(20, 0);
timePicker.setTopLineVisible(false);
// 设置时间选择器的时间点击事件
timePicker.setOnTimePickListener(new TimePicker.OnTimePickListener() {
@Override
public void onTimePicked(String hour, String minute) {
// 拿到当前的开始时间,并为何结束时间作对比做准备
tv_rese_time_present.setText(hour + ":" + minute + "-");
bt_time_choose.setText("选择结束时间");
mStartH = hour;
mStartM = minute;
// 关闭时间选择器,将屏幕变亮
makeWindowLight();
}
});
} else {
// 偶数次点击设置结束时间
if (mCurrentDateWeek.equals("星期六") || mCurrentDateWeek.equals("星期六")) {
// 周末结束时间至少在9点之后
timePicker.setRangeStart(9, 0);
} else {
// 工作日结束时间至少在19点之后
timePicker.setRangeStart(19, 0);
}
// 每天最晚可以到22点
timePicker.setRangeEnd(22, 0);
timePicker.setTopLineVisible(false);
// 设置时间选择器的时间点击事件
timePicker.setOnTimePickListener(new TimePicker.OnTimePickListener() {
@Override
public void onTimePicked(String hour, String minute) {
if (hour.compareTo(mStartH) > 0 || (hour.compareTo(mStartH) == 0 && minute.compareTo(mStartM) > 0)) {
// 当结束时间在开始时间之后才是符合规则
int startTS = Integer.parseInt(mStartH) * 3600 + Integer.parseInt(mStartM) * 60;
int endTS = Integer.parseInt(hour) * 3600 + Integer.parseInt(minute) * 60;
// 需要判断选择的时间是否在规定时间之内
for (int i = 0; i < mAvaiTSList.size() / 2; i ++) {
if (startTS >= mAvaiTSList.get(i * 2)) {
// 如果开始时间戳与某个时间戳相等,则去判断结束时间是否下一个时间戳小或相等
if (endTS <= mAvaiTSList.get(i * 2 + 1)) {
// 符合,则设借用时间给tv
mReseTime = mStartH + ":" + mStartM + "-" + hour + ":" + minute;
tv_rese_time_present.setText(mReseTime);
bt_time_choose.setText("选择开始时间");
}
} else {
// 不符合,清空tv,并弹出吐司提示用户重新选择时间或教室
tv_rese_time_present.setText(" ");
ToastUtil.showLong(mContext, "注意可借时段,请重新选择借用时间或更换教室!");
}
}
} else {
// 不符合规则,提示用户重新选择时间
ToastUtil.showShort(mContext, "结束时间必须在开始时间之后");
bt_choose_clicked --;
}
// 关闭时间选择器,将屏幕变亮
makeWindowLight();
}
});
}
timePicker.show();
}
/**
* 让屏幕变暗
*/
private void makeWindowDark() {
Window window = getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.alpha = 0.5f;
window.setAttributes(lp);
}
/**
* 让屏幕变亮
*/
private void makeWindowLight() {
Window window = getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.alpha = 1f;
window.setAttributes(lp);
}
/**
* 获取并校验输入的负责人和联系人信息
*
* @return 返回符合规则的负责人和联系人
*/
private List<String> provideInputInfo() {
// 创建一个放置输入信息的数组
List<String> inputResult = new ArrayList<>();
// 分别判断输入的负责人和联系人是否符合规则,符合则将之添加到准备好的数组中
if (checkInputInfo(et_manager_contact))
inputResult.add(et_manager_contact.getText().toString());
if (checkInputInfo(et_reserver_contact))
inputResult.add(et_reserver_contact.getText().toString());
return inputResult;
}
/**
* 校验输入的内容是否符合规则
*
* @param editText
* 对应的输入框对象
* @return 校验的结果
*/
private boolean checkInputInfo(EditText editText) {
String inputInfo = editText.getText().toString();
if (inputInfo.isEmpty()) {
editText.setError("此处不能为空!");
} else {
if (inputInfo.contains("#")) {
String[] split = inputInfo.split("#");
// 设置人名和手机号的匹配规则
String nameRE = getString(R.string.nameRE);
String phoneRE = getString(R.string.phoneRE);
if (split[0].matches(nameRE) && split[1].matches(phoneRE)) {
return true;
} else {
editText.setError("输入的信息不规范!");
}
} else {
editText.setError("缺失“#”号!");
}
}
return false;
}
/**
* 提交申请的方法
*
* @param inputResult
* 输入的负责人和联系人信息
*/
private void submitReservation(List<String> inputResult) {
// 获取classroom表
AVQuery<AVObject> classroom = new AVQuery<>("Classroom");
updateBorrowDetail(classroom, inputResult, new DataCallback() {
@Override
public void postData(AVObject avObject, ArrayList<HashMap<String, String>> borrowDetail) {
// 用准备好的新的信息,覆盖原有的details
avObject.put("borrowDetails", borrowDetail);
avObject.saveInBackground(new SaveCallback() {
@Override
public void done(AVException e) {
if (e == null) {
System.out.println("update successfully!");
Intent intent = new Intent(mContext, MainActivity.class);
startActivity(intent);
finish();
} else {
System.out.println("update failed!");
e.printStackTrace();
}
}
});
}
});
}
/**
* 准备申请信息的更新数据
*
* @param classroom
* 教室表
* @param inputResult
* 输入的负责人和联系人
* @param callback
* 回调方法
*/
private void updateBorrowDetail(final AVQuery<AVObject> classroom, List<String> inputResult, final DataCallback callback) {
// 创建一个hashmap用于放置将要上传的申请信息
final HashMap<String, String> updateHashMap = new HashMap<>();
// 拿到输入的借用详细
String reseReason = et_rese_reason.getText().toString();
// 只有所有信息满足要求才能提交申请
if (inputResult.size() != 2) {
// 负责人和联系人输入不全
ToastUtil.showShort(mContext, "请检查输入的负责人和联系人");
} else if (mReseTime==null) {
// 未选择借用时间
ToastUtil.showShort(mContext, "请选择借用时间!");
} else if (TextUtils.isEmpty(reseReason)) {
// 活动详细内容为空
et_rese_reason.setError("活动详细内容不能为空");
} else if (reseReason.length() < 10) {
// 活动详细内容少于10个字
et_rese_reason.setError("活动详细内容不能少于10个字");
} else if (!cb_agree_commitment.isChecked()) {
// 未同意《教室借用承诺书》
ToastUtil.showShort(mContext, "只有同意《教室借用承诺书》才能提交申请");
} else {
// 满足条件,往准备好的hashmap中插入申请信息
updateHashMap.put("borrower", inputResult.get(0));
updateHashMap.put("manager", inputResult.get(1));
String[] split = mReseTime.split("-");
updateHashMap.put("startT", mCurrentdate + " " + split[0] + ":00");
updateHashMap.put("endT", mCurrentdate + " " + split[1] + ":00");
int multiMedia = 0;
if (cb_use_multimedia.isChecked()) {
multiMedia = 1;
}
updateHashMap.put("multiMedia", String.valueOf(multiMedia));
updateHashMap.put("currentState", String.valueOf(1));
updateHashMap.put("activityDetail", reseReason);
// 准备用于更新的数据
classroom.whereContains("roomNo", mRoomNo);
classroom.findInBackground(new FindCallback<AVObject>() {
@Override
public void done(List<AVObject> list, AVException e) {
final ArrayList<HashMap<String, String>> borrowDetails = (ArrayList<HashMap<String, String>>) list.get(0).get("borrowDetails");
borrowDetails.add(updateHashMap);
classroom.getInBackground(list.get(0).getObjectId(), new GetCallback<AVObject>() {
@Override
public void done(AVObject avObject, AVException e) {
callback.postData(avObject, borrowDetails);
}
});
}
});
}
}
/**
* 根据点击的下拉按钮的位置,为不同的输入框弹出下拉选择框
*
* @param imageviewId
* 被点击下拉按钮的id
* @param editTextId
* 需要弹出选择框的输入框对象
*/
private void showPopupWindow(int imageviewId, EditText editTextId) {
// 初始化供popupwindow展示用的listview的数据
initListView(imageviewId, editTextId);
// 设置下拉选择框
popupWindow = new PopupWindow(listView, editTextId.getWidth(), 500);
// 设置点击区域外自动隐藏
popupWindow.setOutsideTouchable(true);
// 设置空的背景,相应点击事件
popupWindow.setBackgroundDrawable(new BitmapDrawable());
// 设置可获取焦点
popupWindow.setFocusable(true);
// 显示在指定控件下
popupWindow.showAsDropDown(editTextId, 0, -5);
}
/**
* 根据点击的下拉按钮的位置,为不同的输入框初始化下拉选择框的数据以及回显
*
* @param viewId
* 被点击下拉按钮的id
* @param editText
* 需要弹出选择框的输入框对象
*/
private void initListView(final int viewId, final EditText editText) {
listView = new ListView(this);
listView.setDividerHeight(0);
listView.setBackgroundResource(R.mipmap.listview_background);
// 设置数据适配器
listView.setAdapter(new MyAdapter(editText));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 给对应的输入框添加数据
if (viewId == R.id.et_manager_contact) {
ContactsDao.Contacts managerInfo = mContactsForManager.get(position);
editText.setText(managerInfo.name + "#" + managerInfo.phone);
} else if (viewId == R.id.et_reserver_contact) {
ContactsDao.Contacts reserverInfo = mContactsForReserver.get(position);
editText.setText(reserverInfo.name + "#" + reserverInfo.phone);
}
// 关闭popupwindow
popupWindow.dismiss();
}
});
}
/**
* 下拉选择框的数据适配器
*/
private class MyAdapter extends BaseAdapter {
int editTextId = 0;
MyAdapter(EditText editText) {
editTextId = editText.getId();
}
@Override
public int getCount() {
if (editTextId == R.id.et_manager_contact) {
return mContactsForManager.size();
} else if (editTextId == R.id.et_reserver_contact) {
return mContactsForReserver.size();
} else {
return 0;
}
}
@Override
public ContactsDao.Contacts getItem(int position) {
if (editTextId == R.id.et_manager_contact) {
return mContactsForManager.get(position);
} else if (editTextId == R.id.et_reserver_contact) {
return mContactsForReserver.get(position);
} else {
return null;
}
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// 复用convertview
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(getApplicationContext(), R.layout.listview_contacts_bg, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// 为listview条目设置相应的数据
holder.tv_contacts_name.setText(getItem(position).name);
holder.tv_contacts_phone.setText(getItem(position).phone);
holder.ib_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 点击了某个条目的删除按钮,删除该条目
if (editTextId == R.id.et_manager_contact) {
mContactsForManager.remove(position);
} else if (editTextId == R.id.et_reserver_contact) {
mContactsForReserver.remove(position);
}
// 删除之后通知更新数据
notifyDataSetChanged();
// 如果数据全部删光则关闭popupwindow
if (editTextId == R.id.et_manager_contact) {
if (mContactsForManager.size() == 0) {
popupWindow.dismiss();
}
} else if (editTextId == R.id.et_reserver_contact) {
if (mContactsForReserver.size() == 0) {
popupWindow.dismiss();
}
}
}
});
return convertView;
}
}
static class ViewHolder {
@Bind(R.id.tv_contacts_name)
TextView tv_contacts_name;
@Bind(R.id.tv_contacts_phone)
TextView tv_contacts_phone;
@Bind(R.id.ib_delete)
ImageButton ib_delete;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
public interface DataCallback {
void postData(AVObject avObject, ArrayList<HashMap<String, String>> details);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
AVAnalytics.onPause(this);
}
@Override
protected void onResume() {
super.onResume();
AVAnalytics.onResume(this);
}
}
| 41,411
|
https://github.com/santoshvijapure/DS_with_hacktoberfest/blob/master/Data_Structures/hashing/Chain_Hashing.c
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
DS_with_hacktoberfest
|
santoshvijapure
|
C
|
Code
| 332
| 1,154
|
//Made by- Subhadeep Saha
//program in c
#include<stdio.h>
#include<stdlib.h>
//code for chain hashing
struct node
{
int info;
struct node *link;
};
struct node *start[10];
void inserter(int value, int key)
{
key=key%10;
struct node* ptr;
struct node* newn=(struct node*)malloc(sizeof(struct node));
newn->info=value;
if(start[key]==NULL)
{
start[key]=newn;
newn->link=NULL;
}
else
{
ptr=start[key];
start[key]=newn;
newn->link=ptr;
}
}
void display()
{
int i=0;
struct node* ptr;
//int d=0;
while(i!=10)
{
ptr=start[i];
printf("\nKey %d : ", i);
if(ptr==NULL)
printf("No value at this key");
while(ptr!=NULL)
{
printf("%d\t",ptr->info);
ptr=ptr->link;
}
i++;
}
}
struct node *searchvalue(int item, int key)
{
struct node* ptr;
key=key%10;
ptr=start[key];
if(ptr==NULL)
{
return ptr;
}
while(ptr!=NULL)
{
if(ptr->info==item)
return ptr;
ptr=ptr->link;
}
return ptr;
}
void deletevalue(int item, int key)
{
key=key%10;
if(start[key]->info==item)
{
start[key]=start[key]->link;
return;
}
struct node* ptr=start[key];
struct node* ptr2=ptr;
//ptr=start[key];
while(ptr->info!=item )
{
ptr2=ptr;
ptr=ptr->link;
}
if(ptr->link==NULL)
{
ptr2->link=NULL;
}
if(ptr->link!=NULL)
{
ptr2->link=ptr->link;
}
free(ptr);
}
int main()
{
struct node* sptr;
int x=0, item, option, key;
while(x!=10)
{
start[x]=NULL;
x++;
}
do
{
printf("\n\n1.Create a Hash Table for separate chaining");
printf("\n2.Searching an item from the Hash Table");
printf("\n3.Delete an item from Hash Table");
printf("\n4.Display the Hash Table");
printf("\n5.Exit from the program");
printf("\nEnter your choice : ");
scanf("%d", &option);
switch(option)
{
case 1:{
printf("\nEnter -1 to terminate");
printf("\nEnter the data item : ");
scanf("%d",&item);
printf("\nEnter the key value : ");
scanf("%d",&key);
while(item!=-1)
{
inserter(item,key);
printf("\nEnter the data item : ");
scanf("%d",&item);
printf("\nEnter the key value : ");
scanf("%d",&key);
}
printf("\nHash Table is created\n");
break;}
case 2:{
printf("\nEnter the data item you want to search : ");
scanf("%d",&item);
printf("\nEnter the key value of the data : ");
scanf("%d",&key);
sptr=searchvalue(item,key);
if(sptr==NULL)
printf("\nItem %d with key value %d is not present",item,key);
else
printf("\nItem %d with key value %d is found at location %d",item,key,sptr);
break;}
case 3:{
printf("\nEnter the data item you want to delete : ");
scanf("%d",&item);
printf("\nEnter the key value of the data : ");
scanf("%d",&key);
deletevalue(item,key);
break;}
case 4:{
display();
break;}
}
}while(option<=4);
printf("\nYour input have terminated the program\n");
return 0;
}
| 10,247
|
https://github.com/betajaen/gorilla/blob/master/examples/gorilla_3d.cpp
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
gorilla
|
betajaen
|
C++
|
Code
| 953
| 4,766
|
#include <OGRE/Ogre.h>
#include <OIS/OIS.h>
#include "Gorilla.h"
#include <sstream>
#pragma warning ( disable : 4244 )
struct Button
{
Button(Ogre::Real x, Ogre::Real y, const Ogre::String& text, Gorilla::Layer* layer)
: hovered(false)
{
caption = layer->createCaption(14, x,y, text);
caption->size(64,25);
caption->align(Gorilla::TextAlign_Centre);
caption->vertical_align(Gorilla::VerticalAlign_Middle);
caption->background(Gorilla::rgb(255,255,255,32));
}
bool isOver(const Ogre::Vector2& pos)
{
bool result = caption->intersects(pos);
if (result && !hovered)
caption->background(Gorilla::rgb(255,255,255,128));
else if (!result && hovered)
caption->background(Gorilla::rgb(255,255,255,32));
hovered = result;
return result;
}
bool hovered;
Gorilla::Caption* caption;
};
struct D3Panel
{
D3Panel(Gorilla::Silverback* silverback, Ogre::SceneManager* sceneMgr, const Ogre::Vector2& size)
: mSize(size)
{
mScreen = silverback->createScreenRenderable(Ogre::Vector2(mSize.x,mSize.y), "dejavu");
mNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
mNode->attachObject(mScreen);
mGUILayer = mScreen->createLayer(0);
mBackground = mGUILayer->createRectangle(0,0, mSize.x * 100, mSize.y * 100);
mBackground->background_gradient(Gorilla::Gradient_NorthSouth, Gorilla::rgb(94,97,255,5), Gorilla::rgb(94,97,255,50));
mBackground->border(2, Gorilla::rgb(255,255,255,150));
mMousePointerLayer = mScreen->createLayer(15);
mMousePointer = mMousePointerLayer->createRectangle(0,0,10,18);
mMousePointer->background_image("mousepointer");
}
Button* check(const Ogre::Ray& ray, bool& isOver)
{
isOver = false;
Ogre::Matrix4 transform;
transform.makeTransform(mNode->getPosition(), mNode->getScale(), mNode->getOrientation());
Ogre::AxisAlignedBox aabb = mScreen->getBoundingBox();
aabb.transform(transform);
std::pair<bool, Ogre::Real> result = Ogre::Math::intersects(ray, aabb);
if (result.first == false)
return 0;
Ogre::Vector3 a,b,c,d;
Ogre::Vector2 halfSize = mSize * 0.5f;
a = transform * Ogre::Vector3(-halfSize.x,-halfSize.y,0);
b = transform * Ogre::Vector3( halfSize.x,-halfSize.y,0);
c = transform * Ogre::Vector3(-halfSize.x, halfSize.y,0);
d = transform * Ogre::Vector3( halfSize.x, halfSize.y,0);
result = Ogre::Math::intersects(ray, c, b, a);
if (result.first == false)
result = Ogre::Math::intersects(ray, c, d, b);
if (result.first == false)
return 0;
if (result.second > 6.0f)
return 0;
isOver = true;
Ogre::Vector3 hitPos = ( ray.getOrigin() + (ray.getDirection() * result.second) );
Ogre::Vector3 localPos = transform.inverse() * hitPos;
localPos.x += halfSize.x;
localPos.y -= halfSize.y;
localPos.x *= 100;
localPos.y *= 100;
// Cursor clip
localPos.x = Ogre::Math::Clamp<Ogre::Real>(localPos.x, 0, (mSize.x * 100) - 10);
localPos.y = Ogre::Math::Clamp<Ogre::Real>(-localPos.y, 0, (mSize.y * 100) - 18);
mMousePointer->position(localPos.x, localPos.y);
for (size_t i=0;i < mButtons.size();i++)
{
if (mButtons[i]->isOver(mMousePointer->position()))
return mButtons[i];
}
return 0;
}
Gorilla::Caption* makeCaption(Ogre::Real x, Ogre::Real y, const Ogre::String& text)
{
return mGUILayer->createCaption(14, x, y, text);
}
Button* makeButton(Ogre::Real x, Ogre::Real y, const Ogre::String& text)
{
Button* button = new Button(x,y, text, mGUILayer);
mButtons.push_back(button);
return button;
}
Gorilla::ScreenRenderable* mScreen;
Ogre::SceneNode* mNode;
Gorilla::Layer* mGUILayer, *mMousePointerLayer;
Gorilla::Rectangle* mBackground, *mMousePointer;
Ogre::Vector2 mSize;
std::vector<Button*> mButtons;
};
class App : public Ogre::FrameListener, public OIS::KeyListener, public OIS::MouseListener
{
public:
Ogre::Real mTimer, mTimer2;
Gorilla::Silverback* mSilverback;
Gorilla::Screen* mHUD, *mControlPanel;
Gorilla::Layer* mHUDLayer;
Gorilla::Layer* mCrosshairLayer;
Gorilla::Rectangle* mCrosshair;
D3Panel* mPowerPanel;
Gorilla::Rectangle* mPowerValue, *mPowerValueBackground;
Button* mPowerUpButton;
Button* mPowerDownButton;
Ogre::Real mBasePower;
Ogre::SceneNode* mNode;
App() : mTimer(0), mTimer2(0), mBasePower(150), mNextUpdate(0)
{
_makeOgre();
_makeOIS();
// Create Silverback and load in dejavu
mSilverback = new Gorilla::Silverback();
mSilverback->loadAtlas("dejavu");
createHUD();
createControlPanel();
}
void createHUD()
{
mHUD = mSilverback->createScreen(mViewport, "dejavu");
mHUDLayer = mHUD->createLayer();
Gorilla::Caption* fakeHealth = mHUDLayer->createCaption(24, 0, 0, "+ 100");
fakeHealth->width(mViewport->getActualWidth()-16);
fakeHealth->height(mViewport->getActualHeight()-4);
fakeHealth->align(Gorilla::TextAlign_Right);
fakeHealth->vertical_align(Gorilla::VerticalAlign_Bottom);
Gorilla::Caption* fakeAmmo = mHUDLayer->createCaption(24, 16, 0, ": 60");
fakeAmmo->width(mViewport->getActualWidth());
fakeAmmo->height(mViewport->getActualHeight()-4);
fakeAmmo->vertical_align(Gorilla::VerticalAlign_Bottom);
mCrosshairLayer = mHUD->createLayer();
mCrosshair = mCrosshairLayer->createRectangle((mViewport->getActualWidth() * 0.5f) - 11, (mViewport->getActualHeight() * 0.5f) - 11, 22, 22);
mCrosshair->background_image("crosshair");
}
void createControlPanel()
{
mPowerPanel = new D3Panel(mSilverback, mSceneMgr, Ogre::Vector2(4,1));
mPowerPanel->mNode->setPosition(Ogre::Vector3(0,1.5f,-10));
Gorilla::Caption* caption = mPowerPanel->makeCaption(0,4, "Power Level");
caption->width(400);
caption->align(Gorilla::TextAlign_Centre);
mPowerValueBackground = mPowerPanel->mGUILayer->createRectangle(10,35,380,10);
mPowerValueBackground->background_colour(Gorilla::rgb(255,255,255,100));
mPowerValue = mPowerPanel->mGUILayer->createRectangle(10,35,200,10);
mPowerValue->background_gradient(Gorilla::Gradient_NorthSouth, Gorilla::rgb(255,255,255,200), Gorilla::rgb(64,64,64,200));
mPowerDownButton = mPowerPanel->makeButton(10, 65, "-");
mPowerUpButton = mPowerPanel->makeButton(84, 65, "+");
}
~App()
{
std::cout << "\n** Average FPS is " << mWindow->getAverageFPS() << "\n\n";
delete mSilverback;
delete mRoot;
}
bool frameStarted(const Ogre::FrameEvent& evt)
{
if (mWindow->isClosed())
return false;
mKeyboard->capture();
if (mKeyboard->isKeyDown(OIS::KC_ESCAPE))
return false;
mMouse->capture();
mTimer += evt.timeSinceLastFrame;
if (mTimer > 1.0f / 60.0f)
{
mPowerPanel->mNode->yaw(Ogre::Radian(0.0005));
mTimer2 += Ogre::Math::RangeRandom(0, mTimer * 10);
mTimer = 0;
Ogre::Math::Clamp<Ogre::Real>(mTimer2, 0, 25);
Ogre::Real power = mBasePower + (Ogre::Math::Cos(mTimer2) * 5);
power = Ogre::Math::Clamp<Ogre::Real>(power, 0, 380);
mPowerValue->width(power);
}
bool isOver = false;
Button* button = mPowerPanel->check( mCamera->getCameraToViewportRay(0.5f,0.5f), isOver );
if (isOver)
mCrosshairLayer->hide();
else
mCrosshairLayer->show();
if (button != 0 && mMouse->getMouseState().buttonDown(OIS::MB_Left))
{
if (button == mPowerDownButton)
{
mBasePower -= 1.0f;
}
if (button == mPowerUpButton)
{
mBasePower += 1.0f;
}
}
Ogre::Vector3 trans(0,0,0);
if (mKeyboard->isKeyDown(OIS::KC_W))
trans.z = -1;
else if (mKeyboard->isKeyDown(OIS::KC_S))
trans.z = 1;
if (mKeyboard->isKeyDown(OIS::KC_A))
trans.x = -1;
else if (mKeyboard->isKeyDown(OIS::KC_D))
trans.x = 1;
if (trans.isZeroLength() == false)
{
Ogre::Vector3 pos = mCamera->getPosition();
pos += mCamera->getOrientation() * (trans * 5.0f) * evt.timeSinceLastFrame;
pos.y = 2.0f;
mCamera->setPosition(pos);
}
return true;
}
bool keyPressed( const OIS::KeyEvent &e )
{
return true;
}
bool keyReleased( const OIS::KeyEvent &e )
{
return true;
}
bool mouseMoved( const OIS::MouseEvent &arg )
{
Ogre::Real pitch = Ogre::Real(arg.state.Y.rel) * -0.005f;
Ogre::Real yaw = Ogre::Real(arg.state.X.rel) * -0.005f;
mCamera->pitch(Ogre::Radian(pitch));
mCamera->yaw(Ogre::Radian(yaw));
return true;
}
bool mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
return true;
}
bool mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
return true;
}
void _makeOgre()
{
srand(time(0));
mRoot = new Ogre::Root("","");
mRoot->addFrameListener(this);
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
mRoot->loadPlugin(OGRE_RENDERER);
#else
#if 1
#ifdef _DEBUG
mRoot->loadPlugin("RenderSystem_Direct3D9_d");
#else
mRoot->loadPlugin("RenderSystem_Direct3D9");
#endif
#else
#ifdef _DEBUG
mRoot->loadPlugin("RenderSystem_GL_d.dll");
#else
mRoot->loadPlugin("RenderSystem_GL.dll");
#endif
#endif
#endif
mRoot->setRenderSystem(mRoot->getAvailableRenderers()[0]);
Ogre::ResourceGroupManager* rgm = Ogre::ResourceGroupManager::getSingletonPtr();
rgm->addResourceLocation(".", "FileSystem");
mRoot->initialise(false);
mWindow = mRoot->createRenderWindow("Gorilla", 1024, 768, false);
mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
mCamera = mSceneMgr->createCamera("Camera");
mViewport = mWindow->addViewport(mCamera);
Ogre::ColourValue BackgroundColour = Ogre::ColourValue(0.1337f, 0.1337f, 0.1337f, 1.0f);
Ogre::ColourValue GridColour = Ogre::ColourValue(0.2000f, 0.2000f, 0.2000f, 1.0f);
mViewport->setBackgroundColour(BackgroundColour);
rgm->initialiseAllResourceGroups();
mCamera->setPosition(10,2,10);
mCamera->lookAt(0,2,0);
mCamera->setNearClipDistance(0.05f);
mCamera->setFarClipDistance(1000);
mReferenceObject = new Ogre::ManualObject("ReferenceGrid");
mReferenceObject->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_LINE_LIST);
Ogre::Real step = 1.0f;
unsigned int count = 200;
unsigned int halfCount = count / 2;
Ogre::Real full = (step * count);
Ogre::Real half = full / 2;
Ogre::Real y = 0;
Ogre::ColourValue c;
for (unsigned i=0;i < count+1;i++)
{
if (i == halfCount)
c = Ogre::ColourValue(0.5f,0.3f,0.3f,1.0f);
else
c = GridColour;
mReferenceObject->position(-half,y,-half+(step*i));
mReferenceObject->colour(BackgroundColour);
mReferenceObject->position(0,y,-half+(step*i));
mReferenceObject->colour(c);
mReferenceObject->position(0,y,-half+(step*i));
mReferenceObject->colour(c);
mReferenceObject->position(half,y,-half+(step*i));
mReferenceObject->colour(BackgroundColour);
if (i == halfCount)
c = Ogre::ColourValue(0.3f,0.3f,0.5f,1.0f);
else
c = GridColour;
mReferenceObject->position(-half+(step*i),y,-half);
mReferenceObject->colour(BackgroundColour);
mReferenceObject->position(-half+(step*i),y,0);
mReferenceObject->colour(c);
mReferenceObject->position(-half+(step*i),y,0);
mReferenceObject->colour(c);
mReferenceObject->position(-half+(step*i),y, half);
mReferenceObject->colour(BackgroundColour);
}
mReferenceObject->end();
mSceneMgr->getRootSceneNode()->attachObject(mReferenceObject);
}
void _makeOIS()
{
// Initialise OIS
OIS::ParamList pl;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
mWindow->getCustomAttribute("WINDOW", &windowHnd);
windowHndStr << windowHnd;
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
mInputManager = OIS::InputManager::createInputSystem( pl );
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true));
mKeyboard->setEventCallback(this);
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true));
mMouse->setEventCallback(this);
mMouse->getMouseState().width = mViewport->getActualWidth();
mMouse->getMouseState().height = mViewport->getActualHeight();
}
Ogre::Root* mRoot;
Ogre::RenderWindow* mWindow;
Ogre::Viewport* mViewport;
Ogre::SceneManager* mSceneMgr;
Ogre::Camera* mCamera;
Ogre::Real mNextUpdate;
OIS::InputManager* mInputManager;
OIS::Keyboard* mKeyboard;
OIS::Mouse* mMouse;
Ogre::ManualObject* mReferenceObject;
};
int main()
{
App* app = new App();
app->mRoot->startRendering();
delete app;
return 0;
}
| 46,829
|
https://github.com/sanatg/Three.js-Solar-Exploration/blob/master/js/index.js
|
Github Open Source
|
Open Source
|
MIT, Apache-2.0
| 2,018
|
Three.js-Solar-Exploration
|
sanatg
|
JavaScript
|
Code
| 396
| 1,769
|
/**
* Created by ss on 2017/10/30.
*/
$(function () {
googleEarth = false;
infoBoard = false;
renderer = SolarEPUtils.getDefaultRenderer();
solarSystemSceneController = new SolarSystemSceneController(renderer);
solarSystemSceneController.initialFadeSceneIn();
activatedScene = solarSystemSceneController;
var PlanetControllers = {};
$.getScript("js/config/planetConfig.js", function () {
$.getScript("js/model/PlanetSceneControllers.js", function () {
PlanetControllers.mercury = new PlanetSceneController(renderer, PlanetConfig.mercury);
PlanetControllers.venus = new PlanetSceneController(renderer, PlanetConfig.venus);
PlanetControllers.mars = new PlanetSceneController(renderer, PlanetConfig.mars);
PlanetControllers.jupiter = new PlanetSceneController(renderer, PlanetConfig.jupiter);
PlanetControllers.saturn = new PlanetSceneController(renderer, PlanetConfig.saturn);
PlanetControllers.uranus = new PlanetSceneController(renderer, PlanetConfig.uranus);
PlanetControllers.neptune = new PlanetSceneController(renderer, PlanetConfig.neptune);
PlanetControllers.pluto = new PlanetSceneController(renderer, PlanetConfig.pluto);
solarSystemSceneController.setPlanetScenes(PlanetControllers);
});
});
$.getScript("js/model/EarthSceneController.js", function () {
earthSceneController = new EarthSceneController(renderer);
solarSystemSceneController.setPlanetScene("earth", earthSceneController);
});
$.getScript("js/model/GlobeSceneController.js", function () {
globe = new DAT.Globe(renderer);
globe.init();
loadData();
});
$("#all").click(function () {
$("body footer div").each(function () {
$(this).attr("class", "unchecked");
});
$(this).attr("class", "checked");
googleEarth = true;
earthSceneController.stopScene();
globe.activateScene();
});
$("body footer div.year").click(function () {
$("body footer div").each(function () {
$(this).attr("class", "unchecked");
});
$(this).attr("class", "checked");
var year = $(this).text();
if (googleEarth) {
googleEarth = false;
globe.deactivateScene();
earthSceneController.startScene();
}
getYearData(year);
});
$("#closeBoard").hover(
function () {
$(this).attr("src", "images/closeButton/close_hover.png");
},
function () {
$(this).attr("src", "images/closeButton/close.png");
});
$("#curtain, #closeBoard").click(function () {
if (infoBoard) {
earthSceneController.restoreScene();
$("#infoBoard").animate({width: 'toggle'}, 350);
$("#curtain").hide();
$("#timeLine").show();
infoBoard = false;
}
});
});
function getYearData(year) {
earthSceneController.clearCones();
earthSceneController.addCones(yearTop10[year]);
}
function enableBackLogo() {
$("#backLogo").hover(
function () {
$(this).css("border", "1px solid #414141");
},
function () {
$(this).css("border", "0");
}).css("cursor", "pointer").click(backToSolar);
}
function disableBackLogo() {
$("#backLogo").hover(function () {
$(this).css("border", "0");
}).css("cursor", "default").unbind("click");
}
function loadData() {
$.ajax({
url: 'data/all.json',
type: 'GET',
contentType: "application/json; charset=utf-8",
async: true,
dataType: 'json',
success: function (data) {
globe.addData(data, {format: 'magnitude'});
globe.createPoints();
}
});
$.ajax({
url: 'data/yearTop10Data.json',
type: 'GET',
contentType: "application/json; charset=utf-8",
async: true,
dataType: 'json',
success: function (data) {
yearTop10 = data;
}
});
}
function backToSolar() {
disableBackLogo();
activatedScene.fadeSceneOut();
}
function showTransition(planetName) {
configureArea(TransitionConfig[planetName]);
typeMessage(TransitionConfig[planetName]);
$("#transition").css("display", "block");
}
function setTransitionImage(config) {
$("#transition>img:eq(0)").attr("src", config.backgroundImg);
$("#transition>img:eq(1)").attr("src", config.decoratorImg);
}
function configureArea(config) {
$("#transition>div>p:eq(3)").css("color", config.color);
}
function typeMessage(config) {
var typingSpeed = 60;
var signatureSpeed = 200;
var typing1 = new Typing({
source: $(config.messageArea + ">div:eq(0)")[0],
output: $("#transition>div>p>span:eq(0)")[0],
delay: typingSpeed,
done: function () {
typing2.start();
}
});
var typing2 = new Typing({
source: $(config.messageArea + ">div:eq(1)")[0],
output: $("#transition>div>p>span:eq(1)")[0],
delay: typingSpeed,
done: function () {
typing3.start();
}
});
var typing3 = new Typing({
source: $(config.messageArea + ">div:eq(2)")[0],
output: $("#transition>div>p>span:eq(2)")[0],
delay: typingSpeed,
done: function () {
typing4.start();
}
});
var typing4 = new Typing({
source: $(config.messageArea + ">div:eq(3)")[0],
output: $("#transition>div>p>span:eq(3)")[0],
delay: signatureSpeed,
done: function () {
$("#transition").hide();
solarSystemSceneController.onTransitionComplete();
$("#transition>div>p>span:eq(0)").empty();
$("#transition>div>p>span:eq(1)").empty();
$("#transition>div>p>span:eq(2)").empty();
$("#transition>div>p>span:eq(3)").empty();
}
});
typing1.start();
}
| 45,134
|
https://github.com/pombredanne/olypy/blob/master/scripts/oid
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
olypy
|
pombredanne
|
Python
|
Code
| 25
| 97
|
#!/usr/bin/env python
import sys
from olypy.oid import to_oid, to_int
for oid in sys.argv[1:]:
if oid.isdigit():
oidint = int(oid)
else:
oidint = to_int(oid)
print('{}: {}'.format(to_oid(oidint), oidint))
| 32,353
|
https://github.com/brvhjustice/donation_backend/blob/master/app.js
|
Github Open Source
|
Open Source
|
MIT
| null |
donation_backend
|
brvhjustice
|
JavaScript
|
Code
| 55
| 226
|
require('dotenv').config()
const express = require('express');
const app = express();
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'));
app.use(express.static("public"));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html")
})
app.get("/views/donate.html", function(req, res){
res.sendFile(__dirname + "/views/donate.html")
})
app.get("/views/donate.html", function(req, res) {
res.redirect("/")
})
app.get("/views/success.html", function(req, res){
res.sendFile(__dirname + "/views/success.html")
})
app.listen(process.env.PORT || 3000, function() {
console.log('Server is running on port 3000');
});
| 19,691
|
https://github.com/PauloBarrantes/Tarea1-Redes/blob/master/NodeTCP.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Tarea1-Redes
|
PauloBarrantes
|
Python
|
Code
| 1,116
| 3,391
|
import threading
from Node import *
from ReachabilityTables import *
from TablaTCP import *
from socket import *
from texttable import *
import time
class BColors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
GG = '\033[96m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class NodeTCP(Node):
def __init__(self, ip, port):
super().__init__("pseudoBGP", ip, int(port))
self.reachability_table = ReachabilityTables()
self.tcp_table = TablaTCP()
# Start our server thread, which will handle new connections.
self.threadServer = threading.Thread(target = self.server_tcp)
self.threadServer.daemon = True
self.threadServer.start()
# Start listening for new connections.
self.listen()
# Start a new server thread that will handle all connections.
def server_tcp(self):
server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.bind((self.ip, self.port))
server_socket.listen(100)
print ("El servidor esta listo para ser usado : ", self.ip, self.port)
while True:
connection_socket, address = server_socket.accept()
self.tcp_table.save_connection(address[0], address[1], connection_socket)
thread_server_c = threading.Thread(target = self.server_tcp_thread, args=(connection_socket, address))
thread_server_c.daemon = True
thread_server_c.start()
# Start a new TCP connection thread with another node.
def server_tcp_thread(self, connection_socket, address):
# Set our flag that will determine when to stop listening.
flag = True
# While the flag is true, keep on receiving messages.
while flag:
try:
# Wait for a message to be received.
message = connection_socket.recv(1024)
# Case where we receive a new message.
if int.from_bytes(message, byteorder="big") != 0 and \
len(message) > 1:
self.log_writer.write_log("TCP node received a message.", 1)
elements_quantity = int.from_bytes(message[:2], byteorder="big")
table = Texttable()
table.set_cols_align(["l", "r", "c","k"])
table.set_cols_valign(["t", "m", "b","a"])
table.add_row(["IP de origen", "Ip", "Máscara","Costo"])
for n in range(0,elements_quantity):
ip_bytes = message[2+(n*8):6+(n*8)]
mask = message[6+(n*8)]
cost_bytes = message[7+(n*8):10+(n*8)]
ip = list(ip_bytes)
ip_str = ""
for byte in range(0,len(ip)):
if(byte < len(ip)-1):
ip_str += str(ip[byte])+"."
else:
ip_str += str(ip[byte])
mask_str = str(mask)
cost = int.from_bytes(cost_bytes,byteorder="big")
table.add_row([address[0], ip_str, mask_str, cost])
# Save to our reachability table.
self.reachability_table.save_address(ip_str, address[0], mask_str,
cost, int(connection_socket.getpeername()[1]))
print (table.draw() + "\n")
# Remove the node from the reachability table and then send a confirmation message.
elif int.from_bytes(message, byteorder="big") == 0:
self.log_writer.write_log("TCP node received a terminating notification.", 1)
self.reachability_table.remove_address(connection_socket.getpeername()[0],
int(connection_socket.getpeername()[1]))
try:
print("Hemos recivido una notificación de terminación del nodo con dirección: "
+ connection_socket.getpeername()[0] + " y puerto: " +
str(connection_socket.getpeername()[1]))
confirmation_message = bytes([2])
connection_socket.send(confirmation_message)
self.tcp_table.close_connection(connection_socket.getpeername()[0],
int(connection_socket.getpeername()[1]))
flag = False
print("La conexión con el nodo ha sido eliminada.")
except BrokenPipeError:
print("No se pudo enviar el mensaje de borrado satisfactorio")
flag = False
# Enter here when we receive a termination notification from another node.
elif int.from_bytes(message, byteorder="big") == 2:
self.log_writer.write_log("TCP node received a termination confirmation.", 1)
print("Recivimos mensaje de terminación del nodo con dirección: "
+ connection_socket.getpeername()[0] + " y puerto: " +
str(connection_socket.getpeername()[1])
+ ". Estamos cerrando la conexión.")
self.tcp_table.close_connection(connection_socket.getpeername()[0],
int(connection_socket.getpeername()[1]))
# Set flag to false, so that we stop listening.
flag = False
except ConnectionResetError:
'''Obtenemos el recurso que es la tabla de conexiones vivas'''
self.tcp_table.close_connection(address[0], int(connection_socket.getpeername()[1]))
print("La conexión se ha perdido con ", address[0], int(connection_socket.getpeername()[1]))
flag = False
# Send messages to other nodes.
def send_message(self):
print("Enviar mensaje:")
self.log_writer.write_log("TCP node is sending a message.", 2)
# Variables that we will use to keep the user's input.
port = ""
mask = ""
ip_destination = ""
# Variable to check each input of the user.
valid_input = False
while not valid_input:
ip_destination = input("Digite la ip de destino a la que desea enviar: ")
valid_input = self.validate_ip(ip_destination)
valid_input = False
while not valid_input:
mask = input("Digite la máscara de destino a la que desea enviar: ")
valid_input = self.validate_mask(mask)
valid_input = False
while not valid_input:
port = input("Digite el puerto de destino a la que desea enviar: ")
valid_input = self.validate_port(port)
num = 1
valid_input = False
while not valid_input:
try:
num = int(input("Digite la cantidad de mensajes que va enviar a ese destino: "))
valid_input = True
except ValueError:
print(BColors.FAIL + "Error: " + BColors.ENDC + "Entrada no númerica")
port_destination = int(port)
mask_destination = int(mask)
elements_quantity = num.to_bytes(2, byteorder="big")
byte_array = bytearray(elements_quantity)
for i in range(0,num):
ip_message = ""
mask_message = ""
cost_message = ""
valid_network_ip = False
# Validate that the ip and mask represents a network address.
while not valid_network_ip:
valid_input = False
while not valid_input:
ip_message = input("Digite la ip de destino a la que desea enviar: ")
valid_input = self.validate_ip(ip_message)
valid_input = False
while not valid_input:
mask_message = input("Digite la máscara de destino a la que desea enviar: ")
valid_input = self.validate_mask(mask_message)
valid_input = False
while not valid_input:
cost_message = input("Digite un costo: ")
valid_input = self.validate_cost(cost_message)
valid_network_ip = self.validate_ip_network(ip_message, mask_message)
if not valid_network_ip:
print("Dirección ip no representa una dirección de red.")
byte_array.extend(bytearray(bytes(map(int, ip_message.split(".")))))
byte_array.extend((int(mask_message)).to_bytes(1, byteorder="big"))
byte_array.extend(int(cost_message).to_bytes(3, byteorder="big"))
try:
# If we already have the connection, then we just send it.
if self.tcp_table.search_connection(ip_destination, port_destination) != -1:
self.tcp_table.search_connection(ip_destination, port_destination).send(byte_array)
else:
client_socket = socket(AF_INET, SOCK_STREAM)
# Try to connect to the other node.
try:
client_socket.connect((ip_destination, port_destination))
self.tcp_table.save_connection(ip_destination, port_destination, client_socket)
# Send confirmation message to the other node.
client_socket.send(byte_array)
print("Nos hemos conectado con el nodo con dirección %s y puerto %s." %
(ip_destination, port_destination))
# Create a new thread to start listening to the node.
thread_server_c = threading.Thread(target=self.server_tcp_thread,
args=(client_socket, {ip_destination, port_destination}))
thread_server_c.daemon = True
thread_server_c.start()
except Exception as e:
print("Error al conectarnos con el nodo %s, en el puerto %s. "
"Debido al error %s" % (ip_destination, port_destination, e))
except BrokenPipeError:
print("Se perdió la conexión con el servidor")
# Tell all nodes that we our node is being terminated.
def terminate_node(self):
# This variable will keep the number of attempts that are being executed
attempts = 0
# Wait for all connections to be closed and at least try three times.
while attempts < 3 and len(self.tcp_table.table) > 0:
for key in list(self.tcp_table.table):
try:
print("Enviando notificación de terminación a todos los nodos.")
connection_socket = self.tcp_table.search_connection(key[0], key[1])
connection_socket.send(bytes([0]))
except Exception:
print("No se pudo conectar con el nodo con dirección " + key[0] +
" y mascara " + str(key[1]) + ".")
# Now we wait a little bit, and after we check that all connections are close.
if len(self.tcp_table.table) > 0:
time.sleep(2)
attempts += 1
else:
break
if len(self.tcp_table.table) > 0:
print("Se intento eliminar este nodo de todas las conexiones, pero quedaron"
" algunas conexiones activas.")
else:
print("Se cerraron todas las conexiones con éxito.")
# Show our user the possible instructions he can accomplish with our node.
def listen(self):
# Print our menu.
print(BColors.WARNING + "Bienvenido!, Node: " + self.ip, ":", str(self.port) + BColors.ENDC)
print(BColors.OKGREEN + "Instrucciones: " + BColors.ENDC)
print(BColors.BOLD + "-1-" + BColors.ENDC, "Enviar un mensaje a otro nodo")
print(BColors.BOLD + "-2-" + BColors.ENDC, "Terminar a este nodo")
print(BColors.BOLD + "-3-" + BColors.ENDC, "Imprimir la tabla de alcanzabilidad")
print(BColors.BOLD + "-4-" + BColors.ENDC, "Salir")
user_input = input("Qué desea hacer?\n")
if user_input == "1":
self.send_message()
self.listen()
elif user_input == "2":
print("Eliminando nodo.")
self.terminate_node()
print("Terminando ejecucción.")
elif user_input == "3":
self.reachability_table.print_table()
self.listen()
elif user_input == "4":
print("Terminando ejecucción.")
else:
print("Por favor, escoja alguna de las opciones.")
self.listen()
| 31,124
|
https://github.com/Utar94/skillcraft/blob/master/api/src/SkillCraft.Core/Languages/Payloads/UpdateLanguagePayload.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
skillcraft
|
Utar94
|
C#
|
Code
| 11
| 37
|
namespace SkillCraft.Core.Languages.Payloads
{
public class UpdateLanguagePayload : SaveLanguagePayload
{
}
}
| 13,261
|
https://github.com/yongHacker/tp5_baiduNM/blob/master/application/data/o2o.sql
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
tp5_baiduNM
|
yongHacker
|
SQL
|
Code
| 1,111
| 3,356
|
#生活服务分类表
CREATE TABLE `o2o_category`(
`id` int(11) unsigned NOT NULL auto_increment,
`name` VARCHAR(50) NOT NULL DEFAULT '',
`parent_id` int(10) unsigned NOT NULL DEFAULT 0,
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY parent_id(`parent_id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#城市表
CREATE TABLE `o2o_city`(
`id` int(11) unsigned NOT NULL auto_increment,
`name` VARCHAR(50) NOT NULL DEFAULT '',
`uname` VARCHAR(50) NOT NULL DEFAULT '',
`parent_id` int(10) unsigned NOT NULL DEFAULT 0,
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY parent_id(`parent_id`),
UNIQUE KEY uname(`uname`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#商圈表
CREATE TABLE `o2o_area`(
`id` int(11) unsigned NOT NULL auto_increment,
`name` VARCHAR(50) NOT NULL DEFAULT '',
`city_id` int(11) unsigned NOT NULL DEFAULT 0,
`parent_id` int(10) unsigned NOT NULL DEFAULT 0,
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY parent_id(`parent_id`),
KEY city_id(`city_id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#商户表
CREATE TABLE `o2o_bis`(
`id` int(11) unsigned NOT NULL auto_increment,
`name` VARCHAR(50) NOT NULL DEFAULT '',
`email` VARCHAR(50) NOT NULL DEFAULT '',
`logo` VARCHAR(255) NOT NULL DEFAULT '',
`licence_logo` VARCHAR(255) NOT NULL DEFAULT '',
`description` text NOT NULL,
`city_id` int(11) unsigned NOT NULL DEFAULT 0,
`city_path` VARCHAR(50) NOT NULL DEFAULT '',
`bank_info` VARCHAR(50) NOT NULL DEFAULT '',
`money` decimal(20,2) NOT NULL DEFAULT '0.00',
`bank_name` VARCHAR(50) NOT NULL DEFAULT '',
`bank_user` VARCHAR(50) NOT NULL DEFAULT '',
`faren` VARCHAR(20) NOT NULL DEFAULT '',
`faren_tel` VARCHAR(20) NOT NULL DEFAULT '',
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY name(`name`),
KEY city_id(`city_id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#商户账号表
CREATE TABLE `o2o_bis_account`(
`id` int(11) unsigned NOT NULL auto_increment,
`username` VARCHAR(50) NOT NULL DEFAULT '',
`password` CHAR(32) NOT NULL DEFAULT '',
`code` VARCHAR(10) NOT NULL DEFAULT '',
`bis_id` int(11) unsigned NOT NULL DEFAULT 0,
`last_login_ip` VARCHAR(20) NOT NULL DEFAULT '',
`last_login_time` int(11) unsigned NOT NULL DEFAULT 0,
`is_main` tinyint(11) NOT NULL DEFAULT 0,
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY username(`username`),
KEY bis_id(`bis_id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#商户门店表
CREATE TABLE `o2o_bis_location`(
`id` int(11) unsigned NOT NULL auto_increment,
`name` VARCHAR(50) NOT NULL DEFAULT '',
`logo` VARCHAR(255) NOT NULL DEFAULT '',
`address` VARCHAR(255) NOT NULL DEFAULT '',
`tel` VARCHAR(20) NOT NULL DEFAULT '',
`contact` VARCHAR(20) NOT NULL DEFAULT '',
`xpoint` VARCHAR(20) NOT NULL DEFAULT '',
`ypoint` VARCHAR(20) NOT NULL DEFAULT '',
`bis_id` int(11) NOT NULL DEFAULT 0,
`open_time` int(11) NOT NULL DEFAULT 0,
`content` text NOT NULL,
`is_main` tinyint(11) NOT NULL DEFAULT 0,
`api_address` VARCHAR(255) NOT NULL DEFAULT '',
`city_id` int(11) unsigned NOT NULL DEFAULT 0,
`city_path` VARCHAR(50) NOT NULL DEFAULT '',
`category_id` int(11) unsigned NOT NULL DEFAULT 0,
`category_path` VARCHAR(50) NOT NULL DEFAULT 0,
`bank_info` VARCHAR(50) NOT NULL DEFAULT '',
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY name(`name`),
KEY city_id(`city_id`),
KEY bis_id(`bis_id`),
KEY category_id(`category_id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#团购商品表
CREATE TABLE `o2o_deal`(
`id` int(11) unsigned NOT NULL auto_increment,
`name` VARCHAR(100) NOT NULL DEFAULT '',
`category_id` int(11) NOT NULL DEFAULT 0,
`se_category_id` int(11) NOT NULL DEFAULT 0,
`bis_id` int(11) NOT NULL DEFAULT 0,
`location_idx` VARCHAR(100) NOT NULL DEFAULT 0,
`image` VARCHAR(200) NOT NULL DEFAULT 0,
`description` text NOT NULL,
`start_time` int(11) NOT NULL DEFAULT 0,
`end_time` int(11) NOT NULL DEFAULT 0,
`origin_price` decimal(20,2) NOT NULL DEFAULT '0.00',
`current_price` decimal(20,2) NOT NULL DEFAULT '0.00',
`city_id` int(11) NOT NULL DEFAULT 0,
`buy_count` int(11) NOT NULL DEFAULT 0,
`total_count` int(11) NOT NULL DEFAULT 0,
`coupons_begin_time` int(11) NOT NULL DEFAULT 0,
`coupons_end_time` int(11) NOT NULL DEFAULT 0,
`xpoint` VARCHAR(20) NOT NULL DEFAULT '',
`ypoint` VARCHAR(20) NOT NULL DEFAULT '',
`bis_account_id` int(10) NOT NULL DEFAULT 0,
`balence_price` decimal(20,2) NOT NULL DEFAULT '0.00',
`notes` text NOT NULL,
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY category_id(`category_id`),
KEY se_category_id(`se_category_id`),
KEY city_id(`city_id`),
KEY start_time(`start_time`),
KEY end_time(`end_time`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#用户表
CREATE TABLE `o2o_user`(
`id` int(11) unsigned NOT NULL auto_increment,
`username` VARCHAR(20) NOT NULL DEFAULT '',
`password` CHAR(32) NOT NULL DEFAULT '',
`code` VARCHAR(10) NOT NULL DEFAULT '',
`last_login_ip` VARCHAR(20) NOT NULL DEFAULT '',
`last_login_time` int(11) unsigned NOT NULL DEFAULT 0,
`email` VARCHAR(30) NOT NULL DEFAULT '',
`mobile` VARCHAR(20) NOT NULL DEFAULT '',
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY username(`username`),
UNIQUE KEY email(`email`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#推荐位表
CREATE TABLE `o2o_featured`(
`id` int(11) unsigned NOT NULL auto_increment,
`type` tinyint(1) NOT NULL DEFAULT 0,
`title` VARCHAR(30) NOT NULL DEFAULT '',
`image` VARCHAR(255) NOT NULL DEFAULT '',
`url` VARCHAR(255) NOT NULL DEFAULT '',
`description` VARCHAR(255) NOT NULL DEFAULT '',
`listorder` int(8) unsigned NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 0,
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#订单表
CREATE TABLE `o2o_order`(
`id` int(11) unsigned NOT NULL auto_increment,
`out_trade_no` VARCHAR(100) NOT NULL DEFAULT '',
`transaction_id` VARCHAR(100) NOT NULL DEFAULT '',
`user_id` int(11) NOT NULL DEFAULT 0,
`username` VARCHAR(50) NOT NULL DEFAULT '',
`pay_time` VARCHAR(25) NOT NULL DEFAULT '',
`payment_id` tinyint(1) NOT NULL DEFAULT 1,
`deal_id` int(11) NOT NULL DEFAULT 0,
`deal_count` int(11) NOT NULL DEFAULT 0,
`pay_status` tinyint(1) NOT NULL DEFAULT 0 COMMENT '支付状态 0:未支付 1:支付成功 2:支付失败',
`total_price` DECIMAL(20,2) NOT NULL DEFAULT '0.00',
`pay_amount` DECIMAL(20,2) NOT NULL DEFAULT '0.00',
`status` tinyint(1) NOT NULL DEFAULT 1,
`referer` VARCHAR(255) NOT NULL DEFAULT '',
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY out_trade_no(`out_trade_no`),
KEY user_id(`user_id`),
KEY create_time(`create_time`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#消费券表
CREATE TABLE `o2o_coupons`(
`id` int(11) unsigned NOT NULL auto_increment,
`sn` VARCHAR(100) NOT NULL DEFAULT '',
`password` VARCHAR(100) NOT NULL DEFAULT '',
`user_id` int(11) NOT NULL DEFAULT 0,
`deal_id` int(11) NOT NULL DEFAULT 0,
`order_id` int(11) NOT NULL DEFAULT 0,
`status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '0:生成未发送给用户 1:已发送给用户 2:用户已使用 3:禁用',
`create_time` int(11) unsigned NOT NULL DEFAULT 0,
`update_time` int(11) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY sn(`sn`),
KEY user_id(`user_id`),
KEY deal_id(`deal_id`),
KEY create_time(`create_time`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
| 22,314
|
https://github.com/figroc/spotless/blob/master/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskImpl.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
spotless
|
figroc
|
Java
|
Code
| 409
| 1,255
|
/*
* Copyright 2016-2021 DiffPlug
*
* 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 com.diffplug.gradle.spotless;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Comparator;
import org.gradle.api.GradleException;
import org.gradle.api.tasks.CacheableTask;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.ChangeType;
import org.gradle.work.FileChange;
import org.gradle.work.InputChanges;
import com.diffplug.common.base.StringPrinter;
import com.diffplug.spotless.Formatter;
import com.diffplug.spotless.PaddedCell;
@CacheableTask
public class SpotlessTaskImpl extends SpotlessTask {
@TaskAction
public void performAction(InputChanges inputs) throws Exception {
if (target == null) {
throw new GradleException("You must specify 'Iterable<File> target'");
}
if (!inputs.isIncremental()) {
getLogger().info("Not incremental: removing prior outputs");
getProject().delete(outputDirectory);
Files.createDirectories(outputDirectory.toPath());
}
try (Formatter formatter = buildFormatter()) {
for (FileChange fileChange : inputs.getFileChanges(target)) {
File input = fileChange.getFile();
if (fileChange.getChangeType() == ChangeType.REMOVED) {
deletePreviousResult(input);
} else {
if (input.isFile()) {
processInputFile(formatter, input);
}
}
}
}
}
private void processInputFile(Formatter formatter, File input) throws IOException {
File output = getOutputFile(input);
getLogger().debug("Applying format to " + input + " and writing to " + output);
PaddedCell.DirtyState dirtyState;
if (ratchet != null && ratchet.isClean(getProject(), rootTreeSha, input)) {
dirtyState = PaddedCell.isClean();
} else {
dirtyState = PaddedCell.calculateDirtyState(formatter, input);
}
if (dirtyState.isClean()) {
// Remove previous output if it exists
Files.deleteIfExists(output.toPath());
} else if (dirtyState.didNotConverge()) {
getLogger().warn("Skipping '" + input + "' because it does not converge. Run {@code spotlessDiagnose} to understand why");
} else {
Path parentDir = output.toPath().getParent();
if (parentDir == null) {
throw new IllegalStateException("Every file has a parent folder.");
}
Files.createDirectories(parentDir);
// Need to copy the original file to the tmp location just to remember the file attributes
Files.copy(input.toPath(), output.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
dirtyState.writeCanonicalTo(output);
}
}
private void deletePreviousResult(File input) throws IOException {
File output = getOutputFile(input);
if (output.isDirectory()) {
Files.walk(output.toPath())
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} else {
Files.deleteIfExists(output.toPath());
}
}
private File getOutputFile(File input) {
String outputFileName = FormatExtension.relativize(getProject().getProjectDir(), input);
if (outputFileName == null) {
throw new IllegalArgumentException(StringPrinter.buildString(printer -> {
printer.println("Spotless error! All target files must be within the project root. In project " + getProject().getPath());
printer.println(" root dir: " + getProject().getProjectDir().getAbsolutePath());
printer.println(" target: " + input.getAbsolutePath());
}));
}
return new File(outputDirectory, outputFileName);
}
}
| 38,158
|
https://github.com/simeonpilgrim/opendct/blob/master/src/main/java/opendct/nanohttpd/client/api/Discovery.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
opendct
|
simeonpilgrim
|
Java
|
Code
| 1,050
| 3,107
|
/*
* Copyright 2015-2016 The OpenDCT Authors. All Rights Reserved
* 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 opendct.nanohttpd.client.api;
import com.google.gson.JsonElement;
import opendct.nanohttpd.client.Plugin;
import opendct.nanohttpd.client.ServerManager;
import opendct.nanohttpd.pojo.JsonDiscoverer;
import opendct.nanohttpd.pojo.JsonException;
import opendct.nanohttpd.pojo.PojoUtil;
import java.util.ArrayList;
import java.util.List;
public class Discovery {
public static final String DISCOVERY = "/discovery";
public static final String DISCOVERY_ENABLED_PROP = "opendct/enabled_discovery";
public static final String DISCOVERY_ENABLED_HELP = "Select the capture device discovery" +
" methods to be enabled.";
public static final String DISCOVERY_ENABLED_LABEL = "Select Enabled Discovery Methods";
public static final String DISCOVERY_SELECT_NONE = "None";
public static final String DISCOVERY_SELECT_PROP = "opendct/selected_discovery";
public static final String DISCOVERY_SELECT_HELP = "Select a discovery method to view/modify" +
" its properties below. Select '" + DISCOVERY_SELECT_NONE + "' to stop displaying" +
" properties for any capture device.";
public static final String DISCOVERY_SELECT_LABEL = "Show/Edit Capture Device Properties";
private static String selectedDiscovery = null;
private static JsonDiscoverer currentDiscoverer;
private static OptionsHandler currentOptions;
public static void newServer() {
selectedDiscovery = null;
refreshOptions();
}
private static void refreshOptions() {
currentOptions = null;
currentDiscoverer = null;
}
private static String[] getAllDiscovererNames(String server) {
String returnValue[] = ServerManager.getInstance().getJson(server, String[].class, DISCOVERY);
return returnValue != null ? returnValue : new String[0];
}
private static JsonDiscoverer[] getAllDiscoverers(String server) {
String names[] = getAllDiscovererNames(server);
StringBuilder builder = new StringBuilder();
for (String name : names) {
builder.append('/').append(ServerManager.encodeFile(name));
}
JsonDiscoverer discoverers[] = ServerManager.getInstance().getJson(server, JsonDiscoverer[].class, DISCOVERY + builder.toString());
return discoverers != null ? discoverers : new JsonDiscoverer[0];
}
private static String[] getEnabledDiscoverers(String server) {
String names[] = getAllDiscovererNames(server);
StringBuilder builder = new StringBuilder();
for (String name : names) {
builder.append('/').append(ServerManager.encodeFile(name));
}
builder.append("?name=true&enabled=true");
JsonDiscoverer discoverers[] = ServerManager.getInstance().getJson(server, JsonDiscoverer[].class, DISCOVERY + builder.toString());
if (discoverers == null) {
return new String[0];
}
List<String> returnValues = new ArrayList<>(discoverers.length);
for (JsonDiscoverer discoverer : discoverers) {
if (discoverer.isEnabled() == null || discoverer.isEnabled()) {
returnValues.add(discoverer.getName());
}
}
return returnValues.toArray(new String[returnValues.size()]);
}
private static void setEnabledDiscovererNames(String server, String discovererNames[]) {
JsonDiscoverer discoverers[] = getAllDiscoverers(server);
StringBuilder enable = new StringBuilder(DISCOVERY);
StringBuilder disable = new StringBuilder(DISCOVERY);
for (String discovererString : discovererNames) {
if (discovererString == null) {
continue;
}
for (int i = 0; i < discoverers.length; i++) {
if (discovererNames[i] == null) {
continue;
}
if (discoverers[i].getName().equals(discovererString)) {
// Only enable discovery methods that actually show they are not currently
// enabled.
if (!discoverers[i].isEnabled()) {
enable.append('/').append(ServerManager.encodeFile(discovererString));
}
// When we find a discovery method is on the enabled list, make it null so
// that we can make sure everything that is not intended to be enabled gets
// disabled later.
discoverers[i] = null;
break;
}
}
}
for (JsonDiscoverer discoverer : discoverers) {
if (discoverer != null && discoverer.isEnabled()) {
disable.append('/').append(ServerManager.encodeFile(discoverer.getName()));
}
}
// Disable first in the rare occurrence that loading these new discovery method creates a
// big spike in memory usage that could cause problems.
if (disable.length() > DISCOVERY.length()) {
JsonElement element = PojoUtil.setOption("disableDevice", "true");
ServerManager.getInstance().postJson(server, JsonException.class, enable.toString(), element);
}
if (enable.length() > DISCOVERY.length()) {
JsonElement element = PojoUtil.setOption("enableDevice", "true");
ServerManager.getInstance().postJson(server, JsonException.class, enable.toString(), element);
}
}
private static JsonDiscoverer getDiscoverer(String server) {
JsonDiscoverer cachedDiscoverer = currentDiscoverer;
if (cachedDiscoverer == null && selectedDiscovery != null) {
JsonDiscoverer discoverers[] = ServerManager.getInstance().getJson(server, JsonDiscoverer[].class, DISCOVERY + "/" + ServerManager.encodeFile(selectedDiscovery));
if (discoverers != null && discoverers.length != 0) {
cachedDiscoverer = discoverers[0];
currentDiscoverer = cachedDiscoverer;
}
}
return cachedDiscoverer;
}
private static OptionsHandler getOptions(String server, JsonDiscoverer discoverer) {
OptionsHandler cachedOptions = currentOptions;
if (cachedOptions == null && discoverer != null) {
cachedOptions = new OptionsHandler(server, DISCOVERY, discoverer.getOptions());
currentOptions = cachedOptions;
}
return cachedOptions;
}
public static String[] getConfigSettings(String server) {
JsonDiscoverer cachedDiscoverer = getDiscoverer(server);
OptionsHandler cachedOptions = getOptions(server, cachedDiscoverer);
String options[];
if (cachedOptions != null) {
options = cachedOptions.getConfigSettings();
} else {
return new String[] { DISCOVERY_ENABLED_PROP, DISCOVERY_SELECT_PROP };
}
String returnValue[] = new String[options.length + 2];
returnValue[0] = DISCOVERY_ENABLED_PROP;
returnValue[1] = DISCOVERY_SELECT_PROP;
System.arraycopy(options, 0, returnValue, 2, options.length);
return returnValue;
}
public static String getConfigValue(String server, String setting) {
switch (setting) {
case DISCOVERY_SELECT_PROP:
String returnValue = selectedDiscovery;
if (returnValue == null) {
return DISCOVERY_SELECT_NONE;
} else {
return returnValue;
}
default:
JsonDiscoverer cachedDiscoverer = getDiscoverer(server);
OptionsHandler cachedOptions = getOptions(server, cachedDiscoverer);
if (cachedOptions != null) {
return cachedOptions.getConfigValue(setting);
}
}
return null;
}
public static String[] getConfigValues(String server, String setting) {
switch (setting) {
case DISCOVERY_ENABLED_PROP:
return getEnabledDiscoverers(server);
default:
JsonDiscoverer cachedDiscoverer = getDiscoverer(server);
OptionsHandler cachedOptions = getOptions(server, cachedDiscoverer);
if (cachedOptions != null) {
return cachedOptions.getConfigValues(setting);
}
}
return null;
}
public static int getConfigType(String server, String setting) {
switch (setting) {
case DISCOVERY_ENABLED_PROP:
return Plugin.CONFIG_MULTICHOICE;
case DISCOVERY_SELECT_PROP:
return Plugin.CONFIG_CHOICE;
default:
JsonDiscoverer cachedDiscoverer = getDiscoverer(server);
OptionsHandler cachedOptions = getOptions(server, cachedDiscoverer);
if (cachedOptions != null) {
return cachedOptions.getConfigType(setting);
}
}
return 0;
}
public static void setConfigValue(String server, String setting, String value) {
switch (setting) {
case DISCOVERY_SELECT_PROP:
if (DISCOVERY_SELECT_NONE.equals(value)) {
selectedDiscovery = null;
} else {
selectedDiscovery = value;
}
refreshOptions();
break;
default:
JsonDiscoverer cachedDiscoverer = getDiscoverer(server);
OptionsHandler cachedOptions = getOptions(server, cachedDiscoverer);
if (cachedOptions != null) {
cachedOptions.setConfigValue(setting, value);
refreshOptions();
}
}
}
public static void setConfigValues(String server, String setting, String[] values) {
switch (setting) {
case DISCOVERY_ENABLED_PROP:
Discovery.setEnabledDiscovererNames(server, values);
break;
default:
JsonDiscoverer cachedDiscoverer = getDiscoverer(server);
OptionsHandler cachedOptions = getOptions(server, cachedDiscoverer);
if (cachedOptions != null) {
cachedOptions.setConfigValues(setting, values);
refreshOptions();
}
}
}
public static String[] getConfigOptions(String server, String setting) {
switch (setting) {
case DISCOVERY_ENABLED_PROP:
case DISCOVERY_SELECT_PROP:
return getAllDiscovererNames(server);
default:
JsonDiscoverer cachedDiscoverer = getDiscoverer(server);
OptionsHandler cachedOptions = getOptions(server, cachedDiscoverer);
if (cachedOptions != null) {
return cachedOptions.getConfigOptions(setting);
}
}
return null;
}
public static String getConfigHelpText(String server, String setting) {
switch (setting) {
case DISCOVERY_ENABLED_PROP:
return DISCOVERY_ENABLED_HELP;
case DISCOVERY_SELECT_PROP:
return DISCOVERY_SELECT_HELP;
default:
JsonDiscoverer cachedDiscoverer = getDiscoverer(server);
OptionsHandler cachedOptions = getOptions(server, cachedDiscoverer);
if (cachedOptions != null) {
return cachedOptions.getConfigHelpText(setting);
}
}
return null;
}
public static String getConfigLabel(String server, String setting) {
switch (setting) {
case DISCOVERY_ENABLED_PROP:
return DISCOVERY_ENABLED_LABEL;
case DISCOVERY_SELECT_PROP:
return DISCOVERY_SELECT_LABEL;
default:
OptionsHandler cachedOptions = getOptions(server, getDiscoverer(server));
if (cachedOptions != null) {
return cachedOptions.getConfigLabel(setting);
}
}
return null;
}
}
| 26,186
|
https://github.com/yyyyffqqqq/jianshuDemo-OC/blob/master/jianshuDemo/jianshuDemo/TopWindow.m
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
jianshuDemo-OC
|
yyyyffqqqq
|
Objective-C
|
Code
| 109
| 392
|
//
// TopWindow.m
// jianshuDemo
//
// Created by quan on 16/8/3.
// Copyright © 2016年 quan. All rights reserved.
//
#import "TopWindow.h"
#import <UIKit/UIKit.h>
@implementation TopWindow
+ (void)scrollViewScrollToTop {
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[self searchScrollViewInView:window];
}
+ (BOOL)isShowingOnKeyWindow:(UIView *)view {
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
CGRect newFrame = [keyWindow convertRect:view.frame fromView:view.superview];
CGRect winBounds = keyWindow.bounds;
BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);
return !view.isHidden && view.alpha > 0.01 && view.window == keyWindow && intersects;
}
+ (void)searchScrollViewInView:(UIView *)supView {
for (UIScrollView *subView in supView.subviews) {
if ([subView isKindOfClass:[UIScrollView class]] && [self isShowingOnKeyWindow:supView]) {
CGPoint offset = subView.contentOffset;
offset.y = -subView.contentInset.top;
[subView setContentOffset:offset animated:YES];
}
[self searchScrollViewInView:subView];
}
}
@end
| 47,524
|
https://github.com/krudowicz/FriendlyBudget2/blob/master/FriendlyBudget2/DTO/Expenditure.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
FriendlyBudget2
|
krudowicz
|
C#
|
Code
| 71
| 160
|
using FriendlyBudget2.Core.Abstracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FriendlyBudget2.DTO
{
class Expenditure : DataObject
{
public long Id { get; set; }
public string Name { get; set; }
public long AmountMain { get; set; }
public long AmountSecondary { get; set; }
public bool isConstant { get; set; }
public DateTime Date { get; set; }
public ExpenditureCategory Category { get; set; }
}
}
| 18,953
|
https://github.com/PeroSar/termux-packages/blob/master/packages/aubio/build.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
termux-packages
|
PeroSar
|
Shell
|
Code
| 42
| 359
|
TERMUX_PKG_HOMEPAGE=https://aubio.org/
TERMUX_PKG_DESCRIPTION="A library to label music and sounds"
TERMUX_PKG_LICENSE="GPL-3.0"
TERMUX_PKG_MAINTAINER="@termux"
TERMUX_PKG_VERSION=0.4.9
TERMUX_PKG_SRCURL=https://aubio.org/pub/aubio-${TERMUX_PKG_VERSION}.tar.bz2
TERMUX_PKG_SHA256=d48282ae4dab83b3dc94c16cf011bcb63835c1c02b515490e1883049c3d1f3da
TERMUX_PKG_DEPENDS="ffmpeg, libsamplerate, libsndfile"
TERMUX_PKG_BUILD_IN_SRC=true
termux_step_pre_configure() {
CPPFLAGS+=" -DFF_API_LAVF_AVCTX"
}
termux_step_configure() {
./waf configure \
--prefix=$TERMUX_PREFIX \
LINKFLAGS="$LDFLAGS" \
$TERMUX_PKG_EXTRA_CONFIGURE_ARGS
}
termux_step_make() {
./waf
}
termux_step_make_install() {
./waf install
}
| 40,756
|
https://github.com/Shofiul-Alam/magento-app/blob/master/src/vendor/magento/module-asynchronous-operations/Model/ResourceModel/System/Message/Collection/Synchronized/Plugin.php
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, MIT, AFL-2.1, AFL-3.0, OSL-3.0
| 2,019
|
magento-app
|
Shofiul-Alam
|
PHP
|
Code
| 421
| 1,743
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\AsynchronousOperations\Model\ResourceModel\System\Message\Collection\Synchronized;
/**
* Class Plugin to add bulks related notification messages to Synchronized Collection
*/
class Plugin
{
/**
* @var \Magento\AdminNotification\Model\System\MessageFactory
*/
private $messageFactory;
/**
* @var \Magento\Framework\Bulk\BulkStatusInterface
*/
private $bulkStatus;
/**
* @var \Magento\Authorization\Model\UserContextInterface
*/
private $userContext;
/**
* @var \Magento\AsynchronousOperations\Model\Operation\Details
*/
private $operationDetails;
/**
* @var \Magento\AsynchronousOperations\Model\BulkNotificationManagement
*/
private $bulkNotificationManagement;
/**
* @var \Magento\Framework\AuthorizationInterface
*/
private $authorization;
/**
* @var \Magento\AsynchronousOperations\Model\StatusMapper
*/
private $statusMapper;
/**
* Plugin constructor.
*
* @param \Magento\AdminNotification\Model\System\MessageFactory $messageFactory
* @param \Magento\Framework\Bulk\BulkStatusInterface $bulkStatus
* @param \Magento\AsynchronousOperations\Model\BulkNotificationManagement $bulkNotificationManagement
* @param \Magento\Authorization\Model\UserContextInterface $userContext
* @param \Magento\AsynchronousOperations\Model\Operation\Details $operationDetails
* @param \Magento\Framework\AuthorizationInterface $authorization
* @param \Magento\AsynchronousOperations\Model\StatusMapper $statusMapper
*/
public function __construct(
\Magento\AdminNotification\Model\System\MessageFactory $messageFactory,
\Magento\Framework\Bulk\BulkStatusInterface $bulkStatus,
\Magento\AsynchronousOperations\Model\BulkNotificationManagement $bulkNotificationManagement,
\Magento\Authorization\Model\UserContextInterface $userContext,
\Magento\AsynchronousOperations\Model\Operation\Details $operationDetails,
\Magento\Framework\AuthorizationInterface $authorization,
\Magento\AsynchronousOperations\Model\StatusMapper $statusMapper
) {
$this->messageFactory = $messageFactory;
$this->bulkStatus = $bulkStatus;
$this->userContext = $userContext;
$this->operationDetails = $operationDetails;
$this->bulkNotificationManagement = $bulkNotificationManagement;
$this->authorization = $authorization;
$this->statusMapper = $statusMapper;
}
/**
* Adding bulk related messages to notification area
*
* @param \Magento\AdminNotification\Model\ResourceModel\System\Message\Collection\Synchronized $collection
* @param array $result
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterToArray(
\Magento\AdminNotification\Model\ResourceModel\System\Message\Collection\Synchronized $collection,
$result
) {
if (!$this->authorization->isAllowed('Magento_Logging::system_magento_logging_bulk_operations')) {
return $result;
}
$userId = $this->userContext->getUserId();
$userBulks = $this->bulkStatus->getBulksByUser($userId);
$acknowledgedBulks = $this->getAcknowledgedBulksUuid(
$this->bulkNotificationManagement->getAcknowledgedBulksByUser($userId)
);
$bulkMessages = [];
foreach ($userBulks as $bulk) {
$bulkUuid = $bulk->getBulkId();
if (!in_array($bulkUuid, $acknowledgedBulks)) {
$details = $this->operationDetails->getDetails($bulkUuid);
$text = $this->getText($details);
$bulkStatus = $this->statusMapper->operationStatusToBulkSummaryStatus($bulk->getStatus());
if ($bulkStatus === \Magento\Framework\Bulk\BulkSummaryInterface::IN_PROGRESS) {
$text = __('%1 item(s) are currently being updated.', $details['operations_total']) . $text;
}
$data = [
'data' => [
'text' => __('Task "%1": ', $bulk->getDescription()) . $text,
'severity' => \Magento\Framework\Notification\MessageInterface::SEVERITY_MAJOR,
'identity' => md5('bulk' . $bulkUuid),
'uuid' => $bulkUuid,
'status' => $bulkStatus,
'created_at' => $bulk->getStartTime()
]
];
$bulkMessages[] = $this->messageFactory->create($data)->toArray();
}
}
if (!empty($bulkMessages)) {
$result['totalRecords'] += count($bulkMessages);
$bulkMessages = array_slice($bulkMessages, 0, 5);
$result['items'] = array_merge($bulkMessages, $result['items']);
}
return $result;
}
/**
* Get Bulk notification message
*
* @param array $operationDetails
* @return \Magento\Framework\Phrase|string
*/
private function getText($operationDetails)
{
if (0 == $operationDetails['operations_successful'] && 0 == $operationDetails['operations_failed']) {
return __('%1 item(s) have been scheduled for update.', $operationDetails['operations_total']);
}
$summaryReport = '';
if ($operationDetails['operations_successful'] > 0) {
$summaryReport .= __(
'%1 item(s) have been successfully updated.',
$operationDetails['operations_successful']
);
}
if ($operationDetails['operations_failed'] > 0) {
$summaryReport .= '<strong>'
. __('%1 item(s) failed to update', $operationDetails['operations_failed'])
. '</strong>';
}
return $summaryReport;
}
/**
* Get array with acknowledgedBulksUuid
*
* @param array $acknowledgedBulks
* @return array
*/
private function getAcknowledgedBulksUuid($acknowledgedBulks)
{
$acknowledgedBulksArray = [];
foreach ($acknowledgedBulks as $bulk) {
$acknowledgedBulksArray[] = $bulk->getBulkId();
}
return $acknowledgedBulksArray;
}
}
| 3,367
|
https://github.com/LuckyDmitry/KinoLenta/blob/master/KinoLenta/MovieDetail/CollectionViewCells/DetailMovieImageCollectionViewCell.swift
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
KinoLenta
|
LuckyDmitry
|
Swift
|
Code
| 79
| 291
|
//
// DetailMovieImageItemCollectionViewCell.swift
// KinoLenta
//
// Created by Dmitry Trifonov on 11.12.2021.
//
import UIKit
final class DetailMovieImageCollectionViewCell: UICollectionViewCell {
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
return imageView
}()
var cancellation: CancellationHandle?
var insets: UIEdgeInsets = .zero
private let layoutManager = AnyLayoutManager<DetailMovieImageCollectionViewCell>(DetailMovieImageLayoutManager())
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutManager.applyLayout(for: self, bounds: bounds.inset(by: insets))
}
}
| 44,123
|
https://github.com/jm-begon/randconv/blob/master/randconv/image/aggregator.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,016
|
randconv
|
jm-begon
|
Python
|
Code
| 1,520
| 3,955
|
# -*- coding: utf-8 -*-
"""
An :class:`Aggregator` maps a 2D or 3D numpy array to a smaller one by
applying a function on a contiguous bloc of pixels.
This module contains several predefined Aggregators.
"""
__author__ = "Begon Jean-Michel <jm.begon@gmail.com>"
__copyright__ = "3-clause BSD License"
__date__ = "20 January 2015"
import numpy as np
from math import ceil, floor
from .pooler import Pooler
__all__ = ["Aggregator", "FixSizeAggregator", "AverageAggregator",
"MaximumAggregator", "MinimumAggregator"]
class Aggregator(Pooler):
"""
==========
Aggregator
==========
An Aggregator maps a 2D or 3D numpy array to a smaller one (of same
dimentionnality) by applying a function on a contiguous bloc of pixels.
**2D array** : The Aggregator defines a neighborhood box and a function.
The function map the content of the box into a single value. The box moves
around the array so as to include each value only once. Therefore,
the result is a smaller array.
**3D array** : Proceeds in the same fashion as 2D by iterating over the 3rd
dimension. The results are appended so as to form a 3D output.
"""
def __init__(self, aggregating_function, neighborhood_width,
neighborhood_height, include_offset=False):
"""
Construct an :class:`Aggregator`
Parameters
----------
aggregating_function : callable
A function which maps a 2D (numpy) array into a single value
neighborhood_width : int
The neighborhood window width
neighborhood_height : int
The neighborhood window height
include_offset: boolean (default : False)
Whether to include the offset or treat it separately. The offset
is the remaining part of the division of the array size by
neigborhood window size.
if True, the last neighborhood windows are enlarge to treat
the offset
if False, the offset is treated separately
"""
self._init(aggregating_function, neighborhood_width,
neighborhood_height, include_offset)
def _init(self, aggregating_function, neighborhood_width,
neighborhood_height, include_offset=False):
# """
# Construct an :class:`Aggregator`
#
# Parameters
# ----------
# aggregating_function : callable
# A function which maps a 2D (numpy) array
# neighborhood_width : int
# The neighborhood window width
# neighborhood_height : int
# The neighborhood window height
# include_offset: boolean
# Whether to include the offset or treat it separately. The offset
# is the remaining part of the division of the array size by
# neigborhood window size.
# if True, the last neighborhood windows are enlarge to treat
# the offset
# if False, the offset is treated separately
# """
self._agg_func = aggregating_function
self._neighb_width = neighborhood_width
self._neigh_height = neighborhood_height
self._include_offset = include_offset
def _get_boxes(self, np_width, np_height):
# """
# Return the number of horizontal and vertical division as well as the
# boxes use by the Aggregator
#
# Parameters
# ----------
# np_width : int
# The width of the original array
# np_height: int
# The hieght of the original array
#
# Return
# ------
# nb_hz_steps : int
# the number of horizontal steps
# nb_v_steps : int
# the number of vertical steps
# boxes : list (of box)
# A box is a tuple (Hz coord, V coord, Hz origin, V origin,
# Hz destination, V destination)
# origin isincluded and destination excluded : [origin, destination)
# """
nb_hz_steps = np_width/self._neighb_width
nb_v_steps = np_height/self._neigh_height
if self._include_offset:
nb_hz_steps = int(floor(nb_hz_steps))
nb_v_steps = int(floor(nb_v_steps))
else:
nb_hz_steps = int(ceil(nb_hz_steps))
nb_v_steps = int(ceil(nb_v_steps))
boxes = []
#All internal
for i in range(nb_hz_steps-1):
for j in range(nb_v_steps-1):
hzOrigin = i*self._neighb_width
hzDest = hzOrigin+self._neighb_width
vOrigin = j*self._neigh_height
vDest = vOrigin+self._neigh_height
boxes.append((i, j, hzOrigin, vOrigin, hzDest, vDest))
#Last column
hzOrigin = i*self._neighb_width
hzDest = hzOrigin+self._neighb_width
vOrigin = (nb_v_steps-1)*self._neigh_height
vDest = np_height
boxes.append((i, nb_v_steps-1, hzOrigin, vOrigin, hzDest, vDest))
#Last line
for j in range(nb_v_steps-1):
hzOrigin = (nb_hz_steps-1)*self._neighb_width
hzDest = np_width
vOrigin = j*self._neigh_height
vDest = vOrigin+self._neigh_height
boxes.append((nb_hz_steps-1, j, hzOrigin, vOrigin, hzDest, vDest))
#Last line+col
hzOrigin = (nb_hz_steps-1)*self._neighb_width
hzDest = np_width
vOrigin = (nb_v_steps-1)*self._neigh_height
vDest = np_height
boxes.append((nb_hz_steps-1, nb_v_steps-1, hzOrigin, vOrigin,
hzDest, vDest))
return nb_hz_steps, nb_v_steps, boxes
def _do_aggregate(self, array2D):
# """
# Aggregate the 2D array
#
# Parameters
# ----------
# array2D : 2D numpy array
# The array to aggregate
#
# Return
# ------
# aggregated : 2D numpy array
# The aggregated numpy array
# """
np_height, np_width = array2D.shape
nb_hz_steps, nb_v_steps, boxes = self._get_boxes(np_width, np_height)
aggregArray = np.zeros((nb_v_steps, nb_hz_steps))
for box in boxes:
newCol, new_row, originCol, originRow, destCol, destRow = box
aggregArray[new_row, newCol] = self._agg_func(
array2D[originRow:destRow, originCol:destCol])
return aggregArray
def aggregate(self, np_array):
"""
Aggregate the `np_array`
Parameters
-----------
np_array : 2D or 3D numpy array
The array to aggregate
Return
-------
aggregated : 2D or 3D numpy array (depending on `np_array`)
The aggregated array
"""
if len(np_array.shape) < 2 or len(np_array.shape) > 3:
raise ValueError
if len(np_array.shape) == 2:
#2D case
return self._do_aggregate(np_array)
#3D case
layers = []
for i in range(np_array.shape[2]):
layers.append(self._do_aggregate(np_array[:, :, i]))
return np.dstack(layers)
def __call__(self, np_array):
"""
Delegate to :meth:`aggregate`
"""
return self.aggregate(np_array)
def pool(self, np_array):
"""
Delegate to :meth:`aggregate`
"""
return self.aggregate(np_array)
class FixSizeAggregator(Aggregator):
"""
=================
FixSizeAggregator
=================
A :class:`FixSizeAggregator` operates on arrays of predefined sizes.
see :class:`Aggregator`
"""
def __init__(self, aggregating_function, neighborhood_width,
neighborhood_height, np_width, np_height,
include_offset=False):
"""
Construct a :class:`FixSizeAggregator`
Parameters
-----------
aggregating_function : callable
A function which maps a 2D (numpy) array
neighborhood_width : int
The neighborhood window width
neighborhood_height : int
The neighborhood window height
np_width : int
The width of the array this :class:`Aggregator` will treat
np_height : int
The height of the array this :class:`Aggregator` will treat
include_offset: boolean
Whether to include the offset or treat it separately. The offset
is the remaining part of the division of the array size by
neigborhood window size.
if True, the last neighborhood windows are enlarge to treat
the offset
if False, the offset is treated separately
"""
self._init2(aggregating_function, neighborhood_width,
neighborhood_height, include_offset, np_width, np_height)
def _init2(self, aggregating_function, neighborhood_width,
neighborhood_height, include_offset, np_width, np_height):
# """
# Construct a :class:`FixSizeAggregator`
#
# Parameters
# -----------
# aggregating_function : callable
# A function which maps a 2D (numpy) array
# neighborhood_width : int
# The neighborhood window width
# neighborhood_height : int
# The neighborhood window height
# np_width : int
# The width of the array this :class:`Aggregator` will treat
# np_height : int
# The height of the array this :class:`Aggregator` will treat
# include_offset: boolean
# Whether to include the offset or treat it separately. The offset
# is the remaining part of the division of the array size by
# neigborhood window size.
# if True, the last neighborhood windows are enlarge to treat
# the offset
# if False, the offset is treated separately
# """
self._init(aggregating_function, neighborhood_width,
neighborhood_height, include_offset)
(self._nb_hz_steps, self._nb_v_steps,
self._boxes) = self._get_boxes(np_width, np_height)
def _do_aggregate(self, array2D):
# """
# Aggregate the 2D array
#
# Parameters
# ----------
# array2D : 2D numpy array
# The array to aggregate
#
# Return
# ------
# aggregated : 2D numpy array
# The aggregated numpy array
# """
aggregArray = np.zeros((self._nb_v_steps, self._nb_hz_steps))
for box in self._boxes:
newCol, new_row, originCol, originRow, destCol, destRow = box
aggregArray[new_row, newCol] = self._agg_func(
array2D[originRow:destRow, originCol:destCol])
return aggregArray
class AverageAggregator(FixSizeAggregator):
"""
=================
AverageAggregator
=================
A :class:`AverageAggregator` computes the arithmetic average of the
neighborhood
See also :class:`Aggregator`, :class:`FixSizeAggregator`
"""
def __init__(self, neighborhood_width, neighborhood_height,
np_width, np_height, include_offset=False):
"""
Construct a :class:`AverageAggregator`
Parameters
-----------
neighborhood_width : int
The neighborhood window width
neighborhood_height : int
The neighborhood window height
np_width : int
The width of the array this :class:`Aggregator` will treat
np_height : int
The height of the array this :class:`Aggregator` will treat
include_offset: boolean
Whether to include the offset or treat it separately. The offset
is the remaining part of the division of the array size by
neigborhood window size.
if True, the last neighborhood windows are enlarge to treat
the offset
if False, the offset is treated separately
"""
self._init2(self._mean, neighborhood_width, neighborhood_height,
include_offset, np_width, np_height)
def _mean(self, x):
return x.mean()
class MaximumAggregator(FixSizeAggregator):
"""
=================
MaximumAggregator
=================
A :class:`MaximumAggregator` computes the maximum of the neighborhood
See also :class:`Aggregator`, :class:`FixSizeAggregator`
"""
def __init__(self, neighborhood_width, neighborhood_height, np_width,
np_height, include_offset=False):
"""
Construct a :class:`MaximumAggregator`
Parameters
-----------
neighborhood_width : int
The neighborhood window width
neighborhood_height : int
The neighborhood window height
np_width : int
The width of the array this :class:`Aggregator` will treat
np_height : int
The height of the array this :class:`Aggregator` will treat
include_offset: boolean
Whether to include the offset or treat it separately. The offset
is the remaining part of the division of the array size by
neigborhood window size.
if True, the last neighborhood windows are enlarge to treat
the offset
if False, the offset is treated separately
"""
self._init2(self._max, neighborhood_width, neighborhood_height,
include_offset, np_width, np_height)
def _max(self, x):
return x.max()
class MinimumAggregator(FixSizeAggregator):
"""
=================
MinimumAggregator
=================
A :class:`MinimumAggregator` computes the minimum of the neighborhood
See also :class:`Aggregator`, :class:`FixSizeAggregator`
"""
def __init__(self, neighborhood_width, neighborhood_height, np_width,
np_height, include_offset=False):
"""
Construct a :class:`MinimumAggregator`
Parameters
-----------
neighborhood_width : int
The neighborhood window width
neighborhood_height : int
The neighborhood window height
np_width : int
The width of the array this :class:`Aggregator` will treat
np_height : int
The height of the array this :class:`Aggregator` will treat
include_offset: boolean
Whether to include the offset or treat it separately. The offset
is the remaining part of the division of the array size by
neigborhood window size.
if True, the last neighborhood windows are enlarge to treat
the offset
if False, the offset is treated separately
"""
self._init2(self._min, neighborhood_width, neighborhood_height,
include_offset, np_width, np_height)
def _min(self, x):
return x.min()
| 38,647
|
https://github.com/SwagSoftware/Kisak-Strike/blob/master/materialsystem/stdshaders/colorout.cpp
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-public-domain, LicenseRef-scancode-unknown-license-reference
| 2,022
|
Kisak-Strike
|
SwagSoftware
|
C++
|
Code
| 343
| 1,845
|
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $Header: $
// $NoKeywords: $
//===========================================================================//
#include "BaseVSShader.h"
#include "colorout_vs20.inc"
#include "colorout_ps20.inc"
#include "colorout_ps20b.inc"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_VS_SHADER_FLAGS( ColorOut, "Help for ColorOut", SHADER_NOT_EDITABLE )
BEGIN_SHADER_PARAMS
SHADER_PARAM( PASSCOUNT, SHADER_PARAM_TYPE_INTEGER, "1", "Number of passes for this material" )
END_SHADER_PARAMS
SHADER_INIT_PARAMS()
{
SET_FLAGS2( MATERIAL_VAR2_SUPPORTS_HW_SKINNING );
}
SHADER_INIT
{
}
SHADER_FALLBACK
{
return 0;
}
SHADER_DRAW
{
SHADOW_STATE
{
//pShaderShadow->EnableDepthTest( true );
//pShaderShadow->EnableDepthWrites( true );
//pShaderShadow->EnableBlending( false );
////pShaderShadow->BlendFunc( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE_MINUS_SRC_ALPHA );
//pShaderShadow->BlendFunc( SHADER_BLEND_ONE, SHADER_BLEND_ONE );
pShaderShadow->EnableDepthTest( true );
pShaderShadow->EnableDepthWrites( true );
pShaderShadow->EnableBlending( false );
pShaderShadow->BlendFunc( SHADER_BLEND_ONE, SHADER_BLEND_ZERO );
// Set stream format (note that this shader supports compression)
unsigned int flags = VERTEX_POSITION | VERTEX_FORMAT_COMPRESSED;
int nTexCoordCount = 1;
int userDataSize = 0;
pShaderShadow->VertexShaderVertexFormat( flags, nTexCoordCount, NULL, userDataSize );
DECLARE_STATIC_VERTEX_SHADER( colorout_vs20 );
SET_STATIC_VERTEX_SHADER( colorout_vs20 );
if( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_STATIC_PIXEL_SHADER( colorout_ps20b );
SET_STATIC_PIXEL_SHADER( colorout_ps20b );
}
else
{
DECLARE_STATIC_PIXEL_SHADER( colorout_ps20 );
SET_STATIC_PIXEL_SHADER( colorout_ps20 );
}
}
DYNAMIC_STATE
{
float color[4];
color[0] = params[PASSCOUNT]->GetFloatValue();
color[1] = 1.0f - params[PASSCOUNT]->GetFloatValue();
color[2] = 0.0f;
color[3] = 0.0f;
pShaderAPI->SetPixelShaderConstant( 1, color, 1 );
DECLARE_DYNAMIC_VERTEX_SHADER( colorout_vs20 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( SKINNING, pShaderAPI->GetCurrentNumBones() > 0 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( COMPRESSED_VERTS, (int)vertexCompression );
SET_DYNAMIC_VERTEX_SHADER( colorout_vs20 );
if( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_DYNAMIC_PIXEL_SHADER( colorout_ps20b );
SET_DYNAMIC_PIXEL_SHADER( colorout_ps20b );
}
else
{
DECLARE_DYNAMIC_PIXEL_SHADER( colorout_ps20 );
SET_DYNAMIC_PIXEL_SHADER( colorout_ps20 );
}
}
Draw();
SHADOW_STATE
{
pShaderShadow->EnableDepthTest( true );
pShaderShadow->EnableDepthWrites( false );
pShaderShadow->EnableBlending( true );
pShaderShadow->BlendFunc( SHADER_BLEND_ONE, SHADER_BLEND_ONE );
pShaderShadow->VertexShaderVertexFormat( VERTEX_POSITION, 1, 0, 0 );
pShaderShadow->PolyMode( SHADER_POLYMODEFACE_FRONT, SHADER_POLYMODE_LINE );
DECLARE_STATIC_VERTEX_SHADER( colorout_vs20 );
SET_STATIC_VERTEX_SHADER( colorout_vs20 );
if( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_STATIC_PIXEL_SHADER( colorout_ps20b );
SET_STATIC_PIXEL_SHADER( colorout_ps20b );
}
else
{
DECLARE_STATIC_PIXEL_SHADER( colorout_ps20 );
SET_STATIC_PIXEL_SHADER( colorout_ps20 );
}
}
DYNAMIC_STATE
{
float color[4];
color[0] = 0.0f;
color[1] = 0.1f;
color[2] = 0.1f;
color[3] = 0.0f;
pShaderAPI->SetPixelShaderConstant( 0, color, 1 );
DECLARE_DYNAMIC_VERTEX_SHADER( colorout_vs20 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( SKINNING, pShaderAPI->GetCurrentNumBones() > 0 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( COMPRESSED_VERTS, (int)vertexCompression );
SET_DYNAMIC_VERTEX_SHADER( colorout_vs20 );
if( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_DYNAMIC_PIXEL_SHADER( colorout_ps20b );
SET_DYNAMIC_PIXEL_SHADER( colorout_ps20b );
}
else
{
DECLARE_DYNAMIC_PIXEL_SHADER( colorout_ps20 );
SET_DYNAMIC_PIXEL_SHADER( colorout_ps20 );
}
}
Draw();
}
END_SHADER
| 5,618
|
https://github.com/Jozwiaczek/smart-gate/blob/master/packages/client/src/pages/authorized/Dashboard/sections/CameraPreviewSection/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
smart-gate
|
Jozwiaczek
|
TypeScript
|
Code
| 152
| 574
|
import React, { useCallback, useLayoutEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CircleLoader } from '../../../../../elements';
import { useAxios } from '../../../../../hooks';
import { isCameraPreviewEnabled } from '../../../../../utils';
import {
CameraPreview,
LoadingContainer,
LoadingLabel,
Wrapper,
} from './CameraPreviewSection.styled';
const CameraPreviewSection = () => {
const cameraURL = process.env.REACT_APP_API_URL && `${process.env.REACT_APP_API_URL}/camera`;
const previewRef = useRef<HTMLImageElement>(null);
const [isPreviewLoaded, setIsPreviewLoaded] = useState(false);
const { t } = useTranslation();
const axios = useAxios();
const reloadCameraPreview = useCallback(() => {
axios
.get<string>('/ticket/generate')
.then((generatedTicket) => {
if (previewRef.current && cameraURL) {
previewRef.current.src = `${cameraURL}/?ticket=${generatedTicket.data}`;
}
})
.catch((ticketErr) => console.log(ticketErr));
}, [axios, cameraURL]);
useLayoutEffect(() => {
reloadCameraPreview();
window.addEventListener('focus', reloadCameraPreview);
return () => {
window.removeEventListener('focus', reloadCameraPreview);
};
}, [cameraURL, reloadCameraPreview]);
if (!isCameraPreviewEnabled()) {
return null;
}
return (
<Wrapper>
{!isPreviewLoaded && (
<LoadingContainer>
<CircleLoader variant="small" />
<LoadingLabel>{t('routes.dashboard.sections.camera.loadingPreview')}</LoadingLabel>
</LoadingContainer>
)}
<CameraPreview
ref={previewRef}
isLoaded={isPreviewLoaded}
alt={t('routes.dashboard.sections.camera.title')}
onLoad={() => {
setIsPreviewLoaded(true);
}}
/>
</Wrapper>
);
};
export default CameraPreviewSection;
| 43,102
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.