language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
1,177
3.390625
3
[]
no_license
// Click on the cookie. clicky = function(interval) { cookie = $("#bigCookie"); setInterval(function() {cookie.click(); }, interval) } // Click on the golden cookies. goldenClicky = function(interval) { setInterval(function() {$("#goldenCookie").click(); }, interval) } // Buy products prodAndUpgradeClicky = function(interval) { getSortedProductsList = function() { // Grab product prices products = []; $("#products").children().each(function(index,element) { $prod = $(element); price = parseInt($($prod.find(".price")[0]).text().replace(/\,/g,"")); products.push({product: $prod, price: price}); }); // Sort products by price return products.sort(function(a,b){return a.price-b.price}); } tryToBuyUpgrades = function() { $("#upgrades").children().each(function(index,element) { element.click(); }); } doWork = function() { tryToBuyUpgrades(); cheapestProduct = getSortedProductsList()[0].product.click(); } setInterval(doWork, interval); } // Do everything everythingClicky = function() { clicky(10); goldenClicky(500); prodAndUpgradeClicky(500); } everythingClicky();
C#
UTF-8
1,098
2.6875
3
[]
no_license
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DrunkiBoy { class Bar : GameObject { public bool choseBurgers, choseKebab, choseBottles, hasBought; public Bar(Vector2 pos, Texture2D tex, bool isActive) : base(pos, tex, isActive) { this.type = "bar"; } public override void Draw(SpriteBatch spriteBatch) { if(choseBurgers) spriteBatch.Draw(Textures.barWithoutBurgers, pos, srcRect, Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, drawLayer); else if (choseKebab) spriteBatch.Draw(Textures.barWithoutKebab, pos, srcRect, Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, drawLayer); else if (choseBottles) spriteBatch.Draw(Textures.barWithoutBottles, pos, srcRect, Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, drawLayer); else base.Draw(spriteBatch); } } }
Java
UTF-8
2,099
2.1875
2
[]
no_license
package com.example.demo.LoginSecurity; import com.example.demo.Dto.AccountDto; import com.example.demo.Entity.AccountEntity; import com.example.demo.Repository.AccountRepository; import com.example.demo.Sevice.AccountSevice; import com.example.demo.Sevice.RoleSevice; import com.example.demo.TransFrom.ConvertAccount; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Service public class UserDetailsServiceImpl implements UserDetailsService{ @Autowired AccountSevice accountSevice; @Autowired RoleSevice roleSevice; @Autowired AccountRepository accountRepository; @Autowired ConvertAccount convertAccount; @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { AccountDto accountDto = accountSevice.findbyEmail(email); if (accountDto == null) { throw new UsernameNotFoundException("User " + email + " was not found in the database"); } List<String> roles = accountDto.getListRole(); List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>(); if (roles != null) { for (String role:roles){ GrantedAuthority authority = new SimpleGrantedAuthority(role); grantList.add(authority); } } UserDetails userDetails = (UserDetails) new User(accountDto.getEmail(), // accountDto.getPwd(), grantList); System.out.println("user=="+userDetails); return userDetails; } }
Java
UTF-8
1,291
2.34375
2
[]
no_license
package com.tmh.entities; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @Table(name = "order_items") @Getter @Setter @NoArgsConstructor public class OrderItem { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToOne @JoinColumn(name = "order_id") private Order order; @ManyToOne @JoinColumn(name = "product_id") private Product product; @Column(name = "quantity") private int quantity; @Column(name = "deleted") private Integer isDeleted; @Column(name = "created_at") @CreationTimestamp private LocalDateTime createDateTime; @Column(name = "updated_at") @UpdateTimestamp private LocalDateTime updateDateTime; public String getDeletedString() { if (this.isDeleted == 0) { return "NOT DELETED"; } else { return "DELETED"; } } }
C#
UTF-8
1,800
3.3125
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.Linq; using HeadFirstCSharp9_1; namespace JimmyLinq { public class ComicAnalyzer { private static PriceRange CalculatePriceRange(Comic comic, IReadOnlyDictionary<int, decimal> prices) { if (prices[comic.Issue] < 100) return PriceRange.Cheap; else return PriceRange.Expensive; } public static IEnumerable<IGrouping<PriceRange, Comic>> GroupComicsByPrice( IEnumerable<Comic> comics, IReadOnlyDictionary<int, decimal> prices) { /* var grouped = from comic in comics orderby prices[comic.Issue] group comic by CalculatePriceRange(comic, prices) into priceGroup select priceGroup; */ var grouped = comics .OrderBy(comic => prices[comic.Issue]) .GroupBy(comic => CalculatePriceRange(comic, prices)); return grouped; } public static IEnumerable<string> GetReviews(IEnumerable<Comic> catalog, IEnumerable<Review> reviews) { /*var joined = from comic in catalog join review in reviews on comic.Issue equals review.Issue select $"{review.Critic} rated #{comic.Issue} '{comic.Name}' {review.Score:0.00}"; */ var joined = catalog.Join ( reviews, comic => comic.Issue, review => review.Issue, (comic, review) => $"{review.Critic} rated #{comic.Issue} '{comic.Name}' {review.Score:0.00}" ); return joined; } } }
Java
UTF-8
490
2.546875
3
[]
no_license
package ch.epfl.moocprog; public class Positionable { private ToricPosition positionne; public Positionable() { positionne = new ToricPosition(); } public Positionable(ToricPosition pos) { positionne = pos; } public ToricPosition getPosition() { return positionne; } protected final void setPosition(ToricPosition position) { positionne = position; } public String toString() { return ""+getPosition(); } }
Markdown
UTF-8
17,886
3.359375
3
[]
no_license
In Cardstack, a user's journey through a UI is reflected in the browser's URL and the data that is fetched at each segment. For example, when someone visits `http://localhost:4200/articles/ten-reasons-love-cardstack`, it has a direct effect on which visual components are used and the information sent in a GET request. But how are those URLs made? What determines the data to fetch? What should happen if there are nested routes? And what should the user see? In this section, we will cover the basics of Routing and how Cards handle their data. ## Routing features Since Cardstack's tools cover the full stack, the routing system offers some major benefits: - **Sharing:** Each Card defines the Routes that it supports, so Cards can be moved around and used in new projects. They bring their route functionality with them, and they continue to work inside any new context. - **Nesting:** Cards and their routes can be nested, like `/articles/my-article-title/authors` - **Data fetching:** The URL of a nested route is automatically transformed into the right API requests to make - **Data display:** Data retrieved becomes available as `content` in a Card's template - **Namespaced Query Parameters:** Query Parameters are namespaced by cards, so we don't need to worry about collisions if we are using someone else's Open Sourced Card or working on a massive project. For example, we could reuse "tag" as a query parameter throughout different Cards: `/articles/my-article-title/authors?articles[tag]=recent&authors[tag]=guest`. - **Flexibility:** Since routing belongs to individual Cards, a project's file structure is decoupled from its routing. Refactors and code sharing become easier. - **Speed:** relationship serialization, traversal, and filtering are done server-side. In one request, your Cards get the data they need. - **Low overhead:** we get to skip a bunch of steps when creating a new Route, compared to the typical web developer experience. For example, a typical Ember app would require that you write `model` hooks, create new Route files, and modify the Router. None of that is needed in Cardstack. ## Default routes By default, each Card has its own route that is auto-generated based on the Card's name. For example, if you have a Card named `contest-entry`, you could view an individual entry at `localhost:4200/contest-entries/1`, where `1` is the id of an entry. This work is done by the Cardstack Router. A default Router in a new project looks like this: ```js module.exports = [{ path: '/:type/:id', query: { filter: { type: { exact: ':type' }, id: { exact: ':id' } } }, }]; ``` What this means is, the Router will create a Route for each Card, and use its name to form the URL. This file can be customized to create custom URLs for each Card, show filtered results, and show a specific "home page" card. ## Types of Routing Cards A Card can define a series of routes that it supports, and that the routes can cascade, such that if a Card's router routes a path to a particular Card, that Card can then in turn route to another Card. The job of the Router is to determine which Cards live at which Route. We use the term "routing-card" to describe a Card that has a router. The "application-card" is a top level routing Card. ### Application Cards Each Cardstack application has an "application card" that is the top level routing card for the Cardstack application. Any card can serve as the application card in the Cardstack application. If no application card is specified, the hub uses a default, "Getting Started", application card. Additionally, if the application card does not specify a router, the hub provides a default router (`@cardstack/routing/cardstack/default-router`) that includes a static mapping route and a vanity URL of "/" to the application card itself. #### Creating an application card Cardstack applications can specify their application cards in the `plugin-configs/@cardstack-hub` configuration. Note that the default application card leverages the default router. Consider the following example for Acme Corp's HR application (Note that we use the term "Cardstack Application", when in fact a Cardstack application is really just another card. Consider "Cardstack Application" as the top level npm module in your project): ```js // <cardstack HR application folder>/cardstack/data-sources/default.js factory.addResource('plugin-configs', '@cardstack/hub') .withAttributes({ 'plugin-config': { // this is the application card for the the Acme Corp's HR application that contains the top level router 'application-card': { type: '@acme-corp/applications', id: 'hr-application' } } }) .withRelated('default-data-source', { data: { type: 'data-sources', id: 'default' } }); ``` In order to specify the name of the router to use for the application card, the Cardstack developer can specify an attribute on the application card's content-type `router`. This is set to an array of routes for the card. ```js // <cardstack HR application folder>/cardstack/static-models.js factory.addResource('content-types', 'acme-applications') .withAttributes({ router: [ { // Note that because this query does not use `:id` nor `:friendly_id`, we would never // use this route as a canonical path for a card in the API response. path: '/latest-article', query: { filter: { type: { exact: 'articles' } }, sort: '-publish-date' } },{ // This is an example of a using a "slug" or human friendly ID in the URL to identify a card // as opposed to the actual card's ID (which may not be easy for a human to remember or type). path: '/good-reads/:friendly_id', query: { filter: { type: { exact: 'articles' }, slug: { exact: ':friendly_id' } } } },{ // This is an example of using a query param in the path to make a routing decision. // Note that because this query does not use `:id` nor `:friendly_id`, we would never // use this route as a canonical path for a card in the API response. path: '/most-popular?since=:date', query: { filter: { type: { exact: 'articles' }, 'publish-date': { range: { gt: ':date' } } }, sort: '-popularity' } },{ // This is an example of a static mapping route, where the type and ID provided in the URL // map directly to the type and ID of the card to route to. path: '/:type/:id', query: { filter: { type: { exact: ':type' }, id: { exact: ':id' } } } },{ // This is an example of a vanity URL, where you have a URL that points to a particular card. // In this example we use the data of the "routing card" to fashion the URL, which happens // to be the routing card itself. The ":card:field-name" convention is used to refer to fields // on the routing card. path: '/', query: { filter: { type: { exact: ':card:type' }, id: { exact: ':card:id' } } } },{ // We can use `additionalParams` to pass additional properties to the card's component // that are unique to the route. In this case we want to render the same card as in '/' // but pass a parameter that will inform the card to scroll to the #section1 anchor in // the '/section-1' route. Note that you can include replacement tags in the `additionalParams` // properties. path: '/section-1', query: { filter: { type: { exact: ':card:type' }, id: { exact: ':card:id' } } }, additionalParams: { scrollTo: '#section1' } },{ path: '/section-2', query: { filter: { type: { exact: ':card:type' }, id: { exact: ':card:id' } } }, additionalParams: { scrollTo: '#section2' } } ]}); factory.addResource('acme-applications', 'hr-application'); // open read grant allows everyone to see the application card's fields when routed directly to it factory.addResource('grants', 'acme-applications-grant') .withAttributes({ 'may-read-fields': true, 'may-read-resource': true }) .withRelated('who', [{ type: 'groups', id: 'everyone' }]) .withRelated('types', [{ type: 'content-types', id: 'acme-applications' }]); ``` ## How Routing works behind-the-scenes The router is leveraged when the client makes a request to get a `space`. A `space` is retrieved by URL. So if the client wants to enter the route `/latest-article`, it makes a request to the API: `GET https://<hub api domain>/api/spaces%2Flatest-article`. The API then uses the router above to match the path to a particular route whose query will be used to find the card to display to the user. In order to accommodate the ability to match paths to routes, on startup, the hub assembles a router map that represents all the possible routes in the system based on all the cards that have routes associated with them. The hub performs this by beginning at the application card, and recursively descending through all the possible cards that the application card routes to, and then descending through all those cards, and so on. As the hub discovers all the possible routes in the system it compiles these routes into the router map. The hub then arranges the routes in the router map such that the most specific routes are matched before the most general routes. ## Error Cards When the router is unable to find a card for the provided path, it will return an error card. A system error card is provided. ### Creating an Error Card Cardstack application developers can provide their own custom error cards by creating a content-type that uses an `*-errors` suffix of the routing card's content type. So if the application card's content-type is `acme-applications`, a custom error card for this application card would be the content type of `acme-applications-errors`, and you should have at least one instance of this type with the ID of `not-found` that is returned when the router cannot find a card for the path provided (this can be established in the `static-model.js` feature of your Cardstack application). You can then provide a custom template for this card as an ember addon in the same way you provide for any card. You should also set a world read grant for this content type, so that errors fields are not inadvertently hidden for API clients. When a routing card triggers an error because a card cannot be found for the path, the error will bubble up through all the routing cards that where involved with the routing of the path. The custom error card that is closest to the router that was unable to resolve the path will be the error card that is returned from the server. ```js // continued from <cardstack HR application folder>/cardstack/static-models.js above... factory.addResource('content-types', 'acme-applications-errors'); // open read grant allows everyone to see the error card factory.addResource('grants', 'acme-applications-errors-grant') .withAttributes({ 'may-read-fields': true, 'may-read-resource': true }) .withRelated('who', [{ type: 'groups', id: 'everyone' }]) .withRelated('types', [{ type: 'content-types', id: 'acme-applications-errors' }]); // need to have a "not-found" instance of the error card factory.addResource('acme-applications-errors', 'not-found'); ``` ## Canonical Paths for Cards The mechanism responsible for generating json:api documents for cards, `DocumentContext`, works such that if `attributes.route-stack`, appears on the document presented to it, `DocumentContext` will add `links.self` to all the resources in the json:api document that it constructs (this is the case for the `spaces` content type). The route stack is an array of all the cards (as `type/id`) that the router routed through in order to reach a particular card. The `links.self` links are the canonical paths for the resources based on the `route-stack`. The way that we derive a canonical path for a resource is to introspect each routing card in the route stack, from the highest level routing card to the deepest level routing card and identify a route whose query will result in the card whose canonical path we are resolving (in the following order): 1. A query that matches the specified resource specifically. This is a vanity URL to the resource, and has the highest precedence when deriving a canonical path to the resource. 2. A query that can match the specified resource using a `:friendly_id` in the router. The `:friendly_id` is a special replacement tag in the router that is the developer's signal to the hub that the field should be considered as a identifier for the content. This is what we have previously called the "routing field". This has the second highest precedence when deriving a canonical path to the resource. 3. A query that can match the specified resource where the `type` field in the query is equal to the content type of the card, and the id field is derived from the path. 4. A static mapping route, where the type and ID are specified as replacement tags in the path, and are used in the query to find a specific resource by type and ID. Note that the hub will take into account any `:card:field-name` replacement tags in the queries and use the cards in the route-stack to resolve these tags before performing the matching above. The resulting `links.self` property is used by the ember client in order to transition to a particular card's canonical path. Note that it is possible for a router to be fashioned that results in not all cards being routable. In such cases, the `{{cardstack-url}}` helper and various tools that depend on getting the route for a card will be unable to operate for non-routable cards. ## Params When the `spaces` document is rendered for a particular route, it will supply the component for the card that is being routed to a bucket of properties in a `params` field. This will include: * any replacement tags we added in the route's path (e.g. dynamic segments) * any query parameters that we specified in the routes path * the path segment for the route * `additionalParams` that have been defined for the route. `additionalParams` may include `:card:field-name` replacement tags if we wish to pass the routing card's data into the card we are routing to. So for example, the following route, which is mounted on the `acme-applications` application card content-type, whose application card instance happens to have a `name` attribute set to "HR Application": ```js { path: '/:foo/most-popular?since=:date', query: { filter: { type: { exact: 'articles' }, 'publish-date': { range: { gt: ':date' } } }, sort: '-popularity' }, additionalParams: { staticValue: 'i am static', routingCardData: ':card:name' } } ``` When matched with the path: `https://acme-corp.com/hassan/most-popular?acme-applications[since]=2018-01-01` will result in the following `params` object being passed to the `articles` card's component: ```js { path: '/hassan/most-popular?acme-applications[since]=2018-01-01', foo: 'hassan', since: '2018-01-01', staticValue: 'i am static', routingCardData: 'HR Application' } ``` ### Query Params A convenience notation is also supported for declaring query parameters consumed by a particular card. If a route omits the `query` property, the router will return the routing card as primary card for the space. In such a manner, you can use the router of a card to simply declare the query parameters that a card can consume. Consider the example where the application card uses the following router: ```js // <cardstack application folder>/cardstack/static-models.js factory.addResource('content-types', 'acme-applications') .withAttributes({ router: [ { path: '/:type/:id', query: { filter: { type: { exact: ':type' }, id: { exact: ':id' } } } }] }); ``` Then you additionally have a content-type `blogs` that uses a query parameter `since` to constrain the articles displayed in a blog instance to only the articles that has been published after the `since` query parameter. To allow the `since` query parameter to be passed to your `blogs` card component, you can specify the following in the `cardstack/static-models.js` to your `blogs` card npm module. ```js // <@acme-corp/acme-blog card module folder>/cardstack/static-models.js for the `blogs` content-type // that the application consumes. factory.addResource('content-types', 'blogs') .withAttributes({ router: [ { path: '?since=:since' }] }); ``` In this example, the URL for the blog, which includes the name-spaced query parameter, looks like this: ``` https://<application domain>/blogs/chris?blogs[since]=2018-01-01 ``` Note that the namespace for the query parameter `since` is `blogs` since the `blogs` content-type's router is the router that declares the query param in the `{ path: '?since=:since' }` route above. #### Changing query params with actions The card's components can also modify the query params in the browser's URL location, i.e. browser history `pushState()`. Each card's component is decorated with a `setParams(name, value)` action that accepts a query param name and its value. An `action` is a function that is available to use in a Card's template. The card can then use the `setParam` action to set query params that have been declared by the router for the card. The namespacing will automatically be added to the query param that is set, so that the card does not need to worry about handling the query param namespacing.
Java
UTF-8
1,615
2.109375
2
[ "Apache-2.0" ]
permissive
/** * Copyright [2016] [Christian Loehnert] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.ks.strudel.route.handler.main; import de.ks.strudel.route.handler.AsyncTracker; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import javax.inject.Inject; /** * Executes before/after filters */ public class BeforeAfterMainHandler implements HttpHandler { protected final BeforeHandler before; protected final MainRoutingHandler main; protected final AfterHandler after; protected final AsyncTracker asyncTracker; @Inject public BeforeAfterMainHandler(BeforeHandler before, MainRoutingHandler main, AfterHandler after, AsyncTracker asyncTracker) { this.before = before; this.main = main; this.after = after; this.asyncTracker = asyncTracker; } @Override public void handleRequest(HttpServerExchange exchange) throws Exception { before.handleRequest(exchange); if (!exchange.isComplete()) { main.handleRequest(exchange); if (!asyncTracker.isAsyncRoute()) { after.handleRequest(exchange); } } } }
Python
UTF-8
159
3.140625
3
[]
no_license
def write_solution_into_file(sentence, path_to_file): out_to_file = open(path_to_file, "a") out_to_file.write(sentence + "\n") out_to_file.close()
C++
UTF-8
3,535
2.625
3
[]
no_license
#ifndef __LCD_H__ #define __LCD_H__ #include <vector> #include "types.hpp" #include "i2c.hpp" #include "delay.hpp" class LCD : private I2C, private Delay { public: LCD(const std::string& i2c_bus, uint8_t i2c_addr) : I2C(i2c_bus, i2c_addr), Delay() { clearVariables(); }; enum scroll_t { SCROLL_CURS_LEFT = 0, SCROLL_CURS_RIGHT, SCROLL_TEXT_LEFT, SCROLL_TEXT_RIGHT }; enum textEntry_t { ENTRY_LEFTTORIGHT = 0, ENTRY_RIGHTTOLEFT, ENTRY_AUTOSCROLL, ENTRY_NOAUTOSCROLL }; enum display_t { DISPLAY_ON = 0, DISPLAY_OFF, CURSOR_SHOW, CURSOR_HIDE, CURSOR_BLINK, CURSOR_NOBLINK }; return_t display(display_t selection); return_t scroll(scroll_t selection, uint32_t moveNb, uint32_t moveDelayMs); return_t textEntry(textEntry_t selection); void setCustomSymbol(uint8_t, uint8_t*); void setCursor(uint8_t, uint8_t); void print(const std::string& str); int clear(void); int home(void); void setDispSize(uint8_t colsNb, uint8_t rowsNb) { columns = colsNb; rows = rowsNb; } protected: void init(); bool isDispSizeInitialized(void) { if( columns != 0 && rows != 0) return true; return false; } private: enum instr_t { INSTR_CLR_DISPLAY = 0x01, INST_RET_HOME = 0x02, INSTR_ENTRYMODESET = 0x04, INSTR_DISPCONTROL = 0x08, INSTR_CURSDISPSHIFT = 0x10, INSTR_FUNCSET = 0x20, INSTR_SETCGRAMADDR = 0x40, INSTR_SETDDRAMADDR = 0x80 }; enum instrCtrl_t { INSTR_CTRL_SINGLE_CMD = 0x00, INSTR_CTRL_MANY_CMDS = 0x80, INSTR_CTRL_RS_INSTR_REG = 0x00, INSTR_CTRL_RS_DATA_REG = 0x40 }; enum funcSet_t { FUNC_SET_5x8DOTS = 0x00, FUNC_SET_5x10DOTS = 0x04, FUNC_SET_1LINE = 0x00, FUNC_SET_2LINES = 0x08, FUNC_SET_4BIT_MODE = 0x00, FUNC_SET_8BIT_MODE = 0x10 }; enum dispCtrl_t { DISP_CTRL_BLINK_OFF = 0x00, DISP_CTRL_BLINK_ON = 0x01, DISP_CTRL_CURS_OFF = 0x00, DISP_CTRL_CURS_ON = 0x02, DISP_CTRL_DISP_OFF = 0x00, DISP_CTRL_DISP_ON = 0x04 }; enum entryModeSet_t { ENTRY_MODE_DISP_NO_SHIFT = 0x00, ENTRY_MODE_DISP_SHIFT = 0x01, ENTRY_MODE_CURS_POS_DECR = 0x00, ENTRY_MODE_CURS_POS_INCR = 0x02 }; enum cursDispShift_t { CURS_DISP_MVLEFT = 0x00, CURS_DISP_MVRIGHT = 0x04, CURS_DISP_MVCURS = 0x00, CURS_DISP_MVDISP = 0x08 }; enum cursLine_t { CURS_LINE_1 = 0x80, CURS_LINE_2 = 0xC0 }; uint8_t funcSetState; uint8_t dispCtrlStatus; uint8_t entryModeSetState; uint8_t columns; uint8_t rows; void clearVariables(void) { funcSetState = 0; dispCtrlStatus = 0; entryModeSetState = 0; columns = 0; rows = 0; } return_t setFunctionSet(uint8_t set); return_t setDisplayCtrl(uint8_t set); return_t setEntryModeSet(uint8_t set); return_t setCursDispShift(uint8_t set); return_t getDisplaySet(display_t selection, uint8_t& set); return_t getScrollSet(scroll_t selection, uint8_t& set); return_t getTextEntrySet(textEntry_t selection, uint8_t& set); size_t writeData(std::vector<uint8_t>& data); void writeInstr(uint8_t); void send(uint8_t* data, uint8_t size) const; }; #endif
C#
UTF-8
4,052
3.734375
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Reflection; namespace ConsoleApplication2 { // Start by declaring a delegate that looks exactly like the library method you want to call, but with TRuntimeType in place of the actual type public delegate void LibraryDelegate<TRuntimeType>(TRuntimeType param, Int32 num, String aStr); // Declare an "adapter" delegate that uses "Object" in place of TRuntimeType for every relevant parameter public delegate void AdapterDelegate(Object param, Int32 num, String aStr); public static class AdapterDelegateHelper { private class Adapter<TRuntimeType> { private readonly LibraryDelegate<TRuntimeType> libDelegate; public Adapter(Object LibraryInstance, String MethodName) { Type libraryType = LibraryInstance.GetType(); Type[] methodParameters = typeof(LibraryDelegate<TRuntimeType>).GetMethod("Invoke").GetParameters().Select(p => p.ParameterType).ToArray(); MethodInfo libMethod = libraryType.GetMethod(MethodName, methodParameters); libDelegate = (LibraryDelegate<TRuntimeType>) Delegate.CreateDelegate(typeof(LibraryDelegate<TRuntimeType>), LibraryInstance, libMethod); } // Method that pricecly matches the adapter delegate public void adapter(Object param, Int32 num, String aStr) { // Convert all TRuntimeType parameters. // This is a true conversion! TRuntimeType r_param = (TRuntimeType)param; // Call the library delegate. libDelegate(r_param, num, aStr); } } public static AdapterDelegate MakeAdapter(Object LibraryInstance, String MethodName, Type runtimeType) { Type genericType = typeof(Adapter<>); Type concreteType = genericType.MakeGenericType(new Type[] { runtimeType }); Object obj = Activator.CreateInstance(concreteType, LibraryInstance, MethodName); return (AdapterDelegate)Delegate.CreateDelegate(typeof(AdapterDelegate), obj, concreteType.GetMethod("adapter")); } } // This class emulates a runtime-identified type; I'll only use it through reflection class LibraryClassThatIOnlyKnowAboutAtRuntime { // Define a number of oberloaded methods to prove proper overload selection public void DoSomething(String param, Int32 num, String aStr) { Console.WriteLine("This is the DoSomething overload that takes String as a parameter"); Console.WriteLine("param={0}, num={1}, aStr={2}", param, num, aStr); } public void DoSomething(Int32 param, Int32 num, String aStr) { Console.WriteLine("This is the DoSomething overload that takes Integer as a parameter"); Console.WriteLine("param={0}, num={1}, aStr={2}", param, num, aStr); } // This would be the bad delegate to avoid! public void DoSomething(Object param, Int32 num, String aStr) { throw new Exception("Do not call this method!"); } } class Program { static void Main(string[] args) { Type castToType = typeof(string); Type libraryTypeToCall = typeof(LibraryClassThatIOnlyKnowAboutAtRuntime); Object obj = Activator.CreateInstance(libraryTypeToCall); AdapterDelegate ad1 = AdapterDelegateHelper.MakeAdapter(obj, "DoSomething", castToType); ad1("param", 7, "aStr"); Console.ReadKey(); } } }
C++
UTF-8
4,942
3.328125
3
[]
no_license
// BirthdayManager.h // Lab 4: partydb // CIS 22C F2016: Matthew Tso #include "BirthdayManager.h" // Static members need to be instantiated at startup. BinarySearchTree<Person<BY_NAME>> BirthdayManager::tree_by_name; BinarySearchTree<Person<BY_BIRTHDAY>> BirthdayManager::tree_by_bday; ofstream BirthdayManager::stream_postorder; ofstream BirthdayManager::stream_breadthfirst; void addToNameSortedTree(Person<BY_BIRTHDAY>& person_bday) { string name = person_bday.getName().getValue(); Birthdate birthday = person_bday.getBirthday(); BirthdayManager::getNameTree().insert(Person<BY_NAME>(name, birthday)); } BinarySearchTree<Person<BY_NAME>>& BirthdayManager::getNameTree() { return tree_by_name; } BinarySearchTree<Person<BY_BIRTHDAY>>& BirthdayManager::getBdayTree() { return tree_by_bday; } ofstream& BirthdayManager::getPostorderStream() { return stream_postorder; } ofstream& BirthdayManager::getBreadthFirstStream() { return stream_breadthfirst; } int BirthdayManager::importDataFrom(const string& filepath) { ifstream input_file; string line; input_file.open(filepath); // Read input data line-by-line Person<BY_BIRTHDAY> person; while (getline(input_file, line)) { person = Person<BY_BIRTHDAY>(line); if (person.getName().getValue().length() < 1) { continue; } tree_by_bday.insert(person); } input_file.close(); // Since our BST is not self-balancing, // and we have over 20000+ data entries, // and the entries are ordered alphabetically by name... // We can't just insert the person object that is created // by each getline() above. // // So, // the tree sorted by name needs to be populated // with data from the tree sorted by birthday // using in-order traversal, which scrambles the name order; // otherwise, it will take a long time.... tree_by_bday.traverseInorder(addToNameSortedTree); return tree_by_name.getNodeCount(); } void BirthdayManager::outputPostorderTo(const string& filepath) { stream_postorder.open(filepath); tree_by_bday.traversePostorder(outputPostorder<BY_BIRTHDAY>); stream_postorder.close(); } void BirthdayManager::outputBreadthFirstTo(const string& filepath) { stream_breadthfirst.open(filepath); tree_by_name.traverseBreadth(outputBreadthFirst<BY_NAME>); stream_breadthfirst.close(); } bool BirthdayManager::search(const string& name, Person<BY_NAME>& result) { Person<BY_NAME> target(name, Birthdate()) ; try { result = tree_by_name.getData(target); return true; } catch (BinarySearchTree<Person<BY_NAME>>::NotFoundException error) { return false; } } bool BirthdayManager::update(const string& name, const Birthdate& birthday) { Person<BY_NAME> found_person_by_name; Person<BY_BIRTHDAY> found_person_by_birthday; try { // First search name tree for name found_person_by_name = tree_by_name.getData(Person<BY_NAME>(name, Birthdate())); // Then search birthday tree using the same name // and the birthday value returned from the name tree search found_person_by_birthday = tree_by_bday.getData(Person<BY_BIRTHDAY>(name, found_person_by_name.getBirthday())); } catch (BinarySearchTree<Person<BY_BIRTHDAY>>::NotFoundException) { return false; } catch (BinarySearchTree<Person<BY_NAME>>::NotFoundException) { return false; } bool name_tree_removal_success = false; bool bday_tree_removal_success = false; name_tree_removal_success = tree_by_name.remove(found_person_by_name); if (!name_tree_removal_success) { return false; } bday_tree_removal_success = tree_by_bday.remove(found_person_by_birthday); if (!bday_tree_removal_success) { // If the bday-tree removal wasn't successful, // Re-insert the removed entry into the name tree tree_by_name.insert(found_person_by_name); return false; } Person<BY_NAME> updated_name_person(name, birthday); Person<BY_BIRTHDAY> updated_bday_person(name, birthday); tree_by_name.insert(updated_name_person); tree_by_bday.insert(updated_bday_person); return true; } bool BirthdayManager::remove(const string& name) { Person<BY_NAME> found_person_by_name = tree_by_name.getData(Person<BY_NAME>(name, Birthdate())); bool name_tree_removal_success = false; bool bday_tree_removal_success = false; name_tree_removal_success = tree_by_name.remove(found_person_by_name); if (!name_tree_removal_success) { return false; } bday_tree_removal_success = tree_by_bday.remove(Person<BY_BIRTHDAY>(name, found_person_by_name.getBirthday())); if (!bday_tree_removal_success) { // If the bday-tree removal wasn't successful, // Re-insert the removed entry into the name tree tree_by_name.insert(found_person_by_name); return false; } else { return true; } } bool BirthdayManager::insert(const string& raw_input) { try { Person<BY_BIRTHDAY> person_by_birthday(raw_input); Person<BY_NAME> person_by_name(raw_input); tree_by_bday.insert(person_by_birthday); tree_by_name.insert(person_by_name); return true; } catch (...) { return false; } }
Python
UTF-8
178
3.796875
4
[]
no_license
#!/usr/bin/python3 def hello(): print("Hello, world") def sqrt(n): return n ** .5 hello() m = sqrt(1234) n = sqrt(2) print("m is {0:.3f} n is {1:.3f}".format(m, n))
C
UTF-8
10,246
2.59375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <ctype.h> #include <arpa/inet.h> #include <fcntl.h> #include <pthread.h> #include "queueList.h" #include "serverUtils.h" #include <signal.h> #define BUFFSIZE 256 #define STATICDIRSIZE 1024 #define INT_DIGITS 19 #define MAX_CON 20 ////////////////////////////////////////////Giving credit to/////////////////////////////////////////////// //stackoverflow.com/questions/4915538/recursing-directories-in-c?rq=1 // //How to recurse through directories and print all of their contents //========================================================================================================= //www.opensource.apple.com/source/groff/groff-10/groff/libgroof/itoa.c // //itoa.c source code //========================================================================================================== //pubs.opengroup.org/onlinepubs/009695399/functions/pthread_sigmask.html // //Using signals with multithreaded processes to kill the program properly with Ctrl+C // //stackoverflow.com/questions/19509420/how-can-i-display-the-client-ip-address-on-the-server-side // //How to diplay the client ip address ///////////////////////////////////////////////////////////////////////////////////////////////////////////// Global_Utilities global_utilities; int main(int argc,char* argv[]){ char clientName[INET_ADDRSTRLEN]; int newsock,i,rc,server_socket; long sz = sysconf(_SC_PAGESIZE); //long sz = 1; long ip; struct sockaddr_in server, client; struct sockaddr *serverptr = (struct sockaddr*) &server; struct sockaddr *clientptr = (struct sockaddr*) &client; struct hostent *rem; socklen_t clientlen; pthread_t producer; pthread_t sig_thr_id; ProducerArgs* serverArgs; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////ARGUMENT HANDLING//////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// argumentHandling(argc,argv,&(global_utilities.port),&(global_utilities.queue_size),&(global_utilities.thread_pool_size)); printf("MAIN THREAD: - Server's paramenters are:\n\tport: %d\n\tthread_pool_size: %d\n\tqueue_size: %d\n\n",global_utilities.port,global_utilities.thread_pool_size,global_utilities.queue_size); global_utilities.blocksize = sz; //BLOCKSIZE for file tranfers global_utilities.active_workers = 0; //Number of non-detached worker threads global_utilities.active_clients = 0; //Number of active clients currently global_utilities.accepting = 0; //Server accepting clients ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////CREATING A THREAD TO CATCH TERMINATION/////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// sigemptyset(&(global_utilities.signal_mask)); sigaddset(&(global_utilities.signal_mask), SIGINT); sigaddset(&(global_utilities.signal_mask), SIGTERM); rc = pthread_sigmask(SIG_BLOCK, &(global_utilities.signal_mask), NULL); if(rc != 0){ perror("MAIN THREAD - Signal mask installation"); exit(1); } rc = pthread_create(&sig_thr_id, NULL, signal_thread, NULL); if(rc != 0){ perror("MAIN THREAD - pthread_create for signals"); exit(1); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////CREATE MAIN QUEUE AND QUEUE OF CLIENT-ITEMS PAIRS//////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// initQueue(&(global_utilities.queueOfItems),global_utilities.queue_size); initQueueP(&(global_utilities.queueOfPairs)); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////ALLOCATE SPACE FOR WORKER THREAD VARIABLES//////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// printf("MAIN THREAD - Now we will allocate %d pointers for worker threads!\n",(global_utilities.thread_pool_size)); global_utilities.worker_threads = NULL; global_utilities.worker_threads = malloc(sizeof(pthread_t)*(global_utilities.thread_pool_size)); printf("MAIN THREAD - Allocated pointers for worker threads!\n"); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////INITIALISE SHARED MUTEXES AND CONDITION VARIABLES///////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// pthread_mutex_init(&(global_utilities.queue_mtx), NULL); //Queue access Mutex pthread_cond_init(&(global_utilities.cond_nonempty), NULL); //Condition queue == non empty pthread_cond_init(&(global_utilities.cond_nonfull), NULL); //Condition queue == non full pthread_mutex_init(&(global_utilities.readdir_mtx), NULL); //Readdir access Mutex pthread_mutex_init(&(global_utilities.malloc_mtx), NULL); //Malloc access Mutex pthread_mutex_init(&(global_utilities.free_mtx), NULL); //Free access Mutex //pthread_cond_init(&(global_utilities.cond_delivered), NULL); //Delivered an item condition (wakes a producer) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////REQUIRED NETWORKING CODE////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// global_utilities.server_socket = 0; if((server_socket = socket(PF_INET, SOCK_STREAM, 0)) < 0){ //Create a TCP Socket printf("MAIN THREAD - TCP socket creation failure! Destroying resources!\n"); perror("socket"); destroyQueue(&(global_utilities.queueOfItems)); destroyQueueP(&(global_utilities.queueOfPairs)); destroyWorkerResources(); exit(1); } server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(global_utilities.port); server.sin_family = AF_INET; //internet addr family if(bind(server_socket,serverptr,sizeof(server)) < 0){ printf("MAIN THREAD - Failed to BIND port: %d\n",global_utilities.port); perror("bind"); destroyQueue(&(global_utilities.queueOfItems)); destroyQueueP(&(global_utilities.queueOfPairs)); destroyWorkerResources(); //close(global_utilities.server_socket); exit(1); } printf("Listening for socket connection from client...\n"); if(listen(server_socket,MAX_CON) < 0){ //listen for connections with Qsize == MAX_CON printf("MAIN THREAD - Failed to LISTEN on port: %d\n",global_utilities.port); perror("listen"); close(server_socket); destroyQueue(&(global_utilities.queueOfItems)); destroyQueueP(&(global_utilities.queueOfPairs)); destroyWorkerResources(); exit(1); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////CREATE THE WORKER THREADS!///////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// for(i=0; i<(global_utilities.thread_pool_size); i++) pthread_create(&(global_utilities.worker_threads[i]), 0, Consumer, NULL); //GO MY WORKER THREADS! global_utilities.active_workers = global_utilities.thread_pool_size; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////BEGIN ACCEPTING CLIENTS///////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// global_utilities.accepting = 1; global_utilities.server_socket = server_socket; while(1){ if(global_utilities.accepting == 1){ if((newsock = accept(server_socket,clientptr,&clientlen)) < 0){ //Accept connection,ignore client address printf("MAIN THREAD - Accept failed! Server socket: |%d| and client socket: |%d|\n",global_utilities.server_socket,newsock); printf("accept - %s\n",strerror(errno)); close(newsock); } else{ //ip = ntohl(clientptr->sin_addr.s_addr); global_utilities.active_clients++; if(inet_ntop(AF_INET,&(client.sin_addr),clientName,sizeof(clientName)) == NULL) //Extract the IP printf("MAIN THREAD: - Unable to get IP address of new client!\n"); printf("MAIN THREAD: - Accepted connection! New client with IP:|%s| on socket:|%d|\n",clientName,newsock); if(global_utilities.accepting == 1){ //To catch SIGINT right after accept check again in here pthread_mutex_lock(&(global_utilities.malloc_mtx)); serverArgs = malloc(sizeof(ProducerArgs)); //Allocate the arguments of a new producer serverArgs->client_socket = newsock; serverArgs->server_socket = global_utilities.server_socket; pthread_create(&producer, 0, ServClCommunication, (void*)(serverArgs)); //Create a new producer } else{ printf("MAIN THREAD - Unfortunately I won't be accepting any more clients!\n"); if(write_all(newsock, "EXIT", 5) == -1){ //Tell client to exit printf("MAIN THREAD: - Telling client to leave: %s\n",strerror(errno)); } close(newsock); global_utilities.active_clients--; } } } } return 0; }
C
UTF-8
3,389
3
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #define N 5000 #define segments 10 void swap (int *x, int *y) { int aux; aux = *x; *x = *y; *y = aux; } void QuickSort(int a[], int l, int r) { int i,j; if (l>=r) return; i = l+1; //razvrstavanje elemenata s obzirom na stozer j = r; while ((i<=j) && (i<=r) && (j>l)) { while ((a[i] <= a[l]) && (i<=r)) i++; while((a[j] >= a[l]) && (j>l)) j--; if (i<j) swap(&a[i], &a[j]); } if (i>r) { // stozer je najveci u polju swap(&a[r], &a[l]); QuickSort(a, l, r-1); } else if (j<=l) { // stozer je najmanji u polju QuickSort(a, l+1, r); } else { //stozer je negdje u sredini swap(&a[j], &a[l]); QuickSort(a, l, j-1); QuickSort(a, j+1, r); } } void merge (FILE *pomocni, FILE *output, int puta) { int i=0, j=0, broj, jedan, dva; FILE *aux; aux=fopen("aux.txt", "w+"); fscanf(pomocni, "%d", &jedan); fscanf(output, "%d", &dva); while (i<(N/segments) && j<(N/segments*puta)) { if (jedan<=dva) { fprintf(aux, "%d\n", jedan); fscanf(pomocni, "%d", &jedan); i++; } else { fprintf(aux, "%d\n", dva); fscanf(output, "%d", &dva); j++; } } if (i<(N/segments)) fprintf(aux, "%d\n", jedan); if (j<(N/segments*puta)) fprintf(aux, "%d\n", dva); while (i<(N/segments)) { fscanf(pomocni, "%d", &broj); fprintf(aux, "%d\n", broj); i++; } while (j<(N/segments*puta)) { fscanf(output, "%d", &broj); fprintf(aux, "%d\n", broj); j++; } // aux pretacemo u output fclose(aux); aux=fopen("aux.txt", "r+"); // rewind valjda ne radi kad je u w mode-u fclose(output); output=fopen("output.txt", "w+"); // reset outputa for (i=0; i<(N/segments*(puta+1)); i++) { fscanf(aux, "%d", &broj); fprintf(output, "%d\n", broj); } fclose(output); fclose(aux); remove("aux.txt"); } int main (void) { char ime[20]; int i,j, broj, niz[N/segments]; FILE *pocetni, *pomocni, *output; // 1) generiranje pocetnog file-a pocetni=fopen("pocetni.txt","w"); for (i=0; i < N; i++) { fprintf(pocetni, "%d\n", rand()); } fclose(pocetni); // 2) cijepanje pocetnog file-a pocetni=fopen("pocetni.txt","r"); for(j=0; j<segments; j++) { sprintf(ime, "%d.txt", j+1); pomocni = fopen(ime, "w"); for(i=j*(N/segments); i<(j+1)*(N/segments); i++) { fscanf(pocetni, "%d", &broj); fprintf(pomocni, "%d\n", broj); } fclose(pomocni); //ucitavanje male datoteke u gl mem pomocni = fopen(ime, "r+"); for (i=0; i<(N/segments); i++) { fscanf(pomocni, "%d", &broj); niz[i]=broj; } // 3) quicksort male datoteke, tj. malog niza QuickSort(niz, 0, (N/segments)-1); rewind(pomocni); //ponovno ispisivanje male datoteke na disk for (i=0; i<(N/segments); i++) { fprintf(pomocni, "%d\n", niz[i]); } fclose(pomocni); } // kreiranje output file-a (sigurno ima jedna mala datoteka) output=fopen("output.txt","w"); pomocni=fopen("1.txt", "r"); for(i=0; i<(N/segments); i++) { //while !feof ne radi jer ima \n na kraju svakog filea fscanf(pomocni, "%d", &broj); fprintf(output, "%d\n", broj); } fclose(output); fclose(pomocni); remove("1.txt"); // 4) merge-anje s preostalim datotekama (ako ih ima :)) for(j=1; j<segments; j++) { output = fopen("output.txt","r+"); sprintf(ime, "%d.txt", j+1); pomocni = fopen(ime, "r+"); merge(pomocni, output, j); fclose(pomocni); remove(ime); } fclose(pocetni); remove("pocetni.txt"); return 0; }
C++
UTF-8
915
4.1875
4
[]
no_license
/* CPP program to demonstrate function overriding in inheritance. */ #include<bits/stdc++.h> using namespace std; class M{ // BASE Class protected: string m; public: M(){ m = "Base"; } void display(){ cout<<m<<endl; } }; class N: public M{ // Derived class. "string m" and void display() from base class is inherited. protected: string n; public: N(){ n = "Derived"; } void display(){ // This has the same skeleton as that of the display() function in base class. // This will override the base class' function cout<<n<<endl; /* To call the display() function of base class: M::display(); */ } }; int main(){ N n; n.display(); // OUTPUT: Derived n.M::display(); // OUTPUT: Base }
Python
UTF-8
322
3.1875
3
[]
no_license
from sys import stdin def input(): return stdin.readline().strip() n = int(input()) a = [] for _ in range(n): a.append(int(input())) a.sort() i = 0 ans = 0 while i < n: num = 1 i += 1 while i < n and a[i] == a[i-1]: num += 1 i += 1 if num % 2 == 1: ans += 1 print(ans)
Java
WINDOWS-1252
297
1.953125
2
[]
no_license
package cn.test.action; import cn.test.domain.Survey; public class SurveyAction extends BaseAction<Survey> { private static final long serialVersionUID = 1303842348519015254L; /***/ private Survey survey = new Survey(); @Override public Survey getModel() { return survey; } }
TypeScript
UTF-8
8,780
3.03125
3
[]
no_license
//地图文件 const FILE_NAME = 'FileList'; const getMapFullPath = function (name: string) { return jsb.fileUtils.getWritablePath() + 'Map/' + name + '.bmap'; } enum HasFlag { BG = 1 << 4, ITEM1 = 1 << 5, ITEM2 = 1 << 6, } class TiledData { x: number; //Int8 1Byte y: number; //Int8 1Byte ground: number; //Int8 1Byte itemID: number[]; //Int16X2 4Byte constructor() { this.x = -1; this.y = -1; this.ground = -1; this.itemID = [0, 0]; } //用一个字节去标记是否有道具和背景 //高位为标记 低位用于储存背景数值 get flag() { let flag = 0; //标记是否有道具1 if (this.itemID[0] != 0) { flag |= HasFlag.ITEM1; } //标记是否有道具2 if (this.itemID[1] != 0) { flag |= HasFlag.ITEM2; } //标记是否有背景 if (this.ground != -1) { flag |= HasFlag.BG; flag += this.ground; //背景数值 } return flag; } static getSize() { return 7; } } //地图数据存储读取数据流 export class MapBuffer { private major_ver: number = 1; //大版本 private minor_ver: number = 4; //小版本 private name: string = ''; //名字 private width: number = 0; //宽度 private height: number = 0; //高度 constructor(name: string, width: number, height: number, defGround: number) { this.name = name; this.width = width; this.height = height; this.defGround = defGround; this.data = []; } public clear() { this.data.length = 0; } public defGround: number = 0; //默认地形 public data: Array<TiledData> = []; //数据信息 //返回一个新数据 public getData(x: number, y: number): TiledData { let itemData = new TiledData(); itemData.x = x; itemData.y = y; this.data.push(itemData); return itemData; } //保存到文件 public saveToFile() { //计算长度 let length = 4; //版本号 length += (this.name.length + 1); //名字长度 length += 3; //width+height+defGround length += (this.data.length * TiledData.getSize()); let buffer = new Uint8Array(length); buffer[0] = this.major_ver; buffer[1] = this.minor_ver; let pos = 4 buffer[pos] = this.name.length; ++pos; for (var i = 0, j = this.name.length; i < j; ++i) { buffer[pos] = this.name.charCodeAt(i); ++pos; } buffer[pos] = this.width; ++pos; buffer[pos] = this.height; ++pos; buffer[pos] = this.defGround; ++pos; let flag, hight, low; for (const itemdata of this.data) { flag = itemdata.flag; buffer[pos] = flag; ++pos; buffer[pos] = itemdata.x; ++pos; buffer[pos] = itemdata.y; ++pos; if (itemdata.itemID[0] != 0) { //存入道具1 hight = itemdata.itemID[0] >> 8; low = itemdata.itemID[0] & 0xff; buffer[pos] = hight; ++pos; buffer[pos] = low; ++pos; } if (itemdata.itemID[1] != 0) { //存入道具2 hight = itemdata.itemID[1] >> 8; low = itemdata.itemID[1] & 0xff; buffer[pos] = hight; ++pos; buffer[pos] = low; ++pos; } } buffer = buffer.subarray(0, pos); if (cc.sys.isNative) { let filePath = getMapFullPath(this.name); jsb.fileUtils.writeDataToFile(buffer, filePath); } else { var dataString = ""; for (var i = 0; i < buffer.length; i++) { dataString += String.fromCharCode(buffer[i]); } cc.sys.localStorage.setItem(this.name, dataString); } } //从文件读取 public readFromFile(): boolean { let buferr: Uint8Array; if (cc.sys.isNative) { let filePath = getMapFullPath(this.name); if (jsb.fileUtils.isFileExist(filePath)) { buferr = jsb.fileUtils.getDataFromFile(filePath); if (buferr == null) { return false; } } else { return false; } } else { let str = cc.sys.localStorage.getItem(this.name); if (str == null || str == "") { return false; } buferr = new Uint8Array(str.length); for (var i = 0, j = str.length; i < j; ++i) { buferr[i] = str.charCodeAt(i); } } let pos = 4 + (this.name.length + 1) + 2; this.defGround = buferr[pos]; ++pos; let flag, x, y, hight, low; for (let i = pos; i < buferr.length;) { flag = buferr[i]; ++i; x = buferr[i]; ++i; y = buferr[i]; ++i; if (x == null || y == null ) break; let itemdata = this.getData(x, y); if (flag & HasFlag.BG) { //获得背景数值 itemdata.ground = (flag & 0xf); } if (flag & HasFlag.ITEM1) { hight = buferr[i]; ++i; low = buferr[i]; ++i; itemdata.itemID[0] = (hight << 8) + low; } if (flag & HasFlag.ITEM2) { hight = buferr[i]; ++i; low = buferr[i]; ++i; itemdata.itemID[1] = (hight << 8) + low; } } return true; } }; //地图简单信息 export class MapInfo extends Object { name: string = ''; //名字 width: number = 10; //宽 height: number = 10; //高 constructor(name: string, width: number, height) { super(); this.name = name; this.width = width; this.height = height; } }; //地图文件管理类 export class MapFile { constructor() { this.readFileList(); } private _fileListPath = ""; private _fileList: Array<MapInfo> = []; public getFileList() { const list = this._fileList; return list; } /* 添加一个文件 */ public addFile(data: MapInfo) { this._fileList.push(data); this.saveFileList(); } /* 删除一个文件 */ public delFile(index: number) { if (index < 0 || this._fileList.length <= index) { return; } if (cc.sys.isNative) { let filePath = getMapFullPath(this._fileList[index].name); if (jsb.fileUtils.isFileExist(filePath)) { jsb.fileUtils.removeFile(filePath); } } else { cc.sys.localStorage.removeItem(this._fileList[index].name); } this._fileList.splice(index, 1); this.saveFileList(); } /* 读取文件列表信息 */ private readFileList() { let filedata; if (cc.sys.isNative) { this._fileListPath = jsb.fileUtils.getWritablePath() + FILE_NAME; if (jsb.fileUtils.isFileExist(this._fileListPath)) { filedata = jsb.fileUtils.getStringFromFile(this._fileListPath); } } else { filedata = cc.sys.localStorage.getItem(FILE_NAME); } if (filedata) { let files = filedata.split('\r\n'); for (let index = 0; index < files.length; index++) { let data = files[index].split('|'); let info = new MapInfo(data[0], Number(data[1]), Number(data[2])); this._fileList.push(info); } } } /* 保存文件列表信息 */ private saveFileList() { let data: string = ''; for (let index = 0; index < this._fileList.length; index++) { const fileInfo = this._fileList[index]; data += (fileInfo.name + '|' + fileInfo.width + '|' + fileInfo.height) if ((index + 1) != this._fileList.length) { data += '\r\n'; } } if (cc.sys.isNative) { jsb.fileUtils.writeStringToFile(data, this._fileListPath); } else { cc.sys.localStorage.setItem(FILE_NAME, data); } } }
Python
UTF-8
993
4.1875
4
[]
no_license
""" Python dictionary Sorting by value references: https://blog.csdn.net/buster2014/article/details/50939892 """ def sort_by_value(mydict): """ :param mydict: :return: sorted dict by value, displaying key """ items = mydict.items() backitems = [[v[1],v[0]] for v in items] # backitems.sort() backitems = sorted(backitems) return [ backitems[i][1] for i in range(0,len(backitems))] def sort_by_value2(mydict): return [v for v in sorted(mydict.values())] def sort_by_value3(mydict): return sorted(mydict.items(), key=lambda item: item[1]) # main program demo_dict = { 1: "c", 2: "a", 3: "b" } print("Original dictionary is: {}".format(demo_dict)) print() # test 1 print("[info] testing sort_by_value()") print(sort_by_value(demo_dict)) print() # test 2 print("[info] testing sort_by_value2()") print(sort_by_value2(demo_dict)) print() # test 3 print("[info] testing sort_by_value3()") print(sort_by_value3(demo_dict)) print()
Markdown
UTF-8
6,532
2.578125
3
[ "LicenseRef-scancode-generic-cla" ]
no_license
--- title: "使用 Azure Functions 執行排程的清除工作 | Microsoft Docs" description: "使用 Azure Functions 建立會根據事件計時器執行的 C# 函數。" services: functions documentationcenter: na author: ggailey777 manager: erikre editor: tags: ms.assetid: 076f5f95-f8d2-42c7-b7fd-6798856ba0bb ms.service: functions ms.devlang: multiple ms.topic: article ms.tgt_pltfrm: multiple ms.workload: na ms.date: 09/26/2016 ms.author: glenga translationtype: Human Translation ms.sourcegitcommit: b873a7d0ef9efa79c9a173a8bfd3522b12522322 ms.openlocfilehash: c0b4a963275dae5bbf203388cb61086393803b15 --- # <a name="use-azure-functions-to-perform-a-scheduled-clean-up-task"></a>使用 Azure Functions 執行排程的清除工作 本主題將示範如何使用 Azure Functions,以 C# 建立可根據事件計時器執行的新函數,來清除資料庫資料表中的資料列。 新的函式是根據 Azure Functions 入口網站中的預先定義範本所建立。 若要支援此案例,您也必須在函數應用程式中設定資料庫連接字串以做為 App Service 設定。 ## <a name="prerequisites"></a>必要條件 您必須先具備有效的 Azure 帳戶,才可以建立函式。 如果您還沒有 Azure 帳戶, [可以使用免費帳戶](https://azure.microsoft.com/free/)。 本主題將示範在 SQL Database 中名為 TodoItems 的資料表中執行大量清除作業的 Transact-SQL 命令。 當您完成 [Azure App Service Mobile Apps 快速入門教學課程](../app-service-mobile/app-service-mobile-ios-get-started.md)時,即會建立這個相同的 TodoItems 資料表。 您也可以使用範例資料庫,如果您選擇使用不同的資料表,您將需要修改命令。 你可以在入口網站中 [所有設定] > [應用程式設定] > [連接字串] > [顯示連接字串值] > [MS_TableConnectionString] 下方,取得行動應用程式後端所使用的連接字串。 您也可以在入口網站中 [所有設定] > [屬性] > [顯示資料庫連接字串] > [ADO.NET (SQL 驗證)] 下方,直接從 SQL Database 中取得連接字串。 此案例會對資料庫使用大量作業。 若要讓您的函數程序在 Mobile Apps 資料表中進行個別的 CRUD 作業,您應該改用行動資料表繫結。 ## <a name="set-a-sql-database-connection-string-in-the-function-app"></a>在函數應用程式中設定 SQL Database 連接字串 函式應用程式可在 Azure 中主控函式的執行。 在函數應用程式設定中儲存連接字串和其他機密資料是最佳做法。 這可以避免當您的函數程式碼在儲存機制中的某處結束時發生意外洩漏。 1. 移至 [Azure Functions 入口網站](https://functions.azure.com/signin) ,然後以您的 Azure 帳戶登入。 2. 如果您要使用現有的函式應用程式,請從 [您的函式應用程式] 中選取,然後按一下 [開啟]。 若要建立新的函式應用程式,請輸入新函式應用程式的唯一 [名稱] 或接受所產生的名稱、選取您偏好的 [區域],然後按一下 [建立 + 開始使用]。 3. 在您的函式應用程式中,按一下 [函式應用程式設定] > [移至 App Service 設定]。 ![函數應用程式設定刀鋒視窗](./media/functions-create-an-event-processing-function/functions-app-service-settings.png) 4. 在函式應用程式中,按一下 [所有設定]、向下捲動至 [應用程式設定],然後在 [連接字串] 下方針對 [名稱] 輸入 `sqldb_connection`、將連接字串貼入 [值] 中、按一下 [儲存],然後關閉函式應用程式刀鋒視窗以返回 Functions 入口網站。 ![App Service 設定連接字串](./media/functions-create-an-event-processing-function/functions-app-service-settings-connection-strings.png) 現在,您可以加入 C# 函數程式碼來連接到 SQL Database。 ## <a name="create-a-timer-triggered-function-from-the-template"></a>從範本建立計時器觸發函數 1. 在函式應用程式中,按一下 [+ 新增函式] > [TimerTrigger - C#] > [建立]。 這會以預設名稱建立函數,此函數會以每分鐘一次的預設排程來執行。 ![建立新的計時器觸發函數](./media/functions-create-an-event-processing-function/functions-create-new-timer-trigger.png) 2. 在 [開發] 索引標籤的 [程式碼] 窗格中,在現有函式程式碼上方新增下列組件參考: ```cs #r "System.Configuration" #r "System.Data" ``` 3. 將下列 `using` 陳述式加入至函數: ```cs using System.Configuration; using System.Data.SqlClient; using System.Threading.Tasks; ``` 4. 使用下列程式碼來取代現有的 **Run** 函數: ```cs public static async Task Run(TimerInfo myTimer, TraceWriter log) { var str = ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString; using (SqlConnection conn = new SqlConnection(str)) { conn.Open(); var text = "DELETE from dbo.TodoItems WHERE Complete='True'"; using (SqlCommand cmd = new SqlCommand(text, conn)) { // Execute the command and log the # rows deleted. var rows = await cmd.ExecuteNonQueryAsync(); log.Info($"{rows} rows were deleted"); } } } ``` 5. 按一下 [儲存]、針對下一個函式執行監看 [記錄] 視窗,然後記下從 TodoItems 資料表中刪除的資料列數目。 6. (選擇性) 使用 [Mobile Apps 快速入門應用程式](../app-service-mobile/app-service-mobile-ios-get-started.md),將其他項目標示為「已完成」,然後返回 [記錄] 視窗,並監看在下一個執行期間該函式會刪除同樣數目的資料列。 ## <a name="next-steps"></a>後續步驟 如需 Azure Functions 的詳細資訊,請參閱下列主題。 * [Azure Functions 開發人員參考](functions-reference.md) 可供程式設計人員撰寫函數程式碼及定義觸發程序和繫結時參考。 * [測試 Azure Functions](functions-test-a-function.md) 說明可用於測試函式的各種工具和技巧。 * [如何調整 Azure 函式](functions-scale.md) 討論 Azure Functions 可用的服務方案,包括取用方案,以及如何選擇正確的方案。 [!INCLUDE [Getting Started Note](../../includes/functions-get-help.md)] <!--HONumber=Nov16_HO5-->
JavaScript
UTF-8
776
2.671875
3
[]
no_license
let menu = document.querySelector('.header__menu'); let hamburger = document.querySelector('.hamburger'); let writeButton = document.querySelector('.footer__write'); let modal = document.querySelector('.modal__window'); let closeButton = document.querySelector('.modal__close'); hamburger.addEventListener('click', () => { menu.classList.toggle("header__menu--active"); hamburger.classList.toggle("hamburger--active"); }); writeButton.addEventListener('click', () => { modal.classList.toggle("modal__window--active"); }); closeButton.addEventListener('click', () => { modal.classList.toggle("modal__window--active"); }); window.addEventListener('click', (e) => { if(e.target == modal){ modal.classList.toggle("modal__window--active"); } });
Shell
UTF-8
522
3.09375
3
[]
no_license
#!/bin/bash ################# # # Scanning script # ################# #Update clamAV database echo "***Updating clamAV databases***" sudo freshclam #Scan for rootkits echo "***RootKit scanner***" sudo chkrootkit #Scan for virus and malware, #notify user with bell when infection found #only show infeected files #takes location param, or default whole system echo "***Scanning ${1:-/}***" sudo clamscan -r --bell -i --exclude-dir="^/sys" ${1:-/} notify-send 'Virus Scan' 'Scan is completed.' --icon=dialog-information
Java
UTF-8
155
1.609375
2
[]
no_license
package com.edu.service; import java.util.List; import com.edu.entity.Auth; public interface IAuthService { public List<Auth> findAll(); }
Java
UTF-8
378
1.570313
2
[]
no_license
package com.analyzeme.scripts; import org.junit.Test; /** * Created by lagroffe on 20.07.2016 13:34 * not a real test (for manual testing) */ public class TestGithubDownloader { @Test public void test() throws Exception { GithubDownloader.download("r/example_anon_vector.R"); GithubDownloader.download("rscripts_info.txt"); } }
SQL
UTF-8
5,040
3.203125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 3.1.1 -- http://www.phpmyadmin.net -- -- Serveur: localhost -- Généré le : Mar 11 Décembre 2012 à 11:48 -- Version du serveur: 5.1.30 -- Version de PHP: 5.2.8 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Base de données: `qlsv` -- -- -------------------------------------------------------- -- -- Structure de la table `ketqua` -- CREATE TABLE IF NOT EXISTS `ketqua` ( `p_id` double unsigned NOT NULL AUTO_INCREMENT, `tensv` varchar(100) NOT NULL, `mnh` varchar(100) NOT NULL, `tenmonhoc` varchar(100) NOT NULL, `lanthi` int(100) NOT NULL, `diem` int(10) NOT NULL, `p_check` tinyint(3) unsigned zerofill NOT NULL, `p_del` tinyint(3) unsigned zerofill NOT NULL, PRIMARY KEY (`p_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=14 ; -- -- Contenu de la table `ketqua` -- INSERT INTO `ketqua` (`p_id`, `tensv`, `mnh`, `tenmonhoc`, `lanthi`, `diem`, `p_check`, `p_del`) VALUES (12, 'Trần Xuân Tuấn', 'LTWB', 'Lập trình website', 1, 8, 000, 000), (13, 'Lê Thu Trang', 'KTCN', 'Kế toán chuyên ngành', 1, 9, 000, 000); -- -------------------------------------------------------- -- -- Structure de la table `khoa` -- CREATE TABLE IF NOT EXISTS `khoa` ( `p_id` double unsigned NOT NULL AUTO_INCREMENT, `makhoa` varchar(100) NOT NULL, `tenkhoa` varchar(100) NOT NULL, `p_check` tinyint(3) unsigned zerofill NOT NULL, `p_del` tinyint(3) unsigned zerofill NOT NULL, PRIMARY KEY (`p_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ; -- -- Contenu de la table `khoa` -- INSERT INTO `khoa` (`p_id`, `makhoa`, `tenkhoa`, `p_check`, `p_del`) VALUES (6, 'TH', 'Công nghệ thông tin', 000, 000), (7, 'KT', 'Kế toán', 000, 000), (8, '', '', 000, 001), (9, 'CDT', 'CÆ¡ Ä‘iện tá»­', 000, 000); -- -------------------------------------------------------- -- -- Structure de la table `lop` -- CREATE TABLE IF NOT EXISTS `lop` ( `p_id` double unsigned NOT NULL AUTO_INCREMENT, `malop` varchar(10) NOT NULL, `tenlop` varchar(50) NOT NULL, `khoa` varchar(100) NOT NULL, `p_check` tinyint(3) unsigned zerofill NOT NULL, `p_del` tinyint(3) unsigned zerofill NOT NULL, PRIMARY KEY (`p_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ; -- -- Contenu de la table `lop` -- INSERT INTO `lop` (`p_id`, `malop`, `tenlop`, `khoa`, `p_check`, `p_del`) VALUES (10, 'C17A-K13', 'Tin học K13', 'Công nghệ thông tin', 000, 000), (11, 'C17A-K14', 'Tin học K14', 'Công nghệ thông tin', 000, 000), (12, 'C15E - K13', 'Kế Toán E K13', 'Kế toán', 000, 000), (13, 'C15A - K14', 'Kế Toán A K14', 'Kế toán', 000, 000), (14, '', '', 'Công nghệ thông tin', 000, 001); -- -------------------------------------------------------- -- -- Structure de la table `monhoc` -- CREATE TABLE IF NOT EXISTS `monhoc` ( `p_id` double unsigned NOT NULL AUTO_INCREMENT, `tensv` varchar(100) NOT NULL, `p_mnh` varchar(100) NOT NULL, `tenmonhoc` varchar(100) NOT NULL, `sotiet` int(11) NOT NULL, `p_check` tinyint(4) NOT NULL, `p_del` tinyint(11) unsigned zerofill NOT NULL, PRIMARY KEY (`p_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4169 ; -- -- Contenu de la table `monhoc` -- INSERT INTO `monhoc` (`p_id`, `tensv`, `p_mnh`, `tenmonhoc`, `sotiet`, `p_check`, `p_del`) VALUES (4167, 'Trần Xuân Tuấn', 'LTWB', 'Lập trình website', 120, 0, 00000000000), (4168, 'Lê Thu Trang', 'KTCN', 'Kế toán chuyên ngành', 120, 0, 00000000000); -- -------------------------------------------------------- -- -- Structure de la table `sinhvien` -- CREATE TABLE IF NOT EXISTS `sinhvien` ( `p_id` double unsigned NOT NULL AUTO_INCREMENT, `masv` varchar(100) NOT NULL, `tensv` varchar(100) NOT NULL, `ngaysinh` varchar(100) NOT NULL, `gioitinh` varchar(10) NOT NULL, `quequan` varchar(100) NOT NULL, `lop` varchar(100) NOT NULL, `khoa` varchar(100) NOT NULL, `p_check` tinyint(3) unsigned zerofill NOT NULL, `p_del` tinyint(3) unsigned zerofill NOT NULL, PRIMARY KEY (`p_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ; -- -- Contenu de la table `sinhvien` -- INSERT INTO `sinhvien` (`p_id`, `masv`, `tensv`, `ngaysinh`, `gioitinh`, `quequan`, `lop`, `khoa`, `p_check`, `p_del`) VALUES (8, 'C17AK13T', 'Trần Xuân Tuấn', '26-11-1991', 'Nam', 'Tam Điệp - Ninh Bình', 'Tin học K13', 'Công nghệ thông tin', 000, 000), (9, 'C15EK13T', 'Lê Thu Trang', '10-04-1994', 'Nữ ', 'Tam Điệp - Ninh Bình', 'Kế Toán E K13', 'Kế toán', 000, 000), (10, '', '', '', '', '', 'Tin học K13', 'Công nghệ thông tin', 000, 001);
TypeScript
UTF-8
1,662
2.5625
3
[]
no_license
import { Formats } from "../../data-interface/formats"; const numberConvertor = new Map(); numberConvertor.set(Formats.positive_fixint, { convert: function(buff: Buffer) { return buff.readUInt8(0); }, } ); numberConvertor.set(Formats.negative_fixint, { convert: function(buff: Buffer) { return buff.readInt8(0); }, } ); numberConvertor.set(Formats.uint_8, { convert: function(buff: Buffer) { return buff.readUInt8(1); }, } ); numberConvertor.set(Formats.int_8, { convert: function(buff: Buffer) { return buff.readInt8(1); }, } ); numberConvertor.set(Formats.uint_16, { convert: function(buff: Buffer) { return buff.readUInt16BE(1); }, } ); numberConvertor.set(Formats.int_16, { convert: function(buff: Buffer) { return buff.readInt16BE(1); }, } ); numberConvertor.set(Formats.uint_32, { convert: function(buff: Buffer) { return buff.readUInt32BE(1); }, } ); numberConvertor.set(Formats.int_32, { convert: function(buff: Buffer) { return buff.readInt32BE(1); }, } ); numberConvertor.set(Formats.float_32, { convert: function(buff: Buffer) { return buff.readFloatBE(1); }, } ); numberConvertor.set(Formats.uint_64, { convert: function(buff: Buffer) { return Number(buff.readBigUInt64BE(1)); }, } ); numberConvertor.set(Formats.int_64, { convert: function(buff: Buffer) { return Number(buff.readBigInt64BE(1)); }, } ); numberConvertor.set(Formats.float_64, { convert: function(buff: Buffer) { return buff.readDoubleBE(1); }, } ); export { numberConvertor }
TypeScript
UTF-8
3,070
2.515625
3
[]
no_license
module egret3d { /** * @private * @class egret3d.ShadowRender * @classdesc * 阴影渲染器 */ export class ShadowRender extends RenderBase { public static frameBuffer: FrameBuffer; public static castShadowLight: LightBase; public static shadowCamera3D: Camera3D; public shadowTexture_width: number = 1024; public shadowTexture_height: number = 1024; /** * @language zh_CN * constructor */ constructor( ) { super(); ShadowRender.shadowCamera3D = new Camera3D(CameraType.orthogonal);//temp ShadowRender.frameBuffer = RttManager.creatFrameBuffer(FrameBufferType.shadowFrameBufrfer,Egret3DDrive.context3D,this.shadowTexture_width,this.shadowTexture_height,FrameBufferFormat.UNSIGNED_BYTE_RGBA); } /** * @language zh_CN * 渲染 * @param time 当前时间 * @param delay 每帧间隔时间 * @param context3D 设备上下文 * @param collect 渲染对象收集器 * @param camera 渲染时的相机 */ public draw(time: number, delay: number, context3D: Context3D, collect: CollectBase, camera: Camera3D, viewPort: Rectangle) { if (ShadowRender.castShadowLight) { this.offsetPos( new Vector3D() ); this._renderList = collect.renderList; this._numEntity = this._renderList.length; for (this._renderIndex = 0; this._renderIndex < this._numEntity; this._renderIndex++) { if (this._renderList[this._renderIndex].material.castShadow) { this._renderList[this._renderIndex].update(camera, time, delay); if (!this._renderList[this._renderIndex].isVisible) { continue; } this._renderList[this._renderIndex].material.renderShadowPass(context3D, ShadowRender.shadowCamera3D , this._renderList[this._renderIndex].modelMatrix, this._renderList[this._renderIndex].geometry, this._renderList[this._renderIndex].animation); } } } } private cameraTarget: Vector3D = new Vector3D(); private cameraPos: Vector3D = new Vector3D(); private distance: number = 0; public offsetPos( offset:Vector3D ) { this.cameraPos.x = ShadowRender.castShadowLight.rotationX; this.cameraPos.y = ShadowRender.castShadowLight.rotationY; this.cameraPos.z = ShadowRender.castShadowLight.rotationZ; this.cameraPos.normalize(); this.cameraPos.scaleBy(1.0 * 500); this.cameraPos.x = this.cameraPos.x + offset.x; this.cameraPos.y = this.cameraPos.y + offset.y; this.cameraPos.z = this.cameraPos.z + offset.z; ShadowRender.shadowCamera3D.lookAt(this.cameraPos, offset ); } } }
Markdown
UTF-8
2,989
3.140625
3
[]
no_license
--- title: 季末 description: 许久没来这里,再来自然不会感到陌生,前些日子积累可以有些记录的东西,有关城市,有关食粮,有关诗和远方,但也只是一闪而过的念头,以致于并没有太大的冲动写下点什么,归结于感悟不足和宁缺勿滥都好。时间点是个很好的借口,能将一些堆积的杂想稍微整理,给文章起名也简单,就像“季末”。 --- 许久没来这里,再来自然不会感到陌生,前些日子积累可以有些记录的东西,有关城市,有关食粮,有关诗和远方,但也只是一闪而过的念头,以致于并没有太大的冲动写下点什么,归结于感悟不足和宁缺勿滥都好。时间点是个很好的借口,能将一些堆积的杂想稍微整理,给文章起名也简单,就像“季末”。 想过总结在小城和大城饮食生活各是怎样一种体验,这两种城自己都有过生活体验,可以从不同地方的人口中听到过各自家里所在的小城有着各种各样好吃的早餐和夜宵,尽管门面没有华丽的装饰,但味道是极好的。大城市里高楼林立灯红酒绿自然不用提,也会汇集各地美味,但对于出生于小城在大城中遇到小城的美食时,在味道上有不小差异外,往往感到的是缺少情怀。 经过一个多月每天晚上无论多晚都做完一套健身运动后,渐渐喜欢上了运动的感觉,而且有渐渐觉得不满足当前的运动量,每天100个俯卧撑加到了150,后面会陆续增加,腹肌锻炼在尝试着几种方法中找到合适自己的。在这个过程中,从身体方面体会到坚持的不容易,从精神层面来讲,“每个在一直坚持的人都值得尊敬”,停下来想了想,自己能坚持的有些什么,结果是原地踏步还是甩当初几条街。注意运动往往会伴随着饮食,周末里做一样以前没尝试过的菜肴,虽然做可乐鸡翅有过失误,但也是一次不错的体验。 之前在晓松奇谈的节目开头都能听到“诗和远方”的歌词,大约一个礼拜前正式发布了歌曲《生活不止眼前的苟且》,每每听着文艺情绪都如黄河水泛滥滔滔不绝。见到有网友的评论“父母尚在苟且,你却想着诗和远方”,生活是不止眼前的苟且,诗和远方的田野也存在,那片海要追求,理性一点的做法是在两者之前平衡着生活。 最近还遇到了让自己情绪波动的事情,这是极其少见的,曾经以为自己的心态稳定到即使情绪有波动也保持起伏不大,甚至能快速恢复平静。这件事情花了较大的精力去让自己平静,甚至还采用了与人交流探讨的手段,事后当然恢复平静了,不过后来想想“有那么一件事能让自己的心境有这么大的改变”这件事情也挺新鲜的,这让我觉得还是有很大的空间进行修行。 要改变点什么。
Markdown
UTF-8
1,899
2.75
3
[]
no_license
<p align="center"> <img src="https://github.com/whyandree/go_finances/blob/master/src/assets/logo.svg" alt="go finances" width="300px"/> </p> <p align="center"> #Ignite 🚀 Rocketseat </p> <h2> 📃 Sobre a aplicação </h2> <i>Go_finances</i> é uma aplicação para controle de rendas e gastos pessoais. Podemos adicionar entradas e saídas e usar como base de consulta de transações, assim consultando o total de renda disponível. <h2>📼 Prévia</h2> <p align="center"> <img src="https://github.com/whyandree/go_finances/blob/master/public/preview/gofinances_preview.gif" alt="go finances prévia"/> </p> <h2>🔧 Ferramentas utilizadas</h2> Para o desenvolvimento do projeto, foram utilizados as principais ferramentas: <ul> <li><a href="https://pt-br.reactjs.org/">ReactJS</a></li> <li><a href="https://www.typescriptlang.org/">Typescript</a></li> <li><a href="https://styled-components.com/">Styled-components</a></li> <li><a href="https://miragejs.com/">MirageJS</a></li> </ul> <h2>⚙ Rodando a aplicação</h2> <ul> <li>É <b>necessário</b> possuir o <a href="https://nodejs.org/en/">Node.js</a> em sua máquina.</li> <li>Também é <b>preciso</b> ter um gerenciador de pacotes, seja o <a href="https://www.npmjs.com/">NPM</a> ou <a href="https://yarnpkg.com/">Yarn</a>.</li> </ul> <h3>Caso tudo esteja certo, basta seguir os passos abaixo.</h3> 1. Clone o repositório em sua maquina utilizando : ```sh $ git clone https://github.com/whyandree/go_finances ``` 2. Instale as dependencias do projeto : ```sh $ npm install ``` 3. Rode o projeto : ```sh $ npm start ``` 3. Se tudo estiver certo, a aplicação irá iniciar no endereço http://localhost:3000/ <br /> E pronto, já é possivel vizualizar a aplicação. <hr> <h4 align="center"> Feito com 💜 by <a href="https://www.linkedin.com/in/andreovski/" target="_blank">André Luiz</a> </h4>
JavaScript
UTF-8
764
3.9375
4
[]
no_license
/** * There are two sorted arrays nums1 and nums2 of size m and n respectively. * Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). * You may assume nums1 and nums2 cannot be both empty. * * example 1 * nums1 = [1, 3] * nums2 = [2] * The median is 2.0 * * example 2 * nums1 = [1, 2] * nums2 = [3, 4] * The median is (2 + 3)/2 = 2.5 */ const findMedianSortedArrays = function(nums1, nums2) { const concatArray = nums1.concat(nums2).sort((a, b) => a - b); const count = concatArray.length; const median = count % 2 === 1 ? concatArray[Math.floor(count / 2)] : (concatArray[count / 2 - 1] + concatArray[count / 2]) / 2; return median; }; module.exports = findMedianSortedArrays;
Shell
UTF-8
375
2.59375
3
[]
no_license
# usage: # ./sendlink.sh "https://cvs.test-app.link/ecQRNoAuthDeals?progname=ecQRNoAuthDeals&mxc=28c83f4635d193b3cf29a03dcda640e46122af04869854943f7364387164e212" # don't forget to wrap the url in quotes url=$1 urlWithEscapedParams="${url//&/\&}" echo Sending Link: ${urlWithEscapedParams} adb shell am start -W -a android.intent.action.VIEW -d ${urlWithEscapedParams}
C
UTF-8
2,515
3.671875
4
[]
no_license
/* 给定两个二进制字符串,返回他们的和(用二进制表示)。 输入为非空字符串且只包含数字 1 和 0。 示例 1 输入 a = 11, b = 1 输出 100 示例 2 输入 a = 1010, b = 1011 输出 10101 */ #include <stdio.h> #include <stdlib.h> #include <string.h> char* addBinary(char * a, char * b){ int len_a = strlen(a) ; int len_b = strlen(b) ; int max_len = len_a > len_b ? len_a : len_b ; int min_len = len_a > len_b ? len_b : len_a ; char* longerstr = len_a > len_b ? a : b ; char* shorterstr = len_a > len_b ? b : a ; int carry_flag = 0 ; /* 0 无进位,1有进位*/ char* ret_pointer = NULL ; int i = 0 ; int temp = 0 ; carry_flag = 0; for(i = max_len-1 ; i >= 0; i--) { if(max_len - i <= min_len) { temp = longerstr[i] - 0x30 + shorterstr[i+min_len-max_len] - 0x30 + carry_flag; } else { temp = longerstr[i] - 0x30 + carry_flag; } longerstr[i] = temp % 2 + 0x30; if(temp>=2) { carry_flag = 1; } else { carry_flag = 0; } } if(carry_flag == 0) { return longerstr; } else { ret_pointer = (char*)malloc(sizeof(char)*(max_len+2)); //memset(ret_pointer,0,sizeof(char)*(max_len+2)); ret_pointer[max_len+1] = 0x00; ret_pointer[0] = '1'; //for(i = 1; i <= max_len ; i++) //{ // ret_pointer[i] = longerstr[i-1]; //} memcpy(&ret_pointer[1],longerstr,max_len*sizoof(char)); return ret_pointer; } } #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char* a = "1"; char* b = "111"; char* c = addBinary(a,b); printf("a+b = %s\n",c); free(c); c = NULL; getchar(); return 0; } /* 执行用时 : 0 ms, 在Add Binary的C提交中击败了100.00% 的用户 内存消耗 : 6.9 MB, 在Add Binary的C提交中击败了35.19% 的用户 294 / 294 个通过测试用例 状态:通过 执行用时:0 ms 提交时间:0 分钟之前 */
C++
UTF-8
3,342
2.53125
3
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
#ifndef CAFFE_LSTM_NODE_LAYER_HPP_ #define CAFFE_LSTM_NODE_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief Processes sequential inputs using a "Long Short-Term Memory" (LSTM) * [1] style recurrent neural network (RNN). Unlike the LSTM layer, this * implementation represents a single LSTM timestep, requiring the full net to * be unrolled in prototxt. However, this approach enables sampling and beam * search through the resulting network, which the LSTM layer cannot do. * * The specific architecture used in this implementation is as described in * "Learning to Execute" [2], reproduced below: * @f$ i_t := \sigmoid[ W_{hi} * h_{t-1} + W_{xi} * x_t + b_i ] @f$ * @f$ f_t := \sigmoid[ W_{hf} * h_{t-1} + W_{xf} * x_t + b_f ] @f$ * @f$ o_t := \sigmoid[ W_{ho} * h_{t-1} + W_{xo} * x_t + b_o ] @f$ * @f$ g_t := \tanh[ W_{hg} * h_{t-1} + W_{xg} * x_t + b_g ] @f$ * @f$ c_t := (f_t .* c_{t-1}) + (i_t .* g_t) @f$ * @f$ h_t := o_t .* \tanh[c_t] @f$ * * Notably, this implementation lacks the "diagonal" gates, as used in the * LSTM architectures described by Alex Graves [3] and others. * * [1] Hochreiter, Sepp, and Schmidhuber, Jürgen. "Long short-term memory." * Neural Computation 9, no. 8 (1997): 1735-1780. * * [2] Zaremba, Wojciech, and Sutskever, Ilya. "Learning to execute." * arXiv preprint arXiv:1410.4615 (2014). * * [3] Graves, Alex. "Generating sequences with recurrent neural networks." * arXiv preprint arXiv:1308.0850 (2013). */ template <typename Dtype> class LSTMNodeLayer : public Layer<Dtype> { public: explicit LSTMNodeLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "LSTMNode"; } virtual inline int MinBottomBlobs() const { return 2; } virtual inline int MaxBottomBlobs() const { return 3; } virtual inline int ExactNumTopBlobs() const { return 2; } protected: /** * @param bottom input Blob vector (length 2 or 3) * -# the inputs @f$ x_t @f$ * -# the previous hidden state @f$ c_{t-1} @f$ * -# optional continuation indicators (1, or 0 for the start of a new sequence) * @param top output Blob vector (length 2) * -# the output @f$ h_t @f$ * -# the current hidden state @f$ c_t @f$ */ virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); int M_; // batch size int N_; // num memory cells int K_; // input data size Blob<Dtype> gates_data_buffer_; bool bias_term_; Blob<Dtype> ones_; Blob<Dtype> tanh_c_; bool cache_gates_; }; } // namespace caffe #endif // CAFFE_LSTM_NODE_LAYER_HPP_
Java
UTF-8
5,739
2.46875
2
[]
no_license
package com.mr2.zaiko.ui.test; import com.mr2.zaiko.useCase.TestApplicationService; public class TestPresenter implements ContractTest.Presenter { private ContractTest.View view; private TestApplicationService service; public TestPresenter(TestApplicationService testApplicationService) { this.service = testApplicationService; } @Override public void onCreate(ContractTest.View view) { registerView(view); String name; if (service.existsData()){ name = service.date(); }else { name = service.createData(); this.view.showToast("On created."); } this.view.changeText(name); } @Override public void onDestroy(ContractTest.View view) { unregisterView(view); } //save @Override public void event_1() { try { service.save(); view.showToast("Data saved."); }catch (IllegalArgumentException e){ view.showToast("Unsaved null data. Message: " + e.getMessage()); } } //load @Override public void event_2() { try { view.changeText(service.load()); view.showToast("Data loaded."); }catch (IllegalStateException e){ view.showToast("Data does not exist. Message: " + e.getMessage()); } } //rename @Override public void event_3(String name) { view.changeText(service.rename(name)); view.showToast("Data name changed."); } //delete @Override public void event_4() { try { view.changeText(service.delete()); view.showToast("Data is deleted."); }catch (IllegalArgumentException e){ view.showToast("Wrong data Message: " + e.getMessage()); } } @Override public void startLoader() { } private void registerView(ContractTest.View view){ this.view = view; } private void unregisterView(ContractTest.View view){ if (this.view != view) throw new IllegalArgumentException("登録されているViewと異なります。"); view = null; } // // //AsyncTaskLoaderコールバックの実装//////// // // /** // * Instantiate and return a new Loader for the given ID. // * // * <p>This will always be called from the process's main thread. // * // * @param id The ID whose loader is to be created. // * @param args Any arguments supplied by the caller. // * @return Return a new Loader instance that is ready to start loading. // */ // @NonNull // @Override // public Loader<String> onCreateLoader(int id, @Nullable Bundle args) { // //Loader生成 // return new TestTaskLoader<String>(); // } // // /** // * Called when a previously created loader has finished its load. Note // * that normally an application is <em>not</em> allowed to commit fragment // * transactions while in this call, since it can happen after an // * activity's state is saved. See {@link FragmentManager#beginTransaction() // * FragmentManager.openTransaction()} for further discussion on this. // * // * <p>This function is guaranteed to be called prior to the release of // * the last data that was supplied for this Loader. At this point // * you should remove all use of the old data (since it will be released // * soon), but should not do your own release of the data since its Loader // * owns it and will take care of that. The Loader will take care of // * management of its data so you don't have to. In particular: // * // * <ul> // * <li> <p>The Loader will monitor for changes to the data, and report // * them to you through new calls here. You should not monitor the // * data yourself. For example, if the data is a {@link Cursor} // * and you place it in a {@link CursorAdapter}, use // * the {@link CursorAdapter#CursorAdapter(Context, // * Cursor, int)} constructor <em>without</em> passing // * in either {@link CursorAdapter#FLAG_AUTO_REQUERY} // * or {@link CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER} // * (that is, use 0 for the flags argument). This prevents the CursorAdapter // * from doing its own observing of the Cursor, which is not needed since // * when a change happens you will get a new Cursor throw another call // * here. // * <li> The Loader will release the data once it knows the application // * is no longer using it. For example, if the data is // * a {@link Cursor} from a {@link CursorLoader}, // * you should not call close() on it yourself. If the Cursor is being placed in a // * {@link CursorAdapter}, you should use the // * {@link CursorAdapter#swapCursor(Cursor)} // * method so that the old Cursor is not closed. // * </ul> // * // * <p>This will always be called from the process's main thread. // * // * @param loader The Loader that has finished. // * @param data The data generated by the Loader. // */ // @Override // public void onLoadFinished(@NonNull Loader<String> loader, String data) { // //Loader終了時 dataがResult // } // // /** // * Called when a previously created loader is being reset, and thus // * making its data unavailable. The application should at this point // * remove any references it has to the Loader's data. // * // * <p>This will always be called from the process's main thread. // * // * @param loader The Loader that is being reset. // */ // @Override // public void onLoaderReset(@NonNull Loader<String> loader) { // // } }
C++
UTF-8
448
2.90625
3
[]
no_license
// // Created by Adeesh Ankaraju Gopalakrishnan on 2019-01-22. // class Solution { public: vector<vector<int>> transpose(vector<vector<int>>& A) { int inner_size = A[0].size(), outer_size = A.size(); vector<vector<int>> ret_list(inner_size, vector<int>(outer_size,0)); for(int i=0;i<outer_size;++i){ for(int j=0;j<inner_size;++j){ ret_list[j][i] = A[i][j]; } } return ret_list; } };
Markdown
UTF-8
5,297
2.734375
3
[]
no_license
# spring-boot-reactive-download-file > ตัวอย่างการเขียน Spring-boot Reactive Download File # 1. เพิ่ม Dependencies และ Plugins pom.xml ``` xml ... <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <id>build-info</id> <goals> <goal>build-info</goal> </goals> <configuration> <additionalProperties> <java.version>${java.version}</java.version> </additionalProperties> </configuration> </execution> </executions> </plugin> </plugins> </build> ... ``` หมายเหตุ lombox เป็น annotation code generator ตัวนึงครับ # 2. เขียน Main Class ``` java @SpringBootApplication @ComponentScan(basePackages = {"me.jittagornp"}) public class AppStarter { public static void main(String[] args) { SpringApplication.run(AppStarter.class, args); } } ``` # 3. เขียน Controller ``` java @Slf4j @Controller public class ResourceController { @GetMapping({"", "/", "/classpath"}) public Mono<ResponseEntity<Resource>> showClassPathImage() { return Mono.just( ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"reactive_spring.png\"") .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) .body(new ClassPathResource("static/image/reactive_spring.png")) ); } @GetMapping({"/classpath/download"}) public Mono<ResponseEntity<Resource>> downloadClassPathImage() { return Mono.just( ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"reactive_spring.png\"") .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) .body(new ClassPathResource("static/image/reactive_spring.png")) ); } @GetMapping("/inputstream") public Mono<ResponseEntity<? extends Resource>> showInputStreamImage() { String fileName = "reactive_spring.png"; return readStream(fileName) .map(stream -> { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"") .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) .body(new InputStreamResource(stream)); }); } @GetMapping("/inputstream/download") public Mono<ResponseEntity<Resource>> downloadInputStreamImage() { String fileName = "reactive_spring.png"; return readStream(fileName) .map(stream -> { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) .body(new InputStreamResource(stream)); }); } private Mono<InputStream> readStream(final String fileName) { return Mono .create((MonoSink<InputStream> callback) -> { try { callback.success(getClass().getResourceAsStream("/static/image/" + fileName)); } catch (Exception ex) { log.warn("read stream error => ", ex); callback.error(ex); } }) .switchIfEmpty(Mono.error(new NotFoundException(fileName + " not found"))); } } ``` # 4. Build Code cd ไปที่ root ของ project จากนั้น ``` sh $ mvn clean package ``` # 5. Run ``` sh $ mvn spring-boot:run ``` # 6. เข้าใช้งาน เปิด browser แล้วเข้า - [http://localhost:8080](http://localhost:8080) - [http://localhost:8080/classpath](http://localhost:8080/classpath) - [http://localhost:8080/classpath/download](http://localhost:8080/classpath/download) - [http://localhost:8080/inputstream](http://localhost:8080/inputstream) - [http://localhost:8080/inputstream/download](http://localhost:8080/inputstream/download)
Shell
UTF-8
1,018
4
4
[ "MIT" ]
permissive
#!/bin/sh # Check if backup specified. if [ "$#" -ne 1 ]; then echo "Backup dirname wasn't specified." echo "NOTE: It must be a dirname without symlinks pointing outside of the current directory." exit 1 fi # Check if backup based on root. first_char="$(printf '%s' "$1" | cut -c1)" if [ "$first_char" = "/" ]; then echo "Backup dirname can't be based on root." echo "NOTE: It must be a dirname without symlinks pointing outside of the current directory." exit 2 fi # Check if backup already exists. if [ -d "/host/$1" ]; then echo "Backup dirname already exists." exit 3 fi # Create backup directories. mkdir -p /host/$1/config if [ ! -d "/host/$1/config" ]; then echo "There was a problem creating the directory $1/config ." echo "NOTE: It must be a dirname without symlinks pointing outside of the current directory." exit 4 fi mkdir -p /host/$1/log mkdir -p /host/$1/world # Do backup. cp -a /tshock/config/. /host/$1/config/ cp -a /tshock/log/. /host/$1/log/ cp -a /tshock/world/. /host/$1/world/
Python
UTF-8
221
2.6875
3
[]
no_license
l=int(input()) m=list(map(int,input().split(" "))) m=sorted(m) p=[] for i in range(len(m)-1): if(m[i]==m[i+1]): p.append(m[i]) if(p): for j in set(p): print(j,end=" ") break else: print("unique")
Markdown
UTF-8
5,428
3.171875
3
[]
no_license
--- title: Synchronous Publication --- xMsg supports publishing a message and receiving a response, with the following method: ```java xMsgMessage syncPublish(xMsgConnection connection, xMsgMessage msg, int timeout) throws xMsgException, TimeoutException ``` This publishes the message just like the `publish` method, but this time the *metadata* is modified with a unique `replyTo` field. Then the method will block until a response message is received or the timeout occurs, whichever happens first. {: .note } In order to receive a response, the subscription callback must support sync-publication and publish response messages to the expected topic. xMsg does not publish a response automatically. As with normal publication, the xMsg actor can sync-publish messages on multiples threads, but each thread must obtain its own connection. ```java executor.submit(() -> { try (xMsgConnection con = actor.getConnection()) { xMsgMessage msg = createMessage(); xMsgMessage res = actor.syncPublish(con, msg, 10000); process(res); } catch (xMsgException | TimeoutException e) { e.printStacktrace(); } }); ``` ## Receiving responses When a message is sync-published, its metadata will be modified to contain a unique `replyTo` field. This value is generated by the actor for each sync-published message, and correspond to the topic that can be used by the subscription to publish a response message. The format of the `replyTo` topic is: `ret:<ID>:LDDDDDD`. The `<ID>` is the unique identifier of the actor, generated on the constructor. `L` is the language (1 for Java, 2 for C++, 3 for Python), and `DDDDDD` is a 6-digit serial number between 0 and 999999, different for each message. When 999999 is reached, it starts from 0 again. This unique `replyTo` value per message ensures that the response can be matched with the sync-publication call that published the request. In order to receive the response message, the actor must have a subscription to the proxy where the response will be published. To avoid creating a new subscription every time a sync message is sent, only a single subscription per proxy will be created, with topic: `ret:<ID>`. This subscription will be running on background because it will be reused to receive the responses of all sync-publication requests to that proxy: ```java if no response socket to address: create socket to address subscribe socket to "ret:<ID>" set reply topic to "ret:<ID>:<SEQ>" publish msg wait response ``` Since response messages are received in a different thread, a concurrent map is used to pass messages to the waiting threads that sync-published those requests, with the unique `replyTo` topic as the key: ```java ConcurrentMap<Topic, Message> responses ``` Waiting a response is just checking the map periodically for a message with topic equals to `replyTo`, until the map contains the expected message or timeout occurs. The actor may have multiple response subscriptions, to many proxies. Unlike *user-defined* subscriptions (each one on its own thread), only a single background **poller thread** checks response messages in all subscribed sockets: ```java while true: poll all sockets for each socket: if socket contains message put message on responses map ``` This poller thread is started on the xMsg constructor, but every socket is created and subscribed the first time a message is sync-published to a proxy. ## Publishing responses To reply sync-publication messages, the *user-defined* callback must explicitly support publication of responses. xMsg will not reply synchronous requests automatically. If the callback does not send a response, the actor doing the `syncPublish` call will timeout. A received message is a synchronous request if the `replyTo` metadata is set. To reply this message, the response must be published to the topic defined by the value of `replyTo`. The `xMsgMessage` class provides methods to quickly access this metatada field: ```java boolean hasReplyTopic() xMsgTopic getReplyTopic() ``` Finally, the response message shall be published to the same proxy used to start the subscription. The xMsg convention is to subscribe to the *default proxy*. If the wrong topic or proxy are used, the response will not be received. ```java xMsgConnection connection = actor.getConnection(); // to default proxy xMsgTopic topic = xMsgTopic.build("data", "power"); xMsgSubscription sub = actor.subscribe(connection, topic, msg -> { try { byte[] data = processMessage(msg); // check if message is a sync request if (msg.hasReplyTopic()) { xMsgTopic resTopic = msg.getReplyTopic(); xMsgMessage resMsg = new xMsgMessage(resTopic, "binary/data", data); // publish response to default proxy (the same of subscription) try (xMsgConnection resCon = actor.getConnection()) { actor.publish(resCon, resMsg); } } } catch (Exception e) { e.printStacktrace(); } }); ``` To quickly create response messages, for example, returning the same input data or data of primitive type, the following static methods are also provided: ```java xMsgMessage createResponse(xMsgMessage msg) xMsgMessage createResponse(xMsgMessage msg, Object data) ``` The response topic and mime-type will be set to the proper values.
Markdown
UTF-8
2,249
3.265625
3
[ "MIT" ]
permissive
# cordova-plugin-datecs-printer The first thing that you must know is that the plugin is available through this variable `window.DatecsPrinter`. So, there's a lot of functions that you can call to execute each operation and perform the printer actions, these are the most important ones (you can see all on [printer.js](www/printer.js) file): _(every function accept at least two parameters, and they're the last ones: onSuccess function and onError function)_ - listBluetoothDevices(): will give you a list of all the already previously paired bluetooth devices - connect(address): this will establish the bluetooth connection with the selected printer (you need pass the address `attribute` of the selected device) - feedPaper(lines): this will "print" blank lines - printText(text): will print the text respecting tags definition ```javascript window.DatecsPrinter.listBluetoothDevices( function (devices) { window.DatecsPrinter.connect(devices[0].address, printSomeTestText); }, function (error) { } ); function printSomeTestText() { window.DatecsPrinter.printText("Print Test!"); } ``` ### Tags definition - `{reset}` Reset to default settings. - `{br}` Line break. Equivalent of new line. - `{b}, {/b}` Set or clear bold font style. - `{u}, {/u}` Set or clear underline font style. - `{i}, {/i}` Set or clear italic font style. - `{s}, {/s}` Set or clear small font style. - `{h}, {/h}` Set or clear high font style. - `{w}, {/w}` Set or clear wide font style. - `{left}` Aligns text to the left paper edge. - `{center}` Aligns text to the center of paper. - `{right}` Aligns text to the right paper edge. ## ConnectionStatus Event To listen about the connection status this is the way you should go: You should use this plugin to receive the broadcasts `cordova plugin add cordova-plugin-broadcaster` ```javascript window.broadcaster.addEventListener( "DatecsPrinter.connectionStatus", function(e) { if (e.isConnected) { //do something } }); ``` ## Angular / Ionic If your intention is to use it with Angular or Ionic, you may take a look at this simple example: https://github.com/giorgiofellipe/cordova-plugin-datecsprinter-example. There's a ready to use angular service implementation.
Python
UTF-8
1,784
2.75
3
[]
no_license
import pytest from Spells.remembered_spells import * from Spells.spell_book import SpellBook class TestRememberedSpells: def test_init(self): sb = SpellBook() rs = RememberedSpells(sb) rs.remembered[0] = {} def test_added_spell(self): sb = SpellBook() sb.add_spell("Fireball", "Fireball_Desc", 3) rs = RememberedSpells(sb) rs.remember("Fireball") assert rs.remembered[3] == {"Fireball": { "Description": "Fireball_Desc", "level": 3, "Casting time": "1 standard action", "Range": "Long", "Area": "Touch", "Duration": "Instant", "Saving throw": "Reflex", "School": "Evocation", "Spell resistance": False }} def test_removed_spell(self): sb = SpellBook() sb.add_spell("Fireball", "Fireball_Desc", 3) rs = RememberedSpells(sb) rs.remember("Fireball") assert rs.remembered[3] == {"Fireball": { "Description": "Fireball_Desc", "level": 3, "Casting time": "1 standard action", "Range": "Long", "Area": "Touch", "Duration": "Instant", "Saving throw": "Reflex", "School": "Evocation", "Spell resistance": False }} rs.forget("Fireball") assert rs.remembered[3] == {} def test_incorrect_add(self): sb = SpellBook() rs = RememberedSpells(sb) with pytest.raises(SpellNotInSpellBook): rs.remember("Fireball") def test_incorrect_forget(self): sb = SpellBook() rs = RememberedSpells(sb) with pytest.raises(SpellNotRemembered): rs.forget("Fireball")
Swift
UTF-8
262
2.734375
3
[]
no_license
import UIKit import RxSwift import RxCocoa /* RxSwift Operators Scan */ // Scan let disposeBag = DisposeBag() let source = Observable.of(1,2,3,5,6) source.scan(0, accumulator: +) .subscribe(onNext: { print($0) }).disposed(by: disposeBag)
C++
UTF-8
989
2.859375
3
[]
no_license
//Equilibrium point #include <iostream> using namespace std; int main() { int t; cin>>t; while(t--) { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; if(n==1) { cout<<1<<endl; continue; } int leftSum[n]; leftSum[0]=arr[0]; for(int i=1;i<n;i++) { leftSum[i]=leftSum[i-1]+arr[i]; } int idx=-1; int rightSum=arr[n-1]; if(rightSum==leftSum[n-1]) { idx=n-1; cout<<idx<<endl; continue; } for(int i=n-2;i>=0;i--) { rightSum=rightSum+arr[i]; if(rightSum==leftSum[i]) { idx=i; break; } } } if(idx==-1) cout<<-1<<endl; else cout<<idx+1<<endl; } return 0; }
PHP
UTF-8
1,650
2.75
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Tale\Cache; use Psr\Cache\CacheItemInterface; abstract class AbstractPool implements PoolInterface { /** @var ItemInterface[] */ private $deferredItems = []; public function getItems(array $keys = []) { foreach ($keys as $key) { yield $this->getItem($key); } } public function hasItem($key): bool { return $this->getItem($key)->isHit(); } public function deleteItems(array $keys): bool { return array_reduce($keys, function ($success, $key) { return $success && $this->deleteItem($key); }, true); } public function saveDeferred(CacheItemInterface $item): bool { $this->filterItem($item); if (\in_array($item, $this->deferredItems, true)) { return false; } $this->deferredItems[] = $item; return true; } public function commit(): bool { $success = array_reduce($this->deferredItems, function ($success, $item) { return $success && $this->save($item); }, true); $this->deferredItems = []; return $success; } protected function filterItem(CacheItemInterface $item): ItemInterface { if (!($item instanceof ItemInterface)) { throw new \InvalidArgumentException(sprintf( 'Passed cache item needs to be instance of %s, you passed a PSR Cache Item. PSR Cache items '. 'are fixed to their own pool, Tale Cache items are not.', ItemInterface::class )); } return $item; } }
Markdown
UTF-8
1,050
3.09375
3
[]
no_license
# 起步 ## 起步 ### 系统要求 * PHP >= 5.3.0 如果你使用加密的cookie,`mcrypt`扩展是必要的。 ### Composer安装 安装composer在你的项目里: ``` curl -s https://getcomposer.org/installer | php ``` 在你项目的根目录创建一个`composer.json`文件: ``` { "require": { "slim/slim": "2.*" } } ``` 通过Composer安装: ``` php composer.phar install ``` 添加这一行到你的应用的`index.php`文件中: ``` <?php require 'vendor/autoload.php'; ``` ### 手动安装 在你的项目的目录下载和解压Slim框架,并且在你的项目的`index.php`中`require`它。 你仍然需要注册Slim的自动加载器。 ``` <?php require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); ``` ### Hello World 实例化一个Slim应用: ``` $app = new \Slim\Slim(); ``` 定义一个HTTP GET路由: ``` $app->get('/hello/:name', function ($name) { echo "Hello, $name"; }); ``` 运行Slim应用: ``` $app->run(); ```
Java
UTF-8
9,747
1.992188
2
[]
no_license
package collab.logic; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import collab.dal.ElementDao; import collab.dal.IdGenerator; import collab.dal.IdGeneratorDao; import collab.data.ElementEntity; import collab.rest.NotFoundException; import collab.rest.boundaries.ElementBoundary; import collab.rest.boundaries.ElementId; import collab.rest.boundaries.User; import collab.rest.boundaries.UserBoundary; import collab.rest.boundaries.UserId; @Service public class ElementServiceRdb implements AdvancedElementsService { private ElementDao elementDao; private ElementConverter elementConverter; private GeneralConverter converter; private Validator validator; private String domain; private UserServiceRdb userService; private IdGeneratorDao idGenerator; @Autowired public ElementServiceRdb(ElementDao elementDao, UserServiceRdb userService, ElementConverter elementConverter, GeneralConverter converter, Validator validator, IdGeneratorDao idGenerator) { super(); this.elementDao = elementDao; this.converter = converter; this.elementConverter = elementConverter; this.validator = validator; this.idGenerator = idGenerator; this.userService = userService; } @Value("${collab.config.domain:defaultDomain}") public void setDomain(String domain) { this.domain = domain; } @Override @Transactional public ElementBoundary create(String managerDomain, String managerEmail, ElementBoundary element) { if (this.validator.isManager(this.userService.getUserById(new UserId(managerDomain, managerEmail)))) element.setCreatedBy(new User(new UserId(managerDomain, managerEmail))); this.generateElementIdAndDate(element); if(!element.getType().equals("cartType")) element.getElementAttributes().put("inCart", false); return this.elementConverter.fromEntity(this.elementDao.save(this.elementConverter.toEntity(element))); } @Override @Transactional public ElementBoundary update(String managerDomain, String managerEmail, String elementDomain, String elementId, ElementBoundary update) { if (this.validator.isManager(this.userService.getUserById(new UserId(managerDomain, managerEmail)))) { ElementBoundary existingElement = this.getElementById(new ElementId(elementDomain, elementId)); if (update.getType() != null) existingElement.setType(update.getType()); if (update.getName() != null && !update.getName().isEmpty()) existingElement.setName(update.getName()); if (update.getActive() != null && !update.getActive().toString().isEmpty()) existingElement.setActive(update.getActive()); if (update.getElementAttributes() != null) existingElement.setElementAttributes(update.getElementAttributes()); if (update.getParentElement() != null) { this.getElementById(update.getParentElement().getElementId()); existingElement.setParentElement(update.getParentElement()); } return this.elementConverter .fromEntity(this.elementDao.save(this.elementConverter.toEntity(existingElement))); } return null; } @Override @Transactional(readOnly = true) public ElementBoundary getSpecificElement(String userDomain, String userEmail, String elementDomain, String elementId) { ElementBoundary element = this.getElementById(new ElementId(elementDomain, elementId)); UserBoundary user = this.userService.getUserById(new UserId(userDomain, userEmail)); if (!this.validator.isPlayer(user)) return this.getElementById(element.getElementId()); else if (this.validator.isPlayer(user) && element.getActive()) return this.getElementById(element.getElementId()); else throw new NotFoundException("Element doesn't exsist"); } @Override @Transactional(readOnly = true) public List<ElementBoundary> getAllElements(String userDomain, String userEmail) { Iterable<ElementEntity> iter = this.elementDao.findAll(); return StreamSupport.stream( // create a stream from the iterable returned iter.spliterator(), false).map(this.elementConverter::fromEntity).collect(Collectors.toList()); } @Override @Transactional(readOnly = true) public List<ElementBoundary> getAllElements(String userDomain, String userEmail, int size, int page) { UserBoundary user = this.userService.getUserById(new UserId(userDomain, userEmail)); if (this.validator.isPlayer(user)) { List<ElementEntity> iter = this.elementDao.findAllByActive(true, PageRequest.of(page, size, Direction.ASC, "elementId")); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } List<ElementEntity> iter = this.elementDao.findAll(PageRequest.of(page, size, Direction.ASC, "elementId")) .getContent(); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } @Override @Transactional(readOnly = true) public List<ElementBoundary> getAllElementsByName(String userDomain, String userEmail, String name, int size, int page) { UserBoundary user = this.userService.getUserById(new UserId(userDomain, userEmail)); if (this.validator.isPlayer(user)) { List<ElementEntity> iter = this.elementDao.findAllByActiveAndNameLike(true, name, PageRequest.of(page, size, Direction.ASC, "elementId")); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } return this.elementDao.findAllByNameLike(name, PageRequest.of(page, size, Direction.ASC, "elementId")).stream() .map(this.elementConverter::fromEntity).collect(Collectors.toList()); } @Override @Transactional(readOnly = true) public List<ElementBoundary> getAllElementsByType(String userDomain, String userEmail, String type, int size, int page) { UserBoundary user = this.userService.getUserById(new UserId(userDomain, userEmail)); if (this.validator.isPlayer(user)) { List<ElementEntity> iter = this.elementDao.findAllByActiveAndType(true, type, PageRequest.of(page, size, Direction.ASC, "elementId")); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } List<ElementEntity> iter = this.elementDao.findAllByType(type, PageRequest.of(page, size, Direction.ASC, "elementId")); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } @Override @Transactional(readOnly = true) public List<ElementBoundary> getAllElementsByParentElement(String userDomain, String userEmail, String parentDomain, String parentId, int size, int page) { ElementId elementId = new ElementId(parentDomain, parentId); UserBoundary user = this.userService.getUserById(new UserId(userDomain, userEmail)); if (this.validator.isPlayer(user)) { List<ElementEntity> iter = this.elementDao.findAllByActiveAndParentElement(true, this.elementConverter.toEntity(this.getElementById(elementId)), PageRequest.of(page, size, Direction.ASC, "elementId")); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } List<ElementEntity> iter = this.elementDao.findAllByParentElement( this.elementConverter.toEntity(this.getElementById(elementId)), PageRequest.of(page, size, Direction.ASC, "elementId")); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } @Override @Transactional(readOnly = true) public List<ElementBoundary> getAllElements() { Iterable<ElementEntity> iter = this.elementDao.findAll(); return StreamSupport.stream( // create a stream from the iterable returned iter.spliterator(), false).map(this.elementConverter::fromEntity).collect(Collectors.toList()); } @Override @Transactional public void deleteAll() { this.elementDao.deleteAll(); } private void generateElementIdAndDate(ElementBoundary element) { element.setCreatedTimestamp(new Date()); IdGenerator newGeneratedValue = this.idGenerator.save(new IdGenerator()); element.setElementId(new ElementId(this.domain, "" + newGeneratedValue.getNextId())); this.idGenerator.delete(newGeneratedValue); } public ElementBoundary getElementById(ElementId elementId) { return this.getElementByStringId(this.converter.toStringElementId(elementId)); } public ElementBoundary getElementByStringId(String stringElementId) { return this.elementConverter.fromEntity(this.elementDao.findById(stringElementId) .orElseThrow(() -> new NotFoundException("No element could be found with id: " + stringElementId))); } @Override public List<ElementBoundary> getAllElementsByTypeNot(String userDomain, String userEmail, String type, int size, int page) { UserBoundary user = this.userService.getUserById(new UserId(userDomain, userEmail)); if (this.validator.isPlayer(user)) { List<ElementEntity> iter = this.elementDao.findAllByActiveAndTypeNotLike(true, type, PageRequest.of(page, size, Direction.ASC, "elementId")); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } List<ElementEntity> iter = this.elementDao.findAllByTypeNotLike(type, PageRequest.of(page, size, Direction.ASC, "elementId")); return iter.stream().map(this.elementConverter::fromEntity).collect(Collectors.toList()); } }
C#
UTF-8
3,506
2.71875
3
[]
no_license
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using TacobellCustomerApi.Models; namespace TacobellCustomerApi.Repository { public class Customerrepo : ICustomerrepo { private readonly TacobellProjectContext _context; public Customerrepo() { } public Customerrepo(TacobellProjectContext context) { _context = context; } public IEnumerable<FoodDetails> getfooddetails() { return _context.FoodDetails.ToList(); } public IEnumerable<OrderDetails> getOrdereddetails() { return _context.OrderDetails.ToList(); } public IEnumerable<FoodandNutrition> getnutritiondetails() { List<FoodDetails> foods = _context.FoodDetails.ToList(); List<FoodandNutrition> foodandNutritions = new List<FoodandNutrition>(); foreach (var item in _context.Nutrition) { FoodDetails foodDetail = new FoodDetails(); foodDetail = foods.FirstOrDefault(f => f.FoodId == item.FoodId); if (foodDetail != null) { foodandNutritions.Add(new FoodandNutrition { NutritionId = item.NuytritionId, FoodName = foodDetail.FoodName, WeightInGrams = item.WeightInGrams, Protein = item.Protein, Calories = item.Calories, Totalsugar = item.Totalsugar, Sodium = item.Sodium, Grain = item.Grain, FruitorVegetable = item.FruitorVegetable, Dairy = item.Dairy, ProteinClassification = item.ProteinClassification }); } } return foodandNutritions; } public async Task<OrderDetails> AddOrderDetails(OrderDetails item) { OrderDetails fr = null; if (item == null) { throw new NullReferenceException(); } else { fr = new OrderDetails() {OrderId= item.OrderId, FoodId = item.FoodId, RegisterId = item.RegisterId, Address = item.Address, OrderStatus = item.OrderStatus }; int id = _context.OrderDetails.Max(x => x.OrderId); fr.OrderId = id + 1; await _context.OrderDetails.AddAsync(fr); await _context.SaveChangesAsync(); } return fr; } public async Task<FoodDetails> UpdateQuantity(FoodDetails item, int id) { FoodDetails fr = await _context.FoodDetails.FindAsync(id); fr.Quantity = item.Quantity; fr.Price = item.Price; fr.TotalPrice = fr.Price * fr.Quantity; await _context.SaveChangesAsync(); return fr; } public OrderDetails IsAlreadyOrdered(int foodId, int regId) { OrderDetails orderDetails = _context.OrderDetails.FirstOrDefault(or => or.FoodId == foodId && or.RegisterId == regId); return orderDetails; } } }
C#
UTF-8
610
2.75
3
[]
no_license
using System.IO; using System.Web; namespace DataLayer { public class ProdutoImagem { private readonly int _id; public ProdutoImagem(int id) { _id = id; } public int ID => _id; public string Imagem80 => Imagem("80"); public string Imagem200 => Imagem("200"); private string Imagem(string size) { var absolutePath = $"{HttpRuntime.AppDomainAppPath}/Images/Products/{ID:000}x{size}x{size}.jpg"; var id = File.Exists(absolutePath) ? ID : 0; return $"{id:000}x{size}x{size}.jpg"; } } }
PHP
UTF-8
7,033
3.03125
3
[]
no_license
<?php namespace Tet\Database; use Tet\Common\CodeGenerator; use Tet\Filesystem\Filesystem; use Tet\Database\Table; use Tet\Database\ColumnDef; use Tet\Database\TableCollection; class DatabaseScheme { function createCode($structure, $destination = "./", $namespace = ""): bool { $dbname = $structure["name"]; $tables = $structure["tables"]; $this->createDirectoryStructure("$destination", "$dbname"); if ($namespace != "") $namespace = $namespace . "\\"; $this->createDatabaseClass($destination, $namespace, $dbname, $tables); $tables->forEach(function ($tablename, Table $table) use ($destination, $namespace, $dbname) { $this->createTableClass($destination, $namespace, $dbname, $table); $this->createRowClass($destination, $namespace, $dbname, $table); $this->createRowCollectionClass($destination, $namespace, $dbname, $table); return true; }); return true; } private function createDirectoryStructure(string $destination, string $dbname):bool { (new Filesystem)->createDirectory("$destination/$dbname"); (new Filesystem)->createDirectory("$destination/$dbname/Tables"); (new Filesystem)->createDirectory("$destination/$dbname/RowCollections"); return true; } private function createDatabaseClass(string $destination, $namespace, string $dbname, TableCollection $tables): bool { $cg = new CodeGenerator(); $cg->open("$destination/$dbname/$dbname.php"); $cg->startTag(); $cg->line(""); $cg->line("namespace $namespace$dbname;"); $cg->line(""); $cg->line("use Tet\Database\MySQL;"); $cg->line(""); $tables->forEach(function ($key, Table $table) use ($cg, $namespace, $dbname) { $cg->line("use $namespace$dbname\Tables\\" . $table->getName() . ";"); }); $cg->line(""); $cg->line("class $dbname"); $cg->line("{"); $tables->forEach(function ($key, Table $table) use ($cg) { $cg->line("public {$table->getName()} \${$table->getName()};", 1); }); $cg->line(""); $cg->line("function __construct(MySQL \$mySQL)", 1); $cg->line("{", 1); $tables->forEach(function ($key, Table $table) use ($cg) { $cg->line("\$this->{$table->getName()} = new {$table->getName()}(\$mySQL);", 2); }); $cg->line("}", 1); $cg->line("}"); $cg->close(); return true; } private function createRowClass(string $destination, $namespace, $dbname, Table $table): bool { (new Filesystem)->createDirectory("$destination/$dbname/Rows"); $tablename = $table->getName(); $cg = new CodeGenerator(); $cg->open("$destination/$dbname/Rows/$tablename.php"); $cg->startTag(); $cg->line(""); $cg->line("namespace $namespace$dbname\Rows;"); $cg->line(""); $cg->line("class {$tablename}"); $cg->line("{"); $table->getColumnsInfo()->forEach(function ($columnname, ColumnDef $column) use ($cg) { $propName = str_replace('-', "_tet_minus_", $column->getName()); $cg->line("public \$$propName;", 1); }); $cg->line(""); $cg->line("function __construct(\$row)", 1); $cg->line("{", 1); $cg->line("foreach (\$row as \$column_name => \$column_value) {", 2); $cg->line("\$this->\$column_name = \$column_value;", 3); $cg->line("}", 2); $cg->line("}", 1); $cg->line("}"); $cg->close(); return true; } private function createRowCollectionClass(string $destination, $namespace, $dbname, Table $table): bool { $tablename = $table->getName(); $cg = new CodeGenerator(); $cg->open("$destination/$dbname/RowCollections/$tablename.php"); $cg->startTag(); $cg->line(""); $cg->line("namespace $namespace$dbname\RowCollections;"); $cg->line(""); $cg->line("use Tet\Common\CollectionReadOnly;"); $cg->line("use {$namespace}$dbname\Rows\\$tablename as {$tablename}_row;"); $cg->line(""); $cg->line("class $tablename extends CollectionReadOnly"); $cg->line("{"); $cg->line("function get(string \$name):{$tablename}_row", 1); $cg->line("{", 1); //$cg->line("return \$this->values[\$name];", 2); $cg->line("return new {$tablename}_row(\$this->values[\$name]);", 2); $cg->line("}", 1); $cg->line("}"); $cg->close(); return true; } private function createTableClass(string $destination, $namespace, $dbname, Table $table): bool { $tablename = $table->getName(); $cg = new CodeGenerator(); $cg->open("$destination/$dbname/Tables/$tablename.php"); $cg->startTag(); $cg->line(""); $cg->line("namespace $namespace$dbname\Tables;"); $cg->line(""); $cg->line("use Tet\Database\TableEntity;"); $cg->line("use Tet\Database\MySQL;"); $cg->line("use {$namespace}$dbname\Rows\\$tablename as {$tablename}_row;"); $cg->line("use {$namespace}$dbname\RowCollections\\$tablename as {$tablename}_row_collection;"); $cg->line(""); $cg->line("class $tablename extends TableEntity"); $cg->line("{"); $cg->line("public static string \$tablename = '$tablename';", 1); $cg->line("public static MySQL \$mySQL;", 1); $cg->line(""); $cg->line("const TABLE_NAME = '{$tablename}';", 1); $table_column_list = $table->getColumnsInfo()->toArray(); $table->getColumnsInfo()->forEach(function ($columnname, ColumnDef $column) use ($cg) { $propName = "COLNAME_" . str_replace('-', "_TET_MINUS_", $column->getName()); $propName = strtoupper($propName); $cg->line("const {$propName} = '{$column->getName()}';", 1); }); foreach ($table_column_list as $value) { } $cg->line(""); $cg->line("function __construct(MySQL \$mySQL)", 1); $cg->line("{", 1); $cg->line("\$this::\$mySQL = \$mySQL;", 2); $cg->line("}", 1); $cg->line(""); $cg->line("private function getRowsArray(\$rows): array", 1); $cg->line("{", 1); $cg->line("\$result = [];", 2); $cg->line("foreach (\$rows as \$row) \$result[] = new {$tablename}_row(\$row);", 2); $cg->line("return \$result;", 2); $cg->line("}", 1); $cg->line(""); $cg->line("function getRows(): ?{$tablename}_row_collection", 1); $cg->line("{", 1); $cg->line("\$tmp = \$this->execute();", 2); $cg->line("\$tmp = \$this->getRowsArray(\$tmp);", 2); $cg->line("return new {$tablename}_row_collection(\$tmp);", 2); $cg->line("}", 1); $cg->line("}"); $cg->close(); return true; } }
Python
UTF-8
2,504
2.609375
3
[]
no_license
# Successful Proton Transfer # O2 and O38 – snapshot 230 – 530 (PT at snap. 380 in centroid data) # O2 and O38 – snapshot 3310 – 3610 (PT at snap. 3460 in centroid data) # O38 and O16 – snapshot 20515 – 20815 (PT at snap. 20665 in centroid data) # O38 and O16 – snapshot 24140– 24440 (PT at snap. 24290 in centroid data) # O16 and O21 – snapshot 36018 – 36318 (PT at snap. 36168 in centroid data) # O16 and O21 – snapshot 37009 – 37309 (PT at snap. 37159 in centroid data) # O21 and O5 – snapshot 41271 – 41571 (PT at snap. 41421 in centroid data) # O21 and O5 – snapshot 43563 – 43863 (PT at snap. 43713 in centroid data) # input package import sys sys.path.append('/home/yunfeng/Downloads/2018/Clark_project/Python_Code/') import pandas as pd import numpy as np import matplotlib.pyplot as plt from plot_persistent_barcode import * from numpy.linalg import norm from generate_rv_complex import * from average_accumulated_distance import * import os # constant windowsize = 10 # set path inputPath = '/home/yunfeng/Downloads/2018/Clark_project/raw_data_csv/' outputPath = '/home/yunfeng/Downloads/2018/Clark_project/Report_20180205/' os.chdir(outputPath) # load data df = pd.read_csv(inputPath + '32rep-H4.csv') targetSnapshots = [380, 3460, 20665, 24290, 36168, 37159, 41421, 43713] # calculate AAD for targetsnapshot in targetSnapshots: average_accumulated_distances = [] windowSnapshots = [i for i in range(targetsnapshot-windowsize, targetsnapshot + windowsize)] for snapshot in windowSnapshots: dfTempt = df[df['Snapshot'] == snapshot] points = np.array(dfTempt.iloc[:,2:5]) rips, m, dgms = generate_rv_complex(points, 3) snapshotDistance = average_accumulated_distance(dgms, [0,1,2]) average_accumulated_distances.append(snapshotDistance) # plot result fig, axs = plt.subplots(4,1, sharex = True, figsize=(16, 8), dpi=80) axs = axs.ravel() for i in range(4): if i == 3: AAD = [average_accumulated_distances[j][0] + average_accumulated_distances[j][1] for j in range(len(average_accumulated_distances))] else: AAD = [average_accumulated_distances[j][i] for j in range(len(average_accumulated_distances))] axs[0].set_title('Snapshot ' +str(targetsnapshot) +'_Average Accumulated Distance for H0, H1, H2 and H0,H1 & H2') axs[i].plot(windowSnapshots, AAD, 'g-') axs[i].axvline(x=targetsnapshot) plt.savefig('snapshot_' +str(targetsnapshot)+' average_accumulated_distances_' + 'step' + str(windowsize)+'.png')
Java
UTF-8
14,976
2.25
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nz.co.lolnet.james137137.dezsteamingserveraccess; import com.myjeeva.digitalocean.common.ActionStatus; import com.myjeeva.digitalocean.exception.DigitalOceanException; import com.myjeeva.digitalocean.exception.RequestUnsuccessfulException; import com.myjeeva.digitalocean.pojo.Action; import com.myjeeva.digitalocean.pojo.Droplet; import com.myjeeva.digitalocean.pojo.Droplets; import com.myjeeva.digitalocean.pojo.Image; import com.myjeeva.digitalocean.pojo.Images; import com.myjeeva.digitalocean.pojo.Region; import com.myjeeva.digitalocean.pojo.Snapshot; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; /** * * @author James */ public class MyAPIMethods { public static List<String> getServerInfo() throws MalformedURLException, IOException { URL oracle = new URL("http://" + Main.domainName + "/computerInfo.txt"); List<String> serverInfo = new ArrayList<>(); BufferedReader in = new BufferedReader( new InputStreamReader(oracle.openStream())); String inputLine; String freeMemory = null; String totalMemory = null; boolean memoryDone = false; boolean internetDone = false; String data = null; int line = 1; while ((inputLine = in.readLine()) != null) { if (line == 1) { serverInfo.add("CPU:" + "\t" + inputLine + "%"); } else if (line == 3) { int count = 1; for (String arg : inputLine.split(" ")) { if (!arg.equals("")) { if (count == 2) { totalMemory = arg; } count++; } } } else if (line == 4) { int count = 1; for (String arg : inputLine.split(" ")) { if (!arg.equals("")) { if (count == 4) { freeMemory = arg; } count++; } } } else if (line == 9) { int count = 1; for (String arg : inputLine.split(" ")) { if (!arg.equals("")) { if (count == 9) { data = arg; } else if (count == 10) { data += " " + arg; } count++; } } } if (data != null && !internetDone) { serverInfo.add("internet usage: " + data); internetDone = true; } if (totalMemory != null && freeMemory != null && !memoryDone) { int memoryFreeP = 100 - (int) (Double.parseDouble(freeMemory) * 100 / Double.parseDouble(totalMemory)); serverInfo.add("Memory:" + "\t" + memoryFreeP + "%"); memoryDone = true; } line++; } in.close(); return serverInfo; } public static void serverInfo() throws DigitalOceanException, RequestUnsuccessfulException { System.out.println("Your current server info:"); Droplets availableDroplets = Main.apiClient.getAvailableDroplets(1); System.out.println("Your have " + availableDroplets.getDroplets().size() + " number of droplets"); List<Droplet> droplets = availableDroplets.getDroplets(); for (Droplet droplet : droplets) { String stat1; if (!droplet.isOff()) { stat1 = "online"; } else { stat1 = "offline"; } System.out.println(droplet.getId() + "-" + droplet.getName() + " is currently " + stat1 + " & " + droplet.getStatus()); } System.out.println(""); } public static boolean SimplePing() { try { return java.net.InetAddress.getByName(Main.domainName).isReachable(5000); } catch (Exception ex) { return false; } } public static boolean serverExist(String ServerName) throws DigitalOceanException, RequestUnsuccessfulException { List<Droplet> droplets = Main.apiClient.getAvailableDroplets(0).getDroplets(); for (Droplet droplet : droplets) { if (droplet.getName().equals(Main.serverName)) { return true; } } return false; } public static void destoryServer(String serverName, ActionEvent event) throws DigitalOceanException, RequestUnsuccessfulException { System.out.println("Removing Server: " + serverName); if (event != null) { ((JButton) event.getSource()).setText("Stoping Server"); } List<Droplet> droplets = Main.apiClient.getAvailableDroplets(0).getDroplets(); for (Droplet droplet : droplets) { if (droplet.getName().equals(serverName)) { if (MainGUI.saveOnStop.getState()) { CreateSnapshot(droplet); } Main.apiClient.deleteDroplet(droplet.getId()); System.out.println("Removed"); } } int i = 0; while (serverExist(serverName)) { if (i == 0 && event != null) { ((JButton) event.getSource()).setText("deleting Server."); } else if (i == 1 && event != null) { ((JButton) event.getSource()).setText("deleting Server.."); } else if (i == 2 && event != null) { ((JButton) event.getSource()).setText("deleting Server..."); } else if (event != null) { ((JButton) event.getSource()).setText("deleting Server"); i = 0; } i++; try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } help(); MainGUI.busy = false; } public static boolean checkClient() { try { Main.apiClient.getAccountInfo(); } catch (DigitalOceanException | RequestUnsuccessfulException ex) { return false; } System.out.println("Connected, API key is correct."); return true; } public static void wellcomeMessage() { System.out.println("Welcome Dez!"); } public static void CreateServer(String serverName, ActionEvent event) throws DigitalOceanException, RequestUnsuccessfulException { int i = 0; System.out.println("Creating Server: " + serverName); System.out.println("Please wait"); ((JButton) event.getSource()).setText("Creating Server."); Droplet newDroplet = new Droplet(); newDroplet.setName(serverName); newDroplet.setSize("512mb"); newDroplet.setRegion(new Region("sfo1")); newDroplet.setImage(new Image(Main.imageId)); newDroplet.setEnableBackup(Boolean.FALSE); newDroplet.setEnableIpv6(Boolean.FALSE); newDroplet.setEnablePrivateNetworking(Boolean.FALSE); Droplet droplet = Main.apiClient.createDroplet(newDroplet); boolean stop = false; ((JButton) event.getSource()).setText("Server Created."); ((JButton) event.getSource()).setText("Preparing server"); try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Created Server."); System.out.println("Waiting for server to be ready to reboot."); System.out.print("Please wait"); while (Main.apiClient.getDropletInfo(droplet.getId()).isNew()) { System.out.print("."); if (i == 0) { ((JButton) event.getSource()).setText("Preparing server."); } else if (i == 1) { ((JButton) event.getSource()).setText("Preparing server.."); } else if (i == 2) { ((JButton) event.getSource()).setText("Preparing server..."); } else { ((JButton) event.getSource()).setText("Preparing server"); i = 0; } i++; try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println(""); while (!stop) { try { Thread.sleep(10 * 1000); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } try { Main.apiClient.rebootDroplet(droplet.getId()); stop = true; System.out.println("rebooted."); ((JButton) event.getSource()).setText("Server Booting up."); } catch (Exception e) { stop = false; System.out.println("failed to reboot"); ((JButton) event.getSource()).setText("Failed to Boot server up."); } } try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } ((JButton) event.getSource()).setText("Pinging server"); System.out.println("Waiting for domain to be reachable..."); System.out.print("Please wait"); while (!SimplePing()) { System.out.print("."); if (i == 0) { ((JButton) event.getSource()).setText("Pinging server."); } else if (i == 1) { ((JButton) event.getSource()).setText("Pinging server.."); } else if (i == 2) { ((JButton) event.getSource()).setText("Pinging server..."); ; } else { ((JButton) event.getSource()).setText("Pinging server"); i = 0; } i++; } System.out.println(""); ((JButton) event.getSource()).setText("Server Ready"); try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } ((JButton) event.getSource()).setText("Stop Server"); MainGUI.busy = false; System.out.println("Server is ready for streaming."); serverInfo(); } public static void help() { System.out.println("Your commands are:"); System.out.println("Create"); System.out.println("Destory"); System.out.println("serverInfo"); System.out.println("changeapikey"); System.out.println("changesnapshot"); System.out.println("help"); System.out.println("exit"); } static String[] getSnapshotList() { List<String> list = new ArrayList<>(); list.add(Main.imageId + " - Current"); try { for (Image image : Main.apiClient.getUserImages(0).getImages()) { list.add(image.getId() + " - " + image.getName() + " - " + image.getCreatedDate()); } } catch (DigitalOceanException ex) { Logger.getLogger(MyAPIMethods.class.getName()).log(Level.SEVERE, null, ex); } catch (RequestUnsuccessfulException ex) { Logger.getLogger(MyAPIMethods.class.getName()).log(Level.SEVERE, null, ex); } return (String[]) list.toArray(new String[list.size()]); } static void changeSnapshotID(int newID) { Preferences userNodeForPackage = java.util.prefs.Preferences.userRoot(); Main.imageId = newID; userNodeForPackage.put("streamdigitaloceanimageid", "" + Main.imageId); } public static boolean changeAPIKey() { Preferences userNodeForPackage = java.util.prefs.Preferences.userRoot(); JTextField field1 = new JTextField(userNodeForPackage.get("streamdigitaloceanapikey", "")); JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(field1); int result = JOptionPane.showConfirmDialog(null, panel, "Set API key", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { if (field1.getText().length() >= 20) { userNodeForPackage.put("streamdigitaloceanapikey", field1.getText()); } return true; } return false; } private static void CreateSnapshot(Droplet droplet) throws DigitalOceanException, RequestUnsuccessfulException { Main.apiClient.shutdownDroplet(droplet.getId()); boolean saved = false; Action takeDropletSnapshot = null; String snapshotName = Main.serverName + "-AutoSave-" + System.currentTimeMillis(); while (!saved) { try { takeDropletSnapshot = Main.apiClient.takeDropletSnapshot(droplet.getId(), snapshotName); System.out.println("Request Snapshot"); saved = true; } catch (Exception e) { System.out.println("Failed to request to save server"); e.printStackTrace(); } try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } boolean snapshotCreated = false; while (!snapshotCreated) { for (Image image : Main.apiClient.getUserImages(0).getImages()) { System.out.print(image.getName() + ", "); if (image.getName().equalsIgnoreCase(snapshotName)) { changeSnapshotID(image.getId()); snapshotCreated = true; } } System.out.println(); try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } } }
JavaScript
UTF-8
214
2.859375
3
[]
no_license
/** * Created by Andre on 3/8/2018. */ module.exports = function repeatStringNumTimes(str, num) { // repeat after me if (num > 0){ return str.repeat(num); } else { return ""; } };
Shell
UTF-8
459
3
3
[ "MIT" ]
permissive
#!/bin/bash envtypes=('CTL2010' 'C285' 'AF1855') runtype='PROD' chunk='s0' if [ $runtype == 'PROD' ];then runstr='' pad='' else pad=' ' fi for envtype in ${envtypes[@]}; do echo "submitting "$envtype"_"$runstr$pad$chunk" ...." bash make_config.sh $envtype $runtype $chunk cfile="PPEn11/configs/"$envtype"_"$runstr$pad$chunk".config" lfile="logfiles/"$envtype"_"$runstr$pad$chunk".log" bash run_ens.sh $cfile > $lfile done
Java
UTF-8
1,016
2.5
2
[ "Apache-2.0" ]
permissive
package model; public class InputInfo { private String hash; private Account account; private Account srcAcc; private Account firstLevel; private Account secondLevel; private Account threeLevel; public void setHash(String hash){ this.hash = hash; } public String getHash(){ return hash; } public void setOutputAccount(Account account){ this.account = account; } public Account getOutputAccount(){ return account; } public void setSrcAcc(Account srcAcc){ this.srcAcc = srcAcc; } public Account getSrcAcc(){ return srcAcc; } public void setFirstLevel(Account account){ this.firstLevel = account; } public Account getFirstLevel(){ return firstLevel; } public void setSecondLevel(Account account){ this.secondLevel = account; } public Account getSecondLevel(){ return secondLevel; } public void setThreeLevel(Account account){ this.threeLevel = account; } public Account getThreeLevel(){ return threeLevel; } }
Python
UTF-8
1,006
3.953125
4
[]
no_license
def binary_search(array, left, right, key): if len(array) == 0: return False mid_index = (left + right) // 2 if array[mid_index] == key: return mid_index if array[mid_index] > key: # subtract one from midpoint since we've already evaluated the element that index right = mid_index - 1 return binary_search(array, left, right, key) else: # and add index here left = mid_index + 1 return binary_search(array, left, right, key) # test case array = [6, 13, 14, 25, 33, 43, 51, 53, 64, 72, 84, 93, 95, 96, 97]; print binary_search(array, 0, len(array) - 1, 43); def binary_search_non_recursive(array, key): total = 0 if len(array) == 0: return start = 0 end = len(array) while (start != end): midpoint = (start + end) // 2 if key == array[midpoint]: return midpoint elif key <= array[midpoint]: end = midpoint else: start = midpoint else: return "not found" print binary_search_non_recursive(array, 97);
TypeScript
UTF-8
1,429
2.5625
3
[ "MIT" ]
permissive
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, InjectionToken, Input} from '@angular/core'; let nextUniqueId = 0; /** * Injection token that can be used to reference instances of `MatHint`. It serves as * alternative token to the actual `MatHint` class which could cause unnecessary * retention of the class and its directive metadata. * * *Note*: This is not part of the public API as the MDC-based form-field will not * need a lightweight token for `MatHint` and we want to reduce breaking changes. */ export const _MAT_HINT = new InjectionToken<MatHint>('MatHint'); /** Hint text to be shown underneath the form field control. */ @Directive({ selector: 'mat-hint', host: { 'class': 'mat-hint', '[class.mat-form-field-hint-end]': 'align === "end"', '[attr.id]': 'id', // Remove align attribute to prevent it from interfering with layout. '[attr.align]': 'null', }, providers: [{provide: _MAT_HINT, useExisting: MatHint}], }) export class MatHint { /** Whether to align the hint label at the start or end of the line. */ @Input() align: 'start' | 'end' = 'start'; /** Unique ID for the hint. Used for the aria-describedby on the form field control. */ @Input() id: string = `mat-hint-${nextUniqueId++}`; }
C
UTF-8
2,244
2.859375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 #include"comment_convert.h" void comment_convert(FILE* pfwrite,FILE* pfread) { enum STATE state = NUL_STATE; while(state != END_STATE) { switch(state) { case NUL_STATE: DO_NULL_STATE(pfwrite,pfread,&state); break; case C_STATE: DO_C_STATE(pfwrite,pfread,&state); break; case CPP_STATE: DO_CPP_STATE(pfwrite,pfread,&state); break; case END_STATE: break; default: break; } } } void DO_NULL_STATE(FILE* pfwrite,FILE* pfread,enum STATE *state) { int first = 0; int second = 0; first = fgetc(pfread); switch(first) { case '/': { second = fgetc(pfread); switch(second) { case '/': { fputc(first,pfwrite); fputc(second,pfwrite); *state = CPP_STATE; } break; case '*': { fputc('/',pfwrite); fputc('/',pfwrite); *state = C_STATE; } break; default: fputc(first,pfwrite); fputc(second,pfwrite); break; } } break; /*case '\n': fputc('\n',pfwrite); break;*/ case EOF: *state = END_STATE; break; default: fputc(first,pfwrite); break; } } void DO_C_STATE(FILE* pfwrite,FILE* pfread,enum STATE *state) { int first = 0; int second = 0; int third = 0; first = fgetc(pfread); switch(first) { case '*': second = fgetc(pfread); switch(second) { case '/': { third = fgetc(pfread); if(third=='\n') fputc('\n',pfwrite); else fputc('\n',pfwrite); *state = NUL_STATE; } break; case '*': { third = fgetc(pfread); fputc(first,pfwrite); if(third=='/') *state = NUL_STATE; } break; default: fputc(first,pfwrite); fputc(second,pfwrite); break; } break; case '\n': fputc('\n',pfwrite); fputc('/',pfwrite); fputc('/',pfwrite); break; case EOF: *state = END_STATE; break; default: fputc(first,pfwrite); break; } } void DO_CPP_STATE(FILE* pfwrite,FILE* pfread,enum STATE *state) { int first = 0; first = fgetc(pfread); switch(first) { case '\n': { fputc('\n',pfwrite); *state = NUL_STATE; } break; case EOF: *state = END_STATE; break; default: fputc(first,pfwrite); } }
Rust
UTF-8
2,441
3.328125
3
[]
no_license
mod event; mod expr; mod marker; mod sink; mod source; use crate::lexer::{Token, Lexer, SyntaxKind}; use crate::syntax::SyntaxNode; use event::Event; use expr::expr; use marker::Marker; use rowan::GreenNode; use sink::Sink; use source::Source; pub fn parse(input: &str) -> Parse { let tokens: Vec<_> = Lexer::new(input).collect(); let parser = Parser::new(&tokens); let events = parser.parse(); let sink = Sink::new(&tokens, events); Parse { green_node: sink.finish(), } } struct Parser<'l, 'input> { source: Source<'l, 'input>, events: Vec<Event>, } impl<'l, 'input> Parser<'l, 'input> { fn new(tokens: &'l [Token<'input>]) -> Self { Self { source: Source::new(tokens), events: Vec::new(), } } fn parse(mut self) -> Vec<Event> { let m = self.start(); expr(&mut self); m.complete(&mut self, SyntaxKind::Root); self.events } fn start(&mut self) -> Marker { let pos = self.events.len(); self.events.push(Event::Placeholder); Marker::new(pos) } fn bump(&mut self) { self.source.next_token().unwrap(); self.events.push(Event::AddToken); } fn peek(&mut self) -> Option<SyntaxKind> { self.source.peek_kind() } fn at(&mut self, kind: SyntaxKind) -> bool { self.peek() == Some(kind) } } pub struct Parse { green_node: GreenNode, } impl Parse { pub fn debug_tree(&self) -> String { let syntax_node = SyntaxNode::new_root(self.green_node.clone()); let formatted = format!("{:#?}", syntax_node); // We cut off the last byte because formatting the SyntaxNode adds on a newline at the end. formatted[0..formatted.len() - 1].to_string() } } #[cfg(test)] fn check(input: &str, expected_tree: expect_test::Expect) { let parse = parse(input); expected_tree.assert_eq(&parse.debug_tree()); } #[cfg(test)] mod tests { use super::*; use expect_test::expect; #[test] fn parse_nothing() { check("", expect![[r#"Root@0..0"#]]); } #[test] fn parse_whitespace() { check( " ", expect![[r#" Root@0..3 Whitespace@0..3 " ""#]], ); } #[test] fn parse_comment() { check( "# hello!", expect![[r##" Root@0..8 Comment@0..8 "# hello!""##]], ); } }
C
UTF-8
498
3.359375
3
[]
no_license
// // main.c // getchar-putchar // // Created by Александр Ерыгин on 22.11.15. // Copyright © 2015 Alex Erygin. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { char c; while((c = getchar()) != EOF){ if(c == '\t'){ printf("\\t"); } else if(c == '\b'){ printf("\\b"); } else if(c == '/'){ printf("\\"); } else{ putchar(c); } } return 0; }
PHP
UTF-8
5,030
2.703125
3
[ "Unlicense" ]
permissive
<?php namespace Jeely\TL\Types; use Jeely\LazyUpdates; /** * @class InlineQueryResultLocation * @description Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location. * * @method string getType() Type of the result, must be location * @method string getId() Unique identifier for this result, 1-64 Bytes * @method float getLatitude() Location latitude in degrees * @method float getLongitude() Location longitude in degrees * @method string getTitle() Location title * @method float getHorizontalAccuracy() Optional. The radius of uncertainty for the location, measured in meters; * 0-1500 * @method int getLivePeriod() Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. * @method int getHeading() Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. * @method int getProximityAlertRadius() Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. * @method InlineKeyboardMarkup getReplyMarkup() Optional. Inline keyboard attached to the message * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the location * @method string getThumbUrl() Optional. Url of the thumbnail for the result * @method int getThumbWidth() Optional. Thumbnail width * @method int getThumbHeight() Optional. Thumbnail height * * @method bool isType() * @method bool isId() * @method bool isLatitude() * @method bool isLongitude() * @method bool isTitle() * @method bool isHorizontalAccuracy() * @method bool isLivePeriod() * @method bool isHeading() * @method bool isProximityAlertRadius() * @method bool isReplyMarkup() * @method bool isInputMessageContent() * @method bool isThumbUrl() * @method bool isThumbWidth() * @method bool isThumbHeight() * * @method $this setType() * @method $this setId() * @method $this setLatitude() * @method $this setLongitude() * @method $this setTitle() * @method $this setHorizontalAccuracy() * @method $this setLivePeriod() * @method $this setHeading() * @method $this setProximityAlertRadius() * @method $this setReplyMarkup() * @method $this setInputMessageContent() * @method $this setThumbUrl() * @method $this setThumbWidth() * @method $this setThumbHeight() * * @method $this unsetType() * @method $this unsetId() * @method $this unsetLatitude() * @method $this unsetLongitude() * @method $this unsetTitle() * @method $this unsetHorizontalAccuracy() * @method $this unsetLivePeriod() * @method $this unsetHeading() * @method $this unsetProximityAlertRadius() * @method $this unsetReplyMarkup() * @method $this unsetInputMessageContent() * @method $this unsetThumbUrl() * @method $this unsetThumbWidth() * @method $this unsetThumbHeight() * * @property string $type Type of the result, must be location * @property string $id Unique identifier for this result, 1-64 Bytes * @property float $latitude Location latitude in degrees * @property float $longitude Location longitude in degrees * @property string $title Location title * @property float $horizontal_accuracy Optional. The radius of uncertainty for the location, measured in meters; 0-1500 * @property int $live_period Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. * @property int $heading Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. * @property int $proximity_alert_radius Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. * @property InlineKeyboardMarkup $reply_markup Optional. Inline keyboard attached to the message * @property InputMessageContent $input_message_content Optional. Content of the message to be sent instead of the location * @property string $thumb_url Optional. Url of the thumbnail for the result * @property int $thumb_width Optional. Thumbnail width * @property int $thumb_height Optional. Thumbnail height * * @see https://core.telegram.org/bots/api#inlinequeryresultlocation */ class InlineQueryResultLocation extends LazyUpdates { const JSON_PROPERTY_MAP = [ 'type' => 'string', 'id' => 'string', 'latitude' => 'float', 'longitude' => 'float', 'title' => 'string', 'horizontal_accuracy' => 'float', 'live_period' => 'int', 'heading' => 'int', 'proximity_alert_radius' => 'int', 'reply_markup' => 'InlineKeyboardMarkup', 'input_message_content' => 'InputMessageContent', 'thumb_url' => 'string', 'thumb_width' => 'int', 'thumb_height' => 'int', ]; }
Java
UTF-8
335
2.4375
2
[]
no_license
package state_pattern; /** 关机状态 * Created by Niwa on 2017/8/20. */ public class PowerOffState implements TvState{ @Override public void nextChannel() { } @Override public void prevChannel() { } @Override public void turnUp() { } @Override public void turnDown() { } }
Java
UTF-8
1,534
3.1875
3
[]
no_license
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; public class StackQueue42586Stack { public static void main(String[] args) { StackQueue42586Stack T = new StackQueue42586Stack(); int[] progresses = {93, 30, 55}; int[] speeds = {1, 30, 5}; // int[] progresses = {95, 90, 99, 99, 80, 99}; // int[] speeds = {1, 1, 1, 1, 1, 1}; int[] result = T.solution(progresses, speeds); System.out.println(Arrays.toString(result)); } public int[] solution(int[] progresses, int[] speeds) { List<Integer> result = new ArrayList<Integer>(); Stack<Integer> stack = new Stack<>(); int count = 0; for(int i = 0; i < progresses.length; i++) { int days = (100 - progresses[i]) / speeds[i]; if((100 - progresses[i]) % speeds[i] != 0) { days++; } if(!stack.isEmpty()) { count++; if(stack.peek() < days) { stack.pop(); result.add(count); count = 0; } else { continue; } } stack.push(days); } if(!stack.isEmpty()) { count++; result.add(count); } int[] answer = new int[result.size()]; for(int i = 0; i < result.size(); i++) { answer[i] = result.get(i); } return answer; } }
Shell
UTF-8
642
3.90625
4
[ "Apache-2.0" ]
permissive
#!/bin/bash declare -a args for arg in "$@"; do file="${arg%:[0-9]*}" file="$(realpath "$file")" args+=("$file") case "$arg" in *:*) num="${arg##*:}" args+=("+$num") ;; esac done declare -a editors=( codeedit vim ) for editor in "${editors[@]}"; do type "$editor" >/dev/null 2>&1 || continue # exit status is 127 if a command is not found # codeedit returns 127 if it wants to be skipped "$editor" ${editor_args[$editor]} "${args[@]}" status=$? test $status -ne 127 && exit $status done printf '%s %s\n' "Couldn't find any editor, looked for" "${editors[*]}" >&2 exit 1
Java
UTF-8
706
1.828125
2
[]
no_license
package io.finstats; import io.finstats.api.FinStatsRestApiVerticle; import io.finstats.statistics.StatisticsService; import io.finstats.statistics.StatisticsServiceImpl; import io.finstats.storage.MetricsStorage; import io.finstats.storage.MetricsStorageImpl; import static io.finstats.utils.LoggingUtils.configureLogging; import io.vertx.core.AbstractVerticle; public class MainVerticle extends AbstractVerticle { @Override public void start() { configureLogging(); final MetricsStorage storage = new MetricsStorageImpl(); final StatisticsService statisticsService = new StatisticsServiceImpl(storage); vertx.deployVerticle(new FinStatsRestApiVerticle(statisticsService)); } }
Java
UTF-8
4,253
2.171875
2
[ "Apache-2.0" ]
permissive
package com.github.microwww.bitcoin.provider; import com.github.microwww.bitcoin.net.MessageHeader; import com.github.microwww.bitcoin.net.NetProtocol; import com.github.microwww.bitcoin.net.PeerChannelClientProtocol; import com.github.microwww.bitcoin.net.protocol.*; import com.github.microwww.bitcoin.util.ByteUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.Attribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import java.io.Closeable; import java.io.IOException; public class PeerChannelClientHandler extends SimpleChannelInboundHandler<MessageHeader> implements Closeable { private static final Logger logger = LoggerFactory.getLogger(PeerChannelClientHandler.class); @Autowired PeerChannelClientProtocol peerChannelClientProtocol; public PeerChannelClientHandler(PeerChannelClientProtocol peerChannelClientProtocol) { this.peerChannelClientProtocol = peerChannelClientProtocol; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Peer attr = ctx.channel().attr(Peer.PEER).get(); Assert.isTrue(null != attr, "Not init peer in channel"); ctx.write(Version.builder(attr, attr.getLocalBlockChain().getChainParams())); } @Override protected void channelRead0(ChannelHandlerContext ctx, MessageHeader header) { Peer peer = ctx.channel().attr(Peer.PEER).get(); try { NetProtocol netProtocol = header.getNetProtocol(); if (logger.isDebugEnabled()) { logger.debug("Get a command : {} \n 0x{}", netProtocol.command(), ByteUtil.hex(header.getPayload())); } AbstractProtocol parse = netProtocol.parse(peer, header.getPayload()); if (parse instanceof AbstractProtocolAdapter) { ((AbstractProtocolAdapter<?>) parse).setPayload(header.getPayload()); } logger.debug("Command: {}, parse to : {}", netProtocol.command(), parse.getClass().getSimpleName()); peerChannelClientProtocol.doAction(ctx, parse); } catch (UnsupportedOperationException ex) { logger.warn("UnsupportedOperation class [{}].service: {} \n {}", peerChannelClientProtocol.getClass().getName(), header.getCommand(), ByteUtil.hex(header.getPayload())); ctx.writeAndFlush(reject(peer, header, ex)); } catch (UnsupportedNetProtocolException ex) { logger.warn("Net-protocol class [{}] unsupported PROTOCOL: {} \n {}", NetProtocol.class.getName(), header.getCommand(), ByteUtil.hex(header.getPayload())); ctx.writeAndFlush(reject(peer, header, ex)); } catch (RuntimeException ex) { logger.error("Server internal error {}: \n{}\n", ex.getMessage(), ByteUtil.hex(header.getPayload()), ex); throw ex; } } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { Peer peer = ctx.channel().attr(Peer.PEER).get(); if (peer != null) { logger.info("Remote peer close: {}", peer.getURI()); peerChannelClientProtocol.channelClose(peer); } super.channelUnregistered(ctx); } public Reject reject(Peer peer, MessageHeader header, Exception ex) { Reject reject = new Reject(peer); reject.setMessage(header.getCommand()); reject.setCode(Reject.Code.REJECT_INVALID.code); String er = ex.getMessage(); if (er == null) { er = "error parsing message"; } reject.setMessage(er); reject.setReason(ex.getClass().getName()); return reject; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { Attribute<Peer> attr = ctx.channel().attr(Peer.PEER); Peer peer = attr.get(); logger.warn("Parse Request OR execute ERROR, peer {}", peer.getURI(), cause); } @Override public void close() throws IOException { peerChannelClientProtocol.close(); } }
JavaScript
UTF-8
1,521
3.921875
4
[]
no_license
/* The ShipL class is a class which represents a L-shaped ship. */ class ShipL { constructor() { this.area = []; this.type = "L Ship"; } /* The randomizeShip() function will randomize the location and determine the area of the ship given the height and width of the board. The area will be set as a L-shape. */ randomizeShip(height, width) { var yStart = Math.floor((Math.random() * height)); var xStart = Math.floor((Math.random() * width)); var block1 = {x:xStart, y:yStart}; var block2 = {x:xStart, y:yStart + 1}; var block3 = {x:xStart, y:yStart + 2}; var block4 = {x:xStart + 1, y:yStart + 2}; this.area.push(block1); this.area.push(block2); this.area.push(block3); this.area.push(block4); } /* The loadJSON() function will set data given a json object. */ loadJSON(json) { this.area = json.area; this.type = json.type; } /* The getArea() function will return the array of area the ship occupies. */ getArea() { return this.area; } /* The occupies() function will return true if the area of the ship overlaps the given coordinate. Otherwise, it will return false. */ occupies(y, x) { for (var i = 0; i < this.getArea().length; i++) { var area = this.getArea()[i]; if (area.x == x && area.y == y) { return true; } } return false; } /* The getType() function will return the type of the ship. */ getType() { return this.type; } }
Python
UTF-8
635
4.34375
4
[]
no_license
Elements = [] try: totalElements = int(input("Enter the List Size: ")) print("Enter Elements:") for elementCount in range(0, totalElements): print("Enter Number", elementCount,) item = int(input()) Elements.append(item) print("Inserted Elements are: ", Elements) odd_count = len(list(filter(lambda element: (element % 2 != 0), Elements))) even_count = len(list(filter(lambda element: (element % 2 == 0), Elements))) print("Odd Numbers in the List: ", odd_count) print("Even Numbers in the List: ", even_count) except Exception: print("Invalid Input.")
Python
UTF-8
1,030
3.625
4
[]
no_license
#! venv/bin/python3.7 """ There are some prime values, p, for which there exists a positive integer, n, such that the expression n^3 + n^2 * p is a perfect cube. For example, when p = 19, 8^3 + 8^2 × 19 = 12^3. What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred. How many primes below one million have this remarkable property? Solution: 173 """ from itertools import count from pyutils.primes import get_primes_up_to_n def PE_131(limit): """ >>> PE_131(100) 4 >>> PE_131(1000000) 173 """ primes = set(get_primes_up_to_n(limit)) solutions = 0 for g in count(1): x = g + g**(3/2) if int(x) == x: n = x - g p = int(round((x**3 - n**3) / n**2, 0)) solutions += 1 if p in primes else 0 if p > limit: break return solutions if __name__ == '__main__': import doctest; doctest.testmod(verbose=True)
Markdown
UTF-8
3,109
2.828125
3
[]
no_license
<!-- Theme: "Olive Green" Color: white --> # Cryptocoin for Swift ### A modular framework for Bitcoin, Litecoin, Dogecoin, etc. written in Swift (and a bit of C) # github.com/CryptoCoinSwift #### Work in progress. Inspired by CryptoCoinJS. #### Sjors Provoost / sjors@purpledunes.com / @provoost #### August 5th, 2014: Dutch Ethereum & Bitcoin meetup Amsterdam ^ iOs developer based in Utrecht, heard about Bitcoin in 2011, ignored it until early 2013. --- # Why build your own framework? * Native iPhone app * Learn Swift * Learn Bitcoin * Learn elliptic curve cryptography ^ Swift is Apples new programming language. --- ![](CryptoCoinSwiftDemo.mp4) ^ Work in progress --- - **UInt256** <sub>0...115792089237316195423570985008687907853269984665640564039457584007913129639935</sub> - **FFInt** Finite field math: (6 + 6) mod 10 = 2 - **ECPoint** A = (x, y) ![40%](http://blog.cloudflare.com/static/images/image02.gif) - **ECurve** A + B - **ECKey** General crypto: public key, signature.. - **CoinKey** Crypto currency specific: address, WIF.. - **Bitcoin** Subclass of CoinKey with 0x80 prefix.. <!-- - **RIPEMD-Swift, etc** Tools --> ^ Modular: several repositories deal with different layers of Bitcoin. ECPoint + Curve : elliptic curve cryptography forms the bases of Bitcoin security CoinKey : e.g. generate address from public key --- # Point addition ![left, 140%](addition-schematic.png) ## The book ![inline, left, 40%](addition-book-top.png) ![inline, left, 40%](addition-book-bottom.png) ## Swift <!-- ```swift let a = (y₂ - y₁) / (x₂ - x₁) let x₃ = a ^^ 2 - x₁ - x₂ let y₃ = a * (x₁ - x₃) - y₁ ``` Unicode not showing correctly --> ![inline, left, 100%](addition-swift.png) <!-- --- # Swift - Hashing example (RIPEMD-160) ## The paper ![inline, left, 100%](RIPEMD-left-paper.png) ## Swift ![inline, left, 100%](RIPEMD-left-Swift.png) --> --- # Operator overload fest ```swift let Q = d * P // d is big number, P is a point on a curve // Handles multiplying a big number with point on curve func * (lhs: UInt256, rhs: ECPoint) -> ECPoint { ... let a = (y₂ - y₁) / (x₂ - x₁) // Multiplication modulo (finite field) func * (lhs: FFInt, rhs: FFInt) -> FFInt { let product: (UInt256, UInt256) = lhs.value * rhs.value return field.int(product % p.p) } // Multiply two 256 bit integers: func * (lhs: UInt256, rhs: UInt256) -> (UInt256, UInt256) { ... } ``` --- # The Future - What I need * 4x faster * ECDSA (signature) * Generate a bitcoin transaction * Submit transaction to cloud * Fetch blockchain data from cloud --- # The Future - For others * Altcoins * Different currencies like Etherium * Blockchain & network : full client * Mining? :-) --- ## Cryptocoin Swift <sub>https://github.com/CryptoCoinSwift/CryptoCoinFramework</sub> ## Sources <sub>Animating curve from CloudFlare Blog: http://blog.cloudflare.com/a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography</sub> <sub>Book: Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone</sub> #### Presentation written in Markdown, powered by Deckset: http://decksetapp.com
Markdown
UTF-8
3,102
2.671875
3
[ "CC-BY-4.0", "CC-BY-SA-4.0" ]
permissive
<!-- loio9164ba7047b74a25a19baf9c5bb986ae --> | loio | | -----| | 9164ba7047b74a25a19baf9c5bb986ae | <div id="loio"> view on: [demo kit nightly build](https://sdk.openui5.org/nightly/#/topic/9164ba7047b74a25a19baf9c5bb986ae) | [demo kit latest release](https://sdk.openui5.org/topic/9164ba7047b74a25a19baf9c5bb986ae)</div> ## Growing Feature for Table and List `sap.m.ListBase` provides growing-related properties, which can be used for tables and lists. A growing list has a loading mechanism that requests data from the model in a lazy way. This enables the app to only fetch data from the server as and when necessary. > ### Note: > Before release 1.16, the `sap.m.GrowingList` control existed as an extension of the `sap.m.List` control. As this is now deprecated, use the properties as described here instead. The growing-related properties of `sap.m.ListBase` are: - `growing`: Boolean to set the growing feature to on or off - `growingScrollToLoad`: If you want to allow more data to be fetched when the user scrolls down to the end of the current items, set this boolean property to true; otherwise a trigger button must be used - `growingThreshold`: The number of items that are requested each time from the model - `growingTriggerText`: The text on a trigger button used to cause a request for more data > ### Note: > For `sap.m.listbase`, the growing feature containing the growing property is not supported when used in combination with two-way binding for a table or list. > > Also, as the growing feature enables extended change detection for the binding, it only updates rows that are changed. This means that if the position of a particular row has not been changed, this row will **not** be updated. To enable data for a table to be fetched on demand like this, you just need to set the values for these properties appropriately on your table control. For example, adding the highlighted lines as shown in the following code will cause five items to be displayed in the table initially along with a *More* button \(this is the default text used if you don't set a different text using the `growingTriggerText` property\), as shown below the code: ```js <List items="{/ProductCollection}" headerText="Products" growing="true" growingThreshold="4" growingScrollToLoad="false"> <StandardListItem title="{Name}" description="{ProductId}" icon="{ProductPicUrl}" iconDensityAware="false" iconInset="false" /> </List> ``` ![](images/loiof77f21836ce04e65b6c5ed258abb8e18_LowRes.png) If you want the user to have to scroll down to see more items \(by setting the `growingScrollToLoad` property to true\), you must ensure that the control is within a container that has a scroll feature, such as an `sap.m.Page` in an `sap.m.App` control, like this: ```js <App> <Page title="Table Events"> <Table> ... </Table> </Page> <App> ``` *** ### Sample For more information, see the [sample](https://sdk.openui5.org/entity/sap.m.List/sample/sap.m.sample.ListGrowing) in the Demo Kit.
Python
UTF-8
3,288
2.640625
3
[ "MIT" ]
permissive
def get_php_fpm_eval(attack_type): php_code = "" if attack_type == "gopher": php_code = """ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "%s"); curl_setopt($ch, CURLOPT_HEADER, 0); $o = curl_exec($ch); curl_close($ch); $o = end(explode('\\n\\n', str_replace('\\r', '', $o), 2)); echo trim($o); """ if attack_type == "sock": php_code = """ $sock_path='%s'; if(function_exists('stream_socket_client') && file_exists($sock_path)){ $sock=stream_socket_client("unix://".$sock_path); } else { die('stream_socket_client function not exist or sock not exist'); } fwrite($sock, base64_decode('%s')); $o = ''; while (!feof($sock)) { $o .= fread($sock, 8192); } $o = end(explode('\\n\\n', str_replace('\\r', '', $o), 2)); echo trim($o); """ if attack_type == "http_sock": php_code = """ $host='%s'; $port=%s; if(function_exists('fsockopen')){ $sock=fsockopen($host, $port, $errno, $errstr, 1); } else if(function_exists('pfsockopen')){ $sock=pfsockopen($host, $port, $errno, $errstr, 1); } else if(function_exists('stream_socket_client')) { $sock=stream_socket_client("tcp://$sock_path:$port",$errno, $errstr, 1); } else { die('fsockopen/pfsockopen/stream_socket_client function not exist'); } fwrite($sock, base64_decode('%s')); $o = ''; while (!feof($sock)) { $o .= fread($sock, 8192); } $o = end(explode('\\n\\n', str_replace('\\r', '', $o), 2)); echo trim($o); """ if attack_type == "ftp": php_code = """ if(function_exists('stream_socket_server') && function_exists('stream_socket_accept')){ $ftp_table = [ "USER" => "331 Username ok, send password.\\r\\n", "PASS" => "230 Login successful.\\r\\n", "TYPE" => "200 Type set to: Binary.\\r\\n", "SIZE" => "550 /test is not retrievable.\\r\\n", "EPSV" => "500 'EPSV': command not understood.\\r\\n", "PASV" => "227 Entering passive mode (%s,0,%s).\\r\\n", "STOR" => "150 File status okay. About to open data connection.\\r\\n", ]; $server = stream_socket_server("tcp://0.0.0.0:%s", $errno, $errstr); $accept = stream_socket_accept($server); fwrite($accept, "200 OK\\r\\n"); while (true) { $data = fgets($accept); $cmd = substr($data, 0, 4); if (array_key_exists($cmd, $ftp_table)) { fwrite($accept, $ftp_table[$cmd]); if ($cmd === "STOR") { break; } } else { break; } } fclose($server); } else { die('stream_socket_server/stream_socket_accept function not exist'); }""" return php_code
PHP
UTF-8
10,093
2.640625
3
[]
no_license
<?php /** * EGmap3 Yii extension * * Object oriented PHP interface to GMAP3 Javascript library for * Google Maps. * * GMAP3 was originally written by DEMONTE Jean-Baptiste. * Special permission has been granted to release under the LGPL for * this extension. * @link http://gmap3.net * * This extension has taken some ideas (but no code) from Antonio Ramirez' * egmap Yii extension. * @link http://www.yiiframework.com/extension/egmap * * @copyright © Digitick <www.digitick.net> 2011 * @license GNU Lesser General Public License v3.0 * @author Ianaré Sévi * */ // load these like this so small classes can be combined into fewer files. require_once 'EGmap3Constants.php'; require_once 'EGmap3MapSubOptions.php'; require_once 'EGmap3Primitives.php'; /** * Main class. * * @author Ianaré Sévi */ class EGmap3Widget extends CWidget { /** * @var boolean Use minified version of gmap3 library, defaults to true. */ public $mini = true; /** * @var integer Width of the map widget. By default uses 'px' but other * units may be used. */ public $width = 550; /** * @var integer Height of the map widget. By default uses 'px' but other * units may be used. */ public $height = 400; /** * @var string CSS size unit to use, such as : 'px', 'em', 'pt', etc .. */ public $unit = 'px'; /** * @var boolean Set the map widget to be resizable, default is false. */ public $resizable = false; /** * @var boolean Show a layer that displays bike lanes and paths and demotes * large roads. */ public $bicyclingLayer; /** * @var boolean Show a layer that displays current road traffic. */ public $trafficLayer; /** * @var boolean Zoom the map to automatically fit the elements it contains. */ public $autofit; // protected $rectangles = array(); protected $polygons = array(); protected $polylines = array(); protected $routes = array(); protected $markers = array(); protected $circles = array(); protected $kmlLayers = array(); protected $styledMaps = array(); /** * @var EGmap3Map The map itself. */ protected $map; /** * Create a new Google map widget. * @param mixed $options Associative array or Options object */ public function __construct($options=null) { if ($options) { $this->setOptions($options); } } public function initOptions() { if (!is_object($this->map)) { $this->map = new EGmap3Map(); } } /** * Set the map display size. * @param integer $width The width. * @param integer $height The height. * @param string $unit CSS size unit to use, such as : 'px', 'em', 'pt', etc .. */ public function setSize($width, $height, $unit='px') { $this->width = $width; $this->height = $height; $this->unit = $unit; } /** * Set map options. * @param EMapOptions $options */ public function setOptions($options) { $this->initOptions(); $this->map->setOptions($options); } /** * @return EGmap3MapOptions */ public function getOptions() { $this->initOptions(); return $this->map->getOptions(); } /** * Add an action to the map. * * @param EGmap3ActionBase $action */ public function add(EGmap3ActionBase $action) { switch (get_class($action)) { case 'EGmap3Marker': $this->markers[] = $action; break; case 'EGmap3InfoWindow': $this->markers[] = $action; break; case 'EGmap3Circle': $this->circles[] = $action; break; case 'EGmap3Rectangle': $this->rectangles[] = $action; break; case 'EGmap3Polygon': $this->polygons[] = $action; break; case 'EGmap3Polyline': $this->polylines[] = $action; break; case 'EGmap3Route': $this->routes[] = $action; break; case 'EGmap3StyledMap': $this->styledMaps[] = $action; break; default: throw new CException('Invalid type given to add.'); break; } } public function getMarkers() { return $this->markers; } public function getCircles() { return $this->markers; } public function getRectangles() { return $this->rectangles; } public function getPolygons() { return $this->polygons; } public function getRoutes() { return $this->routes; } public function getStyledMaps() { return $this->styledMaps; } /** * Registers the core script files. * This method registers jquery and JUI JavaScript files and the theme CSS file. */ protected function registerCoreScripts() { $params = array( 'sensor' => 'false', 'language' => Yii::app()->getLanguage() ); $http = (Yii::app()->getRequest()->isSecureConnection)?'https':'http'; $apiScript = $http.'://maps.google.com/maps/api/js?' . http_build_query($params); $assets = Yii::app()->assetManager->publish(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets'); $cs = Yii::app()->getClientScript(); $cs->registerCoreScript('jquery'); $cs->registerScriptFile($apiScript) ->registerScriptFile($assets . (($this->mini) ? '/gmap3.min.js' : '/gmap3.js')); if ($this->resizable) { $cs->registerCoreScript('jquery.ui'); $cs->registerCssFile($cs->getCoreScriptUrl().'/jui/css/base/jquery-ui.css'); } } /** * Update a marker on the map using a Yii model's fields. The model fields * must exist on the page. * * @param CModel $model Model to use * @param array $attributes Model attributes to use for building the address. * Must be given in the correct order ! * @param array $options Options to set :<ul> * <li>'first' - set to first marker added to map, default is last * <li>'nopan' - do not pan the map on marker update. * <li>'event' => 'change' - valid jQuery event to trigger map update. * </ul> */ public function updateMarkerAddressFromModel(CModel $model, array $attributes, array $options=array()) { // get attribute IDs for ($i = 0; $i < count($attributes); $i++) { $attributes[$i] = CHtml::activeId($model, $attributes[$i]); } // build the hidden field $fieldId = $this->id . '_gmap3MarkerAddress'; echo CHtml::hiddenField('gmap3MarkerAddress', null, array('id' => $fieldId)); // options $marker = (in_array('first', $options)) ? 'first:true' : 'last:true'; $pan = (in_array('nopan', $options)) ? '' : "$('#{$this->id}').gmap3({action:'panTo',args:[marker.position]});"; // construct marker position updater function $setFunction = $this->id . 'setMarkerPosition'; $script = "function {$setFunction}(){ var addr = $('#{$fieldId}').val(); if ( !addr || !addr.length ) return; marker = \$('#{$this->id}').gmap3({action:'get',name:'marker', {$marker}}); $('#{$this->id}').gmap3({ action: 'getlatlng', address: addr, callback: function(results){ if ( !results ) return; latLng = results[0].geometry.location; marker.setPosition(latLng); {$pan} } });}"; // construct address field updater function $upFunction = $this->id . 'updateAddressField'; $jsAttributes = CJavaScript::encode($attributes); $modelClass = get_class($model); $script .= " function {$upFunction}() { var add = ''; var fields = {$jsAttributes}; for (var i = 0; i < fields.length; i++) { field = $('#'+fields[i]); if (!field[0]){continue;} if (field[0].type == 'select-one'){ value = $('#'+fields[i] +' :selected').text(); } else {value = field.val();} if (value && value != 0) { add += value + ', '; } } add = add.substring(0, add.length - 2); $('#{$fieldId}').val(add); {$setFunction}(); }"; if (isset($options['event'])) { $eventType = $options['event']; } else { $eventType = 'change'; } $sAttributes = implode(',#', $attributes); $script .= "$(document).delegate('#{$sAttributes}', '{$eventType}', function(){{$upFunction}();});"; $this->registerScript($script); } protected function registerScript($script, $position=CClientScript::POS_END) { $uid = md5($script); $script = preg_replace('/[\n\r\t]/', null, $script); Yii::app()->getClientScript()->registerScript($uid, $script, $position); } /** * Used internally, should not be called. */ public function init() { $this->registerCoreScripts(); // action initialize $script = $this->map->toJS(); // add objectified actions $overlays = array( 'routes', 'markers', 'circles', 'rectangles', 'polygons', 'polylines', 'styledMaps', ); foreach ($overlays as $actions) { foreach ($this->$actions as $action) { $script .= ',' . $action->toJs(); } } // other actions if ($this->bicyclingLayer === true) { $script .= ",{action:'addBicyclingLayer'}"; } if ($this->trafficLayer === true) { $script .= ",{action:'addTrafficLayer'}"; } if ($this->autofit === true) { $script .= ",{action:'autofit'}"; } $script = "jQuery('#{$this->id}').gmap3($script)"; if ($this->resizable === true) { $script .= '.resizable()'; } $script .= ';'; // $script="jQuery('#yw0').gmap3({ // 'action': 'init', // 'options': { // 'center': ['41.850033', '-87.650052'], // 'mapTypeControlOptions': { // 'mapTypeIds': [google.maps.MapTypeId.ROADMAP, 'style1'] // }, // 'mapTypeId': google.maps.MapTypeId.ROADMAP, // 'zoom': 12 // } //}, { // 'action': 'addStyledMap', // 'id': 'style1', // 'options': { // 'name': 'style 1' // }, // 'style': [{ // 'elementType': 'geometry', // 'featureType': 'road.highway', // 'stylers': [{ // 'hue': '#ff0022', // 'saturation': 60, // 'lightness': -20 // }] // }] //});"; //print_r($script);die; $this->registerScript($script); parent::init(); } /** * Used internally, should not be called. */ public function run() { echo CHtml::openTag('div', array( 'id' => $this->id, 'class' => 'gmap3', 'style' => "width:{$this->width}{$this->unit};height:{$this->height}{$this->unit}")), CHtml::closeTag('div'); } /** * Attach all action objects to the map, convert them to Javascript, * and render the map inside the widget. * * MUST be last method call. */ public function renderMap() { $this->init(); $this->run(); } }
Java
UTF-8
400
1.945313
2
[]
no_license
package com.newvery.web.response; import com.google.gson.annotations.Expose; import com.newvery.record.ArticleRecord; import com.newvery.web.servlet.BaseResponse; public class ArticleResponse extends BaseResponse { @Expose private ArticleRecord article; public ArticleRecord getArticle() { return article; } public void setArticle(ArticleRecord article) { this.article = article; } }
Java
UTF-8
7,653
2.390625
2
[]
no_license
package com.wmz.common.dao; import java.io.Serializable; import java.util.List; import java.util.Map; import com.wmz.common.util.Wrapper; /** *create by yinchong * @param <T> 实体类 */ public interface BaseDao<T> { /** * 保存和更新数据 * @param bean */ void save(T bean); /** * 更新数据 * @param bean */ void update(T bean); /** * 根据id查询数据 * @param id * @return */ T findOne(Serializable id); /** * 根据id删除制定数据 * @param id * @return */ int delete(Serializable id); /** * 查询所有数据 * @return */ List<T> findAll(); /** * 分页显示数据 * @param pageNum * @param pageSize * @return */ List<T> pageList(int pageNum, int pageSize); /** * 查询所有并按主键降序 * @return */ List<T> findAllDesc(); /** * 分页显示并按主键降序 * @return */ List<T> pageListDesc(int pageNum, int pageSize); /** * 对指定字段降序排序 * @param fieldName * @return */ List<T> findAllDesc(String fieldName); /** * 安某个字段并查找指定数据个数 * @param fielName * @param pageNum * @param pageSize * @return */ List<T> pageListDesc(String fielName, int pageNum, int pageSize); /** * 查询所有并按主键升序 * @return */ List<T> findAllAsc(); /** * 查找指定数量并按主键升序 * @param pageNum * @param pageSize * @return */ List<T> pageListAsc(int pageNum, int pageSize); /** * 对指定字段升序排序 * @param fieldName * @return */ List<T> findAllAsc(String fieldName); /** * 对指定字段降序并查询指定数量 * @param fieldName * @param pageNum * @param pageSize * @return */ List<T> pageListAsc(String fieldName, int pageNum, int pageSize); /** * 批量保存 * @param beans */ void batchSave(List<T> beans); /** * 批量更新所有字段 * @param beans */ void batchUpdate(List<T> beans); /** * 批量删除 * @param ids * @return */ int batchDelete(List<? extends Serializable> ids); /** * 批量更新非空字段 * @param beans */ void batchUpdateNotNull(List<T> beans); /** * 这个用于执行删除和更新的sql语句 * * @param sql * @param params */ int executeSql(String sql, Object... params); /** * 这个用于执行删除和更新的hql语句 * @param hql * @param params */ int executeHql(String hql, Object... params); /** * 根据原始sql语句执行sql * @param sql 原始sql语句 * @param params 要传递的参数 * @return map对象 */ List<Map<String, Object>> findSql(String sql, Object... params); /** * @param sql 原始sql语句 * @param clazz 要反射的Class对象 * @param params 要传递的参数 * @param <T> * @return */ <T> List<T> findSql(String sql, Class<T> clazz, Object... params); /** * 执行原始sql并返回Object[]集合 * @param sql * @param params * @return */ List<Object[]> findObjectSql(String sql, Object... params); /** * 分页显示数据 * * @param sql * @param pageNum 第几页 * @param pageSize 每页显示多少个 * @param params 需要传递的参数 * @return */ PageBean<Map<String,Object>> pageSql(String sql, Integer pageNum, Integer pageSize, Object... params); /** * 分页显示数据 * @param sql * @param clazz * @param pageNum * @param pageSize * @param params * @param <T2> * @return */ <T2> PageBean<T2> pageSql(String sql,Class<T2> clazz,int pageNum,int pageSize,Object... params); /** * 分页查询 * @param sql * @param pageNum * @param pageSize * @param params * @return */ PageBean<Object[]> pageObjectSql(String sql, int pageNum, int pageSize, Object... params); /** * 执行hql查询语句 * @param hql * @param params * @return */ <T2> List<T2> findHql(String hql,Class<T2> clazz, Object... params); /** * hql语句返回Object[]对象 * @param hql * @param params * @return */ List<Object[]> findObjectHql(String hql, Object... params); /** * 分页查询 * @param hql hql语句 (注意hql中的未知参数用?表 selec p from Teacher p where p.name = ?) * @param clazz 要查询的对象可以是自定义类型也可是java中自定义类型比如String * @param pageNum 第几页 * @param pageSize 每页显示多少数据 * @param params hql中需要的参数 * @param <T2> * @return */ <T2> PageBean<T2> pageHql(String hql,Class<T2> clazz, Integer pageNum, Integer pageSize, Object... params); /** *hql执行统计总数 * @param hql * @param params * @return */ Long countHql(String hql, Object... params); /** * 执行统计总数 * @param sql * @param params * @return */ Long countSql(String sql, Object... params); /** * 更新非空字段 * @param bean * @return */ int updateNotNull(T bean); /** * 根据字段删除数据 * @param field * @param value * @return */ int deleteEqualField(String field, Object value); /** * like匹配删除 * @param field * @param value * @return */ int deleteLikeField(String field, String value); /** * 相等查找 * @param field 字段名 * @param value 字段对应的值 * @return */ List<T> findEqualField(String field, Object value); /** * like匹配查找 * @param field 字段名 * @param value 字段对应的值 * @return */ List<T> findLikeField(String field, String value); /** * 根据字段进行between查询 * @param field * @param start * @param end * @return */ List<T> findBetweenField(String field, Object start, Object end); /** * 删除所有 */ int deleteAll(); /** * 对bean对象的多个字段and的equal匹配 * @param data * @return */ List<T> findAndFields(Map<String, Object> data); /** * 对bean对象多个字段or的equal匹配 * @param data * @return */ List<T> findOrFields(Map<String, Object> data); /** * 获取一条记录方法 * @param hql * @param clazz * @param <T2> * @return */ <T2> T2 findOneHql(String hql, Class<T2> clazz, Object... params); /** * 返回小于等于一条结果时 * @param sql * @param clazz * @param <T2> * @return */ <T2> T2 findOneSql(String sql, Class<T2> clazz, Object... params); List<Map<String,Object>> findWrapper(Wrapper wrapper); <T2> List<T2> findWrapper(Wrapper wrapper,Class<T2> clazz); }
Ruby
UTF-8
1,440
2.75
3
[]
no_license
# coding: utf-8 # frozen_string_literal: true require "models/application_record" require "services/change_maker" require "utils/counter" require "utils/currency" class Money < ApplicationRecord VALID_DENOMINATIONS = [ 2_00, 1_00, 50, 20, 10, 5, 2, 1, ].freeze validates :denomination_value, presence: true, uniqueness: true, numericality: { greater_than: 0 }, inclusion: { in: VALID_DENOMINATIONS } validates :quantity, presence: true, numericality: { greater_than_or_equal_to: 0 } def self.valid?(denomination) VALID_DENOMINATIONS.include?(denomination) end def self.till_values pluck(:denomination_value, :quantity).to_h end def self.add_to_till!(value_counts:) update_quantities!(value_counts) { |curr_qty, delta| curr_qty + delta } end def self.remove_from_till!(value_counts:) update_quantities!(value_counts) { |curr_qty, delta| curr_qty - delta } end def self.update_quantities!(value_counts) return if value_counts.to_h.empty? transaction do where(denomination_value: value_counts.keys).find_each do |till_slot| curr_qty = till_slot.quantity delta_qty = value_counts.fetch(till_slot.denomination_value) updated_qty = yield(curr_qty, delta_qty) till_slot.quantity = updated_qty till_slot.save! end end end end
C#
UTF-8
1,058
3.15625
3
[]
no_license
var input = @"<?xml version=""1.0"" encoding=""utf-8""?> <Students> <Student> <Ordinal>1</Ordinal> <Name>Student1</Name> <BirthDate>Date1</BirthDate> <ID>ID1</ID> </Student> <Student> <Ordinal>2</Ordinal> <Name>Student2</Name> <BirthDate>Date2</BirthDate> <ID>ID2</ID> </Student> </Students>"; // Parse string is equivalent to load path. XDocument xDoc = XDocument.Parse(input); XElement xEl = XElement.Parse(input); var xDocString = xDoc.ToString(); var XElElement = xEl.Element("Student").ToString(); // => <Student> <Ordinal>1</Ordinal> ... var XElDecendant = xEl.Descendants("Student").ToString(); // => System.Xml.Linq.XContainer+<GetDescendants>d__39 // I'm a linQ container containing XNode, please enumerate me. var xDocElement = xDoc.Element("Student").ToString(); //=> null var xDocDecendant = xDoc.Descendants("Student").ToString(); // => System.Xml.Linq.XContainer+<GetDescendants>d__39 // I'm a linQ container containing XNode, please enumerate me. foreach(var el in xEl.Descendants("Student")){ Console.WriteLine(el); }
Swift
UTF-8
10,127
2.75
3
[]
no_license
import UIKit protocol MosiacLayoutDelegate: AnyObject { func collectionView(_ collectionView: UICollectionView, heightForHeader indexPath: IndexPath) -> CGFloat func collectionView(heightForTabBar collectionView: UICollectionView) -> CGFloat } enum Element: String { case header case cell var id: String { return self.rawValue } var kind: String { return self.rawValue.capitalized } } class MosiacLayout: UICollectionViewLayout { weak var delegate: MosiacLayoutDelegate? private var cache = [Element: [IndexPath: UICollectionViewLayoutAttributes]]() private var contentHeight = CGFloat() private var numberOfItems = 0 private var currentIndex = 0 private let cellPadding = CGFloat(0.5) override public var collectionViewContentSize: CGSize { return CGSize(width: collectionView?.frame.width ?? 0, height: contentHeight) } private var contentOffset: CGPoint { return collectionView!.contentOffset } private var contentWidth: CGFloat { guard let collectionView = collectionView else { return 0 } //let insets = collectionView.contentInset return collectionView.bounds.width //- (insets.left + insets.right) } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func prepare() { guard let collectionView = collectionView else { return } contentHeight = 0 prepareCache() currentIndex = 0 numberOfItems = collectionView.numberOfItems(inSection: 0) prepareHeader(for: collectionView) while numberOfItems > 0 { prepareLeftOrientedLayout() //prepareMiddleOrientedLayout() prepareMiddleOrientedLayout() prepareRightOrientedLayout() } contentHeight += delegate?.collectionView(heightForTabBar: collectionView) ?? 0 } private func prepareHeader(for collectionView: UICollectionView) { let headerIndexPath = IndexPath(item: 0, section: 0) let headerAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: Element.header.kind, with: headerIndexPath) let headerHeight = delegate?.collectionView(collectionView, heightForHeader: headerIndexPath) ?? 200 headerAttributes.frame = CGRect(x: 0, y: contentHeight, width: contentWidth , height: headerHeight) contentHeight += headerAttributes.frame.height cache[.header]?[headerIndexPath] = headerAttributes } private func prepareCache() { cache.removeAll(keepingCapacity: true) cache[.header] = [IndexPath: UICollectionViewLayoutAttributes]() cache[.cell] = [IndexPath: UICollectionViewLayoutAttributes]() } private func prepareLeftOrientedLayout () { if numberOfItems > 0 { contentHeight += contentWidth*2/3 let indexPath1 = IndexPath(item: currentIndex, section: 0) let height1 = contentWidth*2/3 let width1 = 2/3*(contentWidth) let frame1 = CGRect(x: 0, y: contentHeight-contentWidth*2/3, width: width1, height: height1) let attributes1 = UICollectionViewLayoutAttributes(forCellWith: indexPath1) attributes1.frame = frame1.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath1] = attributes1 currentIndex += 1 numberOfItems -= 1 } if numberOfItems > 0 { // computing frame two let indexPath2 = IndexPath(item: currentIndex, section: 0) let height2 = contentWidth/3 let width2 = 1/3*(contentWidth) let frame2 = CGRect(x: contentWidth*2/3, y: contentHeight-contentWidth*2/3, width: width2, height: height2) let attributes2 = UICollectionViewLayoutAttributes(forCellWith: indexPath2) attributes2.frame = frame2.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath2] = attributes2 currentIndex += 1 numberOfItems -= 1 } if numberOfItems > 0 { // computing frame three let indexPath3 = IndexPath(item: currentIndex, section: 0) let height3 = contentWidth/3 let width3 = 1/3*(contentWidth) let frame3 = CGRect(x: contentWidth*2/3, y: contentHeight - contentWidth*2/3 + contentWidth/3, width: width3, height: height3) let attributes3 = UICollectionViewLayoutAttributes(forCellWith: indexPath3) attributes3.frame = frame3.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath3] = attributes3 currentIndex += 1 numberOfItems -= 1 } } private func prepareRightOrientedLayout () { if numberOfItems > 0 { contentHeight += contentWidth*2/3 let indexPath1 = IndexPath(item: currentIndex, section: 0) let height1 = contentWidth/3 let width1 = 1/3*(contentWidth) let frame1 = CGRect(x: 0, y: contentHeight-contentWidth*2/3, width: width1, height: height1) let attributes1 = UICollectionViewLayoutAttributes(forCellWith: indexPath1) attributes1.frame = frame1.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath1] = attributes1 currentIndex += 1 numberOfItems -= 1 } if numberOfItems > 0 { // computing frame two let indexPath2 = IndexPath(item: currentIndex, section: 0) let height2 = contentWidth/3 let width2 = 1/3*(contentWidth) let frame2 = CGRect(x: 0, y: contentHeight-contentWidth/3, width: width2, height: height2) let attributes2 = UICollectionViewLayoutAttributes(forCellWith: indexPath2) attributes2.frame = frame2.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath2] = attributes2 currentIndex += 1 numberOfItems -= 1 } if numberOfItems > 0 { // computing frame three let indexPath3 = IndexPath(item: currentIndex, section: 0) let height3 = contentWidth*2/3 let width3 = 2/3*(contentWidth) let frame3 = CGRect(x: contentWidth*1/3, y: contentHeight - contentWidth*2/3 , width: width3, height: height3) let attributes3 = UICollectionViewLayoutAttributes(forCellWith: indexPath3) attributes3.frame = frame3.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath3] = attributes3 currentIndex += 1 numberOfItems -= 1 } } private func prepareMiddleOrientedLayout () { if numberOfItems > 0 { contentHeight += contentWidth/3 let indexPath1 = IndexPath(item: currentIndex, section: 0) let height1 = contentWidth/3 let width1 = contentWidth/3 let frame1 = CGRect(x: 0, y: contentHeight-contentWidth/3, width: width1, height: height1) let attributes1 = UICollectionViewLayoutAttributes(forCellWith: indexPath1) attributes1.frame = frame1.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath1] = attributes1 currentIndex += 1 numberOfItems -= 1 } if numberOfItems > 0 { // computing frame two let indexPath2 = IndexPath(item: currentIndex, section: 0) let height2 = contentWidth/3 let width2 = contentWidth/3 let frame2 = CGRect(x: contentWidth/3, y: contentHeight-contentWidth/3, width: width2, height: height2) let attributes2 = UICollectionViewLayoutAttributes(forCellWith: indexPath2) attributes2.frame = frame2.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath2] = attributes2 currentIndex += 1 numberOfItems -= 1 } if numberOfItems > 0 { // computing frame three let indexPath3 = IndexPath(item: currentIndex, section: 0) let height3 = contentWidth/3 let width3 = contentWidth/3 let frame3 = CGRect(x: contentWidth*2/3, y: contentHeight - contentWidth/3 , width: width3, height: height3) let attributes3 = UICollectionViewLayoutAttributes(forCellWith: indexPath3) attributes3.frame = frame3.insetBy(dx: cellPadding, dy: cellPadding) cache[.cell]?[indexPath3] = attributes3 currentIndex += 1 numberOfItems -= 1 } } } extension MosiacLayout { override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { switch elementKind { case Element.header.kind: return cache[.header]?[indexPath] default: return cache[.cell]?[indexPath] } } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return cache[.cell]?[indexPath] } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let collectionView = collectionView else { return nil } var visableLayoutAttributes = [UICollectionViewLayoutAttributes]() let headerAttributes = cache[.header]?[IndexPath(item: 0, section: 0)] ?? UICollectionViewLayoutAttributes() let contentOffsetY = collectionView.contentOffset.y let width = collectionView.frame.width let height = headerAttributes.frame.height - contentOffsetY headerAttributes.frame = CGRect(x: 0, y: contentOffsetY , width: width, height: height) visableLayoutAttributes.append(headerAttributes) // cells for (_, attributes) in cache[.cell]! { if attributes.frame.intersects(rect) { visableLayoutAttributes.append(attributes) } } return visableLayoutAttributes } }
JavaScript
UTF-8
630
2.65625
3
[ "MIT" ]
permissive
const { validationResult } = require('express-validator'); // To create middleware, need to return a function module.exports = { handleErrors (templateFunction, dataCb = null) { return async (req, res, next) => { const errors = validationResult(req); //processes the errors and returns a Result Object if(!errors.isEmpty()) { let data = {}; if (dataCb) { data = await dataCb(req); } res.send(templateFunction({ errors, ...data })); return; } next(); } }, requireAuth(req, res, next) { if(!req.session.userId) { res.redirect('/signin'); return; } next(); } }
C#
UTF-8
5,547
2.828125
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.Json; using System.Text.Json.Serialization; using System.IO; namespace hitboard.pipeline { /** * Represents an input setup * Which translates a scancode to Key * * In terms of saving, save files are in config * and saved in c:/ProgramData/hitboard/config */ [Serializable] public class KeyConfiguration { public static string CONFIG_FOLDER { get { return Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "/hitboard/configs/"; } } private const string CONFIG_SUFFIX = ".json"; // Different rules to resolve SOCD's public enum SOCDResolution { Both, Neutral, Up, Down, Left, Right } // Different rules for updating key state public enum KeyActivation { Default, RisingEdge, FallingEdge } // Solution to an SOCD given input static private (bool, bool) ResolveSOCD(bool lowInput, bool highInput, SOCDResolution resolution) { switch (resolution) { case SOCDResolution.Both: return (lowInput, highInput); case SOCDResolution.Neutral: return lowInput && highInput ? (false, false) : (lowInput, highInput); case SOCDResolution.Up: case SOCDResolution.Left: return lowInput && highInput ? (true, false) : (lowInput, highInput); case SOCDResolution.Down: case SOCDResolution.Right: return lowInput && highInput ? (false, true) : (lowInput, highInput); default: return (lowInput, highInput); } } // Updates state given input and key configuration private void UpdateFromInput(KeyState state, Event e) { switch (e.IsSOCDEffecting(this) ? FaceActivation : DirectionActivation) { case KeyActivation.Default: default: state.Buttons[(int)Configuration[e.ScanCode]] = (e.Type == Event.EventType.PRESS); break; } } // Associated to string name public string Name; // SOCD Resolution for given input public SOCDResolution UpDownResolution { get; set; } = SOCDResolution.Both; public SOCDResolution LeftRightResolution { get; set; } = SOCDResolution.Neutral; // Activation for buttons public KeyActivation DirectionActivation { get; set; } = KeyActivation.Default; public KeyActivation FaceActivation { get; set; } = KeyActivation.Default; public SortedDictionary<int, Key> Configuration { get; set; } = new SortedDictionary<int, Key>(); // Given a keystate and event, update keystate // Returns a new state that is presented to controller public KeyState UpdateKeyState(KeyState state, Event e) { // Check this was the correct input if (!Configuration.ContainsKey(e.ScanCode)) return state; // Update keyboard state UpdateFromInput(state, e); // Copy state for SOCD KeyState eState = (KeyState)state.Clone(); // Resolve SOCD (eState.Buttons[(int)Key.UP], eState.Buttons[(int)Key.DOWN]) = ResolveSOCD(eState.Buttons[(int)Key.UP], eState.Buttons[(int)Key.DOWN], UpDownResolution); (eState.Buttons[(int)Key.LEFT], eState.Buttons[(int)Key.RIGHT]) = ResolveSOCD(eState.Buttons[(int)Key.LEFT], eState.Buttons[(int)Key.RIGHT], LeftRightResolution); return eState; } // Save this configuration as a json public void Save(string name) { var options = new JsonSerializerOptions() { WriteIndented = true }; string json = JsonSerializer.Serialize(this, options); File.WriteAllText(CONFIG_FOLDER + name, json); } // Load a configuration given a name static public KeyConfiguration Load(string configFile) { string json = File.ReadAllText(configFile); var configuration = JsonSerializer.Deserialize<KeyConfiguration>(json); configuration.Name = configFile; return configuration; } // Loads all possible key configs static public KeyConfiguration[] LoadConfigurations() { // Create a folder if it doesn't exist Directory.CreateDirectory(CONFIG_FOLDER); // Load all files contained string[] filePaths = Directory.GetFiles(CONFIG_FOLDER, "*" + CONFIG_SUFFIX, SearchOption.TopDirectoryOnly); // Load individual configs KeyConfiguration[] configs = filePaths.ToList() .Select(x => KeyConfiguration.Load(x)) .ToArray(); return configs; } public override string ToString() { return Name; } } }
PHP
UTF-8
1,080
3.0625
3
[]
no_license
<?php namespace src\Utils\Paginacao; class Paginate extends PaginacaoAbstract{ protected $size; protected $quantidadePorPagina; protected $quantidadeDePaginas; public $paginaAtual; public function setSize($size){ $this->size = $size; return $this; } public function setQuantidadePorPagina($quantidadePorPagina){ $this->quantidadePorPagina = $quantidadePorPagina; return $this; } public function setPaginaAtual($paginaAtual){ $this->paginaAtual = $paginaAtual; return $this; } public function getQuantidadeDePaginas(){ $this->quantidadeDePaginas = ceil($this->size / $this->quantidadePorPagina); return $this->quantidadeDePaginas; } public function __toString(){ $quantidade = $this->quantidadePorPagina; if($this->paginaAtual == $this->getQuantidadeDePaginas()){ $quantidade = $this->size - (($this->paginaAtual-1) * $this->quantidadePorPagina); } elseif($this->paginaAtual > $this->getQuantidadeDePaginas()){ $quantidade = 0; } return "Exibindo {$quantidade} de {$this->size}"; } }
C++
UTF-8
1,583
2.578125
3
[]
no_license
#include "worker.h" void Worker::UsingMMap() { this->tails.clear(); int input = ::open(this->logUri.c_str(), O_RDONLY); if (input < 0) { Napi::TypeError::New(Env(), "Could not open " + this->logUri) .ThrowAsJavaScriptException(); return; } struct ::stat infos; //stat seg fault on empty file if (::fstat(input, &infos) != 0) { Napi::TypeError::New(Env(), "Could not stat " + this->logUri) .ThrowAsJavaScriptException(); return; } char *base = (char *)::mmap(NULL, infos.st_size, PROT_READ, MAP_PRIVATE, input, 0); if (base == MAP_FAILED) { Napi::TypeError::New(Env(), "Could not map " + this->logUri) .ThrowAsJavaScriptException(); return; } char const *end = base + infos.st_size; char const *curr = base; char const *next = std::find(curr, end, '\n'); //Skip to target for (int count = this->m_target; count > 0 && curr != end; --count) { curr = next + 1; if(int(*curr) == 0) { break; } next = std::find(curr, end, '\n'); } //Tail file from last index while (curr != end) { //enter the loop empty if(int(*curr) == 0) { break; } auto str = std::string(curr, next); this->tails.push_back(str); this->currentIndex++; curr = next + 1; //next is not empty if(int(*curr) != 0) { next = std::find(curr, end, '\n'); } } ::munmap(base, infos.st_size); }
PHP
UTF-8
923
2.5625
3
[]
no_license
<?php namespace app\mini\service; use app\mini\service\LogService; use app\mini\http\ChuanglanSmsApi; /** * 第三方短信 * Class SmsService * @package app\mini\service */ class SmsService { //短信发送 public static function smsSend($phone,$content){ $clapi = new ChuanglanSmsApi(); //设置您要发送的内容:其中“【】”中括号为运营商签名符号,多签名内容前置添加提交 $result=$clapi->sendSms($phone,$content); if(!is_null(json_decode($result))){ $output=json_decode($result,true); if(isset($output['code'])&&$output['code']=='0'){ return true;//发送成功 }else{ //发送失败写入日志 LogService::writeLog('sms','smscodeerror.log',$result); return false; } }else{ return false; } } }
Java
GB18030
7,323
2.703125
3
[]
no_license
package com.mobileserver.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.List; import com.mobileserver.dao.LiveInfoDAO; import com.mobileserver.domain.LiveInfo; import org.json.JSONStringer; public class LiveInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /*סϢҵ*/ private LiveInfoDAO liveInfoDAO = new LiveInfoDAO(); /*ĬϹ캯*/ public LiveInfoServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*ȡactionactionִֵвͬҵ*/ String action = request.getParameter("action"); if (action.equals("query")) { /*ȡѯסϢIJϢ*/ String studentObj = ""; if (request.getParameter("studentObj") != null) studentObj = request.getParameter("studentObj"); int roomObj = 0; if (request.getParameter("roomObj") != null) roomObj = Integer.parseInt(request.getParameter("roomObj")); Timestamp liveDate = null; if (request.getParameter("liveDate") != null) liveDate = Timestamp.valueOf(request.getParameter("liveDate")); /*ҵ߼ִסϢѯ*/ List<LiveInfo> liveInfoList = liveInfoDAO.QueryLiveInfo(studentObj,roomObj,liveDate); /*2ݴʽһxmlļʽѯĽͨxmlʽͻ StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").append("\r\n") .append("<LiveInfos>").append("\r\n"); for (int i = 0; i < liveInfoList.size(); i++) { sb.append(" <LiveInfo>").append("\r\n") .append(" <liveInfoId>") .append(liveInfoList.get(i).getLiveInfoId()) .append("</liveInfoId>").append("\r\n") .append(" <studentObj>") .append(liveInfoList.get(i).getStudentObj()) .append("</studentObj>").append("\r\n") .append(" <roomObj>") .append(liveInfoList.get(i).getRoomObj()) .append("</roomObj>").append("\r\n") .append(" <liveDate>") .append(liveInfoList.get(i).getLiveDate()) .append("</liveDate>").append("\r\n") .append(" <liveMemo>") .append(liveInfoList.get(i).getLiveMemo()) .append("</liveMemo>").append("\r\n") .append(" </LiveInfo>").append("\r\n"); } sb.append("</LiveInfos>").append("\r\n"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print(sb.toString());*/ //2ֲjsonʽ() ͻ˲ѯͼ󣬷jsonݸʽ JSONStringer stringer = new JSONStringer(); try { stringer.array(); for(LiveInfo liveInfo: liveInfoList) { stringer.object(); stringer.key("liveInfoId").value(liveInfo.getLiveInfoId()); stringer.key("studentObj").value(liveInfo.getStudentObj()); stringer.key("roomObj").value(liveInfo.getRoomObj()); stringer.key("liveDate").value(liveInfo.getLiveDate()); stringer.key("liveMemo").value(liveInfo.getLiveMemo()); stringer.endObject(); } stringer.endArray(); } catch(Exception e){} response.setContentType("text/json; charset=UTF-8"); //JSONΪtext/json response.getOutputStream().write(stringer.toString().getBytes("UTF-8")); } else if (action.equals("add")) { /* סϢȡסϢ浽½סϢ */ LiveInfo liveInfo = new LiveInfo(); int liveInfoId = Integer.parseInt(request.getParameter("liveInfoId")); liveInfo.setLiveInfoId(liveInfoId); String studentObj = new String(request.getParameter("studentObj").getBytes("iso-8859-1"), "UTF-8"); liveInfo.setStudentObj(studentObj); int roomObj = Integer.parseInt(request.getParameter("roomObj")); liveInfo.setRoomObj(roomObj); Timestamp liveDate = Timestamp.valueOf(request.getParameter("liveDate")); liveInfo.setLiveDate(liveDate); String liveMemo = new String(request.getParameter("liveMemo").getBytes("iso-8859-1"), "UTF-8"); liveInfo.setLiveMemo(liveMemo); /* ҵִӲ */ String result = liveInfoDAO.AddLiveInfo(liveInfo); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print(result); } else if (action.equals("delete")) { /*ɾסϢȡסϢļ¼*/ int liveInfoId = Integer.parseInt(request.getParameter("liveInfoId")); /*ҵ߼ִɾ*/ String result = liveInfoDAO.DeleteLiveInfo(liveInfoId); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); /*ɾǷɹϢظͻ*/ out.print(result); } else if (action.equals("updateQuery")) { /*סϢ֮ǰȸliveInfoIdѯijסϢ*/ int liveInfoId = Integer.parseInt(request.getParameter("liveInfoId")); LiveInfo liveInfo = liveInfoDAO.GetLiveInfo(liveInfoId); // ͻ˲ѯסϢ󣬷jsonݸʽ, List<Book>֯JSONַ JSONStringer stringer = new JSONStringer(); try{ stringer.array(); stringer.object(); stringer.key("liveInfoId").value(liveInfo.getLiveInfoId()); stringer.key("studentObj").value(liveInfo.getStudentObj()); stringer.key("roomObj").value(liveInfo.getRoomObj()); stringer.key("liveDate").value(liveInfo.getLiveDate()); stringer.key("liveMemo").value(liveInfo.getLiveMemo()); stringer.endObject(); stringer.endArray(); } catch(Exception e){} response.setContentType("text/json; charset=UTF-8"); //JSONΪtext/json response.getOutputStream().write(stringer.toString().getBytes("UTF-8")); } else if(action.equals("update")) { /* סϢȡסϢ浽½סϢ */ LiveInfo liveInfo = new LiveInfo(); int liveInfoId = Integer.parseInt(request.getParameter("liveInfoId")); liveInfo.setLiveInfoId(liveInfoId); String studentObj = new String(request.getParameter("studentObj").getBytes("iso-8859-1"), "UTF-8"); liveInfo.setStudentObj(studentObj); int roomObj = Integer.parseInt(request.getParameter("roomObj")); liveInfo.setRoomObj(roomObj); Timestamp liveDate = Timestamp.valueOf(request.getParameter("liveDate")); liveInfo.setLiveDate(liveDate); String liveMemo = new String(request.getParameter("liveMemo").getBytes("iso-8859-1"), "UTF-8"); liveInfo.setLiveMemo(liveMemo); /* ҵִи² */ String result = liveInfoDAO.UpdateLiveInfo(liveInfo); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print(result); } } }
Markdown
UTF-8
6,315
2.75
3
[]
no_license
--- author: jock --- * Full-screen and resolutions * Broken A* * Testing and Fixing * Broken pipelines * [Solas 128](https://armorgamesstudios.com/games/solas/) * [RichCast](https://www.richcast.com/) * Release Notes **A-star path-finding video** [![A-star path-finding](http://img.youtube.com/vi/obL0Qsvl1Kg/0.jpg)](https://youtu.be/obL0Qsvl1Kg) On Saturday I move 30 issues out of the to-do and in-progress columns leaving me with 12 to tackle for the release. In the past 138 days I've fixed 147 issues. That's an average of 1.06 issues per day. I have seven days until the release. So I have to remove five issues. I decide to work late as I'm eager to get full-screen support in. It's two minutes to eleven and I just can't stop... so the screen resolution is finished by the morning... and the first draft of the ore-smelting and bronze-working tutorial is done. I'll take some rest before play-testing the tutorial. Breaking all my rules about sustainable levels of productivity. Not proud. It's Wednesday morning and last night I found a tutorial-breaking bug that I'm fairly sure indicates the A* path-finding is broken. It's another case where I've tested at a high level (tell an agent to go to X and then update the world until they get there) so I'm going to add some low-level tests first. Except I didn't... Tools that give you instant feedback are seductive. In this case it's the rendering of the algorithm in progress. I spend time replacing my priority queue, changing the neighbours of a node to include diagonal-neighbours and use a float instead of an integer for priority. I consider weighting the heuristic... and then realise these are all things I've done before and rejected. The bug is that the path-finding runs out of memory before reaching its destination. When this happens my fix is to first find a route half-way to the destination. I didn't write any tests for this so I'm feeling kind of dirty now. It's not going to work if the second half of the route also needs to be broken in half. It's good enough for now but it gets a proper refactoring before the next release. Thursday I spend testing and fixing any critical bugs. Most of that involves saving games from the previous version at various points through the tutorials and loading those games in the new version. Unfortunately, where a script has changed between releases there isn't a reliable way to load the old state and have the game proceed without issues. In this case I've simply marked the script as completed. After fixing a handful of upgrade-path bugs I test a networked game and I'm pleased to see that there are no serious bugs here. Synching issues still happen more often than I'd like but I intend to address these in a future, internet-friendly release. On Friday I fix a couple more critical issues and spend the rest of the time re-testing all the tutorials and mining out a large fortress with all the workshops, stockpiles and buildings I can think of. In the evening I'm ready to do a trial run of the Azure pipelines. Of the four pipelines two of them break and I don't see a way to fix them. An image library depends on a version of the windows runtime that I suspect is no longer available. Next week, support for the MacOS version I use will expire and then I'll be left with one working pipeline. For the next release I'll be using [Docker](https://www.docker.com/). Last year, you may remember I had the pleasure of play-testing a lovely puzzle game called [Solas 128](https://armorgamesstudios.com/games/solas/). I told you it was a good game and it has gone on to win a BAFTA! If you haven't already, definitely give it a blast either on [Steam](https://store.steampowered.com/app/1257850/SOLAS_128/) or [Switch](https://www.nintendo.com/games/detail/solas-128-switch/). Since March I've been contracting with [Panivox](https://www.panivox.com/) working on [RichCast](https://www.richcast.com/), a tool to create voice-controlled interactive audio stories. They are currently running a [competition](https://www.richcast.com/competition) with cash prizes so if you like making that sort of thing I highly recommend it. For the next month I will be fixing bugs. After that I will make another release and then move to a three-month release cycle. At the start of each cycle I will plan what I intend to achieve in more detail than I have in the past. **Release Notes** Features: * Full screen and resolution support * Workshops: Weaponsmith, Armourer, Butchers, Tanners, Wood Smelter, Bronze Tool shop, Bronze Weaponsmith and Bronze Armourer * Tutorials: Mining, Building, Hunting, Stairs, Weapons, Ores, Smelting, Armour, Butchering, Tanning, Workshops, Inventory, Health, Harvesting, Stockpiles and Farming * Detailed combat system, skeletons, armour, injuries, weapon-types * Caverns and Ores * Weapons: Dagger, Spear, Battle-axe and Warhammer * Tools: Knife and Cleaver * Inventory * Dwerg portraits from personality * Copperpedes * Stockpile groups * Feedback for tools and job failure Known Issues: * Options: Saving and restoring applies to all options * Lava is solid and there is no heat model * Building: Sometimes build order prevents access to other build jobs * Rendering: Sometimes doors on the level below appear as if they are on the level above * Workshops: Re-ordering items sometimes breaks visually * Workshop tutorial: Does not proceed if there are no builders * Tooltip: Doesn't update when UI underneath changes * Mac: Some screens are not the correct size when resolution is set to high-res * Building: Sometimes jobs report materials are missing incorrectly * Jobs: Failure appears when only one Dwerg fails it * Workshop tutorial: Sometimes proceeds too soon when reloading while a workshop is under construction * Sometimes Dwergs flee even after being instructed to attack if they don't have a weapon * Cursor information does not update when things under it change * Mood is ecstatic while dying of thirst and hunger * Tutorials grab the camera * Workshop tutorial: Proceeds for items crafted in any workshops * Combat music continues even if hostiles are locked away (workaround: save and reload) * Sometimes builders hold on to building materials * Networked: Clients remain on Networking busy indicator when host quits (workaround: press escape)
Markdown
UTF-8
1,545
2.8125
3
[ "MIT" ]
permissive
# Dynamic matrix control ### Description: The control is a realization of mandatory access table using Javascript. It's absolutely standalone and it doesn't require to include additional libraries. ![example of dynamic matrix control - dymatrix](https://verych.github.io/dymatrix/example.png) ### How to use: ```html <script type="text/javascript" src="bin/dymatrix.min.js"></script> ``` and then: ```javascript dymatrix.init(selector, data, settings, onCreatedCallback); ``` ### Parameters: *selector* - jQuery selector to append rendered control into *data* - init data (see demo source) *settings* - ```{headerPopup: true|false, cellPopup: true|false}``` *onCreatedCallback* - callback when document is loaded and control is created. ### Demo page: https://verych.github.io/dymatrix/ ### Tested web-browsers: IE11, Edge, Firefox, Chrome, Safari. ### Tests coverage: ``` Dynamic Matrix Tests Level 0 (async) - object creating √ Creating matrix object (without container) (316ms) Level 1 - structure √ Number of created groups √ Number of created columns √ Number of created rows √ Number of created group headers √ Number of created bulk actions √ Number of created value cells Level 2 - values √ Initialization √ Bulk init state Level 3 - behaviour √ Simple click (202ms) √ Cycle click (587ms) √ Bulk click 12 passing (1s) ``` ### Used technologies: * node.js * webpack * babel * jquery * mocha * chai see all of them in the package file
Markdown
UTF-8
10,297
2.765625
3
[]
no_license
# 2.3 基于IDEA开发第一个MapReduce大数据程序WordCount >开源地址 https://github.com/wangxiaoleiAI/big-data [卜算子·大数据 目录](./../../README.md) >开源“卜算子·大数据”系列文章、源码,面向大数据(分布式计算)的编程、应用、架构——每周更新!Linux、Java、Hadoop、Spark、Sqoop、hive、pig、hbase、zookeeper、Oozie、flink...etc 本节主要内容: 前提:已经有了大数据集群 [2.2 Hadoop3.1.0完全分布式集群配置与部署](./2.2.Hadoop完全分布式集群配置与部署.md) - 在intellij IDEA中创建一个Gradle的Java程序。 - 引入依赖 - 编写第一个WordCount程序 - 启动大数据集群 - 在Idea中运行(开发、调试) - 在集群中运行(生产) - [项目源码](https://github.com/wangxiaoleiAI/big-data/tree/master/code/chapter2/2.3word-count-map-reduce) ![](./../image/chapter2/2.3/wordcount2-finish.png) ## 2.3.1 HDFS操作 >[官方命令大全](https://hadoop.apache.org/docs/r3.1.0/hadoop-project-dist/hadoop-common/FileSystemShell.html#copyFromLocal) ### 2.3.1.1 创建HDFS文件夹,创建 输入、输出分布式文件夹, ```sh hadoop fs -mkdir -p /cn/busuanzi/big-data/wordcount/input hadoop fs -mkdir -p /cn/busuanzi/big-data/wordcount/output hadoop fs -chmod 777 /cn/busuanzi/big-data/wordcount/output ``` ### 2.3.1.2 创建本地数据文件并将本地文件复制到分布式文件系统input中 ```sh echo "Hello World, Bye World!" > file01 echo "Hello Hadoop, Goodbye to hadoop." > file02 hadoop fs -copyFromLocal file01 /cn/busuanzi/big-data/wordcount/input hadoop fs -copyFromLocal file02 /cn/busuanzi/big-data/wordcount/input ``` ![](./../image/chapter2/2.3/hadoop-fs-ls.png) ### 2.3.1.3 查看input数据内容 ```sh hadoop fs -cat /cn/busuanzi/big-data/wordcount/input/file01 hadoop fs -cat /cn/busuanzi/big-data/wordcount/input/file02 ``` ![](./../image/chapter2/2.3/hadoop-fs-cat.png) ## 2.3.2 更改输出文件权限,任何人有写权限。因为从本地直接使用服务器的大数据集群环境,服务器集群文件没有写权限。 ```sh hadoop fs -mkdir -p /cn/busuanzi/big-data/wordcount/output hadoop fs -chmod 777 /cn/busuanzi/big-data/wordcount/output ``` ## 2.3.3 创建项目 ### 2.3.3.1 [项目源码](https://github.com/wangxiaoleiAI/big-data/tree/master/code/chapter2/2.3word-count-map-reduce)可以下载源码,直接导入项目,跳过此步骤。 gradle配置如下 ```Gradle plugins { id 'java' } group 'org.busuanzi.big-data' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile group: 'org.apache.hadoop', name: 'hadoop-mapreduce-client-core', version: '3.1.0' compile group: 'org.apache.hadoop', name: 'hadoop-common', version: '3.1.0' compile group: 'org.apache.hadoop', name: 'hadoop-client', version: '3.1.0' testCompile group: 'junit', name: 'junit', version: '4.12' } ``` ### 2.3.3.2 WordCout2.java [项目源码](https://github.com/wangxiaoleiAI/big-data/tree/master/code/chapter2/2.3word-count-map-reduce) ```Java package org.busuanzi.bigdata.wordcount; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.StringUtils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.util.*; /** * Create by wangxiaolei on 2018/6/22 9:58 AM */ public class WordCount2 { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{ static enum CountersEnum { INPUT_WORDS } private final static IntWritable one = new IntWritable(1); private Text word = new Text(); private boolean caseSensitive; private Set<String> patternsToSkip = new HashSet<String>(); private Configuration conf; private BufferedReader fis; @Override public void setup(Context context) throws IOException, InterruptedException { conf = context.getConfiguration(); caseSensitive = conf.getBoolean("wordcount.case.sensitive", true); if (conf.getBoolean("wordcount.skip.patterns", false)) { URI[] patternsURIs = Job.getInstance(conf).getCacheFiles(); for (URI patternsURI : patternsURIs) { Path patternsPath = new Path(patternsURI.getPath()); String patternsFileName = patternsPath.getName().toString(); parseSkipFile(patternsFileName); } } } private void parseSkipFile(String fileName) { try { fis = new BufferedReader(new FileReader(fileName)); String pattern = null; while ((pattern = fis.readLine()) != null) { patternsToSkip.add(pattern); } } catch (IOException ioe) { System.err.println("Caught exception while parsing the cached file '" + StringUtils.stringifyException(ioe)); } } @Override public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { String line = (caseSensitive) ? value.toString() : value.toString().toLowerCase(); for (String pattern : patternsToSkip) { line = line.replaceAll(pattern, ""); } StringTokenizer itr = new StringTokenizer(line); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); Counter counter = context.getCounter(CountersEnum.class.getName(), CountersEnum.INPUT_WORDS.toString()); counter.increment(1); } } } public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context ) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); GenericOptionsParser optionParser = new GenericOptionsParser(conf, args); String[] remainingArgs = optionParser.getRemainingArgs(); if ((remainingArgs.length != 2) && (remainingArgs.length != 4)) { System.err.println("Usage: wordcount <in> <out> [-skip skipPatternFile]"); System.exit(2); } Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount2.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); List<String> otherArgs = new ArrayList<String>(); for (int i=0; i < remainingArgs.length; ++i) { if ("-skip".equals(remainingArgs[i])) { job.addCacheFile(new Path(remainingArgs[++i]).toUri()); job.getConfiguration().setBoolean("wordcount.skip.patterns", true); } else { otherArgs.add(remainingArgs[i]); } } FileInputFormat.addInputPath(job, new Path(otherArgs.get(0))); FileOutputFormat.setOutputPath(job, new Path(otherArgs.get(1))); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` ## 2.3.4 IDEA运行设置参数 更改运行参数设置,添加输入、输出参数 ```text hdfs://192.168.56.106:9000/cn/busuanzi/big-data/wordcount/input/ hdfs://192.168.56.106:9000/cn/busuanzi/big-data/wordcount/output/1 ``` ![](./../image/chapter2/2.3/idea-1.png) ### 2.3.5 IDEA运行程序 ![](./../image/chapter2/2.3/wordcount2-finish1.png) ## 2.3.6 查看wordcout输出结果 ```sh # 查看当前output文件下内容 hadoop fs -ls /cn/busuanzi/big-data/wordcount/output/ # 文件已经多了一个1的文件夹 hadoop fs -ls /cn/busuanzi/big-data/wordcount/output/1 # 查看part-r-00000结果文件 hadoop fs -cat /cn/busuanzi/big-data/wordcount/output/1/part-r-00000 ``` ![](./../image/chapter2/2.3/wordcount2-finish.png) ## 2.3.7 命令行提交Jar,将本地文件scp到大数据集群master服务器上(生产环境) ### 2.3.7.1 使用Gradle打jar包 在项目根目录,运行命令,打完包后默认build/libs/WordCount-1.0-SNAPSHOT.jar ```sh gradle build ``` ### 2.3.7.2 将本地文件scp到大数据集群master服务器上 ```sh scp scp WordCount-1.0-SNAPSHOT.jar hadoop@192.168.56.106:/home/hadoop/ ``` ## 2.3.8 命令行运行程序(生产环境) ```sh hadoop jar WordCount-1.0-SNAPSHOT.jar cn/busuanzi/bigdata/wordcount/WordCount2 /cn/busuanzi/big-data/wordcount/input/ /cn/busuanzi/big-data/wordcount/output/2 ``` 查看输出结果 ```sh hadoop fs -cat /cn/busuanzi/big-data/wordcount/output/2/part-r-00000 ``` ![](./../image/chapter2/2.3/fs-cat-2.png) ## 2.3.9 至此已经完成了第一个大数据程序,具体的是基于Hadoop的MapReduce做的单词计数。 - 该教程主要是为了掌握大数据编程的正常的开发流程和方法。 - 利用本地集群、常用开发工具(idea\eclipse)来做大数据的开发、调试与快捷的打包提交大数据程序到集群。 - 至于涉及Hadoop安全问题,将会在之后的章节讲解。 - 至于涉及MapReduce原理,将在后续章节讲解。
C#
UTF-8
629
2.546875
3
[]
no_license
using System.ComponentModel.DataAnnotations; namespace HappyDog.Domain.DataTransferObjects.User { public class SignInDto { [Required(ErrorMessage = "请输入用户名")] [StringLength(12, ErrorMessage = "用户名最长12位")] [Display(Name = "用户名")] public string UserName { get; set; } [Required(ErrorMessage = "请输入密码")] [StringLength(16, ErrorMessage = "密码最长16位")] [Display(Name = "密码")] public string Password { get; set; } [Display(Name = "记住我")] public bool RememberMe { get; set; } } }
C
UTF-8
1,395
2.640625
3
[]
no_license
/****************************************************************************** filename StorageRoomDoor.c author Nico Hickman DP email nicholas.hickman@digipen.edu Brief Description: This file defines the functions to create a specific item, the "SRDoor". ******************************************************************************/ #include "stdafx.h" /* UNREFERENCED_PARAMETER, NULL*/ #include "StorageRoomDoor.h" /* Function declarations */ #include "GameState.h" /* struct GameState, GameState_ChangeScore */ #include "GameFlags.h" /* GameFlags_IsInList */ #include "WorldData.h" /* WorldData_GetRoom */ #include "Room.h" /* Room_GetItemList, Room_SetDescription */ #include "ItemList.h" /* ItemList_FindItem, ItemList_Remove, ItemList_Add */ #include "Item.h" /* Item_Create */ void SRDoor_Use(CommandContext context, GameState* gameState, WorldData* worldData) { UNREFERENCED_PARAMETER(context); UNREFERENCED_PARAMETER(gameState); UNREFERENCED_PARAMETER(worldData); if (GameFlags_IsInList(gameState->gameFlags, "srdoorOpen")) { gameState->currentRoomIndex = 4; printf("TODO: Move storage"); Room* currentRoom = WorldData_GetRoom(worldData, gameState->currentRoomIndex); Room_Print(currentRoom); } else { printf("TODO: NOT OPEN\n"); } } /* Build a "SRDoor" object */ Item* SRDoor_Build() { return Item_Create("srdoor", "TODO: Candy Description", false, SRDoor_Use, NULL, NULL); }
Java
UTF-8
6,529
2.328125
2
[]
no_license
package br.com.fiap.b2w.controller; import java.io.IOException; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.time.DateTimeException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import br.com.fiap.b2w.bo.PerfilBO; import br.com.fiap.b2w.model.Perfil; //REQUEST DISPATCHER N FUNCIONA? N RECONHECE ESSES IMPORTS PQ ERA UM PROJETO JAVA? 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("/perfilServlet") //public class PerfilServlet extends HttpServlet { // private static final long serialVersionUID = 1L; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) // throws ServletException, IOException { // // doPost(request, response); // // } // protected void doPost(HttpServletRequest request, HttpServletResponse response) // throws ServletException, IOException { // // request.setCharacterEncoding("UTF-8"); // // String acao = request.getParameter("acao"); // // switch (acao) { // case "cadastrar": // try { // inserirPerfil(request, response); // } catch (SQLException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // break; // //// case "listarTodos": //// listarPerfilTodos(request, response); //// break; //// //// case "listarId": //// listarPerfil(request, response, Integer.parseInt(request.getParameter("id_cad"))); //// break; //// //// case "atualizar": //// atualizarPerfil(request, response); //// break; //// //// case "excluir": //// excluirPerfil(request, response); //// break; // } // } // public void inserirPerfil // (HttpServletRequest request, HttpServletResponse response) // throws SQLException, IOException { // // // Recuperando os dados do request e adicionando a um objeto // // Perfil pf = new Perfil(); // //// pf.setAreaCad(request.getParameter("area")); // // // Passar os dados para o BO // PerfilBO pb = new PerfilBO(); // // int resultado = pb.cadastroPerfil(pf); // // Verifica��o do resultado para gerar uma mensagem para o usu�rio // // if (resultado == 1) { //// // Criando um redirecionamento com par�metros de sucesso //// //// response.sendRedirect("index.jsp?msgStatus=Os dados foram gravados com SUCESSO!"); //// } else { //// //// } //// // Criando um redirecionamento com par�metros de erro //// response.sendRedirect("index.jsp?msgStatus=Ocorreu um erro ao gravar os dados."); //// } //// // public void listarCadAssociadoTodos(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { // //Instanciar a classe BO // // PerfilBO pb = new PerfilBO(); // List<Perfil> lista = (List<Perfil>) pb.listagemPerfil(0); // // if(lista != null) { // // //Criando um atributo no request com a lista de clientes // request.setAttribute("lista_pf", lista); // // //Realizar o encaminhamento para a p�gina lista.jsp para carregar a lista de clientes // request.getRequestDispatcher("listaCadastro.jsp").forward(request,response); // }else { // // // //Criando um par�metro no com uma mensagem de erro para a p�gina JSP index. // //nao tem isso na index, talvez tirar // response.sendRedirect("index.jsp?msgStatus=Ocorreu um erro com a" + "listagem dos associados!"); // } // de onde vai vir esse m�todo, est� sendo criado aqui??? // public void listarPerfil(HttpServletRequest request , HttpServletResponse response, int idPf) throws ServletException,IOException { // // //Instanciar a classe BO // PerfilBO pbo = new PerfilBO(); // // Perfil pf = pbo.listagemPerfil(idPf); // // if(pf != null) { // // //Criando um atributo no request com o objeto // request .setAttribute("objPf", pf); // request .setAttribute("objIdPf", idPf); // // //Realizar o encaminhamento para a p�gina atualiza.jsp // request .getRequestDispatcher("atualiza.jsp").forward(request ,response); // // }else { // //Criando um par�metro com uma mensagem de erro. // response.sendRedirect("index.jsp?msgStatus=Ocorreu um erro com a sele��o atual."); // } //} // // public void atualizarPerfil(HttpServletRequest request,HttpServletResponse response) throws IOException { // // //Recuperando os dados do request e adicionando em um objeto. // CadAssociado cad = null; // // pf = new CadAssociado(); // pf.setAreaCad(request.getParameter("area")); // pf.setNomeCad(request.getParameter("nome")); // pf.setCpfCad(request.getParameter("cpf")); // pf.setNascCad(request.getParameter("nasc")); // pf.setEmailCad(request.getParameter("email")); // pf.setSenhaCad(request.getParameter("senha")); // pf.setValidaCad(request.getParameter("valida")); // pf.setTelCad(request.getParameter("telefone")); // // //Passar os dados para o BO // PerfilBO pb = new PerfilBO(); // // int resultado = cb.atualizaPerfil(pf,Integer.parseInt(request.getParameter("id"))); // //Verifica��o do resultado para gerar uma mensagem para o usu�rio // // // if(resultado == 1) { // //Criando um redirecionamento com par�metros. // response.sendRedirect("index.jsp?msgStatus=Os dados foram" // + "ATUALIZADOS com SUCESSO!"); // }else { // //Criando um redirecionamento com par�metros. // response.sendRedirect("index.jsp?msgStatus=Ocorreu um erro ao" // + "tentar ATUALIZAR os dados."); // } // } // private void excluirPerfil(HttpServletRequest request,HttpServletResponse response) throws IOException { // // //Passar os dados para o BO // PerfilBO cb = new PerfilBO(); // int resultado = pb.apagaCadAssociado(Integer.parseInt(request.getParameter("id_pf"))); // // //Verifica��o do resultado para gerar uma mensagem para o usu�rio. // if(resultado == 1) { // // //Criando um redirecionamento com par�metros. // response.sendRedirect("index.jsp?msgStatus=Registro excluido com" + "SUCESSO!"); // }else { // // } // //Criando um redirecionamento com par�metros. // response.sendRedirect("index.jsp?msgStatus=Ocorreu um erro ao" // + "tentar EXCLUIR o registro."); // } //// } //}
Python
UTF-8
171
2.984375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Mar 30 22:01:49 2019 @author: peter """ def numerical_diff(f,x):#微分 h=1e-4 return (f(x+h)-f(x-h))/(2*h)
Java
UTF-8
725
2.328125
2
[]
no_license
package com.intech.testing.publisher.service; import com.intech.testing.pubsub.common.data.MessageDto; import java.util.Random; public class MessageProducer { private final Random RANDOMIZER; private final MessageDto.Action[] ACTIONS; public MessageProducer() { RANDOMIZER = new Random(); ACTIONS = MessageDto.Action.values(); } public MessageDto produce() { return MessageDto.builder() .msisdn( RANDOMIZER.nextLong() ) .action( ACTIONS[RANDOMIZER.nextInt(ACTIONS.length)] ) .timestamp(System.currentTimeMillis()) .build(); } }
TypeScript
UTF-8
1,306
2.78125
3
[ "MIT" ]
permissive
import {Card} from '../entities/card'; import {Player} from '../entities/Player'; import {CardSpace} from '../entities/CardSpace'; import {Deck} from '../entities/Deck'; import { GameElementController } from "./GameElementController"; export class DeckController extends GameElementController { public showAllCards: () => void; public model: Deck; public getRandomCard = (): Card => { // TODO:should be move to service const rand = Math.floor(Math.random() * this.model.cards.length); const card: Card = this.model.cards[rand]; this.removeCardFromDeck(rand); return card; } public removeCardFromDeck(cardIndex){ this.model.cards.splice(cardIndex, 1); } public addCardToCardSpace(card: Card) { this.model.cardSpace.addCard(card); } public shuffle = (): void => { // TODO: Implement this.model.cards.forEach((element) => { console.log(element); }); } public assignCardSpace(cardSpace: CardSpace) { this.model.cardSpace = cardSpace; } public assignToPlayer(player: Player) { super.assignToPlayer(player); this.model.cards.forEach((card: Card) => { card.player = player; }); } }
Python
UTF-8
237
3.15625
3
[ "MIT" ]
permissive
""" https://www.hackerrank.com/challenges/polar-coordinates language: Python 3 Sample Input 1+2j Sample Output 2.23606797749979 1.1071487177940904 """ from cmath import phase z = complex(input()) print(abs(z)) print(phase(z))
TypeScript
UTF-8
2,546
2.78125
3
[ "MIT" ]
permissive
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; import { IsNotEmpty } from "class-validator"; export class UpdateDealDto { @IsNotEmpty({ message: `Please enter id&&&subject&&&Please enter id.`, }) @ApiProperty({ description: "Enter id", example: "", }) id: number; @ApiPropertyOptional({ type: "string", format: "binary", description: "deal image (Allow Only 'JPG,JPEG,PNG')", example: "", }) image: string; @ApiPropertyOptional({ description: "Enter location", example: "", }) location: string; @ApiPropertyOptional({ description: `hotel_location`, example: { title: "TD Waterhouse Stadium, London, Ontario, Canada", city: "London", state: "Ontario", country: "Canada", type: "poi", hotel_id: "", lat: "42.9998", long: "-81.2734", }, }) hotel_location: object; } class hotelLocation { @IsNotEmpty({ message: `Please select title.`, }) @ApiProperty({ description: `title`, example: ``, }) title: string; @IsNotEmpty({ message: `Please select city.`, }) @ApiProperty({ description: `city`, example: ``, }) city: string; @IsNotEmpty({ message: `Please select state.`, }) @ApiProperty({ description: `state`, example: ``, }) state: string; @IsNotEmpty({ message: `Please select country.`, }) @ApiProperty({ description: `country`, example: ``, }) country: string; @IsNotEmpty({ message: `Please select type.`, }) @ApiProperty({ description: `type`, example: ``, }) type: string; @IsNotEmpty({ message: `Please select lat.`, }) @ApiProperty({ description: `lat`, example: ``, }) lat: string; @IsNotEmpty({ message: `Please select long.`, }) @ApiProperty({ description: `long`, example: ``, }) long: string; @ApiPropertyOptional({ description: "hotel_id", example: "", }) hotel_id: string; }
Java
UTF-8
3,716
1.65625
2
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
/* * Copyright 2013-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.sleuth.instrument.zuul; import java.lang.invoke.MethodHandles; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.cloud.netflix.zuul.web.ZuulController; import org.springframework.cloud.netflix.zuul.web.ZuulHandlerMapping; import org.springframework.cloud.sleuth.instrument.web.TraceHandlerInterceptor; /** * Bean post processor that wraps {@link ZuulHandlerMapping} in its * trace representation. * * @author Marcin Grzejszczak * @since 1.0.3 */ class TraceZuulHandlerMappingBeanPostProcessor implements BeanPostProcessor { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private final BeanFactory beanFactory; private RouteLocator routeLocator; private ZuulController zuul; private ErrorController errorController; public TraceZuulHandlerMappingBeanPostProcessor(BeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ZuulHandlerMapping && !(bean instanceof TraceZuulHandlerMapping)) { if (log.isDebugEnabled()) { log.debug("Wrapping bean [" + beanName + "] of type [" + bean.getClass().getSimpleName() + "] in its trace representation"); } return new TraceZuulHandlerMapping(this.beanFactory, routeLocator(), zuulController(), errorController()); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } private static class TraceZuulHandlerMapping extends ZuulHandlerMapping { private final BeanFactory beanFactory; public TraceZuulHandlerMapping(BeanFactory beanFactory, RouteLocator routeLocator, ZuulController zuulController, ErrorController errorController) { super(routeLocator, zuulController); this.beanFactory = beanFactory; setErrorController(errorController); } @Override protected void extendInterceptors(List<Object> interceptors) { interceptors.add(new TraceHandlerInterceptor(this.beanFactory)); } } private RouteLocator routeLocator() { if (this.routeLocator == null) { this.routeLocator = this.beanFactory.getBean(RouteLocator.class); } return this.routeLocator; } private ZuulController zuulController() { if (this.zuul == null) { this.zuul = this.beanFactory.getBean(ZuulController.class); } return this.zuul; } private ErrorController errorController() { if (this.errorController == null) { try { this.errorController = this.beanFactory.getBean(ErrorController.class); } catch (BeansException b) { return null; } } return this.errorController; } }
Markdown
UTF-8
1,880
2.59375
3
[]
no_license
# Projet_MDSI_LAAS Projet 4IR S1 MDSI (UML/XML) ## Rappel des commandes à utiliser ### Pour vérifier la validité d’un document : ``` > xmllint --noout doc.xml --schema XSD/schema.xsd ``` avec : doc.xml : le document XML à tester schema.xsd : le schéma qui sert à la validation ### Pour créer un fichier HTML par transformation d’un document XML : ``` > xsltproc -output page.html transform.xslt doc.xml ``` avec : doc.xml : document XML à exploiter dans un affichage HTML transform.xslt : document de transformation XSLT pour le document XML à exploiter page.html : le document au format HTML créé pour un affichage des données ### Pour regrouper les différents documents xml : ``` > xsltproc -output bdd.xml merge.xslt empty.xml ``` avec : empty.xml : un document xml “fake”, juste pour ne pas avoir d’erreur de la part du parseur XML merge.xslt : document de tranformation XLST pour la fusion des documents XML bdd.xml : le document XML créé, équivalent de toute la base de données On peut tester chaque .xml de manière indépendante les uns des autres, au niveau de la syntaxe des documents par rapport aux.xsd, mais afin de tester la validité des références de clés, il faut tester la validité sur le document représentant la base de données entière bdd.xml ## Working ### clonner le projet : ``` git clone https://github.com/anaisrabary/Projet_MDSI_LAAS.git ``` ## travailler ``` git pull git add "nom_fichier" || git add . git commit -m "hey I work this" git push ``` ## Si conflit ``` git pull # conflit git diff --name-only --diff-filter=U # listing les fichiers en conflit # régler les parties conflit selon ce conseil: https://help.github.com/articles/resolving-a-merge-conflict-using-the-command-line/#competing-line-change-merge-conflicts # fini git add . git commit -m "Merge conflict dans ces fichiers" git push ```
Java
UTF-8
6,829
3.15625
3
[]
no_license
package controller.state; import controller.Controller; import data.Graph; import view.editor.Tab; import view.editor.elements.ElementView; import view.editor.elements.VertexView; import java.awt.*; import java.awt.event.MouseEvent; import java.util.HashMap; /** * Classe SelectionState gérant le mode de Sélection de l'application pour sélectionner unitairement les ElementView et avec la zone de sélection */ public class SelectionState extends State { /** * Constructeur de la classe SelectionState * @param controller le Controller de l'application */ public SelectionState(Controller controller) { super(controller); } /** * Méthode pour gérer la sélection d'un Vertex : * - soit on l'ajoute à la sélection si la touche Ctrl est enfoncée * - soit on désire le sélectionner * @param e MouseEvent pour récupérer l'événement isControlDown */ private void manageSelection(ElementView element, MouseEvent e) { if (e.isControlDown()) { this.controller.notifyHandleElementSelected(element); } else { this.controller.notifyHandleElement(element); } this.controller.notifyRepaintTab(); } /** * Override de la méthode quand on clique sur la feuille de dessin : * - si c'est un clic droit, on ouvre le PopUpMenu concernant le Tab * - on clôt l'affichage de la zone de sélection * @param tab le Tab qui a reçu l'événement souris clic * @param graph le Graph correspondant au Tab * @param e l'événement souris */ @Override public void click(Tab tab, Graph graph, MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { // Clic droit openTabPopUpMenu(tab, e.getPoint()); } this.controller.notifyClearSelection(); } /** * Override de la méthode quand on clique sur un ElementView : * - si c'est un clic droit, on demande au Controller de le sélectionner et on ouvre le PopuMenu concernant l'ElementView * @param element l'ElementView reçevant l'événement souris clic * @param e l'événement souris */ @Override public void click(ElementView element, MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { // Clic droit this.controller.notifyHandleElement(element); //Création du menu contextuel avec Edit et Delete comme options. HashMap<String, String> menus = new HashMap<String, String>(){{put("Edit", "Editer");}{put("Delete", "Supprimer");}{put("Copy", "Copier");}{put("Paste", "Coller");}}; initNewPopupMenu(menus, e.getPoint()).show(element, e.getX(), e.getY()); } } /** * Override la méthode quand on effectue un drag avec la souris sur le Tab : * - on créé une zone de sélection en sélectionnant les éléments selon si la touche Ctrl est enfoncée ou non * @param tab le Tab qui a reçu l'événement souris drag * @param graph le Graph correspondant au Tab * @param e l'événement souris */ @Override public void drag(Tab tab, Graph graph, MouseEvent e) { this.dragging = true; if (e.isControlDown()) { this.controller.notifyAddToDragging(this.sourceDrag, e.getPoint()); } else { this.controller.notifyDragging(this.sourceDrag, e.getPoint()); } } /** * Override de la méthode quand on effectue un drag avec la souris sur un VertexView : * - si on commence à faire le drag, on initialise le déplacement des ElementView sélectionnés * - sinon on déplace les ElementView sélectionnés * - on repeint le Tab et on sauvegarde la position actuelle du curseur * (non-Javadoc) * @see controller.state.State#drag(view.editor.elements.VertexView, java.awt.event.MouseEvent) */ @Override public void drag(VertexView vertex, MouseEvent e) { if (!this.dragging) { this.dragging = true; this.controller.notifyInitMoveSelectedElements(new Point(e.getX() - this.sourceDrag.x, e.getY() - this.sourceDrag.y)); } else { this.controller.notifyMoveSelectedElements(new Point(e.getX() - this.sourceDrag.x, e.getY() - this.sourceDrag.y)); } this.controller.notifyRepaintTab(); this.sourceDrag = e.getPoint(); } /** * Override de la méthode quand on presse le bouton de la souris sur la feuille de dessin : * - si on n'a pas la touche Ctrl enfoncée, on déselectionne les ElementView sélectionnés * @param tab le Tab qui a reçu l'événement souris drag * @param graph le Graph correspondant au Tab * @param e l'événement souris */ @Override public void pressed(Tab tab, Graph graph, MouseEvent e) { this.sourceDrag = new Point(e.getX(), e.getY()); // à mettre plus tard dans la méthode pressed de la classe mère ? if (!e.isControlDown()) { this.controller.notifyMousePressedWithoutControlDown(); } } /** * Override de la méthode quand on presse le bouton de la souris sur un ElementView : * - si c'est avec le clic gauche, on s'occupe de gérer la sélection de l'ElementView en fonction de l'état de la touche Ctrl * @param element l'ElementView reçevant l'événement souris pressed * @param e l'événement souris */ @Override public void pressed(ElementView element, MouseEvent e) { this.sourceDrag = new Point(e.getX(), e.getY()); if (e.getButton() == MouseEvent.BUTTON1) { manageSelection(element, e); } } /** * Override de la méthode quand on relâche le bouton de la souris sur la feuille de dessin : * - si on était en train d'effectuer un drag, on sélectionne les ElementView à l'intérieur de la zone de sélection * @param tab le Tab qui a reçu l'événement souris drag * @param graph le Graph correspondant au Tab * @param e l'événement souris */ @Override public void released(Tab tab, Graph graph, MouseEvent e) { if (this.dragging) { this.controller.notifyEndDragging(); } this.dragging = false; } /** * Override de la méthode quand on relâche le bouton de la souris sur un ElementView : * - si la touche Ctrl n'est pas enfoncée, on sélectionne l'ElementView * - si on était en train de faire un drag, on clôt le déplacement des ElementView sélectionnés * @param element l'ElementView reçevant l'événement souris released * @param e l'événement souris */ @Override public void released(ElementView element, MouseEvent e) { if (!e.isControlDown()) { this.controller.notifyHandleElement(element); } if (this.dragging) { this.controller.notifyEndMoveSelectedElements(); } this.dragging = false; } /** * Override de la méthode permettant de connaitre le Mode en cours * @return SELECTION, on est en mode SELECTION */ @Override public String getMode() { return "SELECTION"; } }
TypeScript
UTF-8
1,102
3.484375
3
[]
no_license
export type Handler<Args> = (args?: Args) => void; export interface IEvent<Args> { subscribe(handler: Handler<Args>): ISubscription; unsubscribe(handler: Handler<Args>): void; } export class EventDispatcher<Args> implements IEvent<Args> { private _handlers = new Array<Handler<Args>>(); subscribe(handler: Handler<Args>): ISubscription { this._handlers.push(handler); return new Subscription(this, handler); } unsubscribe(handler: Handler<Args>): void { const ind = this._handlers.indexOf(handler); if (ind > -1) { this._handlers.splice(ind, 1); } } dispatch(args?: Args): void { for (const handler of this._handlers) { handler(args); } } } export interface ISubscription { unsubscribe(): void; } class Subscription<Args> implements ISubscription { constructor(private event: IEvent<Args>, private handler: Handler<Args>) {} unsubscribe(): void { this.event.unsubscribe(this.handler); this.event = undefined; this.handler = undefined; } }
Python
UTF-8
1,108
3.796875
4
[]
no_license
import string def readlines(file): """Reads lines in a file and returns dict containing unique words and frequency of use""" word_frequency = {} for line in file: line = file.readline() words = line.strip().lower().split() for word in words: word = remove_punctuation(word) if word in word_frequency: word_frequency[word] += 1 else: word_frequency[word] = 1 return word_frequency def remove_punctuation(word): for letter in string.punctuation: word = word.replace(letter, "") return word if __name__ == '__main__': file = open('frankenstein.txt') words = readlines(file) output = open('output.html', 'w') output.write('<h2>%s unique words</h2>' % len(words)) output.write('<h2>%s total words</h2>' % sum(words.values())) output.write('<table>') for word in sorted(words, key=words.get, reverse=True): # print(word, words[word]) output.write('<tr><td>%s</td><td>%s</td></tr>' % (word, words[word])) output.write('</table>')