language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Markdown | UTF-8 | 2,969 | 2.734375 | 3 | [] | no_license | # 20-21_viagdi
<p align="center">
<img src="https://github.com/MCYP-UniversidadReyJuanCarlos/20-21_viagdi/blob/main/osint/catalog/static/images/CyberPeek.png" />
</p>
# Descripción del proyecto
CyberPeek es una herramienta de análisis de ciberinteligencia desarrollada para permitir la gestión de la información y las pruebas recogidas en un análisis de fuentes OSINT, sobre los diferentes elementos implicados (individuos, sociedades, relaciones, etc.), así como la representación automática de esta información mediante modelos visuales.
El objetivo de esta herramienta sería entonces facilitar el análisis de la información recogida mostrando, en todo momento, las relaciones existentes entre los elementos identificados.
Esta herramienta permite el trabajo conjunto de los analistas, de forma que puedan compartir estudios específicos de aquellas entidades/individuos que consideren oportunos, añadiendo comentarios entre ellos en la misma investigación.
# Características / Instalación
Utilizar [pip](https://pip.pypa.io/en/stable/) para instalar las librerías de django y bootstrap para desarrollar y diseñar la herramienta:
```bash
pip install django
```
```bash
pip install django-bootstrap
```
Bootstrap se utiliza para diseñar los ficheros .css que ajustan la estética de la interfaz web.
# Preparación de la herramienta
Primero, crear un entorno virtual en el directorio donde se quiera clonar el proyecto/repositorio de la herramienta:
```bash
python3 -m venv /path/to/new/virtual/environment
```
Después, instalar los requisitos de librerías reogidos en el fichero requirements.txt
```bash
pip install -r requirements.txt
```
Ahora, clonar el repositorio localmente. Luego, utilizando alguna herramienta de programación en python como PyCharm, abrir una terminal.
Desde el directorio 20-21_viagdi/osint/, ejecutar los siguientes comandos para configurar los modelos django del proyecto:
```bash
python manage.py makemigrations
```
```bash
python manage.py migrate
```
Ahora la herramienta está lista para usarse.
# Utilización básica
Para ejecutar el proyecto, ejecutar el siguiente comando desde una terminal con el entorno virtual del proyecto activado,
y desde el directorio 20-21_viagdi/osint/
```bash
python manage.py runserver
```
Accediendo a la url http://127.0.0.1:8000/ se accede a la interfaz web de la herramienta para utilizarla.
Ahora puedes registrarte en la herramienta, o loggearte con una cuenta de usuario creada específicamente para probar la herramienta:
```bash
username: user
password: user1234
```
# Arquitectura
Este proyecto tiene dos paquetes python, osint y catalog. El paquete osint es creado por defecto por Django y contiene los principales archivos python para desarrollar y levantar un proyecto django. El paquete catalog contiene todos los archivos relacionados con los modelos del proyecto, y todos los archivos relacionados con el diseño de la interfaz.
|
PHP | UTF-8 | 1,858 | 2.859375 | 3 | [] | no_license | <?php
namespace Phluid\Middleware;
use Phluid\Middleware\Cookies\Cookie;
class Cookies {
function __invoke( $request, $response, $next ){
$cookie = $request->getHeader( 'Cookie' );
if ( $cookie && !property_exists( $request, 'cookies' ) ) {
$request->cookies = $this->parseCookie( $cookie );
} else {
$request->cookies = array();
}
$response->cookies = new CookieJar();
$response->on( 'headers', function() use ( $response ){
if( $value = $response->cookies->headerValues() ){
$response->setHeader( 'Set-Cookie', $value );
}
});
$next();
}
function parseCookie( $cookie ){
$pairs = explode( '; ', $cookie );
$cookies = array();
foreach ( $pairs as $pair ) {
list( $name, $val ) = explode( '=', $pair, 2 );
$cookies[$name] = urldecode( $val );
}
return $cookies;
}
}
class CookieJar implements \ArrayAccess {
private $cookies = array();
public function headerValues( ){
$cookies = array();
if ( count( $this->cookies ) == 0 ) {
return false;
}
foreach ( $this->cookies as $key => $value ) {
array_push( $cookies, "$key=$value" );
}
if( count( $cookies ) == 1 ){
return $cookies[0];
} else {
return $cookies;
}
}
public function offsetExists ( $offset ){
return array_key_exists( $offset, $this->cookies );
}
public function offsetGet ( $offset ){
if ( array_key_exists( $offset, $this->cookies ) ) {
return $this->cookies[$offset];
}
}
public function offsetSet ( $offset , $value ){
if ( $value instanceof Cookie ) {
$this->cookies[$offset] = $value;
} else {
$this->cookies[$offset] = new Cookie( $value );
}
}
public function offsetUnset ( $offset ){
unset( $this->cookies[$offset] );
}
}
|
Java | UTF-8 | 473 | 2.875 | 3 | [] | no_license | package replit;
import java.util.Scanner;
public class Q64 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word = scan.next();
int l = word.length();
if (l>=3 && l%2==1) {
System.out.println(word.charAt(l/2));
}if(l==1) {
System.out.println(word+word+word);
}if(l>=4 && l%2==0) {
System.out.println(word.charAt((l/2)-1)+""+word.charAt(l/2));
}if (l==2) {
System.out.println(word+word);
}
}
}
|
Markdown | UTF-8 | 14,949 | 2.953125 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | ---
layout: lesson
title: "Managing data"
dimension: pf2.1
overview: |
Data is big business. Many contractors have learned that if they build a system that "locks in" the government, they not only "own" the data (potentially tying the government to them as a vendor in perpetuity), but the data itself becomes a valuable commodity to be resold on the open market. Neither of these outcomes necessarily serves the people.
federal:
- modular
- agilecontractformat
- contracttype
- evalproposals
state:
- productownership
- limitspending
- limitcontracts
- operationalexpense
---
## An experiment in data access (40m, solo)
**Timer**: {% include countdowntimer minutes=20 %}
*This is an interactive lesson. Read, reflect, and **do** as you make your way through.*
You may be famliar with [Trello](https://trello.com/), a tool for organizing ideas into *lists* of *cards*. Often, Trello boards are private (that is, requiring a login), but some are public. Here's a public Trello board that demonstrates a bucket list.
[https://trello.com/b/WGQ0ZGKe/bucket-list](https://trello.com/b/WGQ0ZGKe/bucket-list)
Now, imagine that Trello is a case management system being used by a state to manage benefits for the people of your state. The lists and cards are no longer capturing the desire to start a blog, but instead holding critical PII and information about people who have real, life-critical needs. The software was developed by a vendor for a state, and that vendor has failed time-and-again to develop robust, usable software that meets the needs of the people. The state would like to extract the data from the system, and work with a new vendor who is committed to demonstrating excellence as measured by this rubric and the Health Tracker.
**How hard is it to extract the data from Trello?**
### The JSON view
It turns out that we can change the URL just a *tiny* bit, and get a "data-centric" view of the Trello board.
We removed the name of the board, and replaced it with `.json`. Try clicking this one.
[https://trello.com/b/WGQ0ZGKe.json](https://trello.com/b/WGQ0ZGKe.json)
**YOU BROKE IT!**
Just kidding. What you're looking at is JSON (JavaScript Object Notation) format. It is probably not how a MES system would export data, but it is a common interchange format for small amounts of data on the internet. Trello makes it possible to quickly and easily see the underlying data that is used to create a board.
This also means that we can write code that interacts with that data.
### Listing the lists
Given the JSON format, it is possible to 1) fetch it, 2) manipulate it, and 3) do stuff with it. We wrote a small demonstration app as part of this tutorial to show you how this works.
<!-- Code at bottom of page. -->
<div class="grid-container">
<div class="grid-row">
<div class="grid-col-6">
<label class="usa-label" for="with-hint-input">
Trello URL
</label>
<span class="usa-hint">
Paste a Trello URL in the text field below.
</span>
<input class="usa-input" id="trello-url" width="100%" value="https://trello.com/b/WGQ0ZGKe/bucket-list">
</div>
</div>
<div class="grid-row" style="margin-top: 2em;">
<div class="grid-col-6 grid-offset-4" >
<button class="usa-button" onclick="showLists();">Show Board Lists</button>
</div>
</div>
<div class="grid-row" style="margin-top: 2em;">
<div class="grid-col-8">
<table class="usa-table usa-table--borderless" width="100%" id="trello-table">
<tr>
<th scope="col">List</th>
<th scope="col"># of Cards</th>
</tr>
</table>
</div>
</div>
</div>
You can use the "bucket list" board as an example, but you should also try looking at some other [public Trello boards](https://maybevaibhav.medium.com/best-35-trello-boards-for-you-to-see-and-get-inspired-6bf28b565616) to find out what kind of results you get.
### How did we do that?
As "web applications" go, this was relatively straight-forward.
1. You gave us a URL to a Trello board.
2. We manipulated that URL, removing some parts, and adding a ".json" to the end.
3. We asked your browser to fetch that URL.
4. The results came back as JSON, which is easily manipulated in Javascript.
5. We looked into the JSON to find the names of all of the lists.
6. We used that information to count how many cards were in each list.
7. Using Javascript, we rebuilt part of the webpage to show you what we discovered.
There is no testing, minimal validation, and really, you should be unsurprised if it fails. It's a demo that we put together to make an educational point, not robust enterprise software intended for consumption by millions of people.
### Why did we do that?
This all ways to demonstrate one critical point:
**Data in a Trello board is not "locked away" in a proprietary, vendor-controlled database**.
Let's break that down a bit further, though. What is true about the data stored in Trello?
1. **Easily accessible**. The data stored in a Trello board can be accessed simply by changing a URL.
2. **Standard formats**. The data in a Trello board is stored in an industry-standard format.
3. **Simple extraction API**. The data in a Trello board can be extracted with a simple HTTP-based API (Application Programmer Interface) request.
4. **Open, standard tooling**. The languages and tools required to access and manipulate the data are free and open. Further, they are exceedingly common. (In this case, Javascript. We could have also used Python, Java, C, C++... really, *any* programming language.)
5. **Well-documented**. To do this, we used documentation that was easily found on the internet. Most of the documentation needed was actually [standard docs for Javascript](https://developer.mozilla.org/en-US/docs/Web) provided by Mozilla. In other words, we were checking our knowledge of Javascript, not any special features of Trello.
6. **Self-documenting**. The data extracted from Trello was *self-documenting*. That means we could look at the data, and it was immediately apparent what that data represented. No additional documentation or questions to the vendor (in this case, Atlassian) were necessary.
7. **One-click extraction**. It is essentially possible to extract data from Trello with a "single click." We could easily write a script that, given a collection of Trello boards, could extract (and store, backup, migrate, or otherwise manipulate) all of the data in all of the boards.
## Data in your state (40m, solo)
**Timer**: {% include countdowntimer minutes=30 %}
In the section above, you were introduced to Trello, a web-based tool for organizing data into lists and cards. It is widely used by software and product management teams for organizing the work that takes place on software projects. We then wrote a short web application that 1) accesses a Trello board and 2) counts the cards in each of the lists, 3) presents that data back to you, the end-user.
Now think about the systems that your state is paying for year-over-year. In your notebook, ask (and answer) these questions:
1. Is the data in your state's systems easily accessible?
2. Is the data in your state's systems stored using open-source software (e.g. MariaDB or PostgreSQL as a database vs. a product from Oracle)?
3. Is the data in your state's systems stored in open, industry-standard formats? Which ones?
4. Can the data be accessed using free and open tooling (e.g. free, open libraries written in a common programming language like Java, Python, Ruby, or C/C++), or is it only accessible via proprietary, closed-source tools (e.g. Salesforce)?
5. Is process by which data can be accessed and extracted from a vendor's systems well documented?
6. Has that documentation been tested? That is, can someone employed by the state follow the instructions provided and get a complete and correct dump of data in the system?
8. Is the integrity of the data tested as a regular part of software testing?
9. Is it possible to get the data outof the system and validate/verity the integrity of the archive that is extracted?
10. Is the data format self-documenting? That is, once extracted, is it complex and opaque, or could a reasonably dedicated programmer study the data and understand what is going on?
11. Can the data be extracted with a single command?
Once you have answered these questions (some of which might have the answer "I don't know"), take some time to think about other questions you think we should be asking. Our goal should be to have a long, working list of questions that we would be able to ask states and vendors as part of our ongoing oversight process.
A state who has answers to all of these questions, and (in particular) can extract and validate an archive of all of their data in a single command, is in an excellent position to potentially reuse or otherwise migrate their data to new systems. A state whose data is "locked away" or unreachable to them is potentially locked in to a single vendor and has no way to consider new vendors or systems without a lengthy, expensive, and possibly contentious process of first extracting their data from one vendor before moving to another.
{% comment%}
<!-- The previous lesson spills into this one, so we remove the shared experience prompt. -->
{% include shared-experience-prompt.html %}
{% endcomment%}
## Vendor lock-in (1h, group)
Come together with your colleagues for a conversation.
{% include rubric dimension="pf2.1" %}
Google offers a service called *takeout*. If you have a Google account, you can go to [https://takeout.google.com/](https://takeout.google.com/) and download *all* of your data in a single click. You can get a compressed file containing all of your emails. You can get a single download of all of the data you have in Drive. You can download a zip of all of your photos. In short, you can take all of your data and leave Google's services.
We suspect that states cannot move their data from one system to another nearly so easily.
In your group conversation, you fundamentally have two questions to explore:
1. Is your state's data locked in to a single vendor? If so, how?
2. What steps can you take, as {{site.productowner}}s, to help your states break free?
For #2 and #3, below, you'll want someone to take notes. Whomever has a birthday closest to Veteran's Day (after, not before) is encouraged to step up.
1. **Check in**. {% include countdowntimer minutes=5 %} First, check in with each other. How is everyone doing? Take a moment to share something positive from the week, either at work or at home.
2. **Catalog**. {% include countdowntimer minutes=10 %} The first question asked above asks us how data might be "locked away" from a state. As a group, catalog the ways you see your states' health data locked away from them. In the event that you feel a state is *not* "locked in," share that, and why. Your goal is to come up with a catalog of the ways you see your states constrained (or not) by their vendors.
3. **Deconstruct**. {% include countdowntimer minutes=25 %} Once you have a catalog, start working through it. As a group, think about the second question posed above: how could you, given where you sit, help states "break free?" What would be the ideal situation for states when it comes to their health data? How can you help them get there?
4. **Reflect and vote**. {% include countdowntimer minutes=5 %} Take a pause from your conversation, and let the notetaker reflect back what you've said so far. Assuming you have multiple strategies, each of you should pick *two* that you think are of potential interest to explore further. Spend your **+1**s, and after voting, see which two ideas have the most votes.
At your next full team meeting, the note taker should share out a brief summary of your conversation, and highlight the two ideas/strategies for "freeing" state data with the rest of the group. Our hope is that this will be the beginning of a conversational space for potential work amongst the larger group to shift data management/ownership practices.
<script>
function onResponse (request) {
return function () {
const resp = request.response;
console.log(resp);
if (resp) {
// Delete old rows
for (row of document.getElementsByClassName("DELETEME")) {
row.remove();
}
// Grab the table itself, so new rows can be inserted.
var table = document.getElementById("trello-table");
// Lets take a look at the lists in the console.
console.log(resp.lists);
// For each element of lists array...
for (e of resp.lists) {
// Grab the list ID, and count how many times it shows
// up in the list of cards.
listid = e.id;
cardcount = 0;
for (c of resp.cards) {
if (c.idList == listid) cardcount++;
}
// Create the new rows, and populate it with data.
newr = document.createElement("tr");
// Make sure to set the class appropriately,
// so we can delete it later.
newr.setAttribute("class", "DELETEME");
ln = document.createElement("td");
ln.textContent = e.name;
lc = document.createElement("td");
lc.textContent = cardcount;
newr.appendChild(ln);
newr.appendChild(lc);
// Append the new row to the table.
table.appendChild(newr);
}
}
}
}
function showLists() {
console.log("beep.");
var url = document.getElementById("trello-url").value;
console.log(url);
// https://trello.com/b/WGQ0ZGKe/bucket-list
let re = /^https:\/\/trello.com\/b\/(.*?)\/.*$/
let groups = re.exec(url);
// Make sure it is a trello URL.
if (groups) {
//Rewrite the URL.
// https://trello.com/b/WGQ0ZGKe.json
let newURL = "https://trello.com/b/" + groups[1] + ".json";
let request = new XMLHttpRequest();
request.responseType = 'json';
request.open('GET', newURL);
request.onload = onResponse(request);
request.send();
} else {
console.log("url is not a match.");
}
// Prevent the default behavior.
return false;
}
</script>
[](https://www.lifewire.com/what-is-google-takeout-4173795)
|
PHP | UTF-8 | 495 | 4.15625 | 4 | [
"MIT"
] | permissive | <?php
namespace Euler;
/**
* The prime factors of 13195 are 5, 7, 13 and 29.
* What is the largest prime factor of the number 600851475143 ?
*/
class P03
{
public static function largestPrimeFactors(int $number)
{
$prime_factors = [];
$next = gmp_nextprime(1);
for ($i = $next; $next <= $number; $next = gmp_nextprime($i)) {
$prime_factors[] = $next;
}
print_r($prime_factors);
return (int)end($prime_factors);
}
}
|
Java | UTF-8 | 1,260 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | package com.ustore.fileMetadata.model;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.validation.constraints.NotNull;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", length = 1, discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("P")
public abstract class Path {
@Id
private Long id;
@NotNull
@Column(name = "name")
private String name;
@NotNull
@Column(name = "size")
private Long size;
@NotNull
@Column(name = "user_id")
private Long userId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getType() {
return "";
}
}
|
Markdown | UTF-8 | 6,139 | 4.25 | 4 | [
"MIT"
] | permissive | # OOJS: Model an Orange Tree
## Summary
Remember the [orange tree][orange tree challenge] objects that we built in Ruby? We're going to build JavaScript objects with the same attributes and behaviors.
We're going to create orange trees through a constructor function. The constructor will initialize each tree with its own unique attributes: age, height, and a collection of oranges. All trees might start being zero years old, zero feet tall, and with an empty collection of oranges; but, these attributes are unique to each tree object—they're not shared. On the other hand, the behaviors of orange trees will be shared. All trees will share methods for aging, growing, etc.
### Prototypal Inheritance
When thinking about inheritance in JavaScript, throw out what we know about method lookup in Ruby—well, most of it, anyway. JavaScript doesn't have classes, so when an object itself doesn't have a property, we can't look in the class, parent class, grandparent class, etc. Instead, JavaScript objects inherit properties from their prototypes. So, what is a prototype and how does an object get a prototype?
Every JavaScript function has a `prototype` property. Regardless of whether we intend to use the function as a constructor or not, when we write a function, JavaScript will give the function a `prototype` property and set its value to a new empty JavaScript object (`{}`, see Figure 1).
```js
// Create a function and check its prototype property.
var addition = function(number1, number2) {
return number1 + number2;
}
addition.prototype;
// => {}
// Create a function to use as a constructor
// and check its prototype property.
var Person = function(name) {
this.name = name;
}
Person.prototype;
// => {}
// Each function's prototype is a unique object.
addition.prototype === Person.prototype;
// => false
```
*Figure 1*. Creating functions and looking at the value of each function's `prototype` property.
So, every function has a `prototype`, how does that affect inheritance? A function's `prototype` object comes into play when we use a function as a constructor (e.g., `new Person("Jamie")`).
When we use a function as a constructor to initialize an object, the newly created object gets a link to the constructor's prototype object. Through this link, the new object has access to the prototype object's properties. In a manner of speaking, the new object "inherits" the properties defined on the constructor's prototype. All objects made with the same constructor share the constructor's prototype. In this way, things like methods can be shared by multiple objects.
Figure 2 presents some code to demonstrate these concepts; follow along in the browser console or the node REPL if node is installed on our system (use the `node` command from the command line).
```js
// Create a constructor function and check its prototype.
var Person = function(name) {
this.name = name;
}
Person.prototype;
// => {}
// Give the Person constructor's prototype a greeting property.
Person.prototype.greeting = 'Hello';
Person.prototype;
// => { greeting: 'Hello' }
// Create a new Person instance, jamie.
jamie = new Person('Jamie');
// => { name: 'Jamie' }
// Look up the object from which the jamie object inherits.
Object.getPrototypeOf(jamie);
// => { greeting: 'Hello' }
// The object from which the jamie object inherits
// is the Person constructor's prototype.
Object.getPrototypeOf(jamie) === Person.prototype;
// => true
// The jamie object does not have a greeting property
// but inherits it from its prototype.
jamie;
// => { name: 'Jamie' }
jamie.greeting;
// => 'Hello'
// Other objects instantiated through the Person constructor
// also inherit from the constructor's prototype.
nicky = new Person('Nicky');
// => { name: 'Nicky' }
nicky.greeting;
// => 'Hello'
// Add another property to the Person constructor's prototype,
// and show that is it inherited by the Person objects.
Person.prototype.bigName = function() {
return this.name.toUpperCase();
}
jamie.bigName();
// => 'JAMIE'
nicky.bigName();
// => 'NICKY'
```
*Figure 2*. Exploring prototypal inheritance in JavaScript.
## Releases
### Release 0: Model an Orange Tree
Here are some details for how our orange tree model will behave. Don't worry about modeling things like how the temperature affects production; we're just building a basic model. Each of these details should be translated into tests (`spec/orange_tree_spec.js`), so that we can verify that our model conforms to each expectation. Suggested property names are in parentheses; our model may very well include more properties than these.
- A tree has an age, which we should be able to check (`age`).
- A tree has a height, which we should be able to check (`height`).
- A tree has a collection of oranges, which we should be able to check (`oranges`).
- We can check if a tree is old enough to produce fruit (`isMature()`).
- A tree dies at age 100, and we can check if it's dead (`isDead()`).
- We can check if a tree has any oranges (`hasOranges()`).
- Each growing season (`passGrowingSeason()`) ...
- Any unharvested oranges from the previous season should drop.
- A tree should age one year.
- A tree should grow 2.5 feet taller until it reaches its maximum height, say 25 feet.
- A tree should bear fruit if it is mature (i.e. at least six years old), say 10 oranges.
- We can pick an orange off a tree (`pickAnOrange()`).
## Conclusion
Prototypal inheritance is different from the class-based inheritance found in Ruby. When we try to access a property of an object, property look up starts with the object itself. If the object has the property, the value of the property is returned. If the object doesn't have the property itself, then we look for the property in the object's prototype ... then the prototype's prototype, an so on. We should leave this challenge understanding how to share properties among objects created through the same constructor function by relying on inheriting from the constructor's prototype object.
[orange tree challenge]: ../../../orange-tree-1-just-oranges-challenge |
C++ | UTF-8 | 20,647 | 2.953125 | 3 | [
"CC-BY-3.0",
"MIT"
] | permissive | #include "Reaction.h"
#include "Element.h"
//TODO: All of the ReactionNode stuff needs to be moved to separate files.
#define MAX_REACTION_DEPTH (sizeof(uint32) * 8 - 2)
#define ELEMENT_IN_USE_BIT (MAX_REACTION_DEPTH + 1)
//HACK: This is to get around ReactionNode not having a reference to the current reaction, make this not awful later.
Reaction* currentReaction;
class ReactionNode
{
protected:
ReactionNode* firstChild = NULL;
ReactionNode* sibling = NULL;
BondType type = BondType_None;
int leftData = 0;
int rightData = 0;
public:
class Iterator
{
private:
ReactionNode** marker;
public:
Iterator(ReactionNode** start)
{
this->marker = start;
}
void Next()
{
if (*marker != NULL)
{ marker = &(*marker)->sibling; }
}
ReactionNode* Get() const
{
return *marker;
}
Iterator& operator++()
{
Next();
return *this;
}
Iterator& operator++(int)
{
return ++(*this);
}
ReactionNode* operator*() const
{
return Get();
}
bool HasNext()
{
return *marker != NULL && (*marker)->sibling != NULL;
}
ReactionNode** GetMarker()
{
return marker;
}
void GoToEnd()
{
while (HasNext())
{ Next(); }
}
uint32 Count()
{
uint32 ret = 0;
while (HasNext())
{
Next();
ret++;
}
return ret;
}
};
void AddSibling(ReactionNode* node)
{
Iterator it(&sibling);
it.GoToEnd();
it.Next(); // Get marker on location to place node.
*(it.GetMarker()) = node;
}
void AddChild(ReactionNode* node)
{
Iterator it(&firstChild);
it.GoToEnd();
it.Next(); // Get marker on location to place node.
*(it.GetMarker()) = node;
}
void SetBondInfo(BondType type, int leftData, int rightData)
{
this->type = type;
this->leftData = leftData;
this->rightData = rightData;
}
void SetBondInfo(BondType type, int data)
{ SetBondInfo(type, data, data); }
void SetBondInfo(BondType type)
{ SetBondInfo(type, 0, 0); }
void ApplyBond(Compound* compound, Element* left, Element* right)
{
// We need to set the IN_USE bit even if no bond needs to be added.
left->SetMaskBit(ELEMENT_IN_USE_BIT);
right->SetMaskBit(ELEMENT_IN_USE_BIT);
if (this->type == BondType_None)
{ return; }
//LOG("ApplyBond(Compound:0x%X, Element:0x%X, Element:0x%X)\n", compound, left, right);
Assert(left != right); // This means a bond was applied to a passthrough node.
left->SetBondTypeFor(compound, right, type, leftData, rightData);
}
virtual bool ProcessChildren(Compound* compound, Element* inputForChildren, int depth)
{
for (Iterator it(&firstChild); *it; it++)
{
if (!(*it)->Process(compound, inputForChildren, depth))
{
return false; // All children must return true to succeed.
}
}
return true; // If we got this far, all children met their criteria.
}
// Don't override this for most implementations of this class
virtual bool Process(Compound* compound, Element* input, int depth)
{
//LOG("%s:0x%X.Process(Compound:0x%X, Element:0x%X[%s], %d)\n", GetDescription(), this, compound, input, input->GetSymbol(), depth);
Assert(depth >= 0 && depth < MAX_REACTION_DEPTH);
bool success = false;
Element* output = NULL;
Element* lastOutput = NULL;
while (true)
{
// This will return a different element each time it is called, and NULL when no element is available
// Therefore, we can loop until we find an element with child elements that satisfy this branch of the reaction.
lastOutput = output;
output = GetOutput(compound, input, depth);
// If output == NULL, we ran out of possibilities and failed.
// If output == lastOutput, then either the node has a flawed implementation, or (more likely) it is a dummy pass-through node. Either way we want to not loop forever.
if (output == NULL || output == lastOutput)
{ break; }
// Mark this element as being used for this depth of the compound processing
output->SetMaskBit(depth);
// Process children (on the next depth)
if (ProcessChildren(compound, output, depth + 1))
{
// All children succeeded, so we succeed!
success = true;
break;
}
}
currentReaction->ClearElementMasks(depth); // Clear all of the elements we considered for this branch
if (success)
{ ApplyBond(compound, input, output); }
return success;
}
// Override this for most implementations of this class
virtual Element* GetOutput(Compound* compound, Element* input, int depth)
{
LOG("WARN: Called unimplemented ReactionNode:GetOutput with Element:0x%X[%s] as input @ depth %d!\n", input, input->GetSymbol(), depth);
return NULL;
}
Iterator GetChildIterator()
{
return Iterator(&firstChild);
}
virtual const char* GetDescription() { return "ReactionNode"; }
};
class ElementSymbolFilterNode : public ReactionNode
{
private:
const char* symbol;
public:
ElementSymbolFilterNode(const char* symbol)
{
this->symbol = symbol;
LOG("ElementSymbolFilterNode:0x%X %s\n", this, symbol);
}
virtual Element* GetOutput(Compound* compound, Element* input, int depth)
{
return strcmp(input->GetSymbol(), symbol) == 0 ? input : NULL;
}
virtual const char* GetDescription() { return "ElementSymbolFilterNode"; }
};
class ElementSymbolNode : public ReactionNode
{
private:
const char* symbol;
public:
ElementSymbolNode(const char* symbol)
{
this->symbol = symbol;
LOG("ElementSymbolNode:0x%X %s\n", this, symbol);
}
virtual Element* GetOutput(Compound* compound, Element* input, int depth)
{
return input->GetBondWith(symbol);
}
virtual const char* GetDescription() { return "ElementSymbolNode"; }
};
class ElementGroupFilterNode : public ReactionNode
{
private:
groupState group;
public:
ElementGroupFilterNode(groupState group)
{
this->group = group;
LOG("ElementGroupFilterNode:0x%X %d\n", this, group);
}
virtual Element* GetOutput(Compound* compound, Element* input, int depth)
{
return input->GetGroup() == group ? input : NULL;
}
virtual const char* GetDescription() { return "ElementGroupFilterNode"; }
};
class ElementGroupNode : public ReactionNode
{
private:
groupState group;
public:
ElementGroupNode(groupState group)
{
this->group = group;
LOG("ElementGroupNode:0x%X %d\n", this, group);
}
virtual Element* GetOutput(Compound* compound, Element* input, int depth)
{
return input->GetBondWith(group);
}
virtual const char* GetDescription() { return "ElementGroupNode"; }
};
// A logical node that only needs one branch of children to succeed
//NOTE: This should not be used to implement alternative, inclusive reactions as it will not even try the other children once one succeeds.
class EitherOrNode : public ReactionNode
{
public:
virtual bool ProcessChildren(Compound* compound, Element* inputForChildren, int depth)
{
for (Iterator it(&firstChild); *it; it++)
{
if ((*it)->Process(compound, inputForChildren, depth))
{
return true; // Return true when the first child succeeds.
}
}
return false; // If we got this far, then no children succeedeed.
}
virtual Element* GetOutput(Compound* compound, Element* input, int depth)
{
// This node is a pure pass-through node
return input;
}
virtual const char* GetDescription() { return "EitherOrNode"; }
};
//! This node doesn't do anything other than pass the element through, used for coalescing common elements after an EitherOrNode.
class NoOpNode : public ReactionNode
{
public:
virtual Element* GetOutput(Compound* compound, Element* input, int depth)
{
// This node is a pure pass-through node
return input;
}
virtual const char* GetDescription() { return "NoOpNode"; }
};
void InitializeCompoundDatabase();
ReactionNode CompoundDatabaseRoot;
/*
Processes a reaction and determines the outcome, if any.
This algorithm was written with help by:
Christopher Culbertson, Associate Professor at Kansas State University
Michael Ayala, Chemistry Major at UC Davis
*/
bool Reaction::Process()
{
// Initialize the compound database
static bool compoundDatabaseIsInitialized = false;
if (!compoundDatabaseIsInitialized)
{
InitializeCompoundDatabase();
compoundDatabaseIsInitialized = true;
}
// Fail immediately if there's only one element in this reaction
if (elements.Count() == 1)
{ return false; }
// Debug printing
LOG("Reaction:0x%X processing %d elements...\n", this, elements.Count());
LOG("[ ");
for (int i = 0; i < elements.Count(); i++)
{
if (i > 0)
{ LOG(", "); }
LOG("%s", elements[i]->GetSymbol());
}
LOG(" ]\n");
currentReaction = this;
for (int i = 0; i < elements.Count(); i++)
{
LOG("Processing element %d:%s as root to compound...\n", i, elements[i]->GetSymbol());
for (ReactionNode::Iterator it = CompoundDatabaseRoot.GetChildIterator(); *it; it++)
{
Compound* newCompound = StartNewCompound();
if (!(*it)->Process(newCompound, elements[i], 0))
{ CancelCompound(newCompound); } // Cancel the compound if the process was not successful.
}
}
LOG("Reaction processing completed with %d candidate compounds.\n", possibleCompounds.Count());
//--------------------------------------------------------------------------
// Choose the ideal compound and apply it:
//--------------------------------------------------------------------------
//TODO: Allow multiple compounds to form in one reaction when they don't overlap.
idealCompound = NULL;
for (int i = 0; i < possibleCompounds.Count(); i++)
{
Compound* compound = possibleCompounds[i];
if (idealCompound == NULL)
{
idealCompound = compound;
continue;
}
if (idealCompound->ContainsPotentialBonds() && !compound->ContainsPotentialBonds())
{
idealCompound = compound;
continue;
}
if (idealCompound->GetElementCount() < compound->GetElementCount())
{
idealCompound = compound;
continue;
}
}
// Dispose of all compounds other than the ideal one to save memory
for (int i = 0; i < possibleCompounds.Count(); i++)
{
if (possibleCompounds[i] != idealCompound)
{
delete possibleCompounds[i];
}
}
// Clear the possible compounds list to release the linked list memory (The ideal compound will survive.)
possibleCompounds.Clear();
// Apply the ideal compound and return
if (idealCompound != NULL)
{
idealCompound->Apply();
return true;
}
return false;
}
//------------------------------------------------------------------------------
// Nodes for potential compounds
//------------------------------------------------------------------------------
//TOOD: Either make this nicer or generate it with a tool. (I'm leaning towards the latter.)
namespace PerchloricAcid
{
ElementSymbolFilterNode root("Cl");
ElementSymbolNode node_1("O");
ElementSymbolNode node_1_1("H");
ElementSymbolNode node_2("O");
ElementSymbolNode node_3("O");
ElementSymbolNode node_4("O");
void Initialize()
{
root.AddChild(&node_1);
root.AddChild(&node_2);
root.AddChild(&node_3);
root.AddChild(&node_4);
node_1.AddChild(&node_1_1);
node_1.SetBondInfo(BondType_Covalent, 1);
node_2.SetBondInfo(BondType_Covalent, 2);
node_3.SetBondInfo(BondType_Covalent, 2);
node_4.SetBondInfo(BondType_Covalent, 2);
node_1_1.SetBondInfo(BondType_Covalent, 1);
CompoundDatabaseRoot.AddChild(&root);
}
}
namespace Acetylene
{
ElementSymbolFilterNode h1("H");
ElementSymbolNode c1("C");
ElementSymbolNode c2("C");
ElementSymbolNode h2("H");
void Initialize()
{
h1.AddChild(&c1);
c1.AddChild(&c2);
c2.AddChild(&h2);
c1.SetBondInfo(BondType_Covalent, 1);
c2.SetBondInfo(BondType_Covalent, 3);
h2.SetBondInfo(BondType_Covalent, 1);
CompoundDatabaseRoot.AddChild(&h1);
}
}
namespace DisulfurDioxide
{
ElementSymbolFilterNode o1("O");
ElementSymbolNode s1("S");
ElementSymbolNode s2("S");
ElementSymbolNode o2("O");
void Initialize()
{
o1.AddChild(&s1);
s1.AddChild(&s2);
s2.AddChild(&o2);
s1.SetBondInfo(BondType_Covalent, 2);
s2.SetBondInfo(BondType_Covalent, 1);
o2.SetBondInfo(BondType_Covalent, 2);
CompoundDatabaseRoot.AddChild(&o1);
}
}
namespace PhosphorousAcid1 /* H3PO3 Tautomer */
{
ElementSymbolFilterNode p("P");
ElementSymbolNode o1("O");
ElementSymbolNode o2("O");
ElementSymbolNode o3("O");
ElementSymbolNode h1("H");
ElementSymbolNode h2("H");
ElementSymbolNode h3("H");
void Initialize()
{
p.AddChild(&o1);
p.AddChild(&o2);
p.AddChild(&o3);
o1.AddChild(&h1);
o2.AddChild(&h2);
o3.AddChild(&h3);
o1.SetBondInfo(BondType_Covalent, 1);
o2.SetBondInfo(BondType_Covalent, 1);
o3.SetBondInfo(BondType_Covalent, 1);
h1.SetBondInfo(BondType_Ionic);
h2.SetBondInfo(BondType_Ionic);
h3.SetBondInfo(BondType_Ionic);
CompoundDatabaseRoot.AddChild(&p);
}
}
namespace PhosphorousAcid2 /* H2PHO3 Tautomer */
{
ElementSymbolFilterNode p("P");
ElementSymbolNode o1("O");
ElementSymbolNode o2("O");
ElementSymbolNode o3("O");
ElementSymbolNode h1("H");
ElementSymbolNode h2("H");
ElementSymbolNode h3("H");
void Initialize()
{
p.AddChild(&o1);
p.AddChild(&o2);
p.AddChild(&o3);
p.AddChild(&h1);
o1.AddChild(&h2);
o2.AddChild(&h3);
o1.SetBondInfo(BondType_Covalent, 2);
o2.SetBondInfo(BondType_Covalent, 1);
o3.SetBondInfo(BondType_Covalent, 1);
h1.SetBondInfo(BondType_Covalent, 1);
h2.SetBondInfo(BondType_Ionic);
h3.SetBondInfo(BondType_Ionic);
CompoundDatabaseRoot.AddChild(&p);
}
}
//------------------------------------------------------------------------------
// Two Element Reactions
//------------------------------------------------------------------------------
namespace Hydrogen_HydrogenOrHalogenOrAlkali
{
//Hydrogen - Hydrogen
ElementGroupFilterNode h_h1(HYDROGEN);
ElementGroupNode h_h2(HYDROGEN);
// Hydrogen - Halogen
ElementGroupFilterNode h_hal1(HYDROGEN);
ElementGroupNode h_hal2(HALOGEN);
// Hydrogen - Alkali
ElementGroupFilterNode h_a1(HYDROGEN);
ElementGroupNode h_a2(ALKALI);
void Initialize()
{
h_h1.AddChild(&h_h2);
h_h2.SetBondInfo(BondType_Covalent, 1);
CompoundDatabaseRoot.AddChild(&h_h1);
h_hal1.AddChild(&h_hal2);
h_hal2.SetBondInfo(BondType_Covalent, 1);
CompoundDatabaseRoot.AddChild(&h_hal1);
h_a1.AddChild(&h_a2);
h_a2.SetBondInfo(BondType_Ionic);
CompoundDatabaseRoot.AddChild(&h_a1);
}
}
namespace Halogen_HalogenOrAlkali
{
// Halogen - Halogen
ElementGroupFilterNode ha_ha1(HALOGEN);
ElementGroupNode ha_ha2(HALOGEN);
// Halogen - Alkali
ElementGroupFilterNode ha_a1(HALOGEN);
ElementGroupNode ha_a2(ALKALI);
void Initialize()
{
ha_ha1.AddChild(&ha_ha2);
ha_ha2.SetBondInfo(BondType_Covalent, 1);
CompoundDatabaseRoot.AddChild(&ha_ha1);
ha_a1.AddChild(&ha_a2);
ha_a2.SetBondInfo(BondType_Ionic);
CompoundDatabaseRoot.AddChild(&ha_a1);
}
}
namespace LithiumIodine
{
ElementSymbolFilterNode root("Li");
ElementSymbolNode node_1("I");
void Initialize()
{
root.AddChild(&node_1);
node_1.SetBondInfo(BondType_Ionic);
CompoundDatabaseRoot.AddChild(&root);
}
}
//------------------------------------------------------------------------------
// Three Element Reactions
//------------------------------------------------------------------------------
namespace AlkaliEarth_2Halogen
{
ElementGroupFilterNode halogenRoot(ALKALIEARTH);
EitherOrNode or1; // Used as if-else for Be
ElementSymbolFilterNode beFilter("Be");
ElementGroupNode be_1(HALOGEN);
ElementGroupNode be_2(HALOGEN);
/* else */
NoOpNode elseNode;
ElementGroupNode else_1(HALOGEN);
ElementGroupNode else_2(HALOGEN);
void Initialize()
{
halogenRoot.AddChild(&or1);
or1.AddChild(&beFilter);
{
//If the alkali earth metal is Beryllium, the bond will be covalent
beFilter.AddChild(&be_1);
beFilter.AddChild(&be_2);
be_1.SetBondInfo(BondType_Covalent, 1);
be_2.SetBondInfo(BondType_Covalent, 1);
}
or1.AddChild(&elseNode);
{
//If they are the other alkali earth metals, they will make an ionic bond
elseNode.AddChild(&else_1);
elseNode.AddChild(&else_2);
else_1.SetBondInfo(BondType_Ionic);
else_2.SetBondInfo(BondType_Ionic);
}
CompoundDatabaseRoot.AddChild(&halogenRoot);
}
}
namespace AlkaliEarth_2Hydrogen
{
ElementGroupFilterNode halogenRoot(ALKALIEARTH);
EitherOrNode or1; // Used as if-else for Be
ElementSymbolFilterNode beFilter("Be");
ElementGroupNode be_1(HYDROGEN);
ElementGroupNode be_2(HYDROGEN);
/* else if */
ElementSymbolFilterNode mgFilter("Mg");
ElementGroupNode mg_1(HYDROGEN);
ElementGroupNode mg_2(HYDROGEN);
/* else */
NoOpNode elseNode;
ElementGroupNode else_1(HYDROGEN);
ElementGroupNode else_2(HYDROGEN);
void Initialize()
{
halogenRoot.AddChild(&or1);
or1.AddChild(&beFilter);
{
//If the alkali earth metal is Beryllium, the bond will be covalent
beFilter.AddChild(&be_1);
beFilter.AddChild(&be_2);
be_1.SetBondInfo(BondType_Covalent, 1);
be_2.SetBondInfo(BondType_Covalent, 1);
}
or1.AddChild(&mgFilter);
{
//If the alkali earth metal is Magnesium, the bond will be covalent
mgFilter.AddChild(&mg_1);
mgFilter.AddChild(&mg_2);
mg_1.SetBondInfo(BondType_Covalent, 1);
mg_2.SetBondInfo(BondType_Covalent, 1);
}
or1.AddChild(&elseNode);
{
//If they are the other alkali earth metals, they will make an ionic bond
elseNode.AddChild(&else_1);
elseNode.AddChild(&else_2);
else_1.SetBondInfo(BondType_Ionic);
else_2.SetBondInfo(BondType_Ionic);
}
CompoundDatabaseRoot.AddChild(&halogenRoot);
}
}
void InitializeCompoundDatabase()
{
LOG("Initializing compound database...\n");
PerchloricAcid::Initialize();
Hydrogen_HydrogenOrHalogenOrAlkali::Initialize();
Halogen_HalogenOrAlkali::Initialize();
LithiumIodine::Initialize();
AlkaliEarth_2Halogen::Initialize();
AlkaliEarth_2Hydrogen::Initialize();
Acetylene::Initialize();
DisulfurDioxide::Initialize();
PhosphorousAcid1::Initialize();
PhosphorousAcid2::Initialize();
LOG("Done initializing compound database with %d compounds.\n", CompoundDatabaseRoot.GetChildIterator().Count());
}
|
Java | UTF-8 | 1,541 | 3.78125 | 4 | [] | no_license | package Question2;
import java.util.*;
public class SortingProblem {
public static void main(String[] args) {
System.out.println("How many student you want to take as input?");
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
List<Student> studentList = new ArrayList<>();
for(int i=0;i<testCases;i++)
{
int id = in.nextInt();
String name = in.next();
double cgpa = in.nextDouble();
Student st = new Student(id, name, cgpa);
studentList.add(st);
}
studentList.sort(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if (s2.getCgpa() > s1.getCgpa()) {
return 1;
} else if (s2.getCgpa() < s1.getCgpa()) {
return -1;
}
else if(s1.getFirstName().compareTo(s2.getFirstName())< 0)
{
return -1;
}
else if(s1.getFirstName().compareTo(s2.getFirstName())>0)
{
return 1;
}
else if(s1.getId()<s2.getId())
{
return 1;
}
return -1;
}
});
for(Student st: studentList){
System.out.println(st.getFirstName());
}
}
}
|
Markdown | UTF-8 | 4,182 | 3.03125 | 3 | [] | no_license | <div class="inner">
<h2>Hindley-Milner 类型系统的根本性错误</h2>
<p>之前的一个时间,我曾经公开过这样一段<a href="http://www.tudou.com/programs/view/GU9GtDuWSMk">幻灯片</a>,它是2012年10月的时候,我在 Indiana 大学做的最后一次演讲。由于当时的委婉,我并没有直接说出这些结论的重要性。其实它揭示了 ML 和 Haskell 这类基于 Hindley-Milner 类型系统的语言的一个根本性的错误。</p>
<p>这个错误来源于对一阶逻辑的“全称量词”(universal quantifier,通常写作∀)与程序函数之间关系的误解。在 HM 系统里面,多态(polymorphic)的函数能够被推导为含有全称量词的类型,比如 <code class="language-plaintext highlighter-rouge">\x->x</code> 的类型被推导为 <code class="language-plaintext highlighter-rouge">∀a.a->a</code>,但 HM 系统决定这个全称量词的位置的方式,却是没有原则的。这就导致了类型变量(type variable)的作用域(scope)的偏差。</p>
<p>我的研究显示,这个错误来源于 HM 系统最初的一项重要的设计,叫做 let-polymorphism。如果右边的函数是一个多态的函数,比如:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>let f = \x->x in
...
</code></pre></div></div>
<p>let-polymorphism 总是会把全称量词的位置确定在 <code class="language-plaintext highlighter-rouge">let</code> 的“=”右边。然而这是一个非常错误的做法,它的错误程度近似于早期的 Lisp 所采用的 dynamic scoping。这样做的结果是,全称量词的位置会随着程序的“格式”,而不是程序的“结构”,而变化。至于什么是 dynamic scoping,你可以参考我的这篇博文。</p>
<p>为了弥补这个错误,30多年来,许多的人发表了许多的论文,提出了很多的“改进措施”,比如 value restriction,MLF,等等。但是我的研究却显示,所有这些“改进措施”都是丑陋的 hack。因为他们没有看到问题的根源,所以他们的方案只对一些特殊情况起作用,而不能通用。为此,我可以轻而易举的写出正确的程序,而让它不能通过这些类型系统的检查,比如像我这篇英文博文所示。如果你看到了问题的根源,就会发现 HM 系统的这个错误是无法弥补的,因为它触及了 HM 系统的根基。为了根治这个问题,let-polymorphism 必须被去除掉。</p>
<p>我为此提出了自己的解决方案:在 lambda 的位置进行“generalization”,也就是说把 ∀ 放在 <code class="language-plaintext highlighter-rouge">lambda 的位置</code>,而不是 <code class="language-plaintext highlighter-rouge">let</code>。这样一来 let-polymorphism 就不存在了。但是这样一来,HM 系统就不再是 HM 系统,因为它的“模块化类型推导”的性质,就会名存实亡。由于类型里面含有程序的“控制结构”,这个类型系统表面上看起来是在进行“模块化类型检查”,而本质上是在做一个“跨过程静态检查”(interprocedual static analysis)。也就是说,模块化的类型推导,在 HM 这样的没有“类型标记”的体系下,其实是不可能实现的。</p>
<p>为了达到完全通用的模块化类型检查,却又允许多态函数的存在,我们终究会需要在函数的参数位置手工写上类型,这样我们就完全的丧失了 HM 系统设计的初衷。</p>
</div>
<!--
<div class="ad-banner" style="margin-top: 5px">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:inline-block;width:100%;height:90px"
data-ad-client="ca-pub-1331524016319584"
data-ad-slot="6657867155"></ins>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
</div>
<script data-ad-client="ca-pub-1331524016319584" async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
-->
|
C | UTF-8 | 512 | 3.578125 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
// 6.Informa a quantidade de notas para um saque.
int main()
{
int notas[6] = {2,5,10,20,50,100};
int saque, qtd_notas,cont;
printf ("Digite o valor desejado do saque: ");
scanf ("%i", &saque);
printf ("\n ------ \n");
for (cont=0; cont<6; cont++)
{
qtd_notas = saque/notas[cont];
printf("A menor quantidade de notas de %d para o valor de %i. \n",notas[cont],qtd_notas);
}
system("PAUSE");
return 0;
}
|
Markdown | UTF-8 | 13,690 | 2.703125 | 3 | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | permissive | # Using the AWS Cost Explorer API with Cost Insights
Cost Insights currently does not provide a CostInsightsApi client out of the box, this is left up to the implementer. We plan to provide an open-source client and backend eventually that can pull cost data from different cloud providers. In the meantime, we briefly explored the AWS Cost Explorer API and wanted to share our findings. Please contribute to this documentation if you try any experiments with AWS Cost Explorer.
**Note:** Each request using the Cost Explorer API will incur a cost of \$0.01. If you anticipate high usage, adding some caching of Cost Explorer API responses could prove worthwhile over time.
## Authentication
The CostExplorerClient needs to be initialized with access keys tied to an IAM account. You'll need to attach the Cost Explorer policy to the IAM account to be able to make requests to the Cost Explorer API.
Cost Explorer permission policy:
```JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ce:*"
],
"Resource": [
"*"
]
}
]
}
```
## Setup
Install the AWS Cost Explorer SDK. The AWS docs recommend using the SDK over making calls to the API directly as it simplifies authentication and provides direct access to commands.
```bash
# From your Backstage root directory
yarn add --cwd packages/app @aws-sdk/client-cost-explorer
```
## Usage of the SDK
1. Initiate a CostExplorerClient with the appropriate configuration (e.g. credentials, region).
```ts
const client = new CostExplorerClient({
region: 'REGION',
credentials: {
accessKeyId: 'ACCESSKEYID',
secretAccessKey: 'SECRETACCESSKEY',
},
});
```
2. Initiate a command with the relevant input parameters. The SDK provides a variety of commands, but you can access most cost data using the [GetCostAndUsageCommand](https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostAndUsage.html) commands with the relevant [parameters](#GetCostAndUsageCommand-Parameters).
```ts
const command = new GetCostAndUsageCommand(params);
```
3. Call the `send` operation on the Cost Explorer client with the command object.
```ts
// async/await.
try {
const data = await client.send(command);
// process data.
} catch (error) {
// error handling.
} finally {
// finally.
}
```
## Implementing methods on [CostInsightsApi](https://github.com/backstage/backstage/blob/master/plugins/cost-insights/src/api/CostInsightsApi.ts)
We can use the data provided by the Cost Explorer API to implement CostInsightsApi methods such as `getGroupDailyCost`, `getProjectDailyCost`, and `getProductInsights`. You'll still need to provide external data for methods such as `getUserGroups` and `getAlerts`.
### 1. [getGroupDailyCost](https://github.com/backstage/backstage/blob/e0506af8fc54074a160fb91c83d6cae8172d3bb3/plugins/cost-insights/src/api/CostInsightsApi.ts#L119)
The `getGroupDailyCost` method is expected to return daily cost aggregations for a given group and interval time frame as a [`Cost`](https://github.com/backstage/backstage/blob/master/plugins/cost-insights-common/src/types/Cost.ts).
#### Total Daily cost
By using the `GetCostAndUsageCommand` command with some simple parameters, you should be able to use the response to construct a `Cost` object to represent daily cost aggregations.
Sample command:
```ts
const command = new GetCostAndUsageCommand({
TimePeriod: { Start: '2020-12-01', End: '2021-01-02' },
Metrics: ['Unblended Cost'],
Filter: {
Dimensions: { Key: 'LINKED_ACCOUNT', Values: ['ACCOUNT_ID'] },
},
Granularity: 'DAILY',
});
```
The response provides a `ResultsByTime` array, where each [object](https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_ResultByTime.html) contains the time period and costs for a single day. This should give you enough data to represent the `aggregation` field with some minor reformatting.
Sample response:
```ts
{
...
ResultsByTime: [
{
Estimated: false,
TimePeriod: {
End: '2020-12-02',
Start: '2020-12-01',
},
Total: { UnblendedCost: { Amount: '9392.30', Unit: 'USD' } },
},
{
Estimated: false,
TimePeriod: {
End: '2020-12-03',
Start: '2020-12-02',
},
Total: { UnblendedCost: { Amount: '1543.93', Unit: 'USD' } },
},
],
}
```
#### Daily cost breakdown
You can optionally provide a `groupedCosts` field on the `Cost` object to view daily costs broken down by specific groupings. Each key-value pair on `groupedCosts` will result in an additional tab in the top panel that displays an area chart of costs broken down by that key.
You can get grouped daily costs from the API by using the `GetCostAndUsageCommand` command with a [`GroupBy`](https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostAndUsage.html#awscostmanagement-GetCostAndUsage-request-GroupBy) parameter. For example, you can use the `SERVICE` dimension to group costs by cloud product.
Sample command:
```ts
const command = new GetCostAndUsageCommand({
TimePeriod: { Start: '2020-12-01', End: '2021-01-02' },
Metrics: ['Unblended Cost'],
Filter: {
Dimensions: { Key: 'LINKED_ACCOUNT', Values: ['ACCOUNT_ID'] },
},
Granularity: 'DAILY',
GroupBy: [
{
Type: 'DIMENSION',
Key: 'SERVICE',
},
],
});
```
The `ResultsByTime` objects provide a `Groups` array with an entry for each group and its costs for the given day. Since `groupedCosts` expects a separate `Cost` object per group, you'll need to aggregate daily cost data for each group from the response.
Sample Response:
```ts
{
...
ResultsByTime: [
{
TimePeriod: {
End: '2020-12-02',
Start: '2020-12-01',
},
Estimated: false,
Groups: [
{
Keys: ['Amazon Simple Storage Service'],
Metrics: {
UnblendedCost: { Amount: '169.442', Unit: 'USD' },
},
},
{
Keys: ['Amazon Relational Database Service'],
Metrics: {
UnblendedCost: { Amount: '74.11115', Unit: 'USD' },
},
},
...
],
},
],
}
```
Sample `groupedCosts` based on the response:
```ts
{
product: [
{
id: 'Amazon Simple Storage Service',
aggregation: [
{ date: '2020-12-01', amount: 169.442 },
...,
]
},
{
id: 'Amazon Relational Database Service',
aggregation: [
{ date: '2020-12-01', amount: 74.11115 },
...
]
},
]
}
```
### 2. [getProjectDailyCost](https://github.com/backstage/backstage/blob/e0506af8fc54074a160fb91c83d6cae8172d3bb3/plugins/cost-insights/src/api/CostInsightsApi.ts#L137)
The `getProjectDailyCost` method is expected to return daily cost aggregations for a given billing entity and interval time frame as a [`Cost`](https://github.com/backstage/backstage/blob/master/plugins/cost-insights-common/src/types/Cost.ts).
This should be similar to the `getGroupDailyCost` method implementation, but with an updated `LINKED_ACCOUNT` filter to get narrower cost data for a lower-level linked account.
### 3. [getProductInsights](https://github.com/backstage/backstage/blob/e0506af8fc54074a160fb91c83d6cae8172d3bb3/plugins/cost-insights/src/api/CostInsightsApi.ts#L165)
The `getProductInsights` method is expected to return cost aggregations for a particular cloud product and interval time frame as an [`Entity`](https://github.com/backstage/backstage/blob/master/plugins/cost-insights-common/src/types/Entity.ts).
#### Cloud product cost by resource
The Cost Explorer API doesn't provide resource level costs by default. To achieve this, you need to add [cost allocation tags](#cost-allocation-tags) to each resource and use those tags to group costs.
Once resources have been tagged, we can filter by the service (ex: S3) and group by the tag key (ex: S3-Bucket-Name). Any resources that do not have a value for the given tag will be grouped into a single cost group where the key is not the bucket name, but the tag key with a $ appended (ex: S3-Bucket-Name$). We can aggregate the daily costs for each resource and provide the data for the comparison in the bar chart.
Sample command:
```ts
const command = new GetCostAndUsageCommand({
TimePeriod: {
End: '2020-12-02',
Start: '2020-12-01',
},
Metrics: ['UnblendedCost'],
Granularity: 'DAILY',
Filter: {
And: [
{ Dimensions: { Key: 'LINKED_ACCOUNT', Values: ['ACCOUNT_ID'] } },
{
Dimensions: {
Key: 'SERVICE',
Values: ['Amazon Simple Storage Service'],
},
},
],
},
GroupBy: [{ Type: 'TAG', Key: 'S3-Bucket-Name' }],
});
```
The `ResultsByTime` objects provide a `Groups` array with an entry for each resource and its costs for the given day. You'll need to aggregate cost data into two bucketed time periods (e.g. month vs month, or quarter vs quarter) for each resource since this is the expected data type for the `aggregation` field on `Entity`.
Sample response:
```ts
{
...
ResultsByTime: [
{
TimePeriod: {
End: '2020-12-02',
Start: '2020-12-01',
},
Estimated: false,
Groups: [
{
Keys: ['S3-Bucket-Name$'],
Metrics: {
UnblendedCost: { Amount: '345.23', Unit: 'USD' },
},
},
{
Keys: ['Bucket1'],
Metrics: {
UnblendedCost: { Amount: '111.09', Unit: 'USD' },
},
},
{
Keys: ['Bucket2'],
Metrics: {
UnblendedCost: { Amount: '254.1111', Unit: 'USD' },
},
},
],
},
],
};
```
#### Resource cost breakdown
There are a couple of options for breaking down costs for a resource.
1. We can use `USAGE_TYPE` (units used to measure usage for each service) supported by the `GroupBy` field. This requires the lowest amount of effort as we can easily add it to the existing resource request. Examples usage types for EC2: `BoxUsage:c1.medium(Hrs)`, `BoxUsage:m3.xlarge(Hrs)`, and `BoxUsage:t1.micro(Hrs)`
2. Similar to resources, we can use custom tags to group the data. For example, you’re able to tag objects within a bucket so that would be one way to get more granularity within a resource. More info on object tagging [here](https://docs.aws.amazon.com/AmazonS3/latest/dev/object-tagging.html).
## Cost Allocation Tags
Tags are labels that you can assign to an AWS resource, each with a key and value. You can use cost allocation tags to track your AWS costs on a detailed level. You can tag resources through the AWS UI by using the Tags tab on the relevant resource screen. You can also add tags programmatically via the relevant cloud product API.
After tagging your resources (either through UI or API), you still need to activate the tags through the UI. Once tags are activated there’s a 24-hour delay until you see the data in Cost Explorer. The tags don’t apply to historical data, so you only get cost allocation for dates after the tag activation date. More info on activating tags [here](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/activating-tags.html).
### Adding Tags
We've looked into how tagging works for some popular AWS products, but unfortunately the methods seem to be different depending on the service. You'd also need to implement the client and get permissions for each service to be able to add tags programmatically.
S3 Tagging:
There's currently no capability to specify a tag during bucket creation. You must first create the bucket and then perform a second action to add the tag. You can tag buckets through the AWS console, but in order to do this programmatically, you'll need to use and have access to the S3 API. Additionally, there's no way to specify multiple buckets when tagging, so you would need to make a request to tag each bucket. More on tagging buckets through the API [here](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketTagging.html).
Similar to S3, you can add tags through the UI as well the EC2 API itself. The [`CreateTags`](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) method allows you to tag multiple resources (up to a 1000) at a time. You can also specify tags when launching instances or include them in the launch templates. More on EC2 tagging [here](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html).
## [GetCostAndUsageCommand Parameters](https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostAndUsage.html#API_GetCostAndUsage_RequestParameters)
1. TimePeriod (required):
Expects an inclusive `Start` and exclusive `End` date in YYYY-MM-DD format.
2. Metrics (required):
Valid values: AmortizedCost, BlendedCost, NetAmortizedCost, NetUnblendedCost, NormalizedUsageAmount, UnblendedCost, and UsageQuantity
While you can choose any cost dataset, we've used 'UnblendedCost' in the examples above as it is used by the majority of AWS users. More information on different cost types [here](https://aws.amazon.com/blogs/aws-cost-management/understanding-your-aws-cost-datasets-a-cheat-sheet/).
3. Granularity:
Valid values: DAILY, MONTHLY, or HOURLY.
We've used the 'DAILY' granularity above as it allows for the most flexibility depending on the requested time period.
4. GroupBy:
Valid values: AZ, INSTANCE_TYPE, LEGAL_ENTITY_NAME, LINKED_ACCOUNT, OPERATION, PLATFORM, PURCHASE_TYPE, SERVICE, TAGS, TENANCY, RECORD_TYPE, and USAGE_TYPE.
|
Python | UTF-8 | 1,815 | 3.15625 | 3 | [] | no_license | # python3
import sys, threading, os
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class TreeHeight:
def __init__(self):
self.n = 0
self.parent = None
self.cache = [0]
def set(self, file):
with open(file) as source:
self.n = int(source.readline())
self.parent = list(map(int, source.readline().split()))
self.cache = [0] * self.n
def read(self):
self.n = int(sys.stdin.readline())
self.parent = list(map(int, sys.stdin.readline().split()))
self.cache = [0] * self.n
def cached_len(self, node_id):
parent = self.parent[node_id]
if parent == -1:
return 1
if self.cache[node_id]:
return self.cache[node_id]
self.cache[node_id] = 1 + self.cached_len(self.parent[node_id])
return self.cache[node_id]
def compute_height(self):
"""Computes the tree height."""
return max([self.cached_len(i) for i in range(self.n)])
def main():
def prod():
tree = TreeHeight()
tree.read()
print(tree.compute_height())
def test():
test_input = [name for name in os.listdir('./tests') if 'a' not in name]
test_output = [name for name in os.listdir('./tests') if 'a' in name]
for input_val, output_val in zip(test_input,test_output):
tree = TreeHeight()
tree.set('./tests/' + input_val)
with open('./tests/' + output_val) as result_file:
result = int(result_file.readline())
print(result)
print(tree.compute_height())
assert(result == tree.compute_height())
prod()
threading.Thread(target=main).start()
|
C++ | UTF-8 | 1,464 | 2.9375 | 3 | [] | no_license | /* ################################################################# */
/* FILE: TileFactory.h DATE: december 2010
/* PURPOSE: Factory design pattern
/* AUTHOR: Jonas ORINOVSKI, EZJONAS@GMAIL.COM or JORINOVSKI@GMAIL.COM
/* ################################################################# */
#include "stdafx.h"
typedef map <char, ifstream *> file_map_t;
typedef file_map_t :: iterator file_map_iter_t;
class TileFactory
{
public:
TileFactory()
{
}
Tile * BuildTile(char _c)
{
if(_c < 'A' || _c > 'Z')
return NULL;
return new Tile(_c);
// switch(_c)
// {
// case 'A': return new TileA;
// case 'B': return new TileB;
// case 'C': return new TileC;
// case 'D': return new TileD;
// case 'E': return new TileE;
// case 'F': return new TileF;
// case 'G': return new TileG;
// case 'H': return new TileH;
// case 'I': return new TileI;
// case 'J': return new TileJ;
// case 'K': return new TileK;
// case 'L': return new TileL;
// case 'M': return new TileM;
// case 'N': return new TileN;
// case 'O': return new TileO;
// case 'P': return new TileP;
// case 'Q': return new TileQ;
// case 'R': return new TileR;
// case 'S': return new TileS;
// case 'T': return new TileT;
// case 'U': return new TileU;
// case 'V': return new TileV;
// case 'W': return new TileW;
// case 'X': return new TileX;
// default: return NULL;
// }
}
}; |
Java | UTF-8 | 297 | 2.25 | 2 | [] | no_license | package kalah;
/**
*
* @author Eugene Fong (efon103)
*/
public interface IGame {
public void next(int command);
public int move(int command);
public int nextTurn();
public int currentTurn();
public boolean endGame();
public GameBoard board();
public void gameOver();
}
|
Markdown | UTF-8 | 2,095 | 2.78125 | 3 | [] | no_license | ---
name: "Chocolate Ganache Tart Recipe"
slug: "chocolate-ganache-tart-recipe"
layout: 'RecipeLayout'
prepTime: "120"
cuisine: "Continental"
cuisineSlug: "continental"
image: "https://www.archanaskitchen.com/images/archanaskitchen/1-Author/Swayampurna_Mishra/Chocolate_ganache_tart_original-2.jpg"
excerpt: "To begin making the Chocolate Ganache Tart Recipe, first make the crust according to the recipe"
---
### Ingredients
- 4 Fresh Cherries - (or fruits or whipped cream of your choice).
- 340 grams Dark chocolate - (bournville rich cocoa from india works fantastic).
- 1 teaspoon Rock Salt.
- 1 All Purpose Pie Crust.
- 200 ml Heavy whipping cream - (Amul Cream).
### Instructions
1. To begin making the Chocolate Ganache Tart Recipe, first make the crust according to the recipe.
1. Here is the recipe to make the all purpose pie crust.
1. Once the crust is chilled, roll it out into the size to fit the size of a mini tart pan or a 9 inch tart pan.
1. Take care to roll, life and carefully place the pie crust into the tart pan.
1. Preheat the oven to 180 C.
1. Place the pie crust in the preheated and bake for 12 to 15 minutes or until the crust is lightly golden brown.
1. Once the crust is baked, remove from the oven and allow crust to cool in pan while the ganache is prepared.
1. To begin making the Chocolate Ganache Recipe, first place the cream in a saucepan over medium heat and bring to boil.
1. Remove from heat and add the chopped dark chocolate into the cream.
1. Bring the saucepan, back to the heat and keep stirring the chocolate and the cream on low flame until the chocolate melts and until the mixture is glossy and smooth.
1. Once you have a smooth chocolate and cream mixture, set the ganache aside to cool completely.
1. Pour chocolate ganache into cooled crust and chill in refrigerator for a minimum of 4 hours or until set.
1. When set, sprinkle sea salt flakes over the top.
1. Top the Chocolate Ganache Tart with fresh cherries or whipped cream and serve.
1. Serve the Chocolate Ganache Tart Recipe for a quick Dessert for a Special Dinner.
|
Python | UTF-8 | 1,425 | 3.46875 | 3 | [
"MIT"
] | permissive | #se copian las tablas de las bases aqui
class Tabla(object):
def __init__(self, basedatos,nombre,columna,modo):
self.base=basedatos #nombre base
self.tabla = nombre #nombre tabla
self.columnas = columna #numero de columnas
self.modo=modo #modo en que se guardo la tabla
self.pk=None # pk de la tabla
self.fk=None # fk de la tabla
self.datos=[] #las tablas que se guardan abajo se muestra como se guardo
self.codificado=[] # datos de tuplas codificadas
self.compreso = False
def __str__(self) -> str:
return f" MODOTABLA {self.modo} nombreBase {self.base} NOmbreTabla {self.tabla} Ncol {self.columnas} PK {self.pk} FK {self.fk} tuplas {self.datos} "
class Base(object):
def __init__(self, basedatos,modo,encoding):
self.base=basedatos
self.modo=modo
self.encoding=encoding
self.compreso = False
def __str__(self) -> str:
return f" Base {self.base} modo {self.modo} encoding {self.encoding} "
''' ASI SE GUARDAN LOS DATOS DE LAS TABLAS (TUPLAS)
lista=["base","cero","hola"]
lista1=["base1","uno","hola"]
lista2=["base2","dos","hola"]
lista3=["base3","tres","hola"]
lista4=["base4","cuatro","hola"]
dic={}
dic[lista[0]]=lista
dic[lista1[0]]=lista1
dic[lista2[0]]=lista2
dic[lista3[0]]=lista3
dic[lista4[0]]=lista4
for d in dic.values():
print(d)
''' |
Markdown | UTF-8 | 10,766 | 3.140625 | 3 | [] | no_license | MySQL_Note_0
===
**提要**
* 内容目前到书籍《MySQL必知必会》第九章"使用正则表达式搜索"前为止
* 知识点顺序与书本不完全一致:先是命题,然后是SQL语句
* 表达方式可能不适应一般的阅读习惯
* 对 SQL 语句的书写方式,更推荐该书上的写法
**内容概览**
关键字 | 功能介绍 | 性质 | 注意点(规则) |
-|-|-|-
USE | 选择数据库 | 语句 |
SHOW | 了解数据库 | 语句 |
SELECT | 检索数据库 | 语句 |
DISTINCT | 检索不同的行 | 关键字 | 放置在要修饰的列名之前
LIMIT | 限定结果 | 子句 | 后跟数字x解释为限定x行,跟(x,y)则解释为限定从行x开始的y行
ORDER BY | 指定排序方向 | 子句 | 应放置在 WHERE 子句的后方
ASC | 升序排序 | 关键字 | 可作为缺省值不写,MySQL也将按照默认(升序)排序
DESC | 降序排序 | 关键字 | 不可缺省,当有多列作为排序依据时,每一列都需要有一个`DESC`关键字在列名之后修饰
WHERE | 指定搜索条件 | 子句 | 应放置在 ORDER BY 子句的前方
BETWEEN | 范围值检查 | 操作符 | 与 `AND`搭配使用-- BETWEEN a AND b(在a和b之间,包括a、b)
AND | 联结前后两个条件 | 操作符 | 前后联结的条件必须同时成立
NULL | 表示为非0不存在任何元素 | 值 | 特殊的空值即不是0也不是空字符的意思
IN | 指定条件范围 | 操作符 | 后跟的条件范围可看做合法值清单
NOT | 否定之后所有条件 | 操作符 | 有且只有一个否定之后所跟条件的功能
LIKE | 模糊搜索模式 | 操作符 | 将字面值、通配符或两者组合构成搜索条件
`*`| 不指定解释为任意 | 通配符 | 不应经常使用,有时可以检索出未知名的列
`%` | 与`*`类似,匹配任意个任意字符 | 通配符 | 表示任意个任意字符,但不能`NULL`比较
`_` | 与`%`类似,匹配单个字符 | 通配符 | 表示单个任意字符,不能与`NULL`比较
开始使用数据库(不使用可视化操作数据库管理工具时)
---
1. Win+R键
1. cmd内输入`MySQL -uroot -p`
1. 键入密码(输入过程中不可见),回车
**-注-**
> 其中的`uroot`中间不要有空格,root 是在安装 MySQL时设置的管理员用户名
>在使用MySQL的语句大小写均可,但是为了养成好习惯,我们应当尽可能将MySQL的内置词纯大写和可以自行定义的词句纯小写区分开来
>每个语句必须以“;”结尾才会被识别为语句结束
开始使用MySQL语句
---
1. 进入MySQL后显示所有可用(当前用户权限范围内)数据库
```sql
SHOW DATABASES;
```
1. 使用数据库,假设库名为 database_name
```sql
USE database_name;
```
1. 显示数据库 database_name 中可用数据表
```sql
SHOW TABLES FROM database_name;
```
1. 显示数据表 table_name 中所有列的信息
```sql
SHOW COLUMNS FROM table_name;
```
*以上语句也可用 `DESCRIBE`语句来代替*
```sql
DESCRIBE table_name;
```
1. 显示数据表 table_name 中所有数据项
```sql
SHOW * FROM table_name;
```
*`*`称为通配符*
1. 检索数据表 table_name 中 column_1,column_2 两列的所有数据项
```sql
SELECT column_1,column_2 FROM table_name;
```
*检索多列时每两个列名之间都用“,”隔开*
1. 检索数据表 table_name 中 column 列中值不同的数据项
```sql
SELECT DISTINCT column FROM table_name;
```
1. 检索数据表 table_name 中 column 列中所有的数据项并显示不多于5行
```sql
SELECT column FROM table_name LIMIT 5;
```
1. 检索数据表 table_name 中 column 列中所有的数据项并显示从行5开始的5行
```sql
SELECT column FROM table_name LIMIT 5,5;
```
1. 检索数据表 table_name 中 column 列中所有的数据项并显示从第5行开始的5行(注意 *行5* 和 *第5行* 的区别)
```sql
SELECT column FROM table_name LIMIT 4,5;
```
1. 检索数据表 table_name 中 column 列中所有内容(table_name在database_name数据库中)
```sql
SELECT table_name.column FROM database_name.table_name;
```
1. 以 column_1 列字母顺序检索table_name 中 column_1,column_2 列所有数据项
```sql
SELECT column_1,column_2 FROM table_name ORDER BY column_1;
```
1. 检索 table_name 中 column_1,column_2 列所有数据项,首先按照 column_2 列排列,然后按照 column_1 列排列
```sql
SELECT column_1,column_2 FROM table_name ORDER BY column_2,column_1;
```
### 指定排序方向
1. 检索 table_name 中 column 列所有数据项,按照 column 列升序排列
```sql
SELECT column FROM table_name ORDER BY column [ASC];
```
1. 检索 table_name 中 column 列所有数据项,按照 column 列降序排列
```sql
SELECT column FROM table_name ORDER BY column DESC;
```
*以上的1,2 中 ASC关键字可缺省,DESC 必须标出,如若多列时,每个列名之后均要修饰关键词*
1. 检索 table_name 中 column_1,column_2 列所有数据项,首先按照 column_1 降序排列,column_1值相同时按照 column_2 列降序排列
```sql
SELECT column_1,column_2 FROM table_name ORDER BY column_1 DESC,column_2 DESC;
```
1. 检索 table_name 中 column_1,column_2 列所有数据项,首先按照 column_1 降序排列,column_1值相同时按照 column_2 列升序排列
```sql
SELECT column_1,column_2 FROM table_name ORDER BY column_1 DESC,column_2 [ASC];
```
### 检索出该列中最值
*将顺序排列和限制结果结合,即 `ORDER BY`,`LIMIT`结合效果*
1. 检索 table_name 中 column 列中的最大值
```sql
SELECT column FROM table_name ORDER BY column_1 DESC LIMIT 1;
```
1. 检索 table_name 中 column 列中的最小值
```sql
SELECT column FROM table_name ORDER BY column_1 [ASC] LIMIT 1;
```
### 指定搜索条件
1. 检索 table_name 的 column 列中的值为 para_value 的数据项的所有信息
```sql
SELECT * FROM table_name WHERE column = para_value;
```
1. 检索 table_name 的 column 列中的值不为 para_value 的数据项的所有信息
```sql
SELECT * FROM table_name WHERE column <> para_value;
```
1. 检索 table_name 的 column 列中值不为 "String" 的数据项的所有信息
```sql
SELECT * FROM table_name WHERE column = "String";
```
*其中在 MySQL 中 String 和 string 字符串值是相同的,执行匹配时默认不区分大小写*
### 范围值检查
1. 检索 table_name 的 column 列中值在为 x-y (包括x,y)之间的数据项的所有信息
```sql
SELECT column FROM table_name BETWEEN x AND y;
```
### 空值检查
1. 检索 table_name 的column_2 列值为空(column_2字段为NULL)的数据项的 column_1,column_3 列的所有信息
```sql
SELECT column_1,column_3 FROM table_name WHERE column_2 IS NULL;
```
*在这里需要区别空值NULL和不匹配的概念*
### 组合WHERE子句加强数据过滤
+ *为了对不只一个列进行过滤,使用 `AND` 和 `OR` 操作符进行过滤控制*
1. 检索 table_name 的 column_1 列值为空,且 column_2 列的值小于x的所有行的所有信息
```sql
SELECT * FROM table_name WHERE column_1 IS NULL AND column_2 < x ;
```
*当使用超过2个需要同时成立的过滤条件时,每加一条就要增加一个 `AND`*
1. 检索 table_name 的 column_1 列值为空,且 column_2 列的值小于 x 的所有行的所有信息
```sql
SELECT * FROM table_name WHERE column_1 IS NULL AND column_2 < x ;
```
1. 检索 table_name 的 column_1 列值为空,或者 column_2 列的值不小于 x 的所有行的所有信息
```sql
SELECT * FROM table_name WHERE column_1 IS NULL OR column_2 >= x ;
```
+ *WHERE 子句内可以包含任意数目的 `AND` 和 `OR` 操作符,并组合使用*
1. 检索 table_name 的 column_1 列值为空或等于 para_value ,并且 column_2 列的值不小于 x 的所有行的所有信息
```sql
SELECT * FROM table_name WHERE ( column_1 IS NULL OR column_1 = para_value ) AND column_2 >= x ;
```
*以上的圆括号运算优先级较 `AND` 和 `OR` 更高,能够使column_1的两个数据过滤条件先行,操作符不会被错误地组合*
+ *IN 操作符指定条件范围,范围中的每个条件都可以进行匹配*
1. 检索 table_name 的 column_1 列值为 value_0 和等于 value_1 的所有行的所有信息
```sql
SELECT * FROM table_name WHERE column_1 IN ( value_0 , value_1 );
```
*也可以将 `IN` 操作符后面的括号内看成是由逗号间隔的过滤条件合法值清单*
+ *将 OR 和 ORDER BY 操作符进行组合*
1. 检索 table_name 的 column_1 列值为 value_0 或等于 value_1 的所有行的所有信息按照 column_3 列的顺序进行排列
```sql
SELECT * FROM table_name WHERE column_1 = value_0 OR column_1 = value_1 ORDER BY column_3;
```
*实际上也可以继续回到 `IN` 操作符的用法来实现 `OR` 的功能*
```sql
SELECT * FROM table_name WHERE column_1 IN ( value_0 , value_1 ) ORDER BY column_3;
```
**可以看出实际上 IN 操作符的合法值清单要比 OR 更直观易读,不失为 IN 的优点之一**
### `NOT`操作符:否定之后所跟的任何条件
1. 检索 table_name 的 column_1 列值不为 value_0 或 value_1 的所有行的所有信息
```sql
SELECT * FROM table_name WHERE column_1 NOT IN ( value_0 , value_1 );
```
### `LIKE` 操作符
+ 引入 **通配符** 和 **搜索模式**
* 用来匹配值的一部分的特殊字符 —— **通配符**
* 由字面值、通配符或两者结合组成的"搜索"条件
#### 百分号`%`通配符
`%`表示任何字符出现任意次数
* 以字母`xyz`开头的所有值就可写作 `xyz%`
* `%xyz%`——匹配任何位置包含`xyz`的文本
* `%xyz`——匹配文本以`xyz`为结尾 的文本
* `x%z`——匹配以`x`开头以`z`结尾的文本
*这里的搜索条件是区分大小写的,`xyz%`和 `Xyz%`是不同的值*
*`%`能够匹配0个,1个或是多个字符,而匹配0个字符的时候涉及到**尾空格**的问题*
*`%`不能够匹配`NULL`,即*
```sql
SELECT * FROM table_name WHERE column LIKE '%';
```
是无法匹配搜索到值为`NULL`的行
#### 下划线`_`通配符
用途与`%`类似,但是只为匹配单个字符
#### 通配符的注意事项
* 处理时间较其他操作符更长
* 不要过度使用,尽能使用其他操作符代替
* 注意使用的位置正确与否 |
Python | UTF-8 | 2,025 | 3.328125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup # из bs4 вытаскиваем BeautifulSoup
URL="https://obmen24.com.ua/" # адрес который будем парсить
HEADERS={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36', "accept":"*/*"}
#заголовки нужны чтоб сайт воспринемал нас как браузер, а не как бот
HOST ="https://obmen24.com.ua/"
def get_html(url, params=None):
r=requests.get(url, headers=HEADERS, params=params)
return r
def creating_dictionary1 (items):
k=[]
half_dic=[]
for item in items:
k.append(item.text.strip())
for elem in range(2, len(k),2):
half_dic.append(str(k[elem])+'/'+str(k[elem+1]))
return half_dic
def creating_dictionary2(items_currency):
half_dic = []
for item in items_currency:
half_dic.append(item.text.strip().replace(' ','').replace('\n','/'))
half_dic=half_dic[1:]
return half_dic
def combine_dic(items, items_currency):
kurs={}
half_dic1 = []
half_dic2 = []
half_dic1 = creating_dictionary1(items)
half_dic2 = creating_dictionary2(items_currency)
kurs=dict(zip(half_dic2,half_dic1))
return kurs
def get_content(html):
soup=BeautifulSoup(html, 'html.parser') # 'html.parser' - параметр указывающий, что разбераем html-формат
items_currency=soup.findAll("span", {"class": "indexspancurrency"})
items=soup.findAll("span", {"class": "indexspanbuy"})
kurs={} #создаем словарь c курсами
kurs=combine_dic(items,items_currency)
return kurs
def parse():
html=get_html(URL)
if html.status_code== 200:
kurs=[] # пустой список
kurs=get_content(html.text) #дополняем список данными
else:
print ('ERROR')
return kurs
# parse() |
JavaScript | UTF-8 | 492 | 3.0625 | 3 | [] | no_license | /**
* @param {number[]} nums
* @return {number}
*/
var deleteAndEarn = function (nums) {
var record = [], dp = []
var max = Math.max(...nums)
for (let i = 0; i <= max; i++) {
record[i] = 0
dp[i] = 0
}
nums.forEach(x => { record[x] += x })
var max = record[1]
dp[1] = record[1]
for (let i = 2; i < dp.length; i++) {
dp[i] = Math.max(dp[i - 2] + record[i], dp[i - 1])
max = Math.max(max, dp[i])
}
return max
}
|
JavaScript | UTF-8 | 403 | 3.625 | 4 | [] | no_license | function calFeet(meter) {
return (3.279 * meter);
}
function cal1() {
let input1 = document.getElementById("meter").value;
document.getElementById("result1").innerHTML = calFeet(input1);
}
function calMeter(feet) {
return (0.305 * feet);
}
function cal2() {
let input2 = document.getElementById("feet").value;
document.getElementById("result2").innerHTML = calMeter(input2);
} |
Python | UTF-8 | 2,412 | 2.84375 | 3 | [] | no_license | import socket
import argparse
import signal
import sys
from threading import Thread
def signal_handler(signal, frame):
print("terminating client...", flush=True)
sys.exit()
class messageThread(Thread):
def __init__(self, ip, name):
Thread.__init__(self)
self.ip = ip
self.name = name
def run(self):
while True:
data = sock.recv(1024)
DATA_NEW = data.decode('utf-8').split()
MESSAGE = ""
RECV = DATA_NEW[0]
if RECV == "recvfrom":
SENDER_NAME = str(DATA_NEW[1])
del DATA_NEW[0]
del DATA_NEW[0]
for x in DATA_NEW:
if x == DATA_NEW[len(DATA_NEW) - 1]:
MESSAGE = x + MESSAGE
else:
MESSAGE = x + MESSAGE + " "
print(SENDER_NAME + ": " + MESSAGE, flush=True)
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler)
parser = argparse.ArgumentParser()
parser.add_argument("-p", required=True
, help="Add port number to run server on."
, type=int)
parser.add_argument("-s", required=True
, help="Chat server IP address.")
parser.add_argument("-n", required=True
, help="Name of the client")
args = parser.parse_args()
UDP_IP = args.s
UDP_PORT = args.p
CLIENT_NAME = args.n
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
REGISTER = "register " + CLIENT_NAME
REGISTER = REGISTER.encode('utf-8')
sock.sendto(REGISTER, (UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024)
DATA_NEW = data.decode('utf-8')
SUCC_REG = "welcome " + CLIENT_NAME
if DATA_NEW == SUCC_REG:
print("connected to server and registered " + CLIENT_NAME, flush=True)
newThread = messageThread(UDP_IP, CLIENT_NAME)
newThread.daemon = True
newThread.start()
while True:
RAW_MESSAGE = input("")
PROC_MESSAGE = RAW_MESSAGE.split()
if RAW_MESSAGE == 'exit':
print("terminating client...", flush=True)
break
elif PROC_MESSAGE[0] == "sendto":
MESSAGE = RAW_MESSAGE.encode('utf-8')
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT)) |
C++ | UTF-8 | 1,020 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include <stdlib.h>
using namespace std;
// we assume the string length is 10
void replaceSpaces(string str, int trueLength){
int spaceCount =0, index, i=0;
for(int i=0; i<trueLength; i++){
if(str[i]==' '){
spaceCount++;
}
}
cout<<"space count="<<spaceCount<<endl;
index = trueLength + spaceCount*2;
int index2 = index;
cout<<"index="<<index<<endl;
cout<<"string length="<<str.length()<<endl;
char *str2;
str2 = (char*) malloc(index+1);
for(int i=trueLength-1; i>=0; i--){
if(str[i]==' '){
str2[index-1] = '0';
str2[index-2] = '2';
str2[index-3] = '%';
index = index-3;
}else{
str2[index - 1] = str[i];
index--;
}
}
for(int i=0; i<index2; i++){
cout<<str2[i];
}
}
int main(){
char str[100];
// cin>>str;
cin.getline(str,sizeof(str));
replaceSpaces(str, 10);
return 0;
}
|
SQL | UTF-8 | 1,482 | 3.15625 | 3 | [] | no_license |
CREATE DATABASE dahuadb_face;
use dahuadb_face ;
CREATE TABLE `face_detection_camera`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`camera_name` varchar(100),
`camera_type` varchar(100),
`camera_ip` varchar(100),
`venue_id` varchar(50),
`device_id` varchar(100),
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
CREATE TABLE `face_demographics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`api_id` int(11) NOT NULL,
`timestamp` varchar(100),
`camera_id` int(11),
`gender` varchar(50),
`age` varchar(50),
`emotion` varchar(50),
`age_range` varchar(50),
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`, `api_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
CREATE TABLE `face_demographics_record`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` varchar(100),
`camera_id` int(11),
`gender` varchar(50),
`age` varchar(50),
`age_range` varchar(50),
`beginAge` varchar(100),
`endAge` varchar(100),
`emotion` varchar(200),
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
|
Ruby | UTF-8 | 447 | 3.921875 | 4 | [] | no_license | # Write a program that can calculate the Hamming difference
# between two DNA strands.
class DNA
def initialize(dna_one)
@dna_one = dna_one
end
def count_differences
count = 0
@dna_one.chars.zip(@dna_two.chars).each do |sub_ary|
next if sub_ary.compact.length < 2
count += 1 if sub_ary.uniq.length > 1
end
count
end
def hamming_distance(dna_two)
@dna_two = dna_two
count_differences
end
end
|
Python | UTF-8 | 701 | 3.46875 | 3 | [] | no_license | import numpy as np
import time
numbers = list(range(1,1000001))
time1 = time.time()
for i in numbers:
pass
time2 = time.time()
array1 = np.array(numbers)
time3 = time.time()
for x in array1:
pass
time4 = time.time()
print("Time stamp for List: ",time2-time1)
print()
print("Time stamp for numpy: ",time4-time3)
print()
num = [10,20,40,50,60,670,3,2,45,67,11,989,4534,423,42,126,64,1253,5732,276]
tim1= time.time()
print("The maximum from list: ", max(num))
tim2 = time.time()
tim3 = time.time()
arr = np.array(num)
print("Maximum from numpy array: ", np.max(num))
tim4 = time.time()
print("Time stamp for List: ", tim2-tim1)
print()
print("Time stamp for numpy array: ", tim4-time3)
|
Java | UTF-8 | 1,571 | 2.375 | 2 | [] | no_license | package gmail.carlosparrilla32.com.init;
import cpw.mods.fml.common.registry.EntityRegistry;
import net.minecraft.entity.EntityList;
import gmail.carlosparrilla32.com.Main;
import gmail.carlosparrilla32.com.help.Reference;
import gmail.carlosparrilla32.com.help.RegisterHelper;
import gmail.carlosparrilla32.com.entity.EntityTest;
public class ModEntities
{
static int startEntityID;
static int i;
public static void init()
{
registerModEntity(EntityTest.class, "Test");
}
public static void registerModProjectile(Class entityClass, String name)
{
EntityRegistry.registerModEntity(entityClass, name, ++startEntityID, Reference.MODID, 64, 10, true);
System.out.println("Registering mod projectile " + name + " with ID = " + startEntityID);
}
public static void registerModEntity(Class entityClass, String name)
{
EntityRegistry.registerModEntity(entityClass, name, ++startEntityID, Reference.MODID, 80, 3, false);
System.out.println("Registering mod entity " + name + " with ID = " + startEntityID);
}
public static void registerModEntityEgg(Class entityClass, String name, int primary, int secondary)
{
registerModEntity(entityClass, name);
if (i == 0)
{
registerSpawnEgg(name, primary, secondary);
++i;
}
}
public static void registerSpawnEgg(String name, int primary, int secondary)
{
}
public static int getUniqueEntityId()
{
do
{
startEntityID++;
}
while (EntityList.getStringFromID(startEntityID) != null);
return startEntityID;
}
}
|
C# | UTF-8 | 5,120 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | using NUnit.Framework;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
[TestFixture]
public class WebElementTest : DriverTestFixture
{
[Test]
public void ElementShouldImplementWrapsDriver()
{
driver.Url = simpleTestPage;
IWebElement parent = driver.FindElement(By.Id("containsSomeDiv"));
Assert.That(parent, Is.InstanceOf<IWrapsDriver>());
}
[Test]
public void ElementShouldReturnOriginDriver()
{
driver.Url = simpleTestPage;
IWebElement parent = driver.FindElement(By.Id("containsSomeDiv"));
Assert.That(((IWrapsDriver)parent).WrappedDriver, Is.EqualTo(driver));
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void ShouldToggleElementAndCheckIfElementIsSelected()
{
driver.Url = simpleTestPage;
IWebElement checkbox = driver.FindElement(By.Id("checkbox1"));
Assert.That(checkbox.Selected, Is.False);
checkbox.Click();
Assert.That(checkbox.Selected, Is.True);
checkbox.Click();
Assert.That(checkbox.Selected, Is.False);
}
[Test]
public void ShouldThrowExceptionOnNonExistingElement()
{
driver.Url = simpleTestPage;
Assert.That(() => driver.FindElement(By.Id("doesnotexist")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void ShouldGetElementName()
{
driver.Url = simpleTestPage;
IWebElement oneliner = driver.FindElement(By.Id("oneline"));
Assert.AreEqual("p", oneliner.TagName.ToLower());
}
[Test]
public void ShouldGetElementText()
{
driver.Url = simpleTestPage;
IWebElement oneliner = driver.FindElement(By.Id("oneline"));
Assert.AreEqual("A single line of text", oneliner.Text);
IWebElement twoblocks = driver.FindElement(By.Id("twoblocks"));
Assert.AreEqual("Some text" +
System.Environment.NewLine +
"Some more text", twoblocks.Text);
}
[Test]
public void ShouldReturnWhetherElementIsDisplayed()
{
driver.Url = javascriptPage;
IWebElement hidden = driver.FindElement(By.Id("hidden"));
Assert.That(hidden.Displayed, Is.False, "Element with ID 'hidden' should not be displayed");
IWebElement none = driver.FindElement(By.Id("none"));
Assert.That(none.Displayed, Is.False, "Element with ID 'none' should not be displayed");
IWebElement displayed = driver.FindElement(By.Id("displayed"));
Assert.That(displayed.Displayed, Is.True, "Element with ID 'displayed' should not be displayed");
}
[Test]
public void ShouldClearElement()
{
driver.Url = javascriptPage;
IWebElement textbox = driver.FindElement(By.Id("keyUp"));
textbox.SendKeys("a@#$ç.ó");
textbox.Clear();
Assert.AreEqual("", textbox.GetAttribute("value"));
}
[Test]
public void ShouldClearRenderedElement()
{
driver.Url = javascriptPage;
IWebElement textbox = driver.FindElement(By.Id("keyUp"));
textbox.SendKeys("a@#$ç.ó");
textbox.Clear();
Assert.AreEqual("", textbox.GetAttribute("value"));
}
[Test]
public void ShouldSendKeysToElement()
{
driver.Url = javascriptPage;
IWebElement textbox = driver.FindElement(By.Id("keyUp"));
textbox.SendKeys("a@#$ç.ó");
Assert.AreEqual("a@#$ç.ó", textbox.GetAttribute("value"));
}
[Test]
public void ShouldSubmitElement()
{
driver.Url = javascriptPage;
IWebElement submit = driver.FindElement(By.Id("submittingButton"));
submit.Submit();
Assert.That(driver.Url, Does.StartWith(resultPage));
}
[Test]
public void ShouldClickLinkElement()
{
driver.Url = javascriptPage;
IWebElement changedDiv = driver.FindElement(By.Id("dynamo"));
IWebElement link = driver.FindElement(By.LinkText("Update a div"));
link.Click();
Assert.AreEqual("Fish and chips!", changedDiv.Text);
}
[Test]
public void ShouldGetAttributesFromElement()
{
driver.Url = (javascriptPage);
IWebElement dynamo = driver.FindElement(By.Id("dynamo"));
IWebElement mousedown = driver.FindElement(By.Id("mousedown"));
Assert.AreEqual("mousedown", mousedown.GetAttribute("id"));
Assert.AreEqual("dynamo", dynamo.GetAttribute("id"));
}
}
}
|
C# | UTF-8 | 4,656 | 2.609375 | 3 | [] | no_license | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using BoomaEcommerce.Core;
namespace BoomaEcommerce.Data.InMemory
{
public static class RepoContainer
{
public static ConcurrentDictionary<Type, Dictionary<Guid, IBaseEntity>> AllEntities { get; set; } = new();
}
public class InMemoryRepository<T> : IRepository<T> where T : class, IBaseEntity
{
public InMemoryRepository()
{
var dict = new Dictionary<Guid, T>();
RepoContainer.AllEntities.TryAdd(typeof(T), dict.ToDictionary(x => x.Key, x => (IBaseEntity)x.Value));
}
public Task<IEnumerable<T>> FindAllAsync()
{
var entities = RepoContainer.AllEntities[typeof(T)];
return Task.FromResult<IEnumerable<T>>(entities.Values.Select(x => (T)x));
}
public Task<IEnumerable<T>> FilterByAsync(Expression<Func<T, bool>> predicateExp)
{
var entities = RepoContainer.AllEntities[typeof(T)];
var predicate = predicateExp.Compile();
return Task.FromResult(entities.Values.Select(x => (T)x).Where(x => predicate(x)));
}
public Task<IEnumerable<TMapped>> FilterByAsync<TMapped>(Expression<Func<T, bool>> predicateExp, Expression<Func<T, TMapped>> mapExp)
{
var entities = RepoContainer.AllEntities[typeof(T)];
var predicate = predicateExp.Compile();
var mapFunc = mapExp.Compile();
return Task.FromResult(entities.Values.Select(x => (T)x).Where(predicate).Select(mapFunc));
}
public async Task<T> FindOneAsync(Expression<Func<T, bool>> predicateExp)
{
var result = await FilterByAsync(predicateExp);
return result.FirstOrDefault();
}
public Task<T> FindByIdAsync(Guid guid)
{
var entities = RepoContainer.AllEntities[typeof(T)];
return entities.TryGetValue(guid, out var entity)
? Task.FromResult((T)entity)
: Task.FromResult<T>(null);
}
public virtual Task InsertOneAsync(T entity)
{
var entities = RepoContainer.AllEntities[typeof(T)];
entities.TryAdd(entity.Guid, entity);
return Task.CompletedTask;
}
public async Task InsertManyAsync(IEnumerable<T> entities)
{
foreach (var entity in entities)
{
await InsertOneAsync(entity);
}
}
public Task ReplaceOneAsync(T entity)
{
var entities = RepoContainer.AllEntities[typeof(T)];
if (entities.ContainsKey(entity.Guid))
{
entities[entity.Guid] = entity;
}
return Task.CompletedTask;
}
public virtual Task DeleteOneAsync(Expression<Func<T, bool>> predicate)
{
var entities = RepoContainer.AllEntities[typeof(T)];
var pred = predicate.Compile();
foreach (var (guid, entity) in entities)
{
if (pred((T)entity))
{
entities.Remove(guid, out _);
return Task.CompletedTask;
}
}
return Task.CompletedTask;
}
public virtual Task DeleteByIdAsync(Guid guid)
{
var entity = RepoContainer.AllEntities[typeof(T)];
entity.Remove(guid, out _);
return Task.CompletedTask;
}
public Task DeleteManyAsync(Expression<Func<T, bool>> predicate)
{
var entities = RepoContainer.AllEntities[typeof(T)];
var pred = predicate.Compile();
var keysToRemove = entities.Keys.Where(guid => pred((T)entities[guid]));
foreach (var key in keysToRemove)
{
entities.Remove(key, out _);
}
return Task.CompletedTask;
}
public void DeleteRange(IEnumerable<T> entities)
{
throw new NotImplementedException();
}
public Task<TType> FindByIdAsync<TType>(Guid guid)
where TType : class, IBaseEntity
{
var entities = RepoContainer.AllEntities[typeof(T)];
return entities.TryGetValue(guid, out var entity)
? Task.FromResult((TType)entity)
: Task.FromResult<TType>(null);
}
public void Attach(T entity)
{
}
}
}
|
Markdown | ISO-8859-1 | 1,278 | 2.84375 | 3 | [] | no_license | # PHPUnit Logo Suggestions
During the PHPUnit Code Sprint in Hamburg we came up with the task of finding a (new) logo for PHPUnit. This repository holds ideas, sketches and suggestions for now.
## General approach
- it should be flat
- we like the idea of having separate colors for "PHP" and "Unit"
- ideally the logo would contain a reference to code coverage, successfully run tests or similar
## Suggestions
Colors are somewhat off, but I like the checkmark as a sign for a successful test run. The font is Avenir Next Condensed.


One line, the `[x]` is a reference to a passed test with testdox output enabled.


----
Submission from https://github.com/hofmannsven: Thank you!

Variant based on that submission:

----
Submission from [Thorsten Frommen](https://github.com/tfrommen):

The font is Nunito, and the colors are _the PHP color_ as well as the according non-saturated (i.e., monochromatic) variant.
----
Submission from [Ra Siqueira](https://github.com/raisiqueira):

Simple variation of the logo 5, with the Aller Light font
|
Java | UTF-8 | 752 | 1.835938 | 2 | [
"Apache-2.0"
] | permissive | package com.oubowu.ipanda.viewmodel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModel;
import com.oubowu.ipanda.bean.pandalive.TabList;
import com.oubowu.ipanda.repository.PandaLiveRepository;
import com.oubowu.ipanda.util.Resource;
import java.util.List;
import javax.inject.Inject;
/**
* Created by Oubowu on 2018/2/5 14:42.
*/
public class PandaLiveViewModel extends ViewModel {
private PandaLiveRepository mPandaLiveRepository;
@Inject
public PandaLiveViewModel(PandaLiveRepository pandaLiveRepository) {
mPandaLiveRepository = pandaLiveRepository;
}
public LiveData<Resource<List<TabList>>> getTabList(String url) {
return mPandaLiveRepository.getTabList(url);
}
}
|
PHP | UTF-8 | 5,354 | 2.6875 | 3 | [] | no_license | <?php
namespace WordPressdotorg\GitHub\MakeInviter;
function render() {
$allowed_teams = get_allowed_teams();
$all_teams = get_teams();
$teams = [];
foreach ( $allowed_teams as $id ) {
$team = wp_list_filter( $all_teams, [ 'id' => $id ] );
if ( ! $team ) {
continue;
}
$team = array_shift( $team );
// Add the parent..
if ( isset( $team->parent ) ) {
$teams[ $team->parent->id ] = $team->parent;
}
$teams[ $team->id ] = $team;
}
// Add any sub-teams that are not allowed to be selected..
foreach ( $teams as $team ) {
foreach ( $all_teams as $t ) {
if ( $t->parent && $t->parent->id === $team->id && ! in_array( $t->id, $allowed_teams, true ) ) {
$teams[ $t->id ] = clone $t;
}
}
}
// Mark any as disabled as needed.
foreach ( $teams as $team ) {
$team->disabled = ! in_array( $team->id, $allowed_teams, true );
}
if ( isset( $_GET['updated'] ) ) {
$class = 'success';
$message = '';
switch ( $_GET['updated'] ) {
case 'success':
$message = 'Success, invitation sent!';
break;
case 'canceled':
$message = 'Invitation canceled';
break;
case 'error':
$class = 'error';
$message = 'An error occurred inviting this collaborator!';
break;
case 'settings':
$message = 'Settings updated';
break;
case 'no-github':
$class = 'error';
$message = 'The specified WordPress.org account does not have a linked GitHub account.';
break;
}
if ( $message && isset( $_GET['message'] ) ) {
$message .= '<br><em>' . esc_html( $_GET['message'] ) . '</em>';
}
if ( $message ) {
printf(
'<div class="notice notice-%s is-dismissable"><p>%s</p></div>',
$class,
$message
);
}
}
?>
<div class="wrap" id="wp_learn_admin">
<h1>Invite GitHub Member</h1>
<form method="post" action="<?php echo admin_url( 'admin-post.php' ) ?>">
<input type="hidden" name="action" value="github_invite">
<?php wp_nonce_field( 'github_invite' ); ?>
<table class="form-table">
<tr>
<th scope="row"><label for="invite">GitHub Email, GitHub URL, WordPress.org user slug, or WordPress.org Profile URL</label></th>
<td><input type="text" name="invite" id="invite" class="regular-text" placeholder="https://profiles.wordpress.org/<?php echo wp_get_current_user()->user_nicename; ?>/"></td>
</tr>
<tr>
<th scope="row"><label for="team">Teams</label></th>
<td>
<?php
if ( ! $teams ) {
echo '<em>No teams have been configured. Please ask a super-admin via #meta to enable at least one team.</em>';
}
render_team_list( $teams );
?>
</td>
</tr>
</table>
<?php submit_button( 'Invite Collaborator' ); ?>
</form>
<h1>Pending Invites</h1>
<form>
<table class="form-table">
<tr>
<th scope="row">Pending Invitations</th>
<td>
<?php
$pending_invites = get_pending_invites();
if ( ! $pending_invites ) {
echo '<em>No pending invitations</em>';
}
foreach ( $pending_invites as $pending ) {
$can_cancel = in_array( $pending->id, get_option( 'invited_gh_users', [] ), true ) || is_super_admin();
$cancel_url = $can_cancel ? wp_nonce_url( admin_url( 'admin-post.php?action=github_cancel_invite&invite=' . $pending->id ), 'github_cancel_invite_' . $pending->id ) : false;
printf(
'<p>
<strong><code>%s</code></strong>
<em>%s ago</em>
%s
</p>',
$pending->login ?: $pending->email,
human_time_diff( strtotime( $pending->created_at ) ),
$cancel_url ? '<a class="button" href="' . esc_url( $cancel_url ) . '">Cancel</a>' : ''
);
}
?>
</td>
</tr>
</table>
</form>
<?php
// Allow super-admins to set the teams the site users can invite for.
if ( is_super_admin() ) {
?>
<hr>
<h1>Settings</h1>
<form method="post" action="<?php echo admin_url( 'admin-post.php' ) ?>">
<input type="hidden" name="action" value="github_invite_settings">
<?php wp_nonce_field( 'github_invite_settings' ); ?>
<table class="form-table">
<tr>
<th scope="row"><label for="team">Allowed Team(s) for this site <span style="color: red">(super-admin only)</span></label></th>
<td>
<?php render_team_list( $all_teams, $allowed_teams ); ?>
</td>
</tr>
</table>
<?php submit_button( 'Save Settings' ); ?>
</form>
<?php
}
}
/**
* Render the team list.
*/
function render_team_list( $teams, $checked = array(), $for_parent = 0 ) {
if ( $for_parent ) {
$teams = array_filter( $teams, function( $t ) use ( $for_parent ) {
return $for_parent === $t->parent->id ?? 0;
} );
if ( ! $teams ) {
return false;
}
echo '<div class="childen" style="margin-left: 1em">';
}
foreach ( $teams as $team ) {
if ( isset( $team->parent ) && ! $for_parent ) {
continue;
}
?>
<div>
<label>
<input
type="checkbox"
name="team_id[]"
value="<?php echo esc_attr( $team->id ) ?>"
<?php
checked( in_array( $team->id, $checked ) );
disabled( ! empty( $team->disabled ) || in_array( $team->id, get_never_teams() ) );
?>
/>
<?php echo esc_html( $team->name ) ?>
</label>
<?php
// Any child teams of this team?
render_team_list( $teams, $checked, $team->id );
?>
</div>
<?php }
if ( $for_parent ) {
echo '</div>';
}
}
|
C++ | UTF-8 | 776 | 2.703125 | 3 | [] | no_license | #include "Arduino.h"
#include "Info.h"
Info::Info(int count)
{
fileName = new char*[count];
for(int i=0; i<count;i++)
{
fileName[i] = new char[12];
memset(fileName[i],0,12);
}
totalFile = count;
currentFile = 0;
}
void Info::inputFileName(int idx, char* name)
{
strcpy(fileName[idx], name);
}
char* Info::getFileName(int idx)
{
return fileName[idx];
}
int Info::getCurrentFileIndex()
{
return currentFile;
}
int Info::getTotalFile()
{
return totalFile;
}
int Info::currentFileIndexInc()
{
return currentFile++;
}
int Info::setCurrentFileIndex(int idx)
{
currentFile = idx;
}
void Info::initCurrentFileIndex()
{
currentFile = 0;
}
void Info::deleteFileName()
{
for(int i=0; i<totalFile;i++)
{
delete[] fileName[i];
}
delete[] fileName;
}
|
Java | UTF-8 | 470 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package com.landenlabs;
public class JobSpec {
public boolean verbose;
public int jobCount;
public int period;
public String name;
public JobSpec(boolean verbose, int jobCount) {
this.verbose = verbose;
this.jobCount = jobCount;
}
public JobSpec setPeriod(int period) {
this.period = period;
return this;
}
public JobSpec setName(String name) {
this.name = name;
return this;
}
} |
Java | UHC | 4,926 | 2.640625 | 3 | [] | no_license | package JavaChat.Client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.util.StringTokenizer;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
public class Main extends Application {
Socket socket;
TextArea textArea;
DataOutputStream out;
ReceiveCommand command;
String prefix = "";
String nickName = "";
private void startClient(String IP, int port, String name) {
command = new ReceiveCommand(this);
nickName = name;
Thread thread = new Thread() {
public void run() {
try {
socket = new Socket(IP, port);
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(name);
out.flush();
receive();
} catch (ConnectException ce) {
textArea.appendText("[ ] ֽϴ. \n");
} catch (Exception e) {
// TODO: handle exception
if (socket != null && !socket.isClosed()) {
textArea.appendText("[ ] ˼ Ͽϴ.");
stopClient();
Platform.exit();
}
}
};
};
thread.start();
}
protected void receive() {
// TODO Auto-generated method stub
while (true) {
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
String receiveMessage = in.readUTF();
System.out.println("Client receive : "+receiveMessage);
Platform.runLater(() -> {
textArea.appendText(command.checkCommand(receiveMessage));
});
} catch (Exception e) {
// TODO: handle exception
stopClient();
}
}
}
private void stopClient() {
try {
if (socket != null && !socket.isClosed()) {
socket.isClosed();
}
} catch (Exception e) {
// TODO: handle exception
}
}
private void send(String message) {
Thread thread = new Thread() {
public void run() {
try {
out.writeUTF(message);
out.flush();
} catch (Exception e) {
// TODO: handle exception
stopClient();
}
};
};
thread.start();
}
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
root.setPadding(new Insets(5));
HBox xBox = new HBox();
xBox.setSpacing(5);
TextField thField = new TextField();
thField.setPrefWidth(150);
thField.setPromptText("г ԷϽÿ");
HBox.setHgrow(thField, Priority.ALWAYS);
TextField serverIP = new TextField("127.0.0.1");
TextField serverPort = new TextField("9876");
serverPort.setMaxHeight(80);
xBox.getChildren().addAll(thField, serverIP, serverPort);
root.setTop(xBox);
textArea = new TextArea();
textArea.setEditable(false);
root.setCenter(textArea);
TextField input = new TextField();
input.setMaxWidth(Double.MAX_VALUE);
input.setDisable(true);
input.setOnAction(event -> {
send(input.getText());
input.setText("");
input.requestFocus();
});
Button sendBtn = new Button("");
sendBtn.setDisable(true);
sendBtn.setOnAction(event -> {
send(input.getText());
input.setText("");
input.requestFocus();
});
Button connectionButton = new Button("ϱ");
connectionButton.setOnAction(event -> {
if (connectionButton.getText().equals("ϱ")) {
int port = 9876;
try {
port = Integer.parseInt(serverPort.getText());
} catch (Exception e) {
// TODO: handle exception
}
startClient(serverIP.getText().toString(), port, thField.getText().toString());
Platform.runLater(() -> {
textArea.appendText("[äù û]\n");
});
connectionButton.setText("ϱ");
sendBtn.setDisable(false);
input.setDisable(false);
input.requestFocus();
} else {
stopClient();
Platform.runLater(() -> {
textArea.appendText("[äù ]\n");
});
connectionButton.setText("ϱ");
sendBtn.setDisable(true);
input.setDisable(true);
}
});
BorderPane bottomRoot = new BorderPane();
bottomRoot.setLeft(connectionButton);
bottomRoot.setCenter(input);
bottomRoot.setRight(sendBtn);
root.setBottom(bottomRoot);
Scene scene = new Scene(root, 400, 400);
primaryStage.setTitle("[äù Ŭ̾Ʈ]");
primaryStage.setScene(scene);
primaryStage.setOnCloseRequest(event -> {
stopClient();
});
primaryStage.show();
connectionButton.requestFocus();
}
public static void main(String[] args) {
launch(args);
}
}
|
Java | UTF-8 | 3,247 | 2.546875 | 3 | [] | no_license | /** Copyright 2012 University of Washington. All Rights Reserved.
* @author Sai Zhang
*/
package edu.washington.cs.dt.tools;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import edu.washington.cs.dt.OneTestExecResult;
import edu.washington.cs.dt.RESULT;
import edu.washington.cs.dt.TestExecResults;
import edu.washington.cs.dt.runners.AbstractTestRunner;
import edu.washington.cs.dt.runners.FixedOrderRunner;
import edu.washington.cs.dt.runners.RandomOrderRunner;
import edu.washington.cs.dt.util.Files;
import edu.washington.cs.dt.util.Globals;
import edu.washington.cs.dt.util.Utils;
import plume.Option;
import plume.Options;
public class RunTestInFixedOrder {
@Option("See all options")
public static boolean help = false;
@Option("A file containing all tests to be execute")
public static String testFile = null;
@Option("The output file for test results")
public static String outputFile = "./fixed_order_results.txt";
@Option("Randomize the order")
public static boolean random = false;
@Option("Print detailed info")
public static boolean verbose = false;
public static void main(String[] args) {
new RunTestInFixedOrder().nonStaticMain(args);
}
private void nonStaticMain(String[] args) {
parse_and_valid_args(args);
AbstractTestRunner runner = null;
if(!random) {
runner = new FixedOrderRunner(testFile);
} else {
runner = new RandomOrderRunner(testFile);
}
TestExecResults results = runner.run();
Utils.checkTrue(results.getExecutionRecords().size() == 1, "Just a single run");
//get the results, and dump that out
Map<String, OneTestExecResult> result = results.getExecutionRecords().get(0).singleRun;
StringBuilder sb = new StringBuilder();
StringBuilder failedTests = new StringBuilder();
for(String test : result.keySet()) {
sb.append(test);
sb.append(" : ");
sb.append(result.get(test).result);
sb.append(Globals.lineSep);
if(verbose) {
if(!result.get(test).result.equals(RESULT.PASS)) {
System.out.println(" test fail! " + test);
System.out.println(result.get(test).getFullStackTrace());
failedTests.append(test);
failedTests.append(Globals.lineSep);
}
}
}
try {
Files.writeToFile(sb.toString(), outputFile);
if(verbose) {
Files.writeToFile(failedTests.toString(), outputFile + "_only_failed.txt");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void parse_and_valid_args(String[] args) {
Options options = new Options("RunTestInFixedOrder usage: ", RunTestInFixedOrder.class);
String[] file_args = options.parse_or_usage(args);
if(file_args.length != 0) {
Utils.flushToStd(file_args);
System.exit(1);
}
if(help) {
Utils.flushToStd(new String[] {options.usage()});
System.exit(1);
}
List<String> errorMsg = new LinkedList<String>();
if(testFile == null) {
errorMsg.add("You must specify either a file containing all tests via --testFile");
}
if(!errorMsg.isEmpty()) {
Utils.flushToStd(errorMsg.toArray(new String[0]));
Utils.flushToStd(new String[] {options.usage()});
System.exit(1);
}
}
}
|
C | UTF-8 | 2,143 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
int printdatatype( MPI_Datatype datatype )
{
int *array_of_ints;
MPI_Aint *array_of_adds;
MPI_Datatype *array_of_dtypes;
int num_ints, num_adds, num_dtypes, combiner;
int i;
MPI_Type_get_envelope( datatype,
&num_ints, &num_adds, &num_dtypes, &combiner );
switch (combiner) {
case MPI_COMBINER_NAMED:
printf( "Datatype is named:" );
/* To print the specific type, we can match against the
predefined forms. We can NOT use a switch statement here
We could also use MPI_TYPE_GET_NAME if we prefered to use
names that the user may have changed.
*/
if (datatype == MPI_INT) printf( "MPI_INT\n" );
else if (datatype == MPI_DOUBLE) printf( "MPI_DOUBLE\n" );
... else test for other types ...
return 0;
break;
case MPI_COMBINER_STRUCT:
case MPI_COMBINER_STRUCT_INTEGER:
printf( "Datatype is struct containing" );
array_of_ints = (int *)malloc( num_ints * sizeof(int) );
array_of_adds =
(MPI_Aint *) malloc( num_adds * sizeof(MPI_Aint) );
array_of_dtypes = (MPI_Datatype *)
malloc( num_dtypes * sizeof(MPI_Datatype) );
MPI_Type_get_contents( datatype, num_ints, num_adds, num_dtypes,
array_of_ints, array_of_adds, array_of_dtypes );
printf( " %d datatypes:\n", array_of_ints[0] );
for (i=0; i<array_of_ints[0]; i++) {
printf( "blocklength %d, displacement %ld, type:\n",
array_of_ints[i+1], array_of_adds[i] );
if (printdatatype( array_of_dtypes[i] )) {
/* Note that we free the type ONLY if it
is not predefined */
MPI_Type_free( &array_of_dtypes[i] );
}
}
free( array_of_ints );
free( array_of_adds );
free( array_of_dtypes );
break;
... other combiner values ...
default:
printf( "Unrecognized combiner type\n" );
}
return 1;
}
|
PHP | UTF-8 | 611 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Services;
class StorageCostCalculatorService {
const STORAGE_MB_PER_STUDY = 10;
const STORAGE_GB_COST_PER_MONTH_IN_USD = 0.10;
const GB_TO_MB_SCALE = 1000;
const BCMATH_SCALE = 8;
public static function getMonthlyStorageCostPerStudy() : float
{
$monthlyStorageInMBCost = bcdiv(
self::STORAGE_GB_COST_PER_MONTH_IN_USD,
self::GB_TO_MB_SCALE,
self::BCMATH_SCALE
);
return bcmul(
$monthlyStorageInMBCost,
self::STORAGE_MB_PER_STUDY,
self::BCMATH_SCALE
);
}
} |
Markdown | UTF-8 | 1,699 | 2.59375 | 3 | [] | no_license | ---
title: Apologies
date: 2004-05-22T07:42:11+00:00
excerpt: Firstly, I would like to apologize, especially to Gwildor, about my insensitive comments about bullying. I stand by my
layout: post
categories:
- Opinion
tags:
- bullying
- Seinfeld
- Superman
- weather
---
Firstly, I would like to apologize, especially to Gwildor, about my <a href="/cyberbullying.html" target="_blank">insensitive comments</a> about bullying. I stand by my position that cyberbullying is ridiculous; I really suggest to get out and do your bullying in person. And, if you’re the one being bullied, stand up for yourself, as best you can.
Now on to more pleasant (?) things … There is a big thunderstorm outside right now, with really cool lightning. I’m really fascinated by lightning, so I was interested to see some lightning that did not seem to result in thunder. I was always under the impression that thunder was produced when the lightning hit the ground, and that it was the resulting shockwave. From what I have <a href="http://www.nssl.noaa.gov/primer/lightning/ltg_basics.html" target="_blank">read</a>, that does not seem to be the case… I also found <a href="https://www.google.ca/search?q=cool+lightning+pictures&hl=en&prmd=imvns&source=lnms&tbm=isch&sa=X&ei=494rUPbwO6vqiwKXjYH4BA&ved=0CAoQ_AUoAQ&biw=1264&bih=871" target="_blank">some cool lightning pictures</a>.
Related sites:
<del>Lightning Safety for Kids</del>
<a href="http://www.lightningsafety.com/nlsi_pls/lst.html" target="_blank">Lightning Safety Institute</a>
Oh, and have you seen these <a href="http://www.youtube.com/watch?v=B-uQROMtoGc" target="_blank">Seinfeld & Superman</a> ads? Fantastic! |
Java | UTF-8 | 3,742 | 1.90625 | 2 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | /*
* Copyright 2018 Google LLC
*
* 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
*
* https://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.google.android.gnd.system;
import static com.google.android.gnd.rx.RxCompletable.completeOrError;
import android.content.IntentSender.SendIntentException;
import android.util.Log;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gnd.system.rx.RxSettingsClient;
import io.reactivex.Completable;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Manages enabling of settings and related flows to/from the Activity.
*
* <p>Note: Currently only supports location settings, but could be expanded to support other
* settings types in the future.
*/
@Singleton
public class SettingsManager {
private static final String TAG = SettingsManager.class.getSimpleName();
private static final int LOCATION_SETTINGS_REQUEST_CODE =
SettingsManager.class.hashCode() & 0xffff;
private final ActivityStreams activityStreams;
private final RxSettingsClient settingsClient;
@Inject
public SettingsManager(ActivityStreams activityStreams, RxSettingsClient settingsClient) {
this.activityStreams = activityStreams;
this.settingsClient = settingsClient;
}
/**
* Try to enable location settings. If location settings are already enabled, this will complete
* immediately on subscribe.
*/
public Completable enableLocationSettings(LocationRequest locationRequest) {
Log.d(TAG, "Checking location settings");
LocationSettingsRequest settingsRequest =
new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).build();
return settingsClient
.checkLocationSettings(settingsRequest)
.toCompletable()
.onErrorResumeNext(t -> onCheckSettingsFailure(LOCATION_SETTINGS_REQUEST_CODE, t));
}
private Completable onCheckSettingsFailure(int requestCode, Throwable t) {
if (!(t instanceof ResolvableApiException)) {
return Completable.error(t);
}
return startResolution(requestCode, (ResolvableApiException) t)
.andThen(getNextResult(requestCode));
}
private Completable startResolution(int requestCode, ResolvableApiException resolvableException) {
return Completable.create(
em -> {
Log.d(TAG, "Prompting user to enable settings");
activityStreams.withActivity(
act -> {
try {
resolvableException.startResolutionForResult(act, requestCode);
em.onComplete();
} catch (SendIntentException e) {
em.onError(e);
}
});
});
}
private Completable getNextResult(int requestCode) {
return activityStreams
.getNextActivityResult(requestCode)
.flatMapCompletable(r -> completeOrError(r::isOk, SettingsChangeRequestCanceled.class))
.doOnComplete(() -> Log.d(TAG, "Settings change request successful"))
.doOnError(t -> Log.d(TAG, "Settings change request failed", t));
}
public static class SettingsChangeRequestCanceled extends Exception {}
}
|
Java | UTF-8 | 4,887 | 2.203125 | 2 | [] | no_license | package com.wb.tracun.appacademiaarlivre;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Login2Activity extends AppCompatActivity {
private LoginButton loginBotao;
private CallbackManager callbackManager;
EditText txtEmail;
EditText txtPassword;
Button btnEntrar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
//Verifica a quantidade de usuarios cadastrados no BD
GerenciaBD gBD = new GerenciaBD(this);
gBD.teste();
//Verifica se ha alguem logado com o facebook
usuarioLogadoFacebook();
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtPassword = (EditText) findViewById(R.id.txtPassword);
btnEntrar = (Button) findViewById(R.id.btnLogin);
//Login facebook
loginBotao = (LoginButton) findViewById(R.id.loginButton);
callbackManager = CallbackManager.Factory.create();
loginBotao.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
//Vá para a tela inicial
goMain();
Toast.makeText(getApplicationContext(), "Entrei no face", Toast.LENGTH_LONG);
}
@Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Operação de login cancelada", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Erro: " + error.toString(), Toast.LENGTH_SHORT).show();
}
});
//pegando hashKey
try {
PackageInfo info = getPackageManager().getPackageInfo(
getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
}
catch (PackageManager.NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent dada){
super.onActivityResult(requestCode, resultCode, dada);
callbackManager.onActivityResult(requestCode,resultCode,dada);
}
public void goMain(){
Intent intencao = new Intent(this, MainActivity.class);
//Fecha as atividades anteriores, isso evita que quando o botao de voltar for pressionado, o usuario volte a tela de login, no caso, o app se encerra
intencao.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intencao);
}
public void cadastro(View view){
Intent intencao = new Intent(this, CadastroActivity.class);
startActivity(intencao);
}
public void usuarioLogadoFacebook(){
if(AccessToken.getCurrentAccessToken() != null){
goMain();
}
}
public void validarLogin(View view){
if(!isValidEmail()){
txtEmail.setError("Email inválido");
}else{
if(!isValidPassword()){
txtPassword.setError("Senha deve possuir mais de 4 caracteres");
}else{
GerenciaBD gerenciaBD = new GerenciaBD(this);
gerenciaBD.buscaDadoByEmail(txtEmail.getText().toString());
Toast.makeText(this, "Logado com sucesso !", Toast.LENGTH_SHORT);
}
}
}
public boolean isValidEmail(){
if(!txtEmail.getText().toString().contains("@")){
return false;
}
return true;
}
public boolean isValidPassword(){
if(txtPassword.getText().toString().isEmpty() || txtPassword.getText().length() < 4){
return false;
}
return true;
}
}
|
JavaScript | UTF-8 | 529 | 4.625 | 5 | [] | no_license | // Primitives are copied by their value
// Objects are copied by their reference
// Primitive values
let x = 10;
let y = x;
x = 20;
// in console : x = 20, y = 10.
let number = 10;
function increase(number) {
number++;
}
increase(number);
console.log(number);// 10
// ------------------------------
// Reference values
let x1 = { value: 10 };
let y1 = x;
x1 = 20;
// in console : x = 20, y = 20.
let obj = { value: 10 };
function increase(obj) {
obj.value++;
}
increase(obj);
console.log(obj); // {value: 11}
|
Java | UTF-8 | 2,191 | 2.671875 | 3 | [] | no_license | package com.qingcheng.mobilemanager.utils;
import android.util.Log;
/**
* Created by cunhuan.liu on 17/2/8.
*/
public class LogUtil {
//打印重要的log 使用HUAN
//只打印流程 使用-->
//打印所有 HUA
private static String TAG = "HUAN";
private static String FLOW_TAG = "-->";
public static boolean allowD = true;
public static boolean allowI = false;
private static String generateTag(StackTraceElement caller) {
String tag = "%s.%s";
String callerClazzName = caller.getClassName();
callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);// 获取到类名
//tag = String.format(tag, callerClazzName, caller.getMethodName(),caller.getLineNumber()); // 替换
tag = String.format(tag, callerClazzName, caller.getMethodName());
return tag;
}
private static StackTraceElement getCallerStackTraceElement() {
// Log.i("HUAN-PermissionUtil", "" + Thread.currentThread().getStackTrace().toString());
return Thread.currentThread().getStackTrace()[4];
}
public static void i() {
StackTraceElement caller = getCallerStackTraceElement();
String tag = generateTag(caller);
if (allowI)
Log.i("HUA " + FLOW_TAG, tag);
}
public static void i(String content) {
StackTraceElement caller = getCallerStackTraceElement();
String tag = generateTag(caller);
if (allowI)
Log.i(TAG + " " + tag + ":", content);
}
public static void d(String content) {
StackTraceElement caller = getCallerStackTraceElement();
String tag = generateTag(caller);
if (allowD)
Log.d(TAG + " " + tag + ":", content);
}
public static void e(String content) {
StackTraceElement caller = getCallerStackTraceElement();
String tag = generateTag(caller);
Log.e(TAG + " " + tag + ":", content);
}
public static void e(String content,Throwable t) {
StackTraceElement caller = getCallerStackTraceElement();
String tag = generateTag(caller);
Log.e(TAG + " " + tag + ":", content,t);
}
}
|
Markdown | UTF-8 | 1,367 | 2.609375 | 3 | [
"MIT"
] | permissive | # Kendo UI for Angular 2 Proof of Concept — Northwind Dashboard
The goal of this project is to build a dashboard application with the following set of technologies:
* Angular 2
* NativeScript
* Kendo UI for Angular 2
* The [Kendo Bootstrap Theme](https://github.com/telerik/kendo-bootstrap)
It includes a web interface and a set of two mobile applications for iOS and Android.
## Goals
- Sharing business logic through services
- Consistency in the data binding for web and mobile
- Consistent looks that share a common color scheme through the Bootstrap Sass variables
## Getting Started
1. Set up access to the [Progress NPM registry](http://www.telerik.com/kendo-angular-ui/getting-started/#installation)
For the web application, run:
1. Run `npm install`
1. Run `npm start`
1. Load the application at [http://localhost:3000](http://localhost:3000)
For the native applications:
1. Install and [set up NativeScript](http://localhost:3000)
1. Run `npm install`
1. Run `npm run prepare-ios` or `npm run prepare-android`
1. Run `npm run start-ios` or `npm run start-android`
## Credits
This project is based on the [Angular2 Webpack Starter](https://github.com/AngularClass/angular2-webpack-starter) by AngularClass.
You can find the original instructions in [ng-class-readme](https://github.com/telerik/ng2-dashboard/blob/master/ng-class-readme.md).
|
Java | UTF-8 | 4,118 | 2.84375 | 3 | [] | no_license | package helpers;
import static helpers.Handler.*;
import static org.lwjgl.glfw.GLFW.*;
import java.nio.*;
import org.lwjgl.*;
public class Mouse {
private static float x, y;
private static DoubleBuffer xTemp, yTemp;
private static boolean lastLeft = false, currentLeft = false;
private static boolean lastRight = false, currentRight = false;
private static boolean hand = false;
public Mouse() {
xTemp = BufferUtils.createDoubleBuffer(1);
yTemp = BufferUtils.createDoubleBuffer(1);
glfwGetCursorPos(window, xTemp, yTemp);
// int offset = 0;
// if(StateManager.game != null) {
// offset = StateManager.game.player1.getX();
// }
x = (float) xTemp.get(0);// + offset);
y = HEIGHT - (float) (yTemp.get(0)) - 1;
}
/**
* Updates Coordinates and Button States
*/
public static void update() {
updateCoordinates();
updateClicks();
}
/**
* Update x and y coordinates for the mouse
*/
private static void updateCoordinates() {
glfwGetCursorPos(window, xTemp, yTemp);
x = (int) Math.floor(xTemp.get(0));
y = (int) Math.floor(yTemp.get(0));
}
/**
* Updates button states to determine if a button is clicked
*/
private static void updateClicks() {
lastLeft = currentLeft;
lastRight = currentRight;
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) {
currentLeft = true;
} else {
currentLeft = false;
}
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) {
currentRight = true;
} else {
currentRight = false;
}
}
/**
* Gets mouse x coordinate
*
* @return Mouse x coordinate
*/
public static float getX() {
return x;
}
/**
* Gets mouse y coordinate
*
* @return Mouse y coordinate
*/
public static float getY() {
return y;
}
/**
* Returns true if LMB is clicked
*
* @return true if LMB is clicked
*/
public static boolean leftClick() {
return !lastLeft && currentLeft;
}
/**
* Returns true if RMB is clicked
*
* @return true if RMB is clicked
*/
public static boolean rightClick() {
return !lastRight && currentRight;
}
/**
* Returns true if LMB is pressed
*
* @return true if LMB is pressed
*/
public static boolean leftDrag() {
return currentLeft;
}
/**
* Returns true if RMB is pressed
*
* @return true if RMB is pressed
*/
public static boolean rightDrag() {
return currentRight;
}
/**
* Returns true if LMB is not pressed
*
* @return true if LMB is not pressed
*/
public static boolean leftRelease() {
return glfwGetMouseButton(window,
GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE;
}
/**
* Returns true if RMB is not pressed
*
* @return true if RMB is not pressed
*/
public static boolean rightRelease() {
return glfwGetMouseButton(window,
GLFW_MOUSE_BUTTON_RIGHT) == GLFW_RELEASE;
}
public static void setHand(boolean hand) {
if (hand && !Mouse.hand) {
Mouse.hand = true;
glfwSetCursor(window, handCursor);
} else if (!hand && Mouse.hand) {
Mouse.hand = false;
if (StateManager.game != null) {
glfwSetCursor(window, arrowCursor);
} else {
glfwSetCursor(window, menuCursor);
}
}
}
public static void hideCursor() {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
public static void showCursor() {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
|
JavaScript | UTF-8 | 961 | 2.609375 | 3 | [] | no_license | import React from "react";
export default function ProductCard({ productData }) {
function getProductAllergens(product) {
if (Object.keys(product).length !== 0) {
if (product.allergens === "") {
return <p>Aucun allergène n'est associé à ce produit</p>;
} else {
let splittedAllergens = product.allergens.split(",");
return (
<ul className="allergens">
{splittedAllergens.map((elem, key) => {
return <li key={key}>{elem}</li>;
})}
</ul>
);
}
}
}
return (
<div className="product-card">
<h2 className="product-name">{productData.product_name}</h2>
<div>
<img
className="product-img"
src={productData.image_url}
alt="product"
/>
</div>
<div>
<h3>Allergènes : </h3>
{productData && getProductAllergens(productData)}
</div>
</div>
);
}
|
Markdown | UTF-8 | 3,036 | 2.609375 | 3 | [] | no_license | +++
aliases = ["/changing-over-to-a-bluetooth-car-stereo-to-work-with-your-phone/","/2012/01/13/changing-over-to-a-bluetooth-car-stereo-to-work-with-your-phone"]
date = "2012-01-13T09:10:28Z"
draft = false
title = "Changing over to a Bluetooth car stereo to work with your phone"
description = ""
slug = "changing-over-to-a-bluetooth-car-stereo-to-work-with-your-phone"
+++
#"Changing over to a Bluetooth car stereo to work with your phone"
I blogged about this before ages ago but had some recent questions on it so I thought I'd do a quick update. If, like me, you drive an old car, your car stereo probably doesn't have an audio jack and almost definitely doesn't have bluetooth.
If you have a Ford from 1999 onwards then you have the added problem of a double height stereo whose CD player is probably knackered at this stage.
It turns out to be quite easy to replace any of the above with a dirt cheap stereo from Lidl or Aldi which gives you A2DP high-quality bluetooth audio through your car speakers when you pair your smartphone to it. As an added bonus you get an acceptable hands-free system built in too.
The steps are as follows:
<ol>
<li>Buy one of the bluetooth units from Aldi or Lidl. I see <a href="http://www.lidl.ie/cps/rde/xchg/SID-2D79591D-3B4CF92F/lidl_ri_ie/hs.xsl/index_17063.htm">Lidl has one of them for sale</a> this Monday.</li>
<li>Find your car stereo extraction keys or, if you can't, find 4 thin screwdrivers (jewellers ones work on many cars)</li>
<li>You'll need two or threeadapters</li>
<ol>
<li>The ISO audio/power one. e.g. <a href="http://www.incarexpress.co.uk/view_product.php?partno=PC2044">This one works</a> for Opel Astra</li>
<li>The antenna one. e.g. <a href="http://www.incarexpress.co.uk/view_product.php?partno=PC5100&gclid=CMm0me6x46..">This one works</a> for lots of cars</li>
<li>Potentially a fascia blank-plate if you have a double-height Ford stereo. e.g. <a href="http://www.ebay.co.uk/itm/Ford-Focus-Fascia-Facia-Panel-Adapter-Plate-Surround-/250595006485?pt=UK_CarsParts_Vehicles_CarParts_SM&hash=item3a58a05815#ht_2340wt_1139">this one for Ford Focus on eBay</a> (many sellers)</li>
</ol>
<li>Pop the stereo out of the dashboard using the keys or screwdrivers</li>
<li>Disconnect the cables at the back making sure none of them fall down into the bowels of the car</li>
<li>Potentially remove the flimsy metal cage that held the stereo in if it was a third party brand e.g. the old Blaupunkt in my wife's Zafira</li>
<li>Insert the fascia blank-plate if you have a Ford</li>
<li>Connect power/audio to the new stereo etc using the ISO adapter</li>
<li>Connect the antenna to the new stereo using its adapter</li>
<li>Wiggle it all in. This can take a while. Mondeo as a doddle, Zafira was a horror</li>
<li>Done!</li>
</ol>
Now you can pair your phone with the stereo and play all your music/podcasts.
Only word of warning is that the radio reception on our two Lidl/Aldi ones is rubbish in West Cork compared to the factory-fitted models.
|
C++ | UTF-8 | 206 | 2.734375 | 3 | [] | no_license | #pragma once
#include <vector>
using namespace std;
template<class T>
void ClearList(vector<T *> & t)
{
vector<T *>::iterator i = t.begin();
while ( i != t.end() )
{
delete *i;
++i;
}
t.clear();
} |
Python | UTF-8 | 203 | 3.984375 | 4 | [
"Unlicense"
] | permissive | num=int(input("Enter a number:"))
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The number is palindrome!")
else:
print("Not a palindrome!") |
Java | UTF-8 | 448 | 2.734375 | 3 | [] | no_license | package lom;
import lombok.ToString;
@ToString(exclude = {"id","name"})
public class User {
private Integer id;
private String name;
private String phone;
User(Integer id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
public static void main(String[] args) {
User user = new User(1, "gxg", "1");
System.out.println(user);
}
} |
JavaScript | UTF-8 | 1,292 | 3 | 3 | [] | no_license | // TEMP CODE FOR FETCHMYIP
// const { fetchMyIP } = require('./iss');
// fetchMyIP((error, ip) => {
// if (error) {
// console.log("It didn't work!" , error);
// return;
// }
// console.log('It worked! Returned IP:' , ip);
// });
// TEMP CODE FOR FETCHCOORDSBYIP
// const { fetchCoordsByIP } = require('./iss');
// fetchCoordsByIP('136.143.217.38', (error, coordinates) => {
// if (error) {
// console.log("It didn't work!" , error);
// return;
// }
// console.log('It worked! Returned coordinates:' , coordinates);
// });
// TEMP CODE FOR FETCHCISSFLYOVERTIMES
// const { fetchISSFlyOverTimes } = require('./iss');
// const exampleCoords = { latitude: 43.6611, longitude: -79.3298 };
// fetchISSFlyOverTimes(exampleCoords, (error, passTimes) => {
// if (error) {
// console.log("It didn't work!" , error);
// return;
// }
// console.log('It worked! Returned flyover times: ', passTimes);
// });
// REQUIRES
const { nextISSTimesForMyLocation } = require('./iss');
const { printPassTimes } = require('./printPassTimes');
// CALL NEXTISSTIMESFORMYLOCATION
nextISSTimesForMyLocation((error, passTimes) => {
if (error) {
return console.log("It didn't work!", error);
}
// success, print out the deets!
printPassTimes(passTimes);
}); |
C# | UTF-8 | 6,051 | 2.515625 | 3 | [
"MIT"
] | permissive | using ABC.Models.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using System.Collections;
using PagedList;
namespace ABC.Controllers
{
public class PedidosController : Controller
{
private Db db = new Db();
// GET: Pedidos
public ActionResult Index(int? pagina)
{
var pedido = db.Pedido.ToList();
var pageNumber = pagina ?? 1;
// Set paginacao
var onePageOfPedidos = pedido.ToPagedList(pageNumber, 8);
ViewBag.onPaginaDePedidos = onePageOfPedidos;
return View(pedido);
}
// GET: Pedidos/Details/5
public ActionResult Details(int id)
{
Pedido pedido = db.Pedido.Find(id);
return View(pedido);
}
// GET: Pedidos/Create
public ActionResult Create()
{
Db db = new Db();
ViewBag.ClienteId = new SelectList(db.Cliente.ToList(), "Id", "Nome");
ViewBag.ProdutoId = new SelectList(db.Produto.ToList(), "Id", "Nome");
return View();
}
// POST: Pedidos/Create
[HttpPost]
public ActionResult Create(Pedido model)
{
int qtdEstoque=0;
//verifica o produto
var prod = db.Estoque.Where(x => x.ProdutoId == model.ProdutoId).ToList();
//pega armazem com menor prazo
var armazen = prod.OrderBy(x => x.Deposito.Armazem.Prazo).FirstOrDefault();
foreach (var item in prod)
{
qtdEstoque += item.Quantidade;//incrementa a qtd
};
Produto produto = db.Produto.Where(x => x.Id == model.ProdutoId).FirstOrDefault();
decimal precoUnitario = produto.Preco;//pega o preço do produto
if (model.Quantidade > qtdEstoque)
{
TempData["erro"] = string.Format("Estoque insuficiente, Total em estoque {0} ", qtdEstoque);
}
else
{
Estoque es = db.Estoque.Find(armazen.Id);// pega estoque ID
es.Quantidade = es.Quantidade - model.Quantidade;
db.SaveChanges();
model.Quantidade = model.Quantidade;
model.PrecoUnidade = precoUnitario * model.Quantidade;
if (ModelState.IsValid)
{
db.Pedido.Add(model);
db.SaveChanges();//salva pedido
}
//salva relatorio deposito
RelatorioDeposito rd = new RelatorioDeposito();
rd.DepositoId = armazen.DepositoId;
rd.valor = armazen.Produto.Preco;
rd.Nome = armazen.Deposito.Nome;
db.RelatorioDepositosDetalhes.Add(rd);
db.SaveChanges();
//salva relatorio Armazem
RelatorioArmazem ra = new RelatorioArmazem();
ra.ArmazemId = armazen.Deposito.ArmazemId;
ra.valor = model.PrecoUnidade;
ra.Nome = armazen.Deposito.Armazem.Nome;
db.RelatorioArmazemDetalhes.Add(ra);
db.SaveChanges();
TempData["Ok"] = "Pedido cadastrado sucesso!";
}
ViewBag.ClienteId = new SelectList(db.Cliente.ToList(), "Id", "Nome");
ViewBag.ProdutoId = new SelectList(db.Produto.ToList(), "Id", "Nome");
return RedirectToAction("Create");
}
// GET: Pedidos/Edit/5
public ActionResult Edit(int id)
{
Pedido pedido = db.Pedido.Find(id);
ViewBag.ClienteId = new SelectList(db.Cliente.ToList(), "Id", "Nome",pedido.ClienteId);
ViewBag.ProdutoId = new SelectList(db.Produto.ToList(), "Id", "Nome",pedido.ProdutoId);
return View(pedido);
}
// POST: Pedidos/Edit/5
[HttpPost]
public ActionResult Edit(int id,Pedido pedido)
{
int qtdEstoque = 0;
var prod = db.Estoque.Where(x => x.ProdutoId == pedido.ProdutoId).ToList();
var armazen = prod.OrderBy(x => x.Deposito.Armazem.Prazo).FirstOrDefault();
foreach (var item in prod)
{
qtdEstoque += item.Quantidade;
};
Produto produto = db.Produto.Where(x => x.Id == pedido.ProdutoId).FirstOrDefault();
decimal precoUnitario = produto.Preco;
if (pedido.Quantidade > qtdEstoque)
{
TempData["erro"] = string.Format("Estoque insuficiente, Total em estoque {0} ", qtdEstoque);
}
else
{
Estoque es = db.Estoque.Find(armazen.Id);
es.Quantidade = es.Quantidade - pedido.Quantidade;
db.SaveChanges();
pedido.Quantidade = pedido.Quantidade;
pedido.PrecoUnidade = precoUnitario * pedido.Quantidade;
if (ModelState.IsValid)
{
db.Entry(pedido).State = EntityState.Modified;
db.SaveChanges();
}
TempData["Ok"] = "Pedido Alterado sucesso!";
}
ViewBag.ClienteId = new SelectList(db.Cliente.ToList(), "Id", "Nome");
ViewBag.ProdutoId = new SelectList(db.Produto.ToList(), "Id", "Nome");
return RedirectToAction("Edit");
}
// GET: Pedidos/Delete/5
public ActionResult Delete(int id)
{
Pedido pedido = db.Pedido.Find(id);
return View(pedido);
}
// POST: Pedidos/Delete/5
[HttpPost]
public ActionResult Delete(int id,Pedido pedido)
{
pedido = db.Pedido.Find(id);
db.Pedido.Remove(pedido);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
|
Markdown | UTF-8 | 3,002 | 3.015625 | 3 | [
"MIT"
] | permissive | # Adjust layout
This step of the tutorial uses the basic layout of your app, but adds an extra column for charts.
Let's create a new `Dashboard` folder under `/js/` to place the new files.
## Dashboard.js
This code will adjust the page layout, watch the **Viewer** and load the charts when the model date is loaded. It uses [JavaScript classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
Create a new **Dashboard.js** file under `/js/dashboard/` folder with the following content:
```javascript
$(document).ready(function () {
$(document).on('DOMNodeInserted', function (e) {
if ($(e.target).hasClass('orbit-gizmo')) {
// here, viewer represents the variable defined at viewer initialization
if (viewer === null || viewer === undefined) return;
new Dashboard(viewer, [
new BarChart('Material'),
new PieChart('Material')
])
}
});
})
// Handles the Dashboard panels
class Dashboard {
constructor(viewer, panels) {
var _this = this;
this._viewer = viewer;
this._panels = panels;
this.adjustLayout();
this._viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, (viewer) => {
_this.loadPanels();
});
}
adjustLayout() {
// this function may vary for layout to layout...
// for learn forge tutorials, let's get the ROW and adjust the size of the
// columns so it can fit the new dashboard column, also we added a smooth transition css class for a better user experience
let dashdiv = document.getElementById('dashboard');
if(!!dashdiv){
dashdiv.parentElement.removeChild(dashdiv);
}
var row = $(".row").children();
$(row[0]).removeClass('col-sm-4').addClass('col-sm-2 transition-width');
$(row[1]).removeClass('col-sm-8').addClass('col-sm-7 transition-width').after('<div class="col-sm-3 transition-width" id="dashboard"></div>');
}
loadPanels () {
var _this = this;
var data = new ModelData(this);
data.init(function () {
$('#dashboard').empty();
_this._panels.forEach(function (panel) {
// let's create a DIV with the Panel Function name and load it
panel.load('dashboard', viewer, data);
});
});
}
}
```
At the **index.html** add a `<script>` for this new file. This should go inside the `<head>`:
```html
<!-- dashboard files -->
<script src="js/Dashboard/Dashboard.js"></script>
```
## Adjust the main.css
Let's also add a couple extra CSS classes to help on the layout. Add the following to your `/css/main.css` file:
```css
#dashboard{
overflow: auto;
height: calc(100vh - 100px);
}
.transition-width {
transition: width 1s ease-in-out;
}
.dashboardPanel {
width: 100%;
padding: 3%;
display: block;
}
```
Next: [Panel basics](viewer/dashboard/panelbasics) |
Java | UTF-8 | 1,216 | 2.28125 | 2 | [] | no_license | package com.edcan.shareformproject.model;
public class UserModel {
private String nick, phone, bank, acc, uid, profile;
public UserModel(){}
public UserModel(String nick, String phone, String bank, String acc, String uid, String profile) {
this.nick = nick;
this.phone = phone;
this.bank = bank;
this.acc = acc;
this.uid = uid;
this.profile = profile;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getBank() {
return bank;
}
public void setBank(String bank) {
this.bank = bank;
}
public String getAcc() {
return acc;
}
public void setAcc(String acc) {
this.acc = acc;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
}
|
Ruby | UTF-8 | 1,387 | 3.234375 | 3 | [] | no_license | require "minitest/autorun"
require_relative "cat.rb"
require_relative "dog.rb"
require_relative "fox.rb"
class TestAnimalSounds <Minitest::Test
def test_cat_name
animal = Cat.new("Kitty")
assert_equal("Kitty", animal.name)
end
def test_cat_sound
animal = Cat.new("Kitty")
assert_equal("Meow", animal.sound)
end
def test_cat_says_meow
animal = Cat.new("Kitty")
assert_equal("Kitty says Meow", animal.get_sound)
end
def test_dog_name
animal = Dog.new("Doggy")
assert_equal("Doggy", animal.name)
end
def test_dog_sound
animal = Dog.new("Doggy")
assert_equal("Woof", animal.sound)
end
def test_dog_says_woof
animal = Dog.new("Doggy")
assert_equal("Doggy says Woof", animal.get_sound)
end
def test_fox_name
animal = Fox.new("Foxy")
assert_equal("Foxy", animal.name)
end
def test_fox_sound
animal = Fox.new("Foxy")
assert_equal("Ring-ding-ding-ding-dingeringeding", animal.sound)
end
def test_dog_says_woof
animal = Fox.new("Foxy")
assert_equal("Foxy says Ring-ding-ding-ding-dingeringeding", animal.get_sound)
end
end |
Java | UTF-8 | 310 | 1.585938 | 2 | [] | no_license | package ddd.simple.service.ddd3util;
import java.util.List;
import java.util.Map;
import ddd.simple.action.ddd3util.TabInfo;
import ddd.simple.service.base.BaseServiceInterface;
public interface Ddd3utilService extends BaseServiceInterface
{
public String generatorFileds(List<TabInfo> tabs) ;
} |
Python | UTF-8 | 1,670 | 3.265625 | 3 | [] | no_license | board= [[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]]
def solve(board):
pos=check_empty(board)
if not pos:
return True
else:
row,col=pos
for i in range(1,10):
if check_valid(row,col,i)==True:
board[row][col]=i
if solve(board):
return True
#reset if all failed then backtrack
board[row][col]=0
return False
def check_valid(row,col,num):
#check complete same row
for i in range(len(board)):
if board[row][i]==num and i!=col:
return False
##check the same column
for j in range(len(board[0])):
if board[j][col]==num and j!=row:
return False
#check the box
rx=row//3
cy=col//3
for r in range(rx*3,(rx*3)+3):
for c in range(cy*3,(cy*3)+3):
if num==board[r][c] and (r,c)!=(row,col):
return False
return True
def check_empty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]==0:
return (i,j)
return None
def printer(board):
for i in range(len(board)):
for j in range(len(board[0])):
if j%3==0 and j!=0:
print('|',end=' ')
print(board[i][j],end=' ')
print()
if (i+1)%3==0 and i!=0:
print('______________________')
printer(board)
solve(board)
print('===================================================')
printer(board)
|
JavaScript | UTF-8 | 2,775 | 2.71875 | 3 | [] | no_license | import React, {Component} from 'react';
import axios from 'axios';
import styled from 'styled-components';
class SmurfForm extends Component {
constructor(props) {
super(props);
this.state = {
id: 0,
name: '',
age: '',
height: '',
};
this.addSmurf = this.addSmurf.bind(this);
this.updateName = this.updateName.bind(this);
this.updateAge = this.updateAge.bind(this);
this.updateHeight = this.updateHeight.bind(this);
}
addSmurf(event) {
event.preventDefault();
axios
.post('http://localhost:3333/smurfs', this.state)
.then(response => {
console.log('response from post', response);
// console.log('check prosp to see if has onCreation', response.data);
this.props.onCreation(response.data);
})
.catch(error => {
console.error('error saving the data');
});
}
updateName(event) {
this.setState({
name: event.target.value
});
}
updateAge(event) {
this.setState({
age: event.target.value
});
}
updateHeight(event) {
this.setState({
height: event.target.value
});
}
render() {
return (
<SmurtForm className="SmurfForm">
<h1 className="display-4">Add New Smurf </h1>
<form onSubmit={this.addSmurf}>
<div className="form-group">
<input
onChange={this.updateName}
placeholder="name"
value={this.state.name}
/>
</div>
<div className="form-group">
<input
onChange={this.updateAge}
placeholder="age"
value={this.state.age}
/>
</div>
<div className="form-group">
<input
onChange={this.updateHeight}
placeholder="height"
value={this.state.height}
/>
</div>
<button className="btn btn-success btn-lg" type="submit">Add +</button>
</form>
</SmurtForm>
);
}
}
const SmurtForm = styled.div`
border:1px solid grey;
text-align: center;
margin:0px auto;
margin-top: 15%;
padding: 20px;
h1 {
font-size:40px;
}
`;
export default SmurfForm; |
JavaScript | UTF-8 | 6,395 | 2.859375 | 3 | [] | no_license |
var UIModule = (function () {
'use strict'
// landing page elements
var candidatesList = document.querySelector('.candidates-list');
var searchField = document.querySelector('input');
// reports page elements
var candidateName = document.querySelector('#name');
var candidateEmail = document.querySelector('#email');
var candidateBirthday = document.querySelector('#date');
var candidateEducation = document.querySelector('#education');
var candidateAvatar = document.querySelector('#candidate-avatar');
var tableHeaders = document.querySelectorAll('th');
var reportsTable = document.querySelector('tbody');
// modal box elements
var modal = document.querySelector('#modal');
var modalName = document.querySelector('#modal-name');
var modalCompany = document.querySelector('#modal-company');
var modalDate = document.querySelector('#modal-date');
var modalPhase = document.querySelector('#modal-phase');
var modalStatus = document.querySelector('#modal-status');
var modalNotes = document.querySelector('#modal-notes');
var closeButton = document.querySelector('#close');
// selects all candidate card
function getCandidateCard() {
var candidateCard = document.querySelectorAll('.candidate-info');
return candidateCard;
}
// removes loading icon from page
function clearContent() {
candidatesList.innerHTML = '';
}
// creates candidate card from candidate object(landing page)
function createCandidateCards(candidates) {
for (var i = 0; i < candidates.length; i++) {
var candidateCard = "<div class='candidate-info' value='" + JSON.stringify(candidates[i]) + "'><div class='image-box'><img src='" + candidates[i].avatar + "' alt='candidate image'/></div><p class='candidate-name'>" + candidates[i].name + "</p><p class='email'>" + candidates[i].email + "</p></div>";
candidatesList.innerHTML += candidateCard;
}
}
// fills out candidate info(candidate reports page)
function populateCandidateInfo(candidate) {
candidateName.innerHTML = candidate.name;
candidateEmail.innerHTML = candidate.email;
candidateBirthday.innerHTML = candidate.birthday;
candidateEducation.innerHTML = candidate.education;
candidateAvatar.setAttribute('src', candidate.avatar);
}
// creates reports table
function populateReports(reports) {
for (var i = 0; i < reports.length; i++) {
var row = document.createElement('tr');
row.innerHTML = "<td>" + reports[i].companyName + "</td><td>" + reports[i].interviewDate + "</td><td>" + reports[i].status + "</td><td><img class='open-modal' src='../img/preview.png' value='" + JSON.stringify(reports[i]) + "'></td>";
reportsTable.appendChild(row);
}
}
// selects report preview icons
function getModalTriggers() {
var modalTriggers = document.querySelectorAll('.open-modal');
return modalTriggers;
}
// fills modal box with data
function populateModal(report) {
modalName.innerHTML = report.candidateName;
modalCompany.innerHTML = report.companyName;
modalDate.innerHTML = report.interviewDate;
modalPhase.innerHTML = report.phase;
modalStatus.innerHTML = report.status;
modalNotes.innerHTML = report.note;
}
// table sort code
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.querySelector('table');
switching = true;
// Set the sorting direction to ascending:
dir = "asc";
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// Start by saying: no switching is done:
switching = false;
rows = table.querySelectorAll('tr');
/* Loop through all table rows (except the
first, which contains table headers): */
for (i = 1; i < rows.length - 1; i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Get the two elements you want to compare,
one from current row and one from the next: */
x = rows[i].querySelectorAll('td')[n];
y = rows[i + 1].querySelectorAll('td')[n];
/* Check if the two rows should switch place,
based on the direction, asc or desc: */
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
// If so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
// If so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark that a switch has been done: */
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
// Each time a switch is done, increase this count by 1:
switchcount++;
} else {
/* If no switching has been done AND the direction is "asc",
set the direction to "desc" and run the while loop again. */
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
return {
createCandidateCards: createCandidateCards,
clearContent: clearContent,
searchField: searchField,
getCandidateCard: getCandidateCard,
populateCandidateInfo: populateCandidateInfo,
populateReports: populateReports,
getModalTriggers: getModalTriggers,
modal: modal,
populateModal: populateModal,
closeButton: closeButton,
sortTable: sortTable,
tableHeaders: tableHeaders
}
})(); |
Swift | UTF-8 | 2,285 | 2.859375 | 3 | [
"MIT"
] | permissive | //
// CGFloatRepresentable.swift
// AnchorKit
//
// Created by Eddie Kaiger on 5/13/17.
// Copyright © 2017 Weebly. All rights reserved.
//
import CoreGraphics
#if SWIFT_PACKAGE
import Foundation
#endif
/**
A protocol that converts different number types to a `CGFloat` equivalent.
TOOD: Improve in Swift 4 once we have better number protocols.
*/
public protocol CGFloatRepresentable {
var cgFloatValue: CGFloat { get }
}
// MARK: Number Extensions
extension Int8: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension UInt8: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension Int16: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension UInt16: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension Int32: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension UInt32: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension Int64: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension UInt64: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension Int: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension UInt: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension Float: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
#if os(macOS)
extension Float80: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
#endif
extension Double: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(self) }
}
extension NSNumber: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return CGFloat(floatValue) }
}
extension CGFloat: CGFloatRepresentable {
public var cgFloatValue: CGFloat { return self }
}
// MARK: - Internal Operators
func == <LeftType: CGFloatRepresentable & Equatable, RightType: CGFloatRepresentable & Equatable>(lhs: LeftType, rhs: RightType) -> Bool {
return lhs.cgFloatValue == rhs.cgFloatValue
}
|
Swift | UTF-8 | 4,069 | 2.578125 | 3 | [] | no_license | //
// ThreeViewController.swift
// ios-project-ui
//
// Created by 李喜明 on 2019/9/28.
// Copyright © 2019 李喜明. All rights reserved.
//
import UIKit
class ThreeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var data = [[[String: String]]]()
var keys = [String]()
var tabel: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
data = [[["微信支付": "selected"], ["支付宝支付": "no"], ["网银支付": "no"]],
[["易用支付": "no"], ["小米支付": "no"], ["天意支付": "no"]]]
tabel = UITableView(frame: self.view.frame)
navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .add, target: self, action: #selector(addOrDelete))
tabel = UITableView(frame: self.view.frame)
tabel.delegate = self
tabel.dataSource = self
self.view.addSubview(tabel)
}
@objc func addOrDelete() {
tabel.setEditing(!tabel.isEditing, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].count
}
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "支付方式"
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if indexPath.section == 0 {
return .delete
} else{
return .insert
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
let item = data[indexPath.section][indexPath.row]
if editingStyle == .insert {
data[0].insert(item, at: data[0].count)
data[1].remove(at: indexPath.row)
//tableView.deleteRows(at: [indexPath], with: .left)
print("增加了支付方式")
} else {
data[1].insert(item, at: data[1].count)
data[0].remove(at: indexPath.row)
//tableView.deleteRows(at: [indexPath], with: .left)
print("删除了支付方式")
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellId = "cellId"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: cellId)
cell?.selectionStyle = .none
}
let dic = data[indexPath.section][indexPath.row]
cell?.textLabel?.text = dic.keys.first
if dic.values.first == "selected" {
cell?.accessoryType = .checkmark
} else {
cell?.accessoryType = .none
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section == 0 else {
return
}
var i = 0
for item in data[indexPath.section] {
var item = item as Dictionary
if i == indexPath.row {
item[item.keys.first!] = "selected"
} else {
item[item.keys.first!] = "no"
}
data[indexPath.section][i] = item
i = i + 1
}
tableView.reloadData()
print("选择了\(indexPath)")
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let item = data[sourceIndexPath.section][sourceIndexPath.row]
data[sourceIndexPath.section].remove(at: sourceIndexPath.row)
data[sourceIndexPath.section].insert(item, at: destinationIndexPath.row)
}
}
|
Python | UTF-8 | 2,964 | 3.09375 | 3 | [] | no_license | import time
import math
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import os
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
def calc(a):
return str(math.log(abs(12 * math.sin(int(a)))))
#region 2.2.3
try:
driver = webdriver.Chrome()
driver.get("http://suninjuly.github.io/selects1.html")
num1 = driver.find_element_by_id("num1").text
num2 = driver.find_element_by_id("num2").text
summ = str(int(num1) + int(num2))
driver.find_element_by_id("dropdown").click()
select = Select(driver.find_element_by_tag_name("select"))
select.select_by_visible_text(summ)
button = driver.find_element_by_xpath('//*[@type="submit"]')
button.click()
finally:
time.sleep(10)
driver.quit()
#endregion
#region 2.2.6
try:
driver = webdriver.Chrome()
driver.get("http://suninjuly.github.io/execute_script.html")
x = int(driver.find_element_by_id("input_value").text)
y = calc(x)
driver.find_element_by_id("answer").send_keys(y)
driver.find_element_by_id("robotCheckbox").click()
button = driver.find_element_by_id("robotsRule")
driver.execute_script("return arguments[0].scrollIntoView(true);", button)
button.click()
button2 = driver.find_element_by_xpath('//*[@type="submit"]')
driver.execute_script("return arguments[0].scrollIntoView(true);", button2)
button2.click()
finally:
time.sleep(10)
driver.quit()
# endregion
#region 2.2.8
try:
driver = webdriver.Chrome()
driver.get("http://suninjuly.github.io/file_input.html")
driver.find_element_by_name("firstname").send_keys("AAA")
driver.find_element_by_name("lastname").send_keys("AAA")
driver.find_element_by_name("email").send_keys("AAA")
element = driver.find_element_by_id("file")
current_dir = os.path.abspath(os.path.dirname(__file__)) # получаем путь к директории текущего исполняемого файла
file_path = os.path.join(current_dir, 'name.txt') # добавляем к этому пути имя файла
element.send_keys(file_path)
button2 = driver.find_element_by_xpath('//*[@type="submit"]')
driver.execute_script("return arguments[0].scrollIntoView(true);", button2)
button2.click()
finally:
time.sleep(10)
driver.quit()
#endregion
#region 2.4
try:
driver = webdriver.Chrome()
driver.get("http://suninjuly.github.io/explicit_wait2.html")
WebDriverWait(driver, 12).until(
EC.text_to_be_present_in_element((By.ID, "price"), "$100"))
driver.find_element_by_id("book").click()
x = int(driver.find_element_by_id("input_value").text)
driver.find_element_by_id("answer").send_keys(calc(x))
driver.find_element_by_id("solve").click()
finally:
time.sleep(30)
driver.quit()
#endregion |
C++ | UTF-8 | 2,091 | 2.5625 | 3 | [] | no_license | /*
* Gunner.cpp
*
* Created on: Aug 7, 2018
* Author: Samuel Tan
*/
#include <unit/Gunner.h>
#include "Renderer.h"
#include "../Battle.h"
namespace entity
{
// ugh this is gory
Gunner::Gunner(Battle* b, Team t, geometry::Vec2 position, geometry::Vec2 velocity, double angle)
: Unit(b, t, position, velocity, angle),
// Gunner stats
projVel(2),
standoffDistance(200)
{
// Unit stat overrides
attackStrength = 10;
knockback = 10;
topSpeed = 0.7;
}
Gunner::~Gunner()
{
}
void Gunner::render(graphics::Renderer& renderer) const
{
if (!active)
return;
Unit::render(renderer);
// draw emblem
geometry::Vec2 forward;
forward.setPolar(4, box.angle);
geometry::Vec2 right(forward);
right.rotateBy(-Values::HALF_PI);
Values::Color color = { 0.0f, 0.0f, 0.0f, 0.2f };
Values::Quad quad
{{
Values::makeCV( color, box.position + 0.5*forward + forward, Values::Depth::EMBLEMS),
Values::makeCV( color, box.position + 0.5*forward + right, Values::Depth::EMBLEMS),
Values::makeCV( color, box.position + 0.5*forward - 2*forward, Values::Depth::EMBLEMS),
Values::makeCV( color, box.position + 0.5*forward - right, Values::Depth::EMBLEMS)
}};
renderer.addQuad(quad);
}
double Gunner::idealSpeed() const
{
if (!target)
return 0.0;
double targetDistance = rayTo(*target).getLength();
if (targetDistance < standoffDistance)
return -topSpeed;
else if (targetDistance < standoffDistance + 10)
return 0.0;
else
return topSpeed;
}
void Gunner::attack()
{
geometry::Vec2 projVec;
projVec.setPolar(projVel, box.angle);
geometry::Vec2 projPos(box.position);
while (box.containsAbs(projPos))
projPos += projVec;
Projectile* p = new Projectile(battle, Entity::Team::NEUTRAL,
projPos, projVec, attackStrength, knockback/projVel, true);
battle->add(p);
}
} /* namespace entity */
|
JavaScript | UTF-8 | 1,606 | 2.625 | 3 | [] | no_license | const VuelosIdaContainer = document.getElementById("ContenedorVuelosIda")
const VuelosRegresoContainer = document.getElementById("ContenedorVuelosRegreso")
if(VuelosIdaContainer){
VuelosIdaContainer.children[0].classList.add("radioSeleccionado");
a = VuelosIdaContainer.children[0].children[0].children[0].checked=true
VuelosIdaContainer.addEventListener('click', e=>{
let vueloSeleccionado = e.target.parentNode
let radioSeleccionado = vueloSeleccionado.children[0].children[0];
radioSeleccionado.checked="true"
let el = document.querySelector('#ContenedorVuelosIda .radioSeleccionado');
if(el)el.classList.remove('radioSeleccionado');
console.log(vueloSeleccionado)
vueloSeleccionado.classList.add('radioSeleccionado');
console.log(vueloSeleccionado)
})
}
if(VuelosRegresoContainer){
VuelosRegresoContainer.children[0].classList.add("radioSeleccionado");
VuelosRegresoContainer.children[0].children[0].children[0].checked=true
VuelosRegresoContainer.addEventListener('click', e=>{
let vueloSeleccionado = e.target.parentNode
let radioSeleccionado = vueloSeleccionado.children[0].children[0];
radioSeleccionado.checked="true"
let el = document.querySelector('#ContenedorVuelosRegreso .radioSeleccionado');
if(el)el.classList.remove('radioSeleccionado');
console.log(vueloSeleccionado)
vueloSeleccionado.classList.add('radioSeleccionado');
console.log(vueloSeleccionado)
})
}
const backButton = document.getElementById("regresar_vuelos");
if(backButton){
backButton.addEventListener("click", e=>{
history.back();
})
}
|
C++ | UTF-8 | 2,388 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
#include <math.h>
#include <windows.h>
/*
using namespace std;
main()
{
string galpon[3];
galpon[2]="pedro";
galpon[0]="maria";
galpon[1]="pedro";
//cout<<galpon[1];
for(int i=0;i<9;i++)
{
if(i>2)
{
cout<<"El indice ["<<i<<"] no existe"<<" \n";
}
else
{
cout<<"En el indice ["<<i<<"] tenemos "<<galpon[i]<<" \n";
}
}
}
using namespace std;
main()
{
int i;
int edades[]={2,45,567,0,-1,3,12,2,12,78,-45};
//for(int i=0;edades [i]>1;i++)
for(i=0;i!=10;i++)
{
cout<<"En el indice ["<<i<<"] tenemos "<<edades[i]<<" \n";
}
cout<<"El vector tiene: "<<i;
cout<<" \n"<<edades[8];
}
using namespace std;
const int maximoelemento = 6;
main()
{
int i;
int edades[]={2,45,567,0,-1,3,12,20,12,78,-45};
for(i=0;i<maximoelemento;i++)
{
cout<<"En el indice ["<<i<<"] tenemos "<<edades[i]<<" \n";
}
cout<<"El vector tiene: "<<i;
cout<<" \n"<<edades[8];
}
*/
using namespace std;
main()
{
char mensaje[]={'P','R','O','G','R','A','M','A','C','I','O','N',' ','D','E',' ','S','O','F','T','W','A','R','E'};
int fila,columna, temporal,cantidad;
int edades[20];
cout<<"\nPor favor ingresa la cantidad de los elementos del Vector"<<" \n";
cin>>cantidad;
//llenado del vector
cout<<"\nPor favor ingresa los datos del Vector"<<" \n";
for(int i= 0;i<cantidad;i++)
{
cout<<"\n vector numero"<<i<<" :";
cin>>edades[i];
}
//int edades[]={2,45,567,0,-1,3,12,20,12,78,-45};
for(fila=0;fila<cantidad;fila++)
{
for(columna=0;columna<cantidad -1;columna++)
{
if(edades[columna]>edades[columna+1])
{
temporal=edades[columna];
edades[columna]=edades[columna+1];
edades[columna+1]=temporal;
}
}
}
cout<<"\nVector edades ordenado de forma Ascendente"<<" \n";
for(int i=0;i<cantidad;i++)
{
cout<<"En el indice ["<<i<<"] tenemos "<<edades[i]<<" \n";
}
cout<<"\nVector edades ordenado de forma Descendente"<<" \n";
for(int i=cantidad-1;i>=0;i--)
{
cout<<"En el indice ["<<i<<"] tenemos "<<edades[i]<<" \n";
}
cout<<" ";
for(int i=0;i<=23;i++)
{
cout<<" "<<mensaje[i];
Sleep(80);
//cout<<"En el indice ["<<i<<"] tenemos "<<edades[i]<<" \n";
}
}
|
C | UTF-8 | 329 | 2.984375 | 3 | [] | no_license | /*
* File: point.h
* -------------
* This file defines a structure that combines an x and a y coordinate
* value into a single entity.
*/
#ifndef _point_h
#define _point_h
/*
* Type: pointT
* ------------
* This simple structure contains a pair of x and y coordinate values.
*/
struct pointT {
int x, y;
};
#endif
|
Ruby | UTF-8 | 491 | 3.96875 | 4 | [
"Artistic-2.0"
] | permissive | #!/usr/bin/ruby
#
## http://rosettacode.org/wiki/Call_an_object_method
#
class MyClass {
method foo(arg) { arg }
}
var arg = 42;
# Class method
assert_eq(MyClass.(:foo)(arg), arg);
# Create an instance
var instance = MyClass();
# Instance method
assert_eq(instance.foo(arg), arg);
# Alternatively, by using an expression as a method
assert_eq(instance.(:foo)(arg), arg);
# Alternatively, by asking for a method
assert_eq(instance.method(:foo)(arg), arg);
say "** Test passed!";
|
JavaScript | UTF-8 | 2,270 | 3.40625 | 3 | [] | no_license | const ul1 = document.getElementById('ul1');
// ajax获取json数据并放入到DOM中
let xml = new XMLHttpRequest();
xml.open('get', './nav.json', true);
xml.onreadystatechange = () => {
if (xml.status === 200 && xml.readyState === 4) {
let data = JSON.parse(xml.responseText).data;
let li1 = '';
data.forEach(fir => {
let li2 = '';
fir.content.forEach(sec => {
let li3 = '';
sec.content.forEach(thi => {
li3 += `<li class="li3">
<a href="##">${thi}</a>
</li>
`
});
li2 += `<li class="li2">
<a href="##">${sec.title}</a>
<ul class="ul3">
${li3}
</ul>
</li>
`
});
li1 += `<li class="li1">
<a href="##">${fir.title}</a>
<ul class="ul2">
${li2}
</ul>
</li>
`
});
// 插入到DOM树中
ul1.innerHTML = li1;
// 显示和隐藏功能
const one = document.getElementsByClassName('li1');
const ul2 = document.getElementsByClassName('ul2');
const two = document.getElementsByClassName('li2');
const ul3 = document.getElementsByClassName('ul3');
showAndHidden(one,ul2);
showAndHidden(two,ul3);
}
}
xml.send();
/**
* @param {Array} lis li节点构成的集合
* @param {Array} uls ul节点构成的集合
*/
function showAndHidden(lis, uls) {
for (let i = 0; i < lis.length; i++) {
lis[i].index = i;
lis[i].onmouseover = (e) => {
/*
e.target指向当前指向的节点
e.currentTarget指向当前的最父亲节点
*/
const t = e.currentTarget;
uls[t.index].style.display = 'block';
}
lis[i].onmouseout = (e) => {
const t = e.currentTarget;
uls[t.index].style.display = 'none';
}
}
}
|
C# | UTF-8 | 2,863 | 2.671875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace Paint
{
class Frame:PictureBox
{
public Label Border = new Label();
public Label FrameLabel = new Label();
static public int FrameWidth = 100;
static public int FrameHeight = 50;
public Frame(Control Parent, int Loc, string index, double FrameDuration, Bitmap bm):base()
{
this.Parent = Parent;
Border.Parent = Parent;
FrameLabel.Parent = Parent;
this.Width = FrameWidth;
this.Height = FrameHeight;
this.SizeMode = PictureBoxSizeMode.StretchImage;
this.Tag = index;
this.Name = StringResources.FrameNamePrefix + index;
this.Image = (Bitmap)bm.Clone();
this.Cursor = Cursors.Hand;
this.Location = new Point(10, Loc);
Border.Width = 104;
Border.Height = 54;
Border.Location = new Point(8, Loc - 2);
Border.BackColor = Register.NormalFrameBackColor;
Border.Name = StringResources.BorderNamePrefix + index;
Border.Tag = index;
FrameLabel.Location = new Point(10, Loc + 60);
FrameLabel.Text = FrameDuration.ToString() + " секунд";
FrameLabel.Name = StringResources.LabelNamePrefix + index;
FrameLabel.Tag = index;
this.BringToFront();
}
public Frame():base()
{
}
public void ChangeTag(int z)
{
int NewTag = int.Parse(this.Tag.ToString()) + z;
this.Tag = NewTag;
this.Name = StringResources.FrameNamePrefix + NewTag;
Border.Name = StringResources.BorderNamePrefix + NewTag;
Border.Tag = NewTag;
FrameLabel.Name = StringResources.LabelNamePrefix + NewTag;
FrameLabel.Tag = NewTag;
}
public void ChangeLocationY(int z)
{
this.Location = new Point(this.Location.X, this.Location.Y + z);
Border.Location = new Point(Border.Location.X, Border.Location.Y + z);
FrameLabel.Location = new Point(FrameLabel.Location.X, FrameLabel.Location.Y + z);
}
new public void Dispose()
{
Border.Dispose();
FrameLabel.Dispose();
base.Dispose();
}
public Frame Clone()
{
return new Frame()
{
Location = this.Location,
Parent = this.Parent,
Image = (Bitmap)this.Image.Clone(),
SizeMode = this.SizeMode,
Width = this.Width,
Height = this.Height
};
}
}
}
|
Python | UTF-8 | 2,413 | 3.125 | 3 | [] | no_license | class LRUCache(object):
"""
queue to implement LRU in O(1) time
hashmap of
key --> node
for O(1) put and get
head, tail
ex:
size = 3
put(1,1)
[1,1]
{(1,[1,1])}
put (2,2)
[2,2]<->[1,1]
{
(1,[1,1]),
(2,[2,2])
}
put (3,3)
[3,3]<->[2,2]<->[1,1]
{
(1,[1,1]),
(2,[2,2]),
(3,[3,3])
}
get(2)
[2,2]<->[3,3],[1,1]
put(4,4)
[4,4]<->[2,2]<->[3,3]
{
(2,[2,2]),
(3,[3,3]),
(4,[4,4])
}
"""
def __init__(self, size):
self.max_size = size + 1
self.head = DLLNode(None)
self.tail = self.head
self.key_node = {}
self.size = 1
def get(self, k):
if self.key_node[k]:
node = self.key_node[k]
prevNode = node.prev
nextNode = node.next
res = node.val[1]
if node is self.head:
nextNode.prev = None
self.head = nextNode
return res
elif node is self.tail:
return res
prevNode.next = nextNode
nextNode.prev = prevNode
node.next = self.head
self.head.prev = node
self.head = node
else:
return -1
def put(self, k, v):
if self.key_node[k]:
node = self.key_node[k]
node[1] = v
prevNode = node.prev
nextNode = node.next
if node is self.head:
nextNode.prev = None
self.head = nextNode
return
elif node is self.tail:
return
prevNode.next = nextNode
nextNode.prev = prevNode
node.next = self.head
self.head.prev = node
self.head = node
else:
new_node = DLLNode((k, v))
if self.max_size == self.size:
removed_key = self.tail[0]
self.tail = self.tail.prev
del self.key_node[removed_key]
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
self.size += 1
self.key_node[k] = new_node
class DLLNode(object):
def __init__(self, val, next=None, prev=None):
self.val = val
self.next = next
self.prev = prev |
Ruby | UTF-8 | 209 | 3.953125 | 4 | [] | no_license | # Use the dates from the previous example and store them in an array. Then make your program output the same thing as exercise 3.
movies = [2001, 2019, 1994]
puts movies[0]
puts movies[1]
puts movies[2]
|
Java | UTF-8 | 1,279 | 2.296875 | 2 | [] | no_license | package com.rescribe.doctor.model.chat;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class MQTTData implements Parcelable {
@SerializedName("mqttMessages")
@Expose
private ArrayList<MQTTMessage> mqttMessages = new ArrayList<MQTTMessage>();
public final static Creator<MQTTData> CREATOR = new Creator<MQTTData>() {
@SuppressWarnings({
"unchecked"
})
public MQTTData createFromParcel(Parcel in) {
return new MQTTData(in);
}
public MQTTData[] newArray(int size) {
return (new MQTTData[size]);
}
};
protected MQTTData(Parcel in) {
in.readList(this.mqttMessages, (MQTTMessage.class.getClassLoader()));
}
public MQTTData() {
}
public ArrayList<MQTTMessage> getMqttMessages() {
return mqttMessages;
}
public void setMqttMessages(ArrayList<MQTTMessage> mqttMessages) {
this.mqttMessages = mqttMessages;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(mqttMessages);
}
public int describeContents() {
return 0;
}
}
|
PHP | UTF-8 | 372 | 3.078125 | 3 | [] | no_license | <?php
declare(strict_types=1);
require_once '../common.php';
require_once './functions.php';
$rows = readRows('input.txt');
$part1 = 0;
$part2 = 0;
foreach ($rows as $row) {
$words = explode(' ', $row);
$part1 += isValidPassPhrase($words, false) ? 1 : 0;
$part2 += isValidPassPhrase($words, true) ? 1 : 0;
}
echo "part1: $part1\n";
echo "part2: $part2\n";
|
Python | UTF-8 | 184 | 2.65625 | 3 | [] | no_license | def monta_mala(lista_de_peso):
while sum(lista_de_peso) > 25:
del lista_de_peso[-1]
print (lista_de_peso)
if sum(lista_de_peso)<25:
return lista_de_peso |
PHP | UTF-8 | 417 | 3.125 | 3 | [] | no_license | <?php
include '../modelo/distancia.class.php';
$b = new Distancia();
$b->setX1($_POST['numx1']);
$b->setY1($_POST['numy1']);
$b->setX2($_POST['numx2']);
$b->setY2($_POST['numy2']);
echo '<p>Valor de X: '.$b->getX1().
'<br>Valor de Y: '.$b->getY1().
'<br>Valor de X2: '.$b->getX2().
'<br>Valor de Y2: '.$b->getY2().
'<br>Distância entre os pontos: '.$b->calcularDistancia().'<p>';
|
Swift | UTF-8 | 448 | 2.8125 | 3 | [] | no_license | //
// UInt8+Convert.swift
// FitBitChallenge
//
// Created by Andrew Meng on 2018-02-05.
// Copyright © 2018 Andrew Meng. All rights reserved.
//
import Foundation
extension UInt8 {
// Returns UInt8 value as if it would be represented by Int8
func convertToSignedEquivalent() -> Int16 {
if self > 127 {
// Based on Two's Complement
return Int16(~self + 1) * -1
}
return Int16(self)
}
}
|
Java | UTF-8 | 4,915 | 2.75 | 3 | [] | no_license | package kr.or.ddit.fileupload;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/fileDownload.do")
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/*
파일을 다운로드하는 과정
1. FileInputStream 객체를 이용해서 다운로드할 파일을 서버에서 읽는다.
2. 파일을 다운로드하려면 response객체의 setContentType()메서드를 이용하여 content-type을
'application/octet-stream; charset=utf-8'로 설정한다.
3. response객체의 헤더를 다음과 같이 설정한다.
1) 헤더명 : "Content-Disposition"
2) 헤더값 : 'attachment; filename="다운로드할파일명";'
4. response객체의 getOutputStream()을 사용하여 출력할 스트림 객체를 구한 후
이 출력 스트림으로 전송하면 된다.
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// 파라미터로 넘어온 다운로드 할 파일 이름을 구한다.
String fileName = request.getParameter("filename");
// 파일이 저장된 폴더 설정
String uploadPath = "D:\\D_Other\\uploadFiles";
// 파일 경로와 파일명을 연결한 전체 파일 경로를 만든다.
String filePath = uploadPath + File.separator + fileName;
File file = new File(filePath);
OutputStream os = null;
FileInputStream fis = null;
if(file.exists()) { // 다운로드할 파일이 있을 때
// Content-Type 설정하기
response.setContentType("application/octet-stream; charset=utf-8");
// response의 헤더설정
// String headerValue = "attachment; filename=\""+ fileName + "\"";
String headerValue = "attachment; filename=\""+ getDisposition(fileName,getBrowser(request)) + "\"";
response.setHeader("Content-Disposition", headerValue);
try {
// 출력용 스트림 객체 생성
os = response.getOutputStream();
// 파일 입력용 스트림 객체 생성
fis = new FileInputStream(file);
byte[] buffer = new byte[1024*100];
int len = -1;
while((len=fis.read(buffer))>0) {
os.write(buffer, 0, len);
}
os.flush();
} catch (Exception e) {
System.out.println("입출력 오류 : " + e.getMessage());
} finally {
if(fis!=null) try { fis.close();} catch (IOException e) {}
if(os!=null) try { os.close();} catch (IOException e) {}
}
}else { // 다운로드할 파일이 없을 때
response.setContentType("text/html; charset=utf-8" );
response.getWriter().println("<h3>" + fileName + "파일은 존재하지 않습니다. </h3>");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
// 사용자의 웹브라우저 알아내는 메서드
private String getBrowser(HttpServletRequest request) {
String header = request.getHeader("User-Agent");
//System.out.println(header);
if(header.indexOf("MSIE") > -1 ) {
return "MSIE";
}else if(header.indexOf("Chrome") >-1) {
return "Chrome";
}else if(header.indexOf("Opera") >-1) {
return "Opera";
}else if(header.indexOf("Trident/7.0") >-1) { // IE 11 이상
return "MSIE";
}
return "Firefox";
}
// 브라우저별로 한글 파일명을 인코딩하는 메서드
private String getDisposition(String fileName, String browser) {
String encodedFilename = null;
try {
if(browser.equals("MSIE")) {
encodedFilename = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
}else if(browser.equals("Firefox") || browser.equals("Opera")) {
encodedFilename = "\"" + new String(fileName.getBytes("utr-8"), "8859_1") + "\"";
}else if(browser.equals("Chrome")) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < fileName.length(); i++) {
char c = fileName.charAt(i);
if (c > '~') {
sb.append(URLEncoder.encode("" + c, "utf-8"));
}else {
sb.append(c);
}
}
encodedFilename = sb.toString();
}else {
throw new RuntimeException("지원하지 않는 브라우저입니다.");
}
} catch (Exception e) {
e.printStackTrace();
}
return encodedFilename;
}
}
|
JavaScript | UTF-8 | 3,074 | 2.921875 | 3 | [] | no_license | import React, { useState, useEffect } from 'react';
import GithubProfileContainer from './GithubProfileContainer';
import Form from './Form';
import './App.css';
/*
Sections:
-Form and text input button
-GitHub Profile
Components:
-Form
-Avatar
-Username
-Bio
-MetricsContainer
-MetricsItems
-ReposContainer
-RepoItems
-Steps:
-Add the Form component and ensure that it is passing back the value that is submitted to the App component
-Create a few methods in the App component:
-fetchGithubData...will need to hit the API the value of "username" set in state passed in and return the data
-GitHub Response Properties Needed:
-avatar_url, bio, followers, following, public_repos,
*/
function App() {
const githubAPI = "https://api.github.com/users/";
const reposString = "/repos";
// State
const [ githubUsername, setGithubUsername ] = useState("sean21johnson");
const [ githubUserData, setGithubUserData ] = useState({});
const [ githubUserRepos, setGithubUserRepos ] = useState([]);
// useEffect hook to fetch initial data and listen for changes to data
useEffect(() => {
return fetchGithubData(githubUsername)
},[githubUsername])
const fetchGithubData = async (githubUsername) => {
const response = await fetch(`${githubAPI}${githubUsername}`)
const responseJson = await response.json();
updateGithubUserData(responseJson)
updateGithubUsername(githubUsername)
fetchRepoData(githubUsername)
}
//Method to fetch the repos for a user
const fetchRepoData = async (username) => {
const response = await fetch (`${githubAPI}${username}${reposString}`)
const responseJson = await response.json();
console.log('responseJson is', responseJson)
const reposList = responseJson.slice(0, 10).map(repo => {
const item = {
repoId: repo.id,
repoName: repo.name,
}
return item;
})
updateGithubUserRepos(reposList);
}
// Method to update the github user data
const updateGithubUserData = (data) => {
setGithubUserData(data)
}
// Method to update the github username
const updateGithubUsername = (username) => {
setGithubUsername(username);
}
// Method to update the github user's repos collection
const updateGithubUserRepos = (repos) => {
setGithubUserRepos(repos)
}
// Method to handle the submission of the form when a user searches for a Github user
const handleFormSubmit = (e) => {
e.preventDefault();
const searchValue = e.target.searchGithubUser.value;
console.log(searchValue)
fetchGithubData(searchValue);
e.target.searchGithubUser.value = "";
}
return (
<div className="App">
<section className="upper_container">
<Form onFormSubmit={handleFormSubmit}/>
</section>
<section className="lower_container">
<GithubProfileContainer githubUserData={githubUserData} githubUserRepos={githubUserRepos}/>
</section>
</div>
);
}
export default App;
|
C | UTF-8 | 1,561 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pmmintrin.h>
#include <immintrin.h>
#define N 512
int main()
{
double execTime;
double startTime, endTime;
float A[N * N]__attribute__((aligned(16)));
float B[N * N]__attribute__((aligned(16)));
float C[N * N]__attribute__((aligned(16)));
for(int i = 0; i < N * N; i++)
{
A[i] = i + 1;
B[i] = i + 1;
C[i] = 0;
}
double duration = 0.0;
struct timeval start;
gettimeofday(&start, NULL);
startTime = (double)(start.tv_sec + start.tv_usec/1000000.0);
#ifdef SSE2
__m128 temp_a;
__m128 temp_b;
__m128 temp_c;
__m128 temp_d;
for(int i = 0; i < N ; i++)
{
for(int j = 0; j < N ; j++)
{
temp_d = _mm_setzero_ps();
for (int k = 0 ; k < N ; k += 4)
{
temp_a = _mm_load_ps(A + i * N + k);
temp_b = _mm_set_ps(B[(k + 3) * N + j], B[(k + 2) * N + j], B[(k + 1) * N + j], B[(k + 0) * N + j]);
temp_c = _mm_mul_ps(temp_a, temp_b);
temp_d = _mm_add_ps(temp_d, temp_c);
}
temp_d = _mm_hadd_ps(temp_d, temp_d);
temp_d = _mm_hadd_ps(temp_d, temp_d);
_mm_store_ss(C + i * N + j, temp_d);
}
}
#else
for(int i = 0; i < N ; i++)
{
for (int k = 0 ; k < N ; k++)
{
for(int j = 0; j < N ; j++)
{
C[i * N + j] += A[i * N + k] * B[k * N + j];
}
}
}
#endif
gettimeofday(&start, NULL);
endTime = (double)(start.tv_sec + start.tv_usec/1000000.0);
execTime = endTime - startTime;
printf("Execution time is %2.3f seconds\n", execTime);
return 0;
}
|
Java | UTF-8 | 255 | 2 | 2 | [] | no_license | package generic;
import java.util.List;
public class ParseService<T> {
private ResParse<T> parse;
public ParseService(ResParse<T> parse) {
this.parse = parse;
}
public List<T> getResult() throws Exception {
return parse.parse();
}
}
|
Python | UTF-8 | 1,425 | 2.828125 | 3 | [] | no_license | """
*(вместо 1) Написать регулярное выражение для парсинга файла логов web-сервера из ДЗ 6 урока nginx_logs.txt
(https://github.com/elastic/examples/raw/master/Common%20Data%20Formats/nginx_logs/nginx_logs) для получения информации
вида: (<remote_addr>, <request_datetime>, <request_type>, <requested_resource>, <response_code>, <response_size>),
например:
raw = '188.138.60.101 - - [17/May/2015:08:05:49 +0000] "GET /downloads/product_2 HTTP/1.1"
304 0 "-" "Debian APT-HTTP/1.3 (0.9.7.9)"'
parsed_raw = ('188.138.60.101', '17/May/2015:08:05:49 +0000', 'GET', '/downloads/product_2', '304', '0')
Примечание: вы ограничились одной строкой или проверили на всех записях лога в файле? Были ли особенные строки? Можно
ли для них уточнить регулярное выражение?
"""
import re
import requests
raw = re.compile(r'(\d+\.\d+\.\d+\.\d+) . . .([^\]]*). .(\w+) ([^\"]*). (\d+) (\d+)')
url = 'https://github.com/elastic/examples/raw/master/Common%20Data%20Formats/nginx_logs/nginx_logs'
resp = requests.get(url).text
for parsed_raw in raw.findall(resp):
print(parsed_raw)
# parsed_raw = ('188.138.60.101', '17/May/2015:08:05:49 +0000', 'GET', '/downloads/product_2', '304', '0')
|
Python | UTF-8 | 1,224 | 3.3125 | 3 | [] | no_license | import threading
import numpy as np
class GameHistory():
'''Maintain a history of state-action-value tuples, replacing randomly
when we exceed the max storage'''
def __init__(self, features, max_size=50000):
self.max_size = max_size
self._lock = threading.Lock()
self._storage = np.zeros((0,features))
def add(self, samples):
'''Add N rows (samples is a matrix with N rows and some features)'''
self._lock.acquire()
try:
if(self._storage.shape[0] < self.max_size):
self._storage = np.concatenate([self._storage, samples])
# chop if we went over
if(self._storage.shape[0] > self.max_size):
self._storage = self._storage[0:self.max_size,:]
else:
rows_to_replace = np.random.choice(self.max_size, samples.shape[0])
self._storage[rows_to_replace,:] = samples
except Exception as e:
raise e
finally:
self._lock.release()
def sample(self, N):
'''Return N random rows'''
rows = np.random.choice(self._storage.shape[0], N)
return self._storage[rows,:]
|
C++ | UTF-8 | 4,050 | 2.734375 | 3 | [] | no_license | #include<bits/stdc++.h>
#define LL long long
#define ULL unsigned long long
#define MOD 1000000007
using namespace std;
const int maxn=100000+100 ;
LL power(LL x,int n)
{
if(n<=1) return n ? x : 1LL ;
LL t=power(x,n/2) ;
if(n%2) return (t*t%MOD)*x%MOD ;
else return t*t%MOD ;
}
ULL Rand()
{
static ULL _r[5] ;
for(int i=0;i<5;i++) _r[i]=rand() ;
return (_r[0]<<49)^(_r[1]<<34)^(_r[2]<<19)^(_r[3]<<4)^(_r[4]>>11) ;
}
ULL rval[maxn] ;
struct node
{
node *l,*r ;
int len ;
ULL h ; /// hash value
node(int _l=0,ULL _h=0)
{l=r=NULL ; len=_l ; h=_h ;}
};
node *build(int l,int r)
{
if(l==r) return new node() ;
node *u=new node() ;
int mid=(l+r)/2 ;
u->l=build(l,mid) ;
u->r=build(mid+1,r) ;
return u ;
}
void pull(int l,int r,node *u)
{
int mid=(r+l)/2 ;
u->len=(u->r->len==r-mid ?
r-mid+u->l->len : u->r->len) ;
u->h=u->l->h^u->r->h ;
}
void push(node *u)
{
if(u->l) return ;
u->l=new node() ;
u->r=new node() ;
}
node *modify(int l,int r,node *u,int pos)
{
if(l==r) return new node(1,rval[l]) ;
push(u) ;
int mid=(l+r)/2 ;
node *v=new node() ;
if(pos<=mid) v->r=u->r , v->l=modify(l,mid,u->l,pos) ;
else v->l=u->l , v->r=modify(mid+1,r,u->r,pos) ;
pull(l,r,v) ; return v ;
}
node *reset(int l,int r,int L,int R,node *u)
{
if(l==L && r==R) return new node() ;
push(u) ;
int mid=(L+R)/2 ;
node *v=new node() ;
if(r<=mid) v->r=u->r , v->l=reset(l,r,L,mid,u->l) ;
else if(l>mid) v->l=u->l , v->r=reset(l,r,mid+1,R,u->r) ;
else
v->l=reset(l,mid,L,mid,u->l) ,
v->r=reset(mid+1,r,mid+1,R,u->r) ;
pull(L,R,v) ; return v ;
}
int query_r(int l,int r,node *u,int pos)
{
if(l==r) return l ;
int mid=(l+r)/2 ;
push(u) ;
if(pos<=mid && u->l->len<mid-pos+1)
return query_r(l,mid,u->l,pos) ;
else return query_r(mid+1,r,u->r,max(pos,mid+1)) ;
}
node *add(node *u,int pos)
{
int pos2=query_r(0,maxn-1,u,pos) ;
node *u2=modify(0,maxn-1,u,pos2) ;
if(pos2>pos) return reset(pos,pos2-1,0,maxn-1,u2) ;
else return u2 ;
}
bool query(int l,int r,node *u1,node *u2) /// return u1<u2
{
if(l==r) return u1->len<u2->len ;
push(u1) ; push(u2) ;
int mid=(l+r)/2 ;
if(u1->r->h == u2->r->h) return query(l,mid,u1->l,u2->l) ;
else return query(mid+1,r,u1->r,u2->r) ;
}
int cmp(node *a,node *b) /// a-b
{
if(!b) return -1 ;
if(a->h==b->h) return 0 ;
return query(0,maxn-1,a,b) ? -1 : 1 ;
}
struct Q
{
int id ; node *val ;
bool operator < (const Q &rhs) const
{
return cmp(val,rhs.val)==1 ;
}
};
priority_queue<Q> pq ;
struct P{int to,dis;};
vector<P> v[maxn] ;
node *d[maxn] ;
bool done[maxn] ;
int las[maxn] ;
void Dijkstra(int st,int ed)
{
d[st]=build(0,maxn-1) ;
pq.push((Q){st,d[st]}) ;
while(!pq.empty())
{
Q u=pq.top() ; pq.pop() ;
if(u.id==ed) return ;
if(done[u.id]) continue ;
done[u.id]=1 ;
for(auto i : v[u.id]) if(!done[i.to])
{
node *nd=add(d[u.id],i.dis) ;
if(cmp(nd,d[i.to])==-1)
{
las[i.to]=u.id ;
d[i.to]=nd ;
pq.push((Q){i.to,nd}) ;
}
}
}
}
vector<int> ans ;
LL ansd ;
void getans(int st,int x)
{
if(st==x){ans.push_back(x) ; return ;}
getans(st,las[x]) ;
ans.push_back(x) ;
for(auto i : v[las[x]]) if(i.to==x)
ansd=(ansd+power(2,i.dis))%MOD ;
}
main()
{
srand(time(NULL)) ;
for(int i=0;i<maxn;i++) rval[i]=Rand() ;
int n,m ; scanf("%d%d",&n,&m) ;
while(m--)
{
int x,y,dis ; scanf("%d%d%d",&x,&y,&dis) ;
v[x].push_back((P){y,dis}) ;
v[y].push_back((P){x,dis}) ;
}
int st,ed ; scanf("%d%d",&st,&ed) ;
Dijkstra(st,ed) ;
if(!d[ed]){printf("-1\n") ; return 0 ;}
getans(st,ed) ;
printf("%I64d\n%d\n",ansd,ans.size()) ;
for(int i=0;i<ans.size();i++) printf("%d%c",ans[i],i+1==ans.size()?'\n':' ') ;
}
|
Java | UTF-8 | 600 | 2.390625 | 2 | [
"Apache-2.0"
] | permissive | package com.intellij.perlplugin.filters;
import com.intellij.perlplugin.Utils;
import com.intellij.perlplugin.language.Constants;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
/**
* Created by eli on 28-11-14.
*/
public class FileFilter implements FilenameFilter {
@Override
public boolean accept(File file, String path) {
try {
return (Utils.isValidateExtension(path) || (new File(file.getCanonicalPath() + "/" + path).isDirectory()) && file.exists());
} catch (IOException e) {
return false;
}
}
}
|
Go | UTF-8 | 2,279 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | package baserpc
import (
"github.com/dming/lodos/rpc"
"sync"
"fmt"
"github.com/dming/lodos/rpc/pb"
"github.com/dming/lodos/log"
)
type localServer struct {
call_chan chan rpc.CallInfo // chan to rpc server
local_chan chan rpc.CallInfo // chan to local client
done chan error
isClose bool
lock *sync.Mutex
}
func NewLocalServer(call_chan chan rpc.CallInfo) (*localServer, error) {
server := new(localServer)
server.call_chan = call_chan
server.local_chan = make(chan rpc.CallInfo, 1)
server.isClose = false
server.lock = new(sync.Mutex)
go server.on_request_handle(server.local_chan)
return server, nil
}
func (s *localServer) IsClose() bool {
return s.isClose;
}
func (s *localServer) WriteToRpcServer(callInfo rpc.CallInfo) (success bool) {
defer func() {
if recover() != nil {
log.Error("s.call_chan is closed")
success = false
}
}()
if s.isClose {
return false
}
s.call_chan <- callInfo
return true
}
//stop
func (s *localServer) StopConsume() error {
s.lock.Lock()
s.isClose = true
s.lock.Unlock()
return nil
}
/**
注销消息队列
*/
func (s *localServer) Shutdown() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf(r.(string))
}
}()
return nil
}
func (s *localServer) Callback (callInfo rpc.CallInfo) error {
replyTo := callInfo.Props["reply_to"].(chan rpcpb.ResultInfo)
replyTo <- callInfo.Result
return nil
}
func (s *localServer) on_request_handle(local_chan <-chan rpc.CallInfo) {
for {
select {
case callInfo, ok := <-local_chan:
if !ok {
local_chan = nil
} else {
callInfo.Agent = s
if s.WriteToRpcServer(callInfo) {
log.Warning("rpc request [%s] fail : [%s]", callInfo.RpcInfo.Fn, callInfo.RpcInfo.Cid)
}
}
}
if local_chan == nil {
break
}
}
}
func (s *localServer) SafeCallback(local_chan chan rpcpb.ResultInfo, resultInfo rpcpb.ResultInfo) (closed bool) {
defer func() {
if recover() != nil {
closed = true
}
}()
// assume ch != nil here.
local_chan <- resultInfo
return false
}
func (s *localServer) SafeSend(call_chan chan rpc.CallInfo, callInfo rpc.CallInfo) (closed bool) {
defer func() {
if recover() != nil {
closed = true
}
}()
// assume ch != nil here.
call_chan <- callInfo
return false
}
|
Python | UTF-8 | 1,447 | 3.984375 | 4 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
统计Python之禅中所有字符出现的次数
"""
# python 之禅
this_str = """
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
d = {}
for i in this_str:
if i not in d.keys():
d[i] = 1
else:
d[i] += 1
for k, v in d.items():
print(f"字符 {k} 出现了 {v} 次")
# 拓展:对字典进行排序输出
# 1. 字典是无序的,需要改变结构
l = list(d.items())
def func(temp):
return temp[1]
# 2. 需要指定列表里面的元素的第二个值进行排序
l.sort(key=func, reverse=True)
print(l)
for i in l:
print(f"字符 {i[0]} 出现了 {i[1]} 次")
|
PHP | WINDOWS-1250 | 1,173 | 3.171875 | 3 | [] | no_license | <html>
<head>
</head>
<body>
<?php
//Funcion eliminar TILDES
function sinTildes($frase){
$cadBuscar = array("","","","","","","","","","");
$cadPoner = array("a","A","e","E","i","I","o","O","u","U");
$frase = str_replace ($cadBuscar, $cadPoner, $frase);
return $frase;
}
//Funcin eliminar ESPACIOS
function sinEspacios($frase){
$frase = str_replace('/\s+/', ' ', $frase);
return $frase;
}
//Funcin para comparar dos cadenas haciendo uso de
//sinTildes, sinEspacios y sin distinguir Mayus. de Minus.
function compCaseEsp($frase1, $frase2){
//Quitar espacios inecesarios:
$frase2 = trim($frase2);
//Cambiar tildes:
$cadBuscar = array("","","","","","","","","","");
$cadPoner = array("a","A","e","E","i","I","o","O","u","U");
$frase2 = str_replace ($cadBuscar, $cadPoner, $frase2);
//Comparacin sin contar Mayusculas y Minusculas
$codComp = strcasecmp ($frase1, $frase2);
return $codComp;
}
?>
</body>
</html> |
PHP | UTF-8 | 1,030 | 2.96875 | 3 | [] | no_license | <?php
require 'vendor/autoload.php';
$inputFileType1 = 'Excel2007';
$inputFileName1 = 'uploads/sheet.xlsx';
$inputFileType2 = 'Excel2007';
$inputFileName2 = 'uploads/sheet1.xlsx';
$outputFileType = 'Excel2007';
$outputFileName = 'outputData.xlsx';
// Load the first workbook (an xlsx file)
$objPHPExcelReader1 = PHPExcel_IOFactory::createReader($inputFileType1);
$objPHPExcel1 = $objPHPExcelReader1->load($inputFileName1);
// Load the second workbook (an xls file)
$objPHPExcelReader2 = PHPExcel_IOFactory::createReader($inputFileType2);
$objPHPExcel2 = $objPHPExcelReader2->load($inputFileName2);
// Merge the second workbook into the first
var_dump($objPHPExcel2);
exit();
$objPHPExcel2->getActiveSheet()->setTitle('Sheet2');
$objPHPExcel1->addExternalSheet($objPHPExcel2->getActiveSheet());
// Save the merged workbook under a new name (could save under the original name)
// as an xls file
/*$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1,$outputFileType);
$objPHPExcelWriter->save($outputFileName);*/ |
C# | UTF-8 | 8,063 | 2.828125 | 3 | [] | no_license | using System;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace A00457100_Assignment1
{
class Program
{
static void Main(string[] args)
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
string file = "/Users/muralitulluri/Documents/Output.txt";
string Skipped = "/Users/muralitulluri/Documents/Skipped_rows.txt";
string Log = "/Users/muralitulluri/Documents/Log_file.txt";
string header = "First Name,Last Name,Street Number,Street,City,Province,Postal Code,Country,Phone Number,email Address,Date";
string filePath1 = @"/Users/muralitulluri/Documents/Output.txt";
string skipped_rows = @"/Users/muralitulluri/Documents/Skipped_rows.txt";
using (StreamWriter outputFile = new StreamWriter(skipped_rows, true))
{
outputFile.WriteLine(header);
}
using (StreamWriter outputFile = new StreamWriter(filePath1, true))
{
outputFile.WriteLine(header);
}
using (StreamWriter outputFile = new StreamWriter(Log, true))
{
outputFile.WriteLine("This program merges all the CSV files by rejecting any invalid records");
DirWalker traverse = new DirWalker();
traverse.walk(@"/Users/muralitulluri/Documents/Sample Data");
watch.Stop();
outputFile.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
outputFile.WriteLine("Number of total correct lines excluding header are : " + File.ReadLines(file).Count());
outputFile.WriteLine("Number of total skipped lines are : " + File.ReadLines(Skipped).Count());
}
}
}
public class DirWalker
{
public void walk(String path)
{
string[] list = Directory.GetDirectories(path);
SimpleCSVParser simpleCSV = new SimpleCSVParser();
//int directory_count = 0;
//int file_count = 0;
if (list == null) return;
foreach (string dirpath in list)
{
if (Directory.Exists(dirpath))
{
walk(dirpath);
//Console.WriteLine("Dir:" + dirpath);
}
}
// directory_count = directory_count + list.count();
string[] fileList = Directory.GetFiles(path);
// file_count = file_count + fileList.count();
foreach (string filepath in fileList)
{
// n = n + 1;
// if (n%100 == 0)
// {
// Console.WriteLine("Processing the " + n + " st/th file");
// }
if (filepath.Contains(".csv"))
{
char char1 = '\\';
string[] path_split = filepath.Split(char1);
string year1 = path_split[1];
string month1="";
string day = "";
string date_custom = "";
if (path_split[2].Length == 1)
{
month1 = "0" + path_split[2];
//Console.WriteLine("File:" + month+"another month"+month1);
// Console.WriteLine("File:" + date_custom);
}
else month1 = path_split[2];
if (path_split[3].Length == 1)
{
day = "0" + path_split[3];
//Console.WriteLine("File:" + month+"another month"+month1);
// Console.WriteLine("File:" + date_custom);
}
else day = path_split[3];
date_custom = year1 + "/" + month1 + "/" + day;
//Console.WriteLine("File:" + date_custom);
// Console.WriteLine("Call the file parser");
simpleCSV.parse(@filepath, date_custom);
}
}
//Console.WriteLine("All " + n + " files are processed and the output files are generated below are the stats");
}
}
public class SimpleCSVParser
{
public void parse(String fileName,String Date_Custom)
{
try
{
using (TextFieldParser parser = new TextFieldParser(fileName))
{
TextFieldParser parser1 = new TextFieldParser(fileName);
string filePath1 = @"/Users/muralitulluri/Documents/Output.txt";
string skipped_rows= @"/Users/muralitulluri/Documents/Skipped_rows.txt";
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
int i = 1;
int j;
int k;
List<string> rows = new List<string>();
List<string> rows_skipped = new List<string>();
while (!parser.EndOfData)
{
//Process row
string[] fields = parser.ReadFields();
string line = parser1.ReadLine()+ ","+Date_Custom;
j = 0;
k = 0;
if (fields.Count()!=10)
{
//Console.WriteLine("Wrong number of fields in row number " + i);
rows_skipped.Add("There are only "+ fields.Count()+" fields in row number " + i+ " of the file "+ fileName+"so skipping the row and the row data is "+line);
k = 1;
}
foreach (string field in fields)
{
j = j+1;
if (fields.Contains("First Name"))
{
//Console.WriteLine("Wrong number of fields in row number " + i);
k = 1;
break;
}
if (field == "" && k == 0)
{
rows_skipped.Add("Field " + j + " is blank in row number " + i + " of the file " + fileName + " so skipping the row and the row data is " + line);
k = 1;
break;
}
}
if (k == 0)
{
/* using (StreamWriter outputFile = new StreamWriter(filePath1, true))
{
outputFile.WriteLine(line);
}*/
rows.Add(line);
}
i = i+1;
}
using (StreamWriter outputFile = new StreamWriter(filePath1, true))
{
foreach(string data in rows)
outputFile.WriteLine(data);
}
using (StreamWriter outputFile = new StreamWriter(skipped_rows, true))
{
foreach (string data1 in rows_skipped)
outputFile.WriteLine(data1);
}
}
}
catch (IOException ioe)
{
Console.WriteLine(ioe.StackTrace);
}
}
}
}
|
PHP | UTF-8 | 1,273 | 2.71875 | 3 | [] | no_license | <?php
/*
* Openkvk outputs lists of rowtypes, column names and data. This converts it to an array of key-value pairs.
*/
function get_clean($raw) {
$results = json_decode($raw);
$clean = array();
foreach($results[0]->RESULT->ROWS AS $row) {
$new = array();
foreach($row AS $k => $v) {
$new[$results[0]->RESULT->HEADER[$k]] = $v;
}
$clean[] = $new;
}
return $clean;
}
function debug($string) {
if ($debug) {
echo $string;
}
}
$city = addslashes(ucwords(strtolower($_GET['city'])));
$debug = isset($_GET['debug']);
debug('<pre>');
debug("City: {$city}\n");
$query = "SELECT f.* FROM faillissementen AS f WHERE f.plaats = '{$city}' ORDER BY f.datum DESC LIMIT 50;";
$url = 'http://api.openkvk.nl/json/' . rawurlencode($query);
debug("url: {$url}\n");
$a = get_clean(file_get_contents($url));
foreach($a AS $k => $item) {
$kvks = $item['kvks'];
$query = "SELECT adres, postcode FROM kvk WHERE kvks = {$kvks} LIMIT 1;";
$url = 'http://api.openkvk.nl/json/' . rawurlencode($query);
$extra = get_clean(file_get_contents($url));
$a[$k]['adres'] = $extra[0]['adres'];
$a[$k]['postcode'] = $extra[0]['postcode'];
}
debug(print_r($a, true));
debug('</pre>');
$json = json_encode($a);
echo $json;
?> |
Shell | UTF-8 | 144 | 3.359375 | 3 | [
"MIT"
] | permissive | function get_last_version {
target_dir=$1
newest_file=$(ls -1 $target_dir |grep -E '^[0-9]+$' |sort -nr|head -1)
echo "${newest_file}"
}
|
Rust | UTF-8 | 1,262 | 3.328125 | 3 | [] | no_license | struct SnapshotArray {
arrays: Vec<Vec<(i32, i32)>>,
snap_id: i32,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl SnapshotArray {
fn new(length: i32) -> Self {
Self {
arrays: vec![vec![(0, 0)]; length as usize],
snap_id: 0,
}
}
fn set(&mut self, index: i32, val: i32) {
if self.snap_id > self.arrays[index as usize].last().unwrap().0 {
self.arrays[index as usize].push((self.snap_id, val));
} else {
self.arrays[index as usize].last_mut().unwrap().1 = val;
}
}
fn snap(&mut self) -> i32 {
self.snap_id += 1;
self.snap_id - 1
}
fn get(&self, index: i32, snap_id: i32) -> i32 {
match self.arrays[index as usize].binary_search_by_key(&snap_id, |&(a, b)| a) {
Ok(i) => self.arrays[index as usize][i].1,
Err(i) => self.arrays[index as usize][i - 1].1,
}
}
}
/**
* Your SnapshotArray object will be instantiated and called as such:
* let obj = SnapshotArray::new(length);
* obj.set(index, val);
* let ret_2: i32 = obj.snap();
* let ret_3: i32 = obj.get(index, snap_id);
*/
|
Python | UTF-8 | 4,182 | 3.046875 | 3 | [
"BSD-2-Clause-Views"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 14 10:13:54 2017
@author: scd
"""
from __future__ import division
import numpy as np
from scipy.optimize import fsolve
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# final time
tf = 1.0
# solve with ODEINT (for comparison)
def model(x,t):
u = 4.0
return (-x**2 + u)/5.0
t = np.linspace(0,tf,20)
y0 = 0
y = odeint(model,y0,t)
plt.figure(1)
plt.plot(t,y,'r-',label='ODEINT')
# ----------------------------------------------------
# Approach #1 - Write the model equations in Python
# ----------------------------------------------------
# define collocation matrices
def colloc(n):
if (n==2):
NC = np.array([[1.0]])
if (n==3):
NC = np.array([[0.75,-0.25], \
[1.00, 0.00]])
if (n==4):
NC = np.array([[0.436,-0.281, 0.121], \
[0.614, 0.064, 0.0461], \
[0.603, 0.230, 0.167]])
if (n==5):
NC = np.array([[0.278, -0.202, 0.169, -0.071], \
[0.398, 0.069, 0.064, -0.031], \
[0.387, 0.234, 0.278, -0.071], \
[0.389, 0.222, 0.389, 0.000]])
if (n==6):
NC = np.array([[0.191, -0.147, 0.139, -0.113, 0.047],
[0.276, 0.059, 0.051, -0.050, 0.022],
[0.267, 0.193, 0.252, -0.114, 0.045],
[0.269, 0.178, 0.384, 0.032, 0.019],
[0.269, 0.181, 0.374, 0.110, 0.067]])
return NC
# define collocation points from Lobatto quadrature
def tc(n):
if (n==2):
time = np.array([0.0,1.0])
if (n==3):
time = np.array([0.0,0.5,1.0])
if (n==4):
time = np.array([0.0, \
0.5-np.sqrt(5)/10.0, \
0.5+np.sqrt(5)/10.0, \
1.0])
if (n==5):
time = np.array([0.0,0.5-np.sqrt(21)/14.0, \
0.5,0.5+np.sqrt(21)/14.0, 1])
if (n==6):
time = np.array([0.0, \
0.5-np.sqrt((7.0+2.0*np.sqrt(7.0))/21.0)/2.0, \
0.5-np.sqrt((7.0-2.0*np.sqrt(7.0))/21.0)/2.0, \
0.5+np.sqrt((7.0-2.0*np.sqrt(7.0))/21.0)/2.0, \
0.5+np.sqrt((7.0+2.0*np.sqrt(7.0))/21.0)/2.0, \
1.0])
return time*tf
# solve with SciPy fsolve
def myFunction(z,*param):
n = param[0]
m = param[1]
# rename z as x and xdot variables
x = np.empty(n-1)
xdot = np.empty(n-1)
x[0:n-1] = z[0:n-1]
xdot[0:n-1] = z[n-1:m]
# initial condition (x0)
x0 = 0.0
# input parameter (u)
u = 4.0
# final time
tn = tf
# function evaluation residuals
F = np.empty(m)
# nonlinear differential equations at each node
# 5 dx/dt = -x^2 + u
F[0:n-1] = 5.0 * xdot[0:n-1] + x[0:n-1]**2 - u
# collocation equations
# tn * NC * xdot = x - x0
NC = colloc(n)
F[n-1:m] = tn * np.dot(NC,xdot) - x + x0 * np.ones(n-1)
return F
sol_py = np.empty(5) # store 5 results
for i in range(2,7):
n = i
m = (i-1)*2
zGuess = np.ones(m)
z = fsolve(myFunction,zGuess,args=(n,m))
# add to plot
yc = np.insert(z[0:n-1],0,0)
plt.plot(tc(n),yc,'o',markersize=20)
# store just the last x[n] value
sol_py[i-2] = z[n-2]
# ----------------------------------------------------
# Approach #2 - Write model in APMonitor and let
# modeling language create the collocation equations
# ----------------------------------------------------
# load GEKKO
from gekko import GEKKO
m = GEKKO()
u = m.Param(value=4)
x = m.Var(value=0)
m.Equation(5*x.dt() == -x**2 + u)
m.time = [0,tf]
m.options.imode = 4
m.options.TIME_SHIFT = 0
sol_apm = np.empty(5) # store 5 results
i = 0
for nodes in range(2,7):
m.options.nodes = nodes
m.clear_data() # clear prior application
x.value=0
u.value=4
m.solve() # solve problem
sol_apm[i] = x.value[-1] # store solution (last point)
i += 1
# print the solutions
print(sol_py)
print(sol_apm)
m.GUI()
# # show plot
# plt.ylabel('x(t)')
# plt.xlabel('time')
# plt.show()
|
Java | UTF-8 | 2,038 | 2.6875 | 3 | [] | no_license | package com.example.spm1.Utils;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.spm1.Entities.Parcel;
import com.example.spm1.R;
import java.util.List;
public class ParcelArrayAdapter extends ArrayAdapter<Parcel> {
private int listItemLayout;
public ParcelArrayAdapter(Context context, int layoutId, List<Parcel> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Parcel parcel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(listItemLayout, parent, false);
viewHolder.parcelId = (TextView) convertView.findViewById(R.id.idParcel);
viewHolder.parcelName = (TextView) convertView.findViewById(R.id.nameTextView);
viewHolder.parcelDM = (TextView) convertView.findViewById(R.id.DMName);
convertView.setTag(viewHolder); // view lookup cache stored in tag
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.parcelId.setText(parcel.getId());
viewHolder.parcelName.setText(parcel.getFirstName()+" "+parcel.getLastName());
viewHolder.parcelDM.setText(parcel.getAddress());
// Return the completed view to render on screen
return convertView;
}
private static class ViewHolder {
TextView parcelId;
TextView parcelName;
TextView parcelDM;
}
}
|
Java | UTF-8 | 353 | 3.078125 | 3 | [] | no_license | package b06.s71;
public class Person {
public String nome=" ";
public String cognome=" ";
public Person(String nome, String cognome) {
this.nome = nome;
this.cognome= cognome;
}
public String getNome() {
return nome;
}
public String getCognome() {
return cognome;
}
}
|
Java | UTF-8 | 1,441 | 2.5 | 2 | [] | no_license | package thinlet.drafts;
import java.awt.*;
import thinlet.*;
/**
*
*/
public class Drafts extends Thinlet {
/**
*
*/
public Drafts() {
//setFont(new Font("Trebuchet MS", Font.PLAIN, 12));
try {
add(parse("drafts.xml"));
} catch (Exception exc) { exc.printStackTrace(); }
}
/**
*
*/
public void loadDraft(Object splitpane, Object tree) {
if (getCount(splitpane) > 2) {
remove(getItem(splitpane, 1));
}
Object node = getSelectedItem(tree);
if (node != null) {
Object draft = getProperty(node, "draft");
if (draft == null) {
String ui = (String) getProperty(node, "ui");
String logic = (String) getProperty(node, "logic");
if ((ui != null) && (logic != null)) {
try {
Object handler = Class.forName(logic).getConstructor(null).newInstance(null);
draft = parse(ui, handler);
putProperty(node, "draft", draft);
} catch (Exception exc) { exc.printStackTrace(); }
}
}
if (draft != null) {
add(splitpane, draft, 1);
}
}
}
/**
*
*/
public void paint(Graphics g) {
Utilities.getUtilities().initGraphics(g);
super.paint(g);
}
/**
*
*/
protected void handleException(Throwable throwable) {
new ExceptionDialog(this, throwable);
}
/**
*
*/
public static void main(String[] args) {
new FrameLauncher("Thinlet Drafts", new Drafts(), 580, 435);
}
} |
Rust | UTF-8 | 708 | 3.171875 | 3 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /// Tile id
use std::fmt;
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, From, Serialize, Deserialize)]
pub struct Tile(u8);
impl Tile {
pub fn to_char(self) -> char {
self.0 as char
}
pub fn to_byte(self) -> u8 {
self.0
}
}
impl fmt::Display for Tile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0 as char)
}
}
/// drawable object
pub trait Drawable {
const NONE: Tile = Tile(b' ');
fn tile(&self) -> Tile;
fn color(&self) -> Color {
Color(0)
}
}
/// color representation
/// currently it's not used at all
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Color(pub u8);
|
C++ | UTF-8 | 2,111 | 3.40625 | 3 | [
"MIT"
] | permissive | #include "stdio.h"
int letterCounter[8];
char validCharacters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()_+[]{}:;<>,./?'";
char bruteString[9]; // One more to null terminate.
bool evaluateString(char *testString)
{
// Do something here, to test the zero terminated string testString, and if it is valid, return true.
//printf("%s\n", testString);
return false;
}
int main()
{
int nDigits = 1;
int maxDigits = -1;
int validResult = -1;
int letterIndex = 0;
while (!((maxDigits < 8) && (maxDigits > 0)) && (validResult != 1))
{
printf("\nHow many characters to brute force ? ");
validResult = scanf_s("%d", &maxDigits);
}
for (int i = 0; i < maxDigits;i++)
{
letterCounter[i] = -1; // Initialize them all to nill.
bruteString[i+1] = 0; // Null terminate the string.
}
letterCounter[0] = 0; // But we will initialize the first counter to 0.
int wordLength = 0;
while (true)
{
// First thing we do, is update the text string with the character that changed.
bruteString[letterIndex] = validCharacters[letterCounter[letterIndex]];
if (evaluateString(&bruteString[0]) == true)
{
printf("%d character String \"%s\" has been found\n", wordLength+1, &bruteString[0]);
return 0;
}
// We always start incrementing the first character.
letterIndex = 0;
// And if it overflows, then we start walking up the letterCounter stack.
while (++letterCounter[letterIndex] == sizeof(validCharacters)-1)
{
letterCounter[letterIndex] = 0;
// Update the text string, at the stack position.
bruteString[letterIndex] = validCharacters[0];
// Let's check the next position on the stack.
letterIndex++;
// If we are starting a new wordlength. We need to update that counter.
if (letterIndex > wordLength)
{
wordLength++;
// If we have searched all characters, for all wordlengths, we are done.
if (wordLength >= maxDigits)
{
printf("No valid password found.\n");
return -1;
}
}
}
}
}
|
Python | UTF-8 | 1,975 | 3.140625 | 3 | [
"MIT"
] | permissive | '''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''
# Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk
# Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB
# Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu
# Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd
# contact :- github@jamessawyer.co.uk
# run using python fibonacci_search.py -v
'''
@params
arr: input array
val: the value to be searched
output: the index of element in the array or -1 if not found
return 0 if input array is empty
'''
def fibonacci_search(arr, val):
"""
>>> fibonacci_search([1,6,7,0,0,0], 6)
1
>>> fibonacci_search([1,-1, 5, 2, 9], 10)
-1
>>> fibonacci_search([], 9)
0
"""
fib_N_2 = 0
fib_N_1 = 1
fibNext = fib_N_1 + fib_N_2
length = len(arr)
if length == 0:
return 0
while (fibNext < len(arr)):
fib_N_2 = fib_N_1
fib_N_1 = fibNext
fibNext = fib_N_1 + fib_N_2
index = -1
while (fibNext > 1):
i = min(index + fib_N_2, (length - 1))
if (arr[i] < val):
fibNext = fib_N_1
fib_N_1 = fib_N_2
fib_N_2 = fibNext - fib_N_1
index = i
elif (arr[i] > val):
fibNext = fib_N_2
fib_N_1 = fib_N_1 - fib_N_2
fib_N_2 = fibNext - fib_N_1
else:
return i
if (fib_N_1 and index < length - 1) and (arr[index + 1] == val):
return index + 1
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
|
JavaScript | UTF-8 | 2,895 | 4.21875 | 4 | [] | no_license | // es5 类的写法
// let Animal = function (type) {
// this.type = type
// // this.eat = function () {
// // console.log('I am eating food')
// // }
// }
//
// // let dog = new Animal('dog')
// // let monkey = new Animal('monkey')
// // console.log(dog)
// // console.log(monkey)
// // monkey.eat = function () {
// // console.log('I am eating food monkey')
// // }
// // dog.eat()
// // monkey.eat()
// // 注意:eat写在函数体内,各自实例互不影响,只能改变自己的方法,违背了继承的原则,并且每个生成的对象都很大,因为每个对象下都会有声明的函数
//
// Animal.prototype.eat = function () {
// console.log('I am eating food')
// }
//
// let dog = new Animal('dog')
// let monkey = new Animal('monkey')
// console.log(dog)
// console.log(monkey)
// // obj.constructor.prototype.fn 可以改变原型链上的方法,每个实例的fn都进行了改变
// monkey.constructor.prototype.eat = function () {
// console.log('I am eating food monkey')
// }
// dog.eat()
// monkey.eat()
// es6 class
// class Animal {
// constructor (type) {
// this.type = type
// }
// eat () {
// console.log('I am eating food')
// }
// }
// let dog = new Animal('dog')
// console.log(dog)
// dog.eat()
//
// console.log(typeof Animal) // function
// es6 setter getter实现
// let _age = 4
// class Animal {
// constructor (type) {
// this.type = type
// }
// eat () {
// console.log('I am eating food')
// }
// get age () {
// return _age
// }
// set age (val) {
// if (val < 7 && val > 4) {
// _age = val
// }
// }
// }
// let dog = new Animal('dog')
// console.log(dog.age)
// dog.age = 5
// console.log(dog.age)
// console.log(dog._age) // undefined
// ========== static methods ==========
// es5实现方式
// let Animal = function (type) {
// this.type = type
// }
// Animal.prototype.eat = function () {
// Animal.walk() // 静态方法需要使用class.xxx调用
// console.log('i am eating food')
// }
// Animal.walk = function () {
// console.log('i am walking')
// }
// let dog = new Animal('dog')
// dog.eat()
// es6实现方式 static
// class Animal {
// constructor (type) {
// this.type = type
// }
// eat () {
// Animal.walk()
// console.log('I am eating food')
// }
// static walk () {
// console.log('i am walking')
// }
// }
// let dog = new Animal('dog')
// dog.eat()
// ======= 继承 =======
// es5实现方式
let Animal = function (type) {
this.type = type
}
Animal.prototype.eat = function () {
Animal.walk() // 静态方法需要使用class.xxx调用
console.log('i am eating food')
}
Animal.walk = function () {
console.log('i am walking')
}
let Dog = function () {
// 初始化父类的构造函数
Animal.call(this, 'dog')
}
Dog.prototype = Animal.prototype
let dog = new Dog('dog')
dog.eat()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.