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
Python
UTF-8
1,262
2.6875
3
[]
no_license
#coding=utf-8 import psutil from util import data_from_pipe, l_split # Implementations for Mac OS X system def physmem(): return psutil.TOTAL_PHYMEM def swapinfo(): return (psutil.total_virtmem(),psutil.used_virtmem(),) # Return total and used swap def meminfo(): return (physmem(), psutil.avail_phymem(), psutil.used_phymem()) def cpuinfo(): return (psutil.NUM_CPUS, psutil.cpu_percent()) def iostat(): out = data_from_pipe('/usr/sbin/iostat','-d') disks = out[0].split() data = {} values = out[2].split() for i,a in enumerate(l_split(values, 3)): data[disks[i]]={'kbs':a[0],'tps':a[1],'mbs':a[2]} # Зачем это нужно? # Флаг 'style' может принимать значение MacOS, Linux, FreeBSD # Это свзяно с тем, что команда iostat выдает разную информация в разных ОС # И чтобы аггрегатор знал с чем работает добавлен этот флаг data['style'] = 'MacOS' return (data) def diskinfo(raw=False): out = data_from_pipe('/bin/df','-a')[1:] data = {} if raw: data['raw'] = out for line in out: line = line.split() if line: data[line[5]] = [line[1],line[2],line[3]] print data return (data)
Java
UTF-8
3,204
2.40625
2
[]
no_license
package com.zybooks.twister; import android.content.Context; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class DataFetcher { private Context mContext; public DataFetcher(Context context) { mContext = context; } public interface OnTwistsReceivedListener { void onTwistsReceived(ArrayList<Twist> twist); void onErrorResponse(VolleyError error); } public void getData(String HttpExtension, final OnTwistsReceivedListener listener) { // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(mContext); String url = "http://jsonstub.com" + HttpExtension; // Request a string response from the provided URL final JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonTwistArray = response.getJSONArray("twists"); ArrayList<Twist> twists = new ArrayList<>(); for (int i = 0; i < jsonTwistArray.length(); i++){ Twist twist = new Twist(); JSONObject jsonTwist = jsonTwistArray.getJSONObject(i); twist.setId(jsonTwist.getInt("id")); twist.setName(jsonTwist.getString("username")); twist.setDescription(jsonTwist.getString("message")); twist.setmTimeAgo(jsonTwist.getString("timestamp")); twists.add(twist); } listener.onTwistsReceived(twists); } catch (Exception ex) { Log.d("temp", "Error: " + ex.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onErrorResponse(error); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Content-Type", "application/json"); params.put("JsonStub-User-Key", "edbc267a-f880-4dec-8dec-727cccc27e5d"); params.put("JsonStub-Project-Key", "40e26003-fc1b-40f3-9ae4-bfab71e6d186"); return params; } }; // Add the request to the RequestQueue queue.add(jsonRequest); } }
Markdown
UTF-8
44,198
3.265625
3
[]
no_license
# Object-Oriented Programming — The Trillion Dollar Disaster Original Article: https://betterprogramming.pub/object-oriented-programming-the-trillion-dollar-disaster-92a4b666c7c7 ## Why it’s time to move on from OOP <img src="./images/2*9S9l47dN6pCSTT7yPa6nyg.jpeg" width="60"> Ilya Suzdalnitski Jul 10, 2019 · 27 min read <img alt="Photo by Jungwoo Hong on Unsplash" src="./images/1*yX-lpOM2F9cQYJqBl2dBSg.jpeg" width="400"> OOP is considered by many to be the crown jewel of computer science. The ultimate solution to code organization. The end to all our problems. The only true way to write our programs. Bestowed upon us by the one true God of programming himself… Until…it’s not, and people start succumbing under the weight of abstractions, and the complex graph of promiscuously shared mutable objects. Precious time and brainpower are being spent thinking about “abstractions” and “design patterns” instead of solving real-world problems. Many people have criticized Object-Oriented Programming, including very prominent software engineers. Heck, even the inventor of OOP himself is a well-known critic of modern OOP! The ultimate goal of every software developer should be to write *reliable* code. Nothing else matters if the code is buggy and unreliable. And what is the best way to write code that is reliable? *Simplicity*. Simplicity is the opposite of *complexity*. Therefore our first and foremost responsibility as software developers should be to *reduce code complexity.* <img src="https://miro.medium.com/max/1000/1*eSgw4TrT3_5kUU3QFFW4qA.jpeg" width="200"> ### Disclaimer I’ll be honest, I’m not a raving fan of object-orientation. Of course, this article is going to be biased. However, I have good reasons to dislike OOP. I also understand that criticism of OOP is a very sensitive topic — I will probably offend many readers. However, I’m doing what I think is right. My goal is not to offend, but to raise awareness of the issues that OOP introduces. I’m not criticizing Alan Kay’s OOP — he is a genius. I wish OOP was implemented the way he designed it. I’m criticizing the modern **Java/C#** approach to OOP. I think that it is not right that OOP is considered the de-facto standard for code organization by many people, including those in very senior technical positions. It is also unacceptable that many mainstream languages don’t offer any other alternatives to code organization other than OOP. Hell, I used to struggle a lot myself while working on OOP projects. And I had no single clue why I was struggling this much. Maybe I wasn’t good enough? I had to learn a couple more design patterns (I thought)! Eventually, I got completely burned out. This post sums up my first-hand decade-long journey from Object-Oriented to Functional programming. Unfortunately, no matter how hard I try, I can no longer find use cases for OOP. I have personally seen OOP projects fail because they become too complex to maintain. ### TLDR; > Object oriented programs are offered as alternatives to correct ones… > > — **Edger W. Dijkstra, pioneer of computer science** <img alt="Photo by Sebastian Herrmann on Unsplash" src="./images/1*MTb-Xx5D0H6LUJu_cQ9fMQ.jpeg" width="400"> Object-Oriented Programming has been created with one goal in mind — to *manage the complexity* of procedural codebases. In other words, it was supposed to *improve code organization.* There’s no objective and open evidence that OOP is better than plain procedural programming. The bitter truth is that OOP *fails* at the only task it was intended to address. It looks good on paper — we have clean hierarchies of animals, dogs, humans, etc. However, it falls flat once the complexity of the application starts increasing. Instead of reducing complexity, it encourages promiscuous *sharing of* *mutable state* and introduces additional complexity with its numerous *design patterns*. OOP makes common development practices, like refactoring and testing, needlessly hard. Some might disagree with me, but the truth is that modern Java/C# OOP has never been properly designed. It never came out of a proper research institution (in contrast with Haskell/FP). Lambda calculus offers a complete theoretical foundation for Functional Programming. OOP has nothing to match that. Using OOP is seemingly innocent in the short-term, especially on greenfield projects. But what are the *long-term* consequences of using OOP? OOP is a time bomb, set to explode sometime in the future when the codebase gets big enough. Projects get delayed, deadlines get missed, developers get burned-out, adding in new features becomes next to *impossible.* The organization labels the codebase as the *“legacy codebase”*, and the development team plans a *rewrite*. OOP is not natural for the human brain, our thought process is centered around “doing” things — go for a walk, talk to a friend, eat pizza. Our brains have evolved to do things, not to organize the world into complex hierarchies of abstract objects. OOP code is non-deterministic — unlike with functional programming, we’re not guaranteed to get the same output given the same inputs. This makes reasoning about the program very hard. As an oversimplified example, the output of `2+2` or `calculator.Add(2, 2)` mostly is equal to four, but sometimes it might become equal to three, five, and maybe even 1004. The dependencies of the `Calculator` object might change the result of the computation in subtle, but profound ways. OOPs… ### The Need for a Resilient Framework Good programmers write good code, bad programmers write bad code, no matter the programming paradigm. However, the programming paradigm should constrain bad programmers from doing too much damage. Of course, this is not you, since you already are reading this article and putting in the effort to learn. Bad programmers never have the time to learn, they only press random buttons on the keyboard like crazy. Whether you like it or not, you will be working with bad programmers, some of them will be really really bad. And, unfortunately, OOP does not have enough constraints in place that would prevent bad programmers from doing too much damage. OOPs… I don’t consider myself a bad programmer, but even I am unable to write good code without a strong framework to base my work on. Yes, there are frameworks that concern themselves with some very particular problems (e.g. Angular or ASP.Net). I’m not talking about the software frameworks. I’m talking about the more abstract *dictionary definition* of a framework: “an essential *supporting structure*” — frameworks that concern themselves with the more abstract things like code organization and tackling code complexity. Even though Object-Oriented and Functional Programming are both programming paradigms, they’re also both very high-level frameworks. ### Limiting our choices > C++ is a horrible \[object-oriented\] language… And limiting your project to C means that people > don’t screw things up with any idiotic “object model” c&@p. > — Linus Torvalds, the creator of Linux Linus Torvalds is widely known for his open criticism of C++ and OOP. One thing he was 100% right about is **limiting** programmers in the choices they can make. In fact, the **fewer choices** programmers have, the more **resilient** their code becomes. In the quote above, Linus Torvalds **highly recommends** having a good framework to base our code upon. <img alt="Photo by specphotops on Unsplash" src="./images/1*ujt2PMrbhCZuGhufoxfr5w.jpeg" width="400"> Many dislike speed limits on the roads, but they’re essential to help prevent people from crashing to death. Similarly, a good programming framework should provide mechanisms that prevent us from doing *stupid* things. A good programming framework helps us to write reliable code. First and foremost, it should help reduce complexity by providing the following things: 1. Modularity and reusability 2. Proper state isolation 3. High signal-to-noise ratio Unfortunately, OOP provides developers too many tools and choices, without imposing the right kinds of limitations. Even though OOP promises to address modularity and improve reusability, it fails to deliver on its promises (more on this later). OOP code encourages the use of shared mutable state, which has been proven to be unsafe time and time again. OOP typically requires a lot of boilerplate code (low signal-to-noise ratio). ## Functional programming What exactly is Functional Programming? Some people consider it to be a highly complicated programming paradigm that is only applicable in academia and is not suitable for the “real-world”. This couldn’t be further from the truth! Yes, Functional Programming has a strong mathematical foundation and takes its roots in lambda calculus. However, most of its ideas emerged as a response to the *weaknesses* in the more mainstream programming languages. *Functions* are the core abstraction of Functional Programming. When used properly, functions provide a level of code modularity and reusability never seen in OOP. It even features design patterns that address the issues of nullability and provides a superior way of error handling. The one thing that Functional Programming does really well is it helps us write *reliable* software. The need for a debugger almost disappears completely. Yep, no need to step through your code and watch variables. I personally haven’t touched a debugger in a very long time. The best part? If you already know how to use functions, then you’re already a functional programmer. You just need to learn how to make the best use of those functions! I’m not preaching Functional Programming, I don’t really care what programming paradigm you use writing your code. I’m simply trying to convey the mechanisms that Functional Programming provides to address the problems inherent with OOP/imperative programming. ## We Got OOP All Wrong > *I’m sorry that I long ago coined the term “objects” for this topic because it gets many people to > focus on the lesser idea. The big idea is messaging. > - Alan Kay, the inventor of OOP* Erlang is not usually thought of as an Object-Oriented language. But probably Erlang is the ***only*** mainstream Object-Oriented language out there. Yes, of course Smalltalk is a proper OOP language — however, it is not in wide use. Both Smalltalk and Erlang make use of OOP the way it was *originally intended* by its inventor, Alan Kay. ### Messaging Alan Kay coined the term “Object Oriented Programming” in the 1960s. He had a background in biology and was attempting to make computer programs communicate the same way living cells do. <img alt="Photo by Muukii on Unsplash" src="./images/1*bzRsnzakR7O4RMbDfEZ1sA.jpeg" width="300"> Alan Kay’s big idea was to have independent programs (cells) communicate by sending *messages* to each other. The state of the independent programs would *never be shared* with the outside world (encapsulation). That’s it. OOP was *never intended* to have things like inheritance, polymorphism, the “new” keyword, and the myriad of design patterns. ### OOP in its purest form Erlang is OOP in its *purest* form. Unlike more mainstream languages, it focuses on the core idea of OOP — messaging. In Erlang, objects communicate by passing immutable messages between objects. Is there proof that immutable messages are a superior approach compared to method calls? ***Hell yes!*** Erlang is probably the most *reliable* language in the world. It powers most of the world’s telecom (and hence the internet) infrastructure. Some of the systems written in Erlang have reliability of 99.9999999% (you read that right — nine nines). ## Code Complexity > With OOP-inflected programming languages, computer software becomes more verbose, less readable, > less descriptive, and harder to modify and maintain. > > — Richard Mansfield The *most important* aspect of software development is keeping the code complexity down. Period. None of the fancy features matter if the codebase becomes impossible to maintain. Even 100% test coverage is worth nothing if the codebase becomes too *complex* and *unmaintainable*. What makes the codebase complex? There are many things to consider, but in my opinion, the top offenders are: shared mutable state, erroneous abstractions, and low signal-to-noise ratio (often caused by boilerplate code). All of them are prevalent in OOP. ## The Problems of State <img alt="Photo by Mika Baumeister on Unsplash" src="./images/1*1WeuR9OoKyD5EvtT9KjXOA.jpeg" width="300"> What is state? Simply put, state is any temporary data stored in memory. Think variables or fields/properties in OOP. Imperative programming (including OOP) describes computation in terms of the program state and *changes to that state*. Declarative (functional) programming describes the *desired results* instead, and don’t specify changes to the state explicitly. ### Mutable State — the act of mental juggling > I think that large objected-oriented programs struggle with increasing complexity as you build > this large object graph of mutable objects. You know, trying to understand and keep in your mind > what will happen when you call a method and what will the side effects be. > > — Rich Hickey, creator of Clojure <img alt="Image source: https://www.flickr.com/photos/48137825@N05/8707342427" src="./images/1*n1piNNED9MaIjNPSLRj-8w.jpeg" width="300"> State by itself is quite harmless. However, mutable state is the big offender. Especially if it is shared. What exactly is mutable state? Any state that can change. Think variables or fields in OOP. ***Real-world example, please!*** You have a blank piece of paper, you write a note on it, and you end up with the same piece of paper in a different state (text). You, effectively, have mutated the state of that piece of paper. That is completely fine in the real world since *nobody* else probably cares about that piece of paper. Unless this piece of paper is the original Mona Lisa painting. **Limitations of the Human Brain** Why is mutable state such a big problem? The human brain is the most powerful machine in the known universe. However, our brains are really bad at working with state since we can only hold about *5 items* at a time in our working memory. It is much easier to reason about a piece of code if you only think about *what* the code does, not what variables it changes around the codebase. Programming with mutable state is an act of mental juggling️. I don’t know about you, but I could probably juggle two balls. Give me three or more balls and I will certainly drop all of them. Why are we then trying to perform this act of mental juggling every single day at work? Unfortunately, the mental juggling of mutable state is at the very core of OOP . The sole purpose for the existence of methods on an object is to mutate that same object. ## Scattered state <img alt="Photo by Markus Spiske on Unsplash" src="./images/1*G02W6-MM2CSCsa9DiA5NFg.jpeg" width="300"> OOP makes the problem of code organization even worse by scattering state all over the program. The scattered state is then shared *promiscuously* between various objects. **Real-world example, please!** Let’s forget for a second that we’re all grown-ups, and pretend we’re trying to assemble a cool lego truck. However, there’s a catch — all the truck parts are randomly mixed with parts from your other lego toys. And they have been put in 50 different boxes, randomly again. And you’re not allowed to group your truck parts together — you have to keep in your head where the various truck parts are, and can only take them out one by one. Yes, you will *eventually* assemble that truck, but how long will it take you? How does this relate to programming? In Functional Programming, state typically is being *isolated.* You always know where some state is coming from. State is never scattered across your different functions. In OOP, every object has its own state, and when building a program , you have to keep in mind the state of ***all*** of the objects that you currently are working with. To make our lives easier, it is best to have only a very small portion of the codebase deal with state. Let the core parts of your application be stateless and pure. This actually is the main reason for the huge success of the flux pattern on the frontend (aka Redux). ### Promiscuously shared state As if our lives aren’t already hard enough because of having scattered mutable state, OOP goes one step further! **Real-world Example, Please!** Mutable state in the real world is almost never a problem, since things are kept private and never shared. This is “proper encapsulation” at work. Imagine a painter who is working on the next Mona Lisa painting. He is working on the painting alone, finishes up, and then sells his masterpiece for millions. Now, he’s bored with all that money and decides to do things a little bit differently. He thinks that it would be a good idea to have a painting party. He invites his friends elf, Gandalf, policeman, and a zombie to help him out. Teamwork! They all start painting on the same canvas at the same time. Of course, nothing good comes out of it — the painting is a complete disaster! Shared mutable state makes no sense in the real world. Yet this is exactly what happens in OOP programs — state is promiscuously shared between various objects, and they mutate it in any way they see fit. This, in turn, makes reasoning about the program harder and harder as the codebase keeps growing. ### Concurrency issues The promiscuous sharing of mutable state in OOP code makes parallelizing such code almost impossible. Complex mechanisms have been invented in order to address this problem. Thread locking, mutex, and many other mechanisms have been invented. Of course, such complex approaches have their own drawbacks — deadlocks, lack of composability, debugging multi-threaded code is very hard and time-consuming. I’m not even talking about the increased complexity caused by making use of such concurrency mechanisms. ### Not all state is evil Is all state evil? No, Alan Kay state probably is not evil! State mutation probably is fine if it is truly isolated (not the “OOP-way” isolated). It is also completely fine to have immutable data-transfer-objects. The key here is “immutable”. Such objects are then used to pass data between functions. However, such objects would also make OOP methods and properties completely redundant. What’s the use in having methods and properties on an object if it cannot be mutated? ### Mutability is Inherent to OOP Some might argue that mutable state is a design choice in OOP, not an obligation. There is a problem with that statement. It is not a design choice, but pretty much the only option. Yes, one can pass immutable objects to methods in Java/C#, but this is rarely done since most of the developers default to data mutation. Even if developers attempt to make proper use of immutability in their OOP programs, the languages provide no built-in mechanisms for immutability, and for working effectively with immutable data (i.e. persistent data structures). Yes, we can ensure that objects communicate only by passing immutable messages and never pass any references (which is rarely done). Such programs would be more reliable than mainstream OOP. However, the objects still have to mutate their own state once a message has been received. A message is a side effect, and its single purpose is to cause changes. Messages would be useless if they couldn’t mutate the state of other objects. It is impossible to make use of OOP without causing state mutations. ## The Trojan Horse of Encapsulation <img alt="Photo by Jamie McInall from Pexels" src="./images/1*tKw00xGqVz0df_dFntT_Zg.jpeg" width="300"> We’ve been told that encapsulation is one of the greatest benefits of OOP. It is supposed to *protect* \*\*\*\* the object’s internal state from outside access. There’s a small problem with this though. It doesn’t work. Encapsulation is the *trojan horse* of OOP. It sells the idea of shared mutable state by making it *appear* safe. Encapsulation allows (and even encourages) unsafe code to sneak into our codebase, making the codebase rot from within. ### The global state problem We’ve been told that *global state* is the root of all evil. It should be avoided at all costs. What we have never been told is that encapsulation, in fact, is glorified global state. To make the code more efficient, objects are passed not by their value, but by their *reference*. This is where “dependency injection” falls flat. Let me explain. Whenever we create an object in OOP, we pass *references* to its dependencies to the *constructor*. Those dependencies also have their own *internal state.* The newly created object happily stores references to those dependencies in its internal state and is then happy to modify them in any way it pleases. And it also passes those references down to anything else it might end up using. This creates a complex graph of promiscuously shared objects that all end up changing each other’s state. This, in turn, causes *huge* problems since it becomes almost impossible to see what caused the program state to change. Days might be wasted trying to debug such state changes. And you’re lucky if you don’t have to deal with concurrency (more on this later). ## Methods/Properties The methods or properties that provide access to particular fields are *no better* than changing the value of a field directly. It doesn’t matter whether you mutate an object’s state by using a fancy property or method — the *result is the same: mutated state.* ## The Problem with Real World Modeling <img alt="Photo by Markus Spiske on Unsplash" src="./images/1*Jom0iTH8tdFrCnb1Ah99TA.jpeg" width="300"> Some people say that OOP tries to model the real world. This is simply not true — OOP has nothing to relate to in the real world. Trying to model programs as objects probably is one of the biggest OOP mistakes. ### The real world is not hierarchical OOP attempts to model everything as a hierarchy of objects. Unfortunately, that is not how things work in the real world. Objects in the real world interact with each other using messages, but they mostly are independent of each other. ### Inheritance in the real world OOP inheritance is not modeled after the real world. The parent object in the real world is unable to change the behavior of child objects at run-time. Even though you inherit your DNA from your parents, they’re unable to make changes to your DNA as they please. You do not inherit “behaviors” from your parents, you develop your own behaviors. And you’re unable to “override” your parents’ behaviors. ### The real world has no methods Does the piece of paper you’re writing on have a “write” *method*? No! You take an empty piece of paper, pick up a pen, and write some text. You, as a person, don’t have a “write” method either — you make the decision to write some text based on outside events or your internal thoughts. ## The Kingdom of Nouns > Objects bind functions and data structures together in indivisible units. I think this is a > fundamental error since functions and data structures belong in totally different worlds. > > — Joe Armstrong, creator of Erlang <img alt="Photo by Cederic X on Unsplash" src="./images/1*GuXanDmlOQ1UVX_73Kkojw.jpeg" width="300"> Objects (or nouns) are at the very core of OOP. A fundamental limitation of OOP is that it forces everything into nouns. And not everything should be modeled as nouns. Operations (functions) should not be modeled as objects. Why are we forced to create a `Multiplier`class when all we need is a function that multiplies two numbers? Simply have a `Multiply` function, let data be data and let functions be functions! In non-OOP languages, doing trivial things like saving data to a file is straightforward — very similar to how you would describe an action in plain English. **Real-world example, please!** Sure, going back to the painter example, the painter owns a `PaintingFactory`. He has hired a dedicated `BrushManager` , `ColorManager`, a `CanvasManager` and a `MonaLisaProvider`. His good friend zombie makes use of a `BrainConsumingStrategy`. Those objects, in turn, define the following methods: `CreatePainting` , `FindBrush` , `PickColor` , `CallMonaLisa` , and `ConsumeBrainz`. Of course, this is plain stupidity, and could never have happened in the real world. How much unnecessary complexity has been created for the simple act of drawing a painting? There’s no need to invent strange concepts to hold your functions when they’re allowed to exist separately from the objects. ## Unit Testing <img alt="Photo by Ani Kolleshi on Unsplash" src="./images/1*xGn4uGgVyrRAXnqSwTF69w.jpeg" width="300"> Automated testing is an important part of the development process and helps tremendously in preventing regressions (i.e. bugs being introduced into existing code). *Unit Testing* plays a huge role in the process of automated testing. Some might disagree, but OOP code is notoriously difficult to unit test. Unit Testing assumes testing things in isolation, and to make a method unit-testable: 1. Its dependencies have to be extracted into a separate class. 2. Create an interface for the newly created class. 3. Declare fields to hold the instance of the newly created class. 4. Make use of a mocking framework to mock the dependencies. 5. Make use of a dependency-injection framework to inject the dependencies. How much more complexity has to be created just to make a piece of code testable? How much time was wasted just to make some code testable? > *PS we’d also have to instantiate the entire class in order to test a single method. This will also bring in the code from all of its parent classes.* With OOP, writing tests for legacy code is even harder — almost impossible. Entire companies have been created (TypeMock) around the issue of testing legacy OOP code. ### Boilerplate code Boilerplate code is probably the biggest offender when it comes to the signal-to-noise ratio. Boilerplate code is “noise” that is required to get the program to compile. Boilerplate code takes time to write and makes the codebase less readable because of the added noise. While “program to an interface, not to an implementation” is the recommended approach in OOP, not everything should become an interface. We’d have to resort to using interfaces in the entire codebase, for the sole purpose of testability. We’d also probably have to make use of dependency injection, which further introduced unnecessary complexity. ### Testing private methods Some people say that private methods shouldn’t be tested… I tend to disagree, unit testing is called “unit” for a reason — test small units of code in isolation. Yet testing of private methods in OOP is nearly impossible. We shouldn’t be making private methods`internal` just for the sake of testability. In order to achieve testability of private methods, they usually have to be extracted into a separate object. This, in turn, introduces unnecessary complexity and boilerplate code. ## Refactoring Refactoring is an important part of a developer’s day-to-day job. Ironically, OOP code is notoriously hard to refactor. Refactoring is supposed to make the code less complex, and more maintainable. On the contrary, refactored OOP code becomes significantly more complex — to make the code testable, we’d have to make use of dependency injection, and create an interface for the refactored class. Even then, refactoring OOP code is really hard without dedicated tools like Resharper. In the simple example above, the line count has more than doubled just to extract a single method. Why does refactoring create even more complexity, when the code is being refactored in order to decrease complexity in the first place? Contrast this to a similar refactor of non-OOP code in JavaScript: ```js // before refactoring: public class CalculatorForm { private string aText, bText; private bool IsValidInput(string text) => true; private void btnAddClick(object sender, EventArgs e) { if ( !IsValidInput(bText) || !IsValidInput(aText) ) { return; } } } // after refactoring: public class CalculatorForm { private string aText, bText; private readonly IInputValidator _inputValidator; public CalculatorForm(IInputValidator inputValidator) { _inputValidator = inputValidator; } private void btnAddClick(object sender, EventArgs e) { if ( !_inputValidator.IsValidInput(bText) || !_inputValidator.IsValidInput(aText) ) { return; } } } public interface IInputValidator { bool IsValidInput(string text); } public class InputValidator : IInputValidator { public bool IsValidInput(string text) => true; } public class InputValidatorFactory { public IInputValidator CreateInputValidator() => new InputValidator(); } ``` The code has literally stayed the same — we simply moved the `isValidInput` function to a different file and added a single line to import that function. We’ve also added `_isValidInput` to the function signature for the sake of testability. This is a simple example, but in practice the complexity grows exponentially as the codebase gets bigger. And that’s not all. Refactoring OOP code is *extremely risky*. Complex dependency graphs and state scattered all over OOP codebase, make it impossible for the human brain to consider all of the potential issues. ## The Band-aids <img alt="Photo by Pixabay on Unsplash" src="./images/1*JOtbVvacgu-nH3ZR4mY2Og.jpeg" width="300"> What do we do when something is not working? It is simple, we only have two options — throw it away or try fixing it. OOP is something that can’t be thrown away easily, millions of developers are trained in OOP. And millions of organizations worldwide are using OOP. You probably see now that OOP *doesn’t really work*, it makes our code complex and unreliable. And you’re not alone! People have been thinking hard for *decades* trying to address the issues prevalent in OOP code. They’ve come up with a myriad of \*design patterns\*\*.\* ### Design patterns OOP provides a set of guidelines that should *theoretically* allow developers to incrementally build larger and larger systems: SOLID principle, dependency injection, design patterns, and others. Unfortunately, the design patterns are nothing other than band-aids. They exist solely to address the *shortcomings* of OOP. A myriad of books has even been written on the topic. They wouldn’t have been so bad, had they not been responsible for the introduction of enormous complexity to our codebases. ### The problem factory In fact, it is impossible to write good and maintainable Object-Oriented code. On one side of the spectrum we have an OOP codebase that is inconsistent and doesn’t seem to adhere to any standards. On the other side of the spectrum, we have a tower of over-engineered code, a bunch of erroneous abstractions built one on top of one another. Design patterns are very helpful in building such towers of abstractions. Soon, adding in new functionality, and even making sense of all the complexity, gets harder and harder. The codebase will be full of things like `SimpleBeanFactoryAwareAspectInstanceFactory`, `AbstractInterceptorDrivenBeanDefinitionDecorator`, `TransactionAwarePersistenceManagerFactoryProxy`or`RequestProcessorFactoryFactory` . Precious brainpower has to be wasted trying to understand the tower of abstractions that the developers themselves have created. The absence of structure is in many cases better than having bad structure (if you ask me). <img alt="Image source: https://www.reddit.com/r/ProgrammerHumor/comments/418x95/theory_vs_reality/" src="./images/1*_xDSrTC0F2lke6OYtkRm8g.png" width="1000"> Further reading: [FizzBuzzEnterpriseEdition](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition) ## The Fall of the Four OOP Pillars The four pillars of OOP are: 1. Abstraction, 2. Inheritance, 3. Encapsulation, 4. and Polymorphism. Let’s see what they really are, one-by-one. ### Inheritance > I think the lack of reusability comes in object-oriented languages, not in functional languages. > Because the problem with object-oriented languages is they’ve got all this implicit environment > that they carry around with them. You wanted a banana but what you got was a gorilla holding the > banana and the entire jungle. > > — Joe Armstrong, creator of Erlang OOP inheritance has nothing to do with the real world. Inheritance, in fact, is an inferior way to achieve code reusability. The gang of four has explicitly recommended preferring composition over inheritance. Some modern programming languages avoid inheritance altogether. There are a few problems with inheritance: 1. Bringing in a lot of code that your class doesn’t even need (banana and the jungle problem). 2. Having parts of your class defined somewhere else makes the code hard to reason about, especially with multiple levels of inheritance. 3. In most programming languages, multiple inheritance isn’t even possible. This mostly renders inheritance useless as a code-sharing mechanism. ### OOP polymorphism Polymorphism is great, it allows us to change program behavior at runtime. However, it is a very basic concept in computer programming. I’m not too sure why OOP focuses so much on polymorphism. OOP polymorphism gets the job done but once again it results in the act of mental juggling. It makes the codebase significantly more complex, and reasoning about the concrete method that is being invoked becomes really hard. Functional programming, on the other hand, allows us to achieve the same polymorphism in a much more elegant way…by simply passing in a function that defines the desired runtime behavior. What could be simpler than that? No need to define a bunch of overloaded abstract virtual methods in multiple files (and the interface). ### Encapsulation As we discussed earlier, encapsulation is the trojan horse of OOP. It is actually a glorified global mutable state and makes the *unsafe* code appear safe. An unsafe coding practice is a pillar that OOP programmers rely on in their day-to-day job… ### Abstraction Abstraction in OOP attempts to tackle complexity by hiding unnecessary details from the programmer. *Theoretically*, it should allow the developer to reason about the codebase without having to think about the hidden complexity. I don’t even know what to say…a fancy word for a simple concept. In procedural/functional languages we can simply “hide” the implementation details in a neighboring file. No need to call this basic act an “abstraction”. *For more details on the fall of OOP pillars, please read* *Goodbye, Object Oriented Programming* ## Why Does OOP Dominate the Industry? The answer is simple, the reptiloid alien race has conspired with the NSA (and the Russians) to torture us programmers to death… <img alt="Photo by Gaetano Cessati on Unsplash" src="./images/1*5XI0phuXVaXDD5hcVv6clA.jpeg" width="300"> But seriously, Java is probably the answer. > Java is the most distressing thing to happen to computing since MS-DOS. > > \- Alan Kay, the inventor of object-oriented programming ### Java was Simple When it was first introduced in 1995, Java was a very simple programming language, compared to the alternatives. At that time, the barrier of entry for writing desktop applications was high. Developing desktop applications involved writing low-level win32 APIs in C, and developers also had to concern themselves with manual memory management. The other alternative was Visual Basic, but many probably didn’t want to lock themselves into the Microsoft ecosystem. When Java was introduced, it was a no-brainer for many developers since it was free, and could be used across all platforms. Things like built-in garbage collection, friendly-named APIs (compared to the cryptic win32 APIs), proper namespaces, and familiar C-like syntax made Java even more approachable. GUI programming was also becoming more popular, and it seemed that various UI components mapped well to classes. Method autocompletion in the IDEs also made people claim that OOP APIs are easier to use. Perhaps Java wouldn’t have been so bad had it not forced OOP on developers. Everything else about Java seemed pretty good. Its garbage collection, portability, exception handling features, which other mainstream programming languages lacked, were really great in 1995, ### Then C# came along Initially, Microsoft had been relying heavily on Java. When things started getting awry (and after a long legal battle with Sun Microsystems over Java licensing), Microsoft decided to invest in its own version of Java. That is when C# 1.0 was born. C# as a language has always been thought of as “the better Java”. However, there’s one huge problem — it was the same OOP language with the same flaws, hidden under a slightly improved syntax. Microsoft has been investing heavily in its .NET ecosystem, which also included good developer tooling. For years Visual Studio has probably been one of the best IDEs available. This, in turn, has led to wide-spread adoption of the .NET framework, especially in the enterprise. More recently Microsoft has been investing heavily in the browser ecosystem, by pushing its TypeScript. TypeScript is great because it can compile pure JavaScript and adds in things like static type checking. What’s not so great about it is it has no proper support for functional constructs — no built-in immutable data structures, no function composition, no proper pattern matching. TypeScript is OOP-first, and mostly is C# for the browser. Anders Hejlsberg was even responsible for the design of both C# and TypeScript. ### Functional languages Functional languages, on the other hand, have never been backed by someone as big as Microsoft. F# doesn’t count since the investment was minuscule. The development of functional languages is mostly community-driven. This probably explains the differences in popularity between OOP and FP languages. ## Time to Move On? > We now know that OOP is an experiment that failed. It is time to move on. It is time that we, as a > community, admit that this idea has failed us, and we must give up on it. > > \- Lawrence Krubner <img alt='Photo by SpaceX on Unsplash' src='./images/1*jfFiJr4OxVaU882JZBp1Hg.jpeg' width='400'> Why are we stuck using something that fundamentally is a suboptimal way to organize programs? Is this plain ignorance? I doubt it, the people working in software engineering aren’t stupid. Are we perhaps more worried about “looking smart” in the face of our peers by making use of fancy OOP terms like “design patterns”, “abstraction”, “encapsulation”, “polymorphism” and “interface segregation”? Probably not. I think that it’s really easy to continue using something that we’ve been using for decades. Most of the people have never really tried Functional Programming. Those who have (like myself) can never go back to writing OOP code. Henry Ford once famously said — “If I had asked people what they wanted, they would have said *faster horses*”. In the world of software, most people would probably want a “better OOP language”. People can easily describe a problem they’re having (getting the codebase organized and less complex), but not the best solution. ## What Are the Alternatives? *Spoiler alert: Functional Programming*. <img alt='Photo by Harley-Davidson on Unsplash' src='./images/1*Ljy--Q00zpoRgQE1SJRReA.jpeg' width='400'> If terms like functors and monads make you a little uneasy, then you’re not alone! Functional Programming wouldn’t have been so scary had they given more intuitive names to some of its concepts. Functor? That’s simply something we can transform with a function, think `list.map`. Monad? Simply computations that can be chained! Trying out Functional Programming will make you a better developer. You will finally have the time to write real code that solves real-world problems, rather than having to spend most of your time thinking about abstractions and design patterns. You might not realize this, but you already are a functional programmer. Are you using functions in your day-to-day work? Yes? Then you’re already a functional programmer! You just have to learn how to make the best use of those functions. Two great functional languages with a very gentle learning curve are Elixir and Elm. They let the developer focus on what matters most — writing reliable software while removing all of the complexity that more traditional functional languages have. What are the other options? Is your organization already is using C#? Give F# a try — it is an amazing functional language, and provides great interoperability with the existing .NET code. Using Java? Then using Scala or Clojure are both really good options. Using JavaScript? With the right guidance and linting, JavaScript can be a good functional language. ## The Defenders of OOP <img alt='Photo by Ott Maidre from Pexels' src='./images/1*P5vemKZMHHBFySM644aCzQ.jpeg' width='400'> I expect some sort of reaction from the defenders of OOP. They will say that this article is full of inaccuracies. Some might even start calling names. They might even call me a “junior” developer with no real-world OOP experience. Some might say that my assumptions are erroneous, and examples are useless. Whatever. They have the right to their opinion. However, their arguments in the defense of OOP are usually quite weak. It is ironic that most of them probably have never really programmed in a true functional language. How can someone draw comparisons between two things if you have never really tried both? Such comparisons aren’t very useful. The Law of Demeter is not very useful — it does nothing to address the issue of non-determinism, shared mutable state is still shared mutable state, no matter how you access or mutate that state. `a.total()`is not much better than `a.getB().getC().total()`. It simply sweeps the problem under the rug. Domain-Driven Design? That’s a useful design methodology, it helps a bit with the complexity. However, it still does nothing to address the fundamental issue of shared mutable state. ### Just a tool in a toolbox… I often hear people say that OOP is just another tool in a toolbox. Yes, it is as much a tool in a toolbox as horses and cars are both tools for transportation… After all, they all serve the same purpose, right? Why use cars when we can continue riding good old horses? ### History repeats itself This actually reminds me of something. At the beginning of the 20th century, automobiles started replacing the horses. In the year 1900 New York had only a few cars on the roads, people have been using horses for transportation. In the year 1917, no more horses were left on the roads. A huge industry was centered around horse transportation. Entire businesses have been created around things like manure cleaning. And people resisted change. They called automobiles another “fad” that eventually pass. After all, horses have been here for centuries! Some even asked the government to intervene. How is this relevant? The software industry is centered around OOP. Millions of people are trained in OOP, and millions of companies make use of OOP in their code. Of course, they will try to discredit anything that threatens their bread-and-butter! It’s just common sense. We clearly see the history repeating itself — in the 20th century it was the horses vs automobiles, in the 21st century it is Object-Oriented vs Functional Programming.
SQL
UTF-8
5,871
3.25
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.5.4.1deb2ubuntu2.1 -- http://www.phpmyadmin.net -- -- Хост: localhost -- Время создания: Дек 06 2018 г., 00:46 -- Версия сервера: 10.0.36-MariaDB-0ubuntu0.16.04.1 -- Версия PHP: 7.0.32-0ubuntu0.16.04.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!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 utf8mb4 */; -- -- База данных: `test_db` -- -- -------------------------------------------------------- -- -- Структура таблицы `collaborators` -- CREATE TABLE `collaborators` ( `id` bigint(19) NOT NULL, `fullname` varchar(900) CHARACTER SET utf8 DEFAULT NULL, `org_id` bigint(19) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Дамп данных таблицы `collaborators` -- INSERT INTO `collaborators` (`id`, `fullname`, `org_id`) VALUES (1, 'Джордж Вашингтон', 1), (3, 'Исаак Ньютон', 1), (4, 'Альберт Эйнштейн', 2), (5, 'Луи Пастер', 1), (6, 'Антуан Лавуазье', 2), (7, 'Джеймс Максвелл', 2), (8, 'Мартин Лютер', 1); -- -------------------------------------------------------- -- -- Структура таблицы `courses` -- CREATE TABLE `courses` ( `id` bigint(19) NOT NULL, `name` varchar(900) CHARACTER SET utf8 DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Дамп данных таблицы `courses` -- INSERT INTO `courses` (`id`, `name`) VALUES (1, 'Планирование. Объекты закупок'), (2, 'Планирование. Детализированные объекты закупок'), (3, 'Планирование. Планы-графики'), (4, 'Реестр контрактов. Ввод сведений о переходящих контрактах'); -- -------------------------------------------------------- -- -- Структура таблицы `learnings` -- CREATE TABLE `learnings` ( `id` bigint(19) NOT NULL, `person_id` bigint(19) DEFAULT NULL, `course_id` bigint(19) DEFAULT NULL, `state_id` bigint(19) DEFAULT NULL, `start_date` datetime DEFAULT NULL, `finish_date` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Дамп данных таблицы `learnings` -- INSERT INTO `learnings` (`id`, `person_id`, `course_id`, `state_id`, `start_date`, `finish_date`) VALUES (1, 1, 1, 2, '2018-12-01 02:06:13', '2018-12-02 04:00:00'), (2, 1, 1, 3, '2018-12-01 01:00:00', '2018-12-03 01:00:00'), (3, 3, 2, 2, '2018-12-02 00:00:00', '2018-12-04 00:00:00'), (4, 4, 2, 4, '2018-12-02 00:00:00', '2018-12-03 00:00:00'), (5, 5, 1, 3, '2018-12-02 00:00:00', '2018-12-05 00:00:00'), (7, 7, 1, 2, '2018-12-01 00:00:00', '2018-12-03 00:00:00'), (8, 8, 3, 1, '2018-12-03 00:00:00', '2018-12-05 00:00:00'), (9, 1, 3, 2, '2018-12-03 00:00:00', '2018-12-05 00:00:00'), (10, 4, 4, 4, '2018-12-02 00:00:00', '2018-12-04 00:00:00'), (11, 6, 2, 2, '2018-12-04 00:00:00', '2018-12-05 00:00:00'), (12, 7, 3, 4, '2018-12-02 00:00:00', '2018-12-04 00:00:00'), (13, 3, 1, 2, '2018-12-02 00:00:00', '2018-12-05 00:00:00'), (14, 5, 4, 3, '2018-12-01 00:00:00', '2018-12-02 00:00:00'), (15, 8, 4, 2, '2018-12-03 00:00:00', '2018-12-05 00:00:00'), (16, 8, 2, 4, '2018-12-01 00:00:00', '2018-12-04 00:00:00'), (17, 1, 2, 2, '2018-12-01 00:00:00', '2018-12-03 00:00:00'), (18, 1, 4, 3, '2018-12-03 00:00:00', '2018-12-04 00:00:00'), (19, 3, 3, 2, '2018-12-03 00:00:00', '2018-12-04 00:00:00'), (20, 3, 4, 4, '2018-12-02 00:00:00', '2018-12-04 00:00:00'), (21, 4, 1, 1, '2018-12-01 00:00:00', '2018-12-03 00:00:00'), (22, 4, 3, 2, '2018-12-02 00:00:00', '2018-12-05 00:00:00'), (23, 5, 2, 2, '2018-12-02 00:00:00', '2018-12-03 00:00:00'), (24, 6, 3, 2, '2018-12-04 00:00:00', '2018-12-05 00:00:00'), (25, 6, 4, 3, '2018-12-02 00:00:00', '2018-12-05 00:00:00'), (26, 7, 4, 3, '2018-12-03 00:00:00', '2018-12-05 00:00:00'); -- -------------------------------------------------------- -- -- Структура таблицы `orgs` -- CREATE TABLE `orgs` ( `id` bigint(19) NOT NULL, `name` varchar(900) CHARACTER SET utf8 DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Дамп данных таблицы `orgs` -- INSERT INTO `orgs` (`id`, `name`) VALUES (1, 'Администрация Пермского края'), (2, 'Администрация города Перми'); -- -- Индексы сохранённых таблиц -- -- -- Индексы таблицы `collaborators` -- ALTER TABLE `collaborators` ADD PRIMARY KEY (`id`); -- -- Индексы таблицы `courses` -- ALTER TABLE `courses` ADD PRIMARY KEY (`id`); -- -- Индексы таблицы `learnings` -- ALTER TABLE `learnings` ADD PRIMARY KEY (`id`); -- -- Индексы таблицы `orgs` -- ALTER TABLE `orgs` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT для сохранённых таблиц -- -- -- AUTO_INCREMENT для таблицы `collaborators` -- ALTER TABLE `collaborators` MODIFY `id` bigint(19) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT для таблицы `courses` -- ALTER TABLE `courses` MODIFY `id` bigint(19) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT для таблицы `learnings` -- ALTER TABLE `learnings` MODIFY `id` bigint(19) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27; -- -- AUTO_INCREMENT для таблицы `orgs` -- ALTER TABLE `orgs` MODIFY `id` bigint(19) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
TypeScript
UTF-8
624
2.5625
3
[]
no_license
import axios from 'axios' // create an axios instance const service = axios.create({ timeout: 5000 // request timeout }) // request interceptor service.interceptors.request.use( config => { return config }, error => { // do something with request error return Promise.reject(error) } ) // response interceptor service.interceptors.response.use( response => { const res = response.data if (res.code !== 200) { return Promise.reject(new Error(res.message || 'Error')) } else { return res } }, error => { return Promise.reject(error) } ) export default service
Rust
UTF-8
956
3.125
3
[]
no_license
use std::borrow::Borrow; use std::hash::Hash; use std::any::Any; use std::sync::Arc; use std::collections::HashMap; #[derive(Default, Clone, Debug)] pub struct AnyHashMap<K>(HashMap<K, Arc<dyn Any + 'static + Send + Sync>>); impl<K: Eq + Hash> AnyHashMap<K> { pub fn insert<V: 'static + Send + Sync>(&mut self, key: K, value: V) -> Arc<V> { let value = Arc::new(value); self.0.insert(key, value.clone()); value } pub fn or_insert_with<F: FnOnce() -> V, V: 'static + Send + Sync>(&mut self, key: K, f: F) -> Arc<V> { if let Some(r) = self.get(&key) { r } else { self.insert(key, f()) } } pub fn get<Q: ?Sized + Eq + Hash, V: 'static + Send + Sync>(&self, key: &Q) -> Option<Arc<V>> where K: Borrow<Q> { let any = self.0.get(key)?.clone(); match any.downcast::<V>() { Ok(r) => Some(r), _ => None, } } }
Java
UTF-8
520
2.09375
2
[ "Apache-2.0" ]
permissive
package customer; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.net.URL; import org.junit.Test; import com.cloudant.client.api.ClientBuilder; public class CloudantDatabaseBuilder_cbTest { @Test public void clientBuilder_good() throws MalformedURLException { CloudantDatabaseBuilder builder = new CloudantDatabaseBuilder(); URL url = new URL("http", "test.com", 1234, ""); ClientBuilder cb = builder.clientBuilder(url); assertTrue(cb != null); } }
C++
UTF-8
256
2.90625
3
[]
no_license
#include<iostream> using namespace std; int main(){ for (int i=1;i<=100;i++){ if(i%3==0){ cout<<"Fizz "; } else if(i%5==0){ cout<<"Buzz "; } else if(i%15==0){ cout<<"FizzBuzz "; } else{ cout<<i<<" "; } } }
Java
UTF-8
2,013
2.078125
2
[]
no_license
package com.test.kambi.task; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.test.kambi.handler.NetworkHandler; import com.test.kambi.handler.ResponseHandler; import com.test.kambi.model.Event; import com.test.kambi.model.LiveEvent; import com.test.kambi.model.ResponseBody; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; public class EventCheckerTaskTest extends Mockito { private ObjectMapper mapper; @Before public void setUp() { mapper = new ObjectMapper(); } @Test public void runTest() throws InterruptedException, ExecutionException, TimeoutException, IOException { NetworkHandler networkHandler = mock(NetworkHandler.class); Optional<String> responseBody = getDummyResponse(); when(networkHandler.getApiResponseBody()).thenReturn(responseBody); ResponseHandler responseHandler = mock(ResponseHandler.class); EventCheckerTask eventCheckerTask = new EventCheckerTask(networkHandler, responseHandler, 2312312); eventCheckerTask.run(); verify(responseHandler).handleResponseBody(anyString(), anyLong()); } private Optional<String> getDummyResponse() throws JsonProcessingException { ResponseBody responseBody = new ResponseBody(); List<LiveEvent> liveEvents = new ArrayList<>(); LiveEvent liveEvent1 = new LiveEvent(); Event event1 = new Event(); event1.setId(200044); event1.setTags(Arrays.asList("MATCH", "OPEN_FOR_LIVE")); liveEvent1.setEvent(event1); liveEvents.add(liveEvent1); responseBody.setLiveEvents(liveEvents); return Optional.of(mapper.writeValueAsString(responseBody)); } }
Markdown
UTF-8
1,377
3.671875
4
[]
no_license
_Exercise 3-1: In English, write out the ow for a simple computer game, such as Pong. If you’re not familiar with Pong, visit: http://en.wikipedia.org/wiki/Pong to find out about it_ # PONG 1. Draw a centerline, paddles on left and right edges of the screen, a ball in the centre, and a score for each paddle at the top of the screen. 2. Launch the ball to the left if the right paddle just won a point, to the right if the left paddle just won a point, and in a random direction if this is the first point. 3. When the left player moves their joystick up, move the left paddle up. 4. When the left player moves their joystick down, move the left paddle down. 5. When the right player moves their joystick up, move the right paddle up. 6. When the right player moves their joystick down, move the right paddle down. 7. If the ball hits a paddle, reflect it back in the opposite direction. The closer the ball is to an edge of the paddle, the more oblique the angle should be. 8. If the ball moves past the left edge of the screen, add one to the right player's score. 9. If the ball moves past the right edge of the screen, add one to the left player's score. 10. If the ball is off the edge, move the ball to the center. If one player's score is 11 or greater and at least 2 higher than the other player's score, the game is over and that player won. Otherwise, go to 2.
Python
UTF-8
2,667
2.515625
3
[ "MIT" ]
permissive
import torch from utils.ipa_encoder import SOS_ID, EOS_ID def get_seq_len(x, eos_id=EOS_ID): mask = x != eos_id inds = (torch.arange(x.size(1), device=x.device) .unsqueeze(0) .repeat(x.size(0), 1)) inds.masked_fill_(mask, x.size(1) - 1) return inds.min(dim=1).values def edit_distance(outputs, targets, eos_id=EOS_ID, w_del=1.0, w_ins=1.0, w_sub=1.0): max_output_len = outputs.size(-1) max_target_len = targets.size(-1) batch_size = targets.size(0) D = torch.zeros((batch_size, max_output_len, max_target_len), device=outputs.device) D[:, 0, 0] = torch.where(outputs[:, 0] == targets[:, 0], torch.full((batch_size,), 0., device=outputs.device), torch.full((batch_size,), w_sub, device=outputs.device)) D[:, 1:, 0] = (torch.arange(1, max_output_len) .unsqueeze(0) .repeat(batch_size, 1) .to(outputs.device)) * w_ins D[:, 0, 1:] = (torch.arange(1, max_target_len) .unsqueeze(0) .repeat(batch_size, 1) .to(outputs.device)) * w_del for i in range(1, max_output_len): for j in range(1, max_target_len): d_same = D[:, i - 1, j - 1] d_different = torch.stack((D[:, i - 1, j].unsqueeze(-1) + w_ins, D[:, i, j - 1].unsqueeze(-1) + w_del, D[:, i - 1, j - 1].unsqueeze(-1) + w_sub), dim=-1).min(dim=-1).values D[:, i, j] = torch.where(outputs[:, i] == targets[:, j], d_same, d_different.squeeze(-1)) output_last_inds = get_seq_len(outputs, eos_id) - 1 target_last_inds = get_seq_len(targets, eos_id) - 1 batch_inds = torch.arange(0, batch_size, dtype=torch.long).to(outputs.device) index_vector = torch.stack((batch_inds, output_last_inds, target_last_inds), dim=-1) index_vector = (index_vector[:, 0] * max_output_len * max_target_len + index_vector[:, 1] * max_target_len + index_vector[:, 2]) edit_distances = D.take(index_vector) / (target_last_inds + 1) return edit_distances if __name__ == '__main__': x = 'Hell, ward.' y = 'Hello, world.' vocab = {'SOS': SOS_ID, 'EOS': EOS_ID} for c in x + y: if c not in vocab: vocab[c] = len(vocab) x = torch.Tensor([vocab[c] for c in x] + [EOS_ID, EOS_ID]).unsqueeze(0) y = torch.Tensor([vocab[c] for c in y] + [EOS_ID, EOS_ID, EOS_ID]).unsqueeze(0) d = edit_distance(x, y) print(f'edit distance is {d}')
Markdown
UTF-8
480
2.515625
3
[]
no_license
# 定时触发方式 定时触发方式可以让用户在指定时间触发流水线,适用于希望在构建资源空闲的时间(比如深夜)触发流水线的场景。用户可以选择基础规则和 crontab 表达式,两者可以同时选择。 **注意:** 触发时间以服务器时间为准,建议将BKCI服务器时区调整到用户所在时区 ![png](../../../assets/image-trigger-timer-plugin.png) ![png](../../../assets/image-trigger-timer-rule.png)
Java
UTF-8
4,851
1.953125
2
[]
no_license
package com.rainbowland.service.hotfixes.domain; import io.r2dbc.spi.Row; import org.springframework.data.relational.core.mapping.Table; import org.springframework.data.relational.core.mapping.Column; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.r2dbc.core.Parameter; import org.springframework.data.convert.WritingConverter; import org.springframework.data.r2dbc.mapping.OutboundRow; import lombok.Data; import java.util.Optional; @Data @Table("chr_specialization") public class ChrSpecialization { @Column("Name") private String name; @Column("FemaleName") private String femaleName; @Column("Description") private String description; @Column("ID") private Integer id; @Column("ClassID") private Integer classId; @Column("OrderIndex") private Integer orderIndex; @Column("PetTalentType") private Integer petTalentType; @Column("Role") private Integer role; @Column("Flags") private Integer flags; @Column("SpellIconFileID") private Integer spellIconFileId; @Column("PrimaryStatPriority") private Integer primaryStatPriority; @Column("AnimReplacements") private Integer animReplacements; @Column("MasterySpellID1") private Integer masterySpellId1; @Column("MasterySpellID2") private Integer masterySpellId2; @Column("VerifiedBuild") private Integer verifiedBuild; @ReadingConverter public static class RowMapper implements Converter<Row, ChrSpecialization> { public ChrSpecialization convert(Row row) { ChrSpecialization domain = new ChrSpecialization(); domain.setName(row.get("Name", String.class)); domain.setFemaleName(row.get("FemaleName", String.class)); domain.setDescription(row.get("Description", String.class)); domain.setId(row.get("ID", Integer.class)); domain.setClassId(row.get("ClassID", Integer.class)); domain.setOrderIndex(row.get("OrderIndex", Integer.class)); domain.setPetTalentType(row.get("PetTalentType", Integer.class)); domain.setRole(row.get("Role", Integer.class)); domain.setFlags(row.get("Flags", Integer.class)); domain.setSpellIconFileId(row.get("SpellIconFileID", Integer.class)); domain.setPrimaryStatPriority(row.get("PrimaryStatPriority", Integer.class)); domain.setAnimReplacements(row.get("AnimReplacements", Integer.class)); domain.setMasterySpellId1(row.get("MasterySpellID1", Integer.class)); domain.setMasterySpellId2(row.get("MasterySpellID2", Integer.class)); domain.setVerifiedBuild(row.get("VerifiedBuild", Integer.class)); return domain; } } @WritingConverter public static class ParamMapper implements Converter<ChrSpecialization, OutboundRow> { public OutboundRow convert(ChrSpecialization source) { OutboundRow row = new OutboundRow(); Optional.ofNullable(source.getName()).ifPresent(e -> row.put("Name", Parameter.from(e))); Optional.ofNullable(source.getFemaleName()).ifPresent(e -> row.put("FemaleName", Parameter.from(e))); Optional.ofNullable(source.getDescription()).ifPresent(e -> row.put("Description", Parameter.from(e))); Optional.ofNullable(source.getId()).ifPresent(e -> row.put("ID", Parameter.from(e))); Optional.ofNullable(source.getClassId()).ifPresent(e -> row.put("ClassID", Parameter.from(e))); Optional.ofNullable(source.getOrderIndex()).ifPresent(e -> row.put("OrderIndex", Parameter.from(e))); Optional.ofNullable(source.getPetTalentType()).ifPresent(e -> row.put("PetTalentType", Parameter.from(e))); Optional.ofNullable(source.getRole()).ifPresent(e -> row.put("Role", Parameter.from(e))); Optional.ofNullable(source.getFlags()).ifPresent(e -> row.put("Flags", Parameter.from(e))); Optional.ofNullable(source.getSpellIconFileId()).ifPresent(e -> row.put("SpellIconFileID", Parameter.from(e))); Optional.ofNullable(source.getPrimaryStatPriority()).ifPresent(e -> row.put("PrimaryStatPriority", Parameter.from(e))); Optional.ofNullable(source.getAnimReplacements()).ifPresent(e -> row.put("AnimReplacements", Parameter.from(e))); Optional.ofNullable(source.getMasterySpellId1()).ifPresent(e -> row.put("MasterySpellID1", Parameter.from(e))); Optional.ofNullable(source.getMasterySpellId2()).ifPresent(e -> row.put("MasterySpellID2", Parameter.from(e))); Optional.ofNullable(source.getVerifiedBuild()).ifPresent(e -> row.put("VerifiedBuild", Parameter.from(e))); return row; } } }
Go
UTF-8
341
2.953125
3
[]
no_license
//project eular - problem 5 - Smallest multiple package main import "fmt" // با دادن مقدار 2520 به شمارشگر i // و شروع j از 11 خیلی سرعت برنامه بیشتر شد func main() { i:=2520 for j :=11;j<=20 ; j++{ if i%j==0 { continue }else { i += 2520 j=11 continue } } fmt.Println(i) }
Java
UTF-8
1,277
3.46875
3
[]
no_license
package com.charlieperson; public class Car extends Vehicle { private int wheels; private int doors; private String manufacturer; private boolean automatic; public Car(String color, int wheels, int doors, String manufacturer, boolean automatic) { super(color); this.wheels = wheels; this.doors = doors; this.manufacturer = manufacturer; this.automatic = automatic; } private void pushDownGasPedal() { System.out.println("Car.pushDownGasPedal() called."); } private void turnWheels() { System.out.println("Car.turnWheels() called."); } private void putInClutch(){ System.out.println("Car.putInClutch() called"); } public void changeGears() { System.out.println("Car.changeGears() called."); if(automatic) { System.out.println("Automatic- gear changed"); } else { putInClutch(); System.out.println("Manuel- gear changed"); } } public void drive(int speed) { pushDownGasPedal(); turnWheels(); System.out.println("Car.drive() called."); move(speed); } public void handSteer() { System.out.println("Car.handSteer() called."); } }
Java
UTF-8
2,489
2.203125
2
[ "Apache-2.0" ]
permissive
package cn.k12soft.servo.domain; import cn.k12soft.servo.domain.enumeration.PlanType; import com.fasterxml.jackson.annotation.JsonIgnore; import java.time.Instant; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToOne; import org.hibernate.annotations.DynamicUpdate; @Entity @DynamicUpdate public class KlassPlan extends SchoolEntity { @Id @GeneratedValue private Integer id; private String title; @Lob @Basic(fetch = FetchType.LAZY) private String content; @Enumerated(EnumType.STRING) private PlanType planType; @ManyToOne private Actor createdBy; private Instant createdAt; @ManyToOne private Actor updatedBy; private Instant updatedAt; @JsonIgnore @ManyToOne private Klass klass; KlassPlan() { } public KlassPlan(Klass klass, PlanType planType, String title, String content, Actor createdBy) { super(klass.getSchoolId()); this.klass = klass; this.title = title; this.content = content; this.planType = planType; this.updatedBy = this.createdBy = createdBy; this.createdAt = this.updatedAt = Instant.now(); } public Integer getId() { return id; } public Klass getKlass() { return klass; } public String getTitle() { return title; } public KlassPlan title(String title) { setTitle(title); setUpdatedAt(Instant.now()); return this; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public KlassPlan content(String content) { setContent(content); setUpdatedAt(Instant.now()); return this; } public void setContent(String content) { this.content = content; } public PlanType getPlanType() { return planType; } public Actor getCreatedBy() { return createdBy; } public Instant getCreatedAt() { return createdAt; } public Actor getUpdatedBy() { return updatedBy; } public void setUpdatedBy(Actor updatedBy) { this.updatedBy = updatedBy; } public Instant getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } }
Java
UTF-8
293
1.804688
2
[]
no_license
import org.junit.Test; public class CareersTest extends RidezumBaseTest { protected HomePage homePage; protected CareersPage careersPage; @Test public void testCareers() { homePage = new HomePage(driver); careersPage = homePage.clickCareerButton(); } }
Java
UTF-8
3,281
2.796875
3
[]
no_license
package web.asana.servelet; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; /** * @author Aniruddha varshney * */ public class Database_Handler { private Connection connect = null; private Statement statement = null; private PreparedStatement preparedStatement = null; private ResultSet resultSet = null; private static final String DB_URL = "jdbc:mysql://localhost:3306/Asana?user=webaroo&password=webar00"; // storing data handler public boolean StorageHandler(Token token, String email) { // check if token already exists or not if (CheckToken(email, token)) { return StoreToken(token, email); } else { return UpdateToken(email, token); } } // check if data exists in the server against that email private boolean CheckToken(String email_id, Token token) { try { Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection(DB_URL); statement = connect.createStatement(); resultSet = statement .executeQuery("select email from asana_authorized where email='" + email_id + "'"); // check if result set is empty or not while (resultSet.next()) { return false; } } catch (Exception e) { e.printStackTrace(); } finally { close(); } // default case return true; } // set the authentication data into the table private boolean StoreToken(Token token, String email_id) { try { Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection(DB_URL); statement = connect.createStatement(); preparedStatement = connect .prepareStatement("insert into asana_authorized values (default, ?, ?, ?, ?, ?)"); preparedStatement.setString(1, email_id); preparedStatement.setString(2, token.getAccess_token()); preparedStatement.setString(3, token.getRefresh_token()); preparedStatement.setInt(4, token.getExpires_in()); preparedStatement.setBoolean(5, true); preparedStatement.executeUpdate(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { close(); } } // update the authentication data into the table private boolean UpdateToken(String email, Token token) { try { Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection(DB_URL); statement = connect.createStatement(); preparedStatement = connect .prepareStatement("update asana_authorized set access_token = ?, refresh_token = ?, expires_in = ?, authenticated = ? where email = ?"); preparedStatement.setString(1, token.getAccess_token()); preparedStatement.setString(2, token.getRefresh_token()); preparedStatement.setInt(3, token.getExpires_in()); preparedStatement.setBoolean(4, true); preparedStatement.setString(5, email); preparedStatement.executeUpdate(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { close(); } } // You need to close the resultSet private void close() { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connect != null) { connect.close(); } } catch (Exception e) { e.printStackTrace(); } } }
JavaScript
UTF-8
702
3.484375
3
[]
no_license
/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function(nums, target) { var len = nums.length; var l = 0, r = nums.length - 1, m; while (l <= r) { m = parseInt((l + r) / 2); if (nums[m - 1] >= nums[m] || l === r) { break; } else if (nums[m] <= nums[r]) { r = m; } else if (nums[l] <= nums[m]) { l = m + 1; } } var i, n, res = -1; l = m; r = m + len - 1; while (l <= r) { m = parseInt((l + r) / 2); i = m < len ? m : m - len; n = nums[i]; if (n === target) { res = i; break; } else if (n < target) { l = m + 1; } else if (n > target) { r = m - 1; } } return res; };
C#
UTF-8
1,465
3.015625
3
[]
no_license
private static void DecryptFile(string path, byte[] key) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { byte[] buffer = new byte[1024]; byte[] iv = new byte[16]; long readPos = 0; long writePos = 0; int bytesRead; long readLength = fs.Length - iv.Length; // IV is the last 16 bytes if (fs.Length < iv.Length) throw new IOException("File is too short"); fs.Position = readLength; fs.Read(iv, 0, iv.Length); fs.SetLength(readLength); using (var aes = new RijndaelManaged() { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CFB, }) using (var cs = new CryptoStream(fs, aes.CreateDecryptor(), CryptoStreamMode.Read)) { while (readPos < readLength) { fs.Position = readPos; bytesRead = cs.Read(buffer, 0, buffer.Length); readPos = fs.Position; fs.Position = writePos; fs.Write(buffer, 0, bytesRead); writePos = fs.Position; } // Trim the padding and IV fs.SetLength(writePos); } } }
Markdown
UTF-8
2,128
2.78125
3
[]
no_license
Overview ======== A POC to take a list of content sets (basically a listing of directories) and pack them into a format optimized for space efficieny and reading. For details on the file format, please see `FORMAT.md`, `ALGORITHM.md`, and the included source. Compilation and Usage ===================== This repo holds two commands, `thing.rb` (TODO: give it a better name) and `unpack`. `thing.rb` is used to pack content sets into our custom data format. `unpack` reads the format. To compile the `unpack` command, just run `make`. This requires make, gcc, and zlib-devel. thing.rb -------- `thing.rb` generates files in our packed data format from newline delimited lists of content sets. It can also dump content sets from a hosted v1 entitlement certificate, and print the tree structure of the content sets. Take in an v1 x509 certificate, and extract the content sets, output them to newline delimited output `./thing.rb d this-cert.pem` This would produce a file named `this-cert.txt` To see this txt list, in the tree format, do: `./thing.rb p this-cert.txt | less` Process this output to generate the packed data format: `./thing.rb c this-cert.txt` This would produce a file named `this-cert.bin`. The `c` command expects as input a file containing a newline delimited list of content sets; you are free to manipulate the output from a pem file or come up with your own crazy listing to push the boundaries of the data format. `thing.rb` supports a "-v" verbose flag to print debug information. unpack ------ `unpack` can read and examine files in our data format. To view stats on a packed file (size of dictionary, number of unique nodes, etc): `./unpack s this-cert.bin` To dump the raw packed file as text: `./unpack r this-cert.bin` To reconstruct the content sets and dump them to stdout: `./unpack d this-cert.bin` To check if the path `/content/rhel/6/6Server/x86_64/os/repodata/repomd.xml` matches a content set in `this-cert.bin`: `./unpack c this-cert.bin /content/rhel/6/6Server/x86_64/os/repodata/repomd.xml` There is also a WIP ruby version of unpack, unpack.rb
Ruby
UTF-8
70
2.84375
3
[]
no_license
array = [] 50.times do |i| i +=1 array << "jean.dupont.#{i}@email.com" end puts array
Python
UTF-8
4,567
3.15625
3
[]
no_license
import csv import matplotlib.pyplot as plt import networkx as nx import numpy as np from sklearn.decomposition import PCA from sklearn.cluster import KMeans from sklearn.linear_model import LogisticRegression # REDUCE, MULTI-CLUSTER, AND PLOT # first applies PCA, then clusters using k-means for k up to 'max_clusters' # cells in a cluster are treated as a 'cell-type' def reduce_and_cluster(data, max_clusters, show_plots=True): r_data = reduce(data) scores = [] print('Clustering data...') cluster_nums = range(2, max_clusters) for cn in cluster_nums: km = KMeans(n_clusters=cn).fit(r_data) # negative sum of distances of samples to their closest cluster center cluster_score = km.score(r_data) scores.append(-cluster_score) print('Success\n') if show_plots: plot(r_data, cluster_nums, scores) return r_data # reduces data to 2 dimensions (good for visualizations) def reduce(data): print('Reducing dimension to 2D...') pca = PCA(n_components=2) r_data = pca.fit_transform(data) print('Success\n') return r_data def plot(r_data, cluster_nums, scores): # plot reduced data plt.scatter(r_data[:, 0], r_data[:, 1]) plt.xlabel("PC1") plt.ylabel("PC2") plt.title("Trapnell Data Reduced to 2 Dimensions") plt.show() # plot cluster scores plt.scatter(cluster_nums, scores) plt.xlabel("Number of clusters") plt.ylabel("Sum of distances to closest cluster center") plt.title("Clustering Score as Function of Cluster Number") plt.show() ############################################################################ ############################################################################ # CLUSTER, AND PRINT CLUSTER MARKERS # clusters cells into 'nc' cell types # finds genes that are top 'k' markers for each cell type, using multi-class log regression def cluster_markers(data, reduced_data, nc, k): print('Clustering data...') km = KMeans(n_clusters=nc) labels = km.fit_predict(reduced_data) print('Success\n') print('Finding cluster markers...') lr = LogisticRegression(penalty="l2", multi_class="multinomial", solver="lbfgs").fit(data, labels) for i, cf in enumerate(lr.coef_): print(f'Top markers for cluster {i}: {top_k_markers(cf, k)}') print('Success\n') return labels, np.array(km.cluster_centers_) # returns indices of largest k numbers in gene_coefs. def top_k_markers(gene_coefs, k): idx = np.argpartition(-gene_coefs.ravel(), k)[:k] return np.unravel_index(idx, gene_coefs.shape) ############################################################################ ############################################################################ # PLOT DIFFERENTIATION TREE # nodes represent cell-types. edges mean that one cluster differentiated from the other # node size = number of cells of that type def differentiation_tree(labels, centers): d_matrix, cluster_sizes = distance_matrix(labels, centers) G = nx.Graph() G.add_nodes_from(range(len(d_matrix))) for i, cl in enumerate(d_matrix): neigh = np.argmin(cl) G.add_edge(i, neigh) nx.draw(G, node_size=30*cluster_sizes) plt.show() # returns matrix of pairwise distances between centers, and array of cluster sizes def distance_matrix(labels, centers): dist_matrix = np.full((len(centers), len(centers)), fill_value=np.inf) for i in range(len(centers)): for j in range(i, len(centers)): if i != j: c1 = centers[i] c2 = centers[j] distance = np.linalg.norm(c1 - c2) dist_matrix[i, j] = distance dist_matrix[j, i] = distance return dist_matrix, get_cluster_sizes(labels) # returns array, a, where a[i] = # cells in cluster i def get_cluster_sizes(labels): counts = [0] * max(labels+1) for l in labels: counts[l] += 1 return np.array(counts) if __name__ == '__main__': path = './Trapnell.csv' max_clusters = 10 top_k_feats = 3 print('Reading data...') data = [] with open(path, newline='') as f: reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC) for row in reader: data.append(row) print('Success\n') reduced_data = reduce_and_cluster(data, max_clusters, show_plots=True) nc = int(input('Enter # clusters to use: ')) assigned_clusters, centers = cluster_markers(data, reduced_data, nc, top_k_feats) differentiation_tree(assigned_clusters, centers)
C++
UTF-8
6,578
2.84375
3
[ "MIT" ]
permissive
#include "AABB.h" #include "math.h" #include <algorithm> namespace tzw { AABB::AABB() { reset(); } AABB::~AABB() { } void AABB::update(vec3 *vec, int num) { for (size_t i = 0; i < num; i++) { // Leftmost point. if (vec[i].x < m_min.x) m_min.setX(vec[i].x); // Lowest point. if (vec[i].y < m_min.y) m_min.setY (vec[i].y); // Farthest point. if (vec[i].z < m_min.z) m_min.setZ (vec[i].z); // Rightmost point. if (vec[i].x > m_max.x) m_max.setX(vec[i].x); // Highest point. if (vec[i].y > m_max.y) m_max.setY (vec[i].y); // Nearest point. if (vec[i].z > m_max.z) m_max.setZ (vec[i].z); } } void AABB::update(vec3 vec) { // Leftmost point. if (vec.x < m_min.x) m_min.setX(vec.x); // Lowest point. if (vec.y < m_min.y) m_min.setY (vec.y); // Farthest point. if (vec.z < m_min.z) m_min.setZ (vec.z ); // Rightmost point. if (vec.x > m_max.x) m_max.setX(vec.x ); // Highest point. if (vec.y > m_max.y) m_max.setY (vec.y ); // Nearest point. if (vec.z > m_max.z) m_max.setZ (vec.z ); } void AABB::transForm(Matrix44 mat) { vec3 corners[8]; // Near face, specified counter-clockwise // Left-top-front. corners[0] = vec3(m_min.x, m_max.y, m_max.z); // Left-bottom-front. corners[1] = vec3(m_min.x, m_min.y, m_max.z); // Right-bottom-front. corners[2] = vec3(m_max.x, m_min.y, m_max.z); // Right-top-front. corners[3] = vec3(m_max.x, m_max.y, m_max.z); // Far face, specified clockwise // Right-top-back. corners[4] = vec3(m_max.x, m_max.y, m_min.z); // Right-bottom-back. corners[5] = vec3(m_max.x, m_min.y, m_min.z); // Left-bottom-back. corners[6] = vec3(m_min.x, m_min.y, m_min.z); // Left-top-back. corners[7] = vec3(m_min.x, m_max.y, m_min.z); for(int i =0 ; i < 8 ; i++) { vec4 result = mat*vec4(corners[i].x,corners[i].y,corners[i].z,1); corners[i] = vec3(result.x,result.y,result.z); } reset(); update(corners,8); } void AABB::reset() { m_min = vec3(999999,999999,999999); m_max = vec3(-999999,-999999,-999999); } void AABB::merge(AABB box) { // Calculate the new minimum point. m_min.setX (std::min(m_min.x, box.min ().x)); m_min.setY (std::min(m_min.y, box.min ().y)); m_min.setZ (std::min(m_min.z, box.min ().z)); // Calculate the new maximum point. m_max.setX (std::max(m_max.x, box.max().x)); m_max.setY(std::max(m_max.y, box.max().y)); m_max.setZ(std::max(m_max.z, box.max().z)); } vec3 AABB::min() const { return m_min; } void AABB::setMin(const vec3 &min) { m_min = min; } vec3 AABB::max() const { return m_max; } vec3 AABB::centre() { return (m_max + m_min)/2; } /** * @brief 将当前AABB八等分,返回八个子AABB * @note 可以用来构建八叉树 * @return 八个子AABB */ std::vector<AABB> AABB::split8() { AABB aabb_list[8]; std::vector<AABB> result; auto the_centre = centre(); //bottom //#1 aabb_list[0].update(m_min); aabb_list[0].update(the_centre); //#2 aabb_list[1].update(vec3(the_centre.x,m_min.y,m_min.z)); aabb_list[1].update(vec3(m_max.x,the_centre.y,the_centre.z)); //#3 aabb_list[2].update(vec3(the_centre.x,m_min.y,the_centre.z)); aabb_list[2].update(vec3(m_max.x,the_centre.y,m_max.z)); //#4 aabb_list[3].update(vec3(m_min.x,m_min.y,the_centre.z)); aabb_list[3].update(vec3(the_centre.x,the_centre.y,m_max.z)); //top //#5 aabb_list[4].update(vec3(m_min.x,the_centre.y,m_min.z)); aabb_list[4].update(vec3(the_centre.x,m_max.y,the_centre.z)); //#6 aabb_list[5].update(vec3(the_centre.x,the_centre.y,m_min.z)); aabb_list[5].update(vec3(m_max.x,m_max.y,the_centre.z)); //#7 aabb_list[6].update(vec3(the_centre.x,the_centre.y,the_centre.z)); aabb_list[6].update(vec3(m_max.x,m_max.y,m_max.z)); //#8 aabb_list[7].update(vec3(m_min.x,the_centre.y,the_centre.z)); aabb_list[7].update(vec3(the_centre.x,m_max.y,m_max.z)); for(int i =0;i<8;i++) { result.push_back(aabb_list[i]); } return result; } bool AABB::isInside(vec3 p) const { if(p.x>=m_min.x&&p.y>=m_min.y && p.z>= m_min.z &&p.x<=m_max.x && p.y <=m_max.y && p.z <= m_max.z) { return true; } else{ return false; } } void AABB::setMax(const vec3 &max) { m_max = max; } bool AABB::isCanCotain(AABB aabb) { if(m_min.x <aabb.min ().x && m_min.y <aabb.min ().y && m_min.z <aabb.min ().z && m_max.x>aabb.max ().x && m_max.y>aabb.max ().y && m_max.z>aabb.max ().z) { return true; }else { return false; } } bool AABB::isIntersect(AABB aabb,vec3 &overLap) { bool isHit= ((m_min.x >= aabb.m_min.x && m_min.x <= aabb.m_max.x) || (aabb.m_min.x >= m_min.x && aabb.m_min.x <= m_max.x)) && ((m_min.y >= aabb.m_min.y && m_min.y <= aabb.m_max.y) || (aabb.m_min.y >= m_min.y && aabb.m_min.y <= m_max.y)) && ((m_min.z >= aabb.m_min.z && m_min.z <= aabb.m_max.z) || (aabb.m_min.z >= m_min.z && aabb.m_min.z <= m_max.z)); if(isHit) { if(min().x<aabb.min().x || max().x >aabb.max().x) { float offset_x_1 =aabb.max().x - min().x,offset_x_2 = aabb.min().x - max().x; if(fabs(offset_x_1)< fabs(offset_x_2)) { overLap.x = offset_x_1; }else{ overLap.x = offset_x_2; } } if(min().y<aabb.min().y || max().y >aabb.max().y) { float offset_y_1 =aabb.max().y - min().y,offset_y_2 = aabb.min().y - max().y; if(fabs(offset_y_1)< fabs(offset_y_2)) { overLap.y = offset_y_1; }else{ overLap.y = offset_y_2; } } if(min().z<aabb.min().z || max().z >aabb.max().z) { float offset_z_1 =aabb.max().z - min().z,offset_z_2 = aabb.min().z - max().z; if(fabs(offset_z_1)< fabs(offset_z_2)) { overLap.z = offset_z_1; }else{ overLap.z = offset_z_2; } } } return isHit; } vec3 AABB::half() { return size() / 2.0f; } vec3 AABB::size() { return max() - min(); } } // namespace tzw
TypeScript
UTF-8
3,741
2.765625
3
[ "BSD-3-Clause" ]
permissive
export interface ResourceData<S> { [index: string]: S; } export interface ResourceIdMap { [index: string]: string; } export interface ResourceOrder { [index: string]: string[]; } export interface Pagination { [index: string]: PaginationResult; } export interface PaginationResult { total: number; pages: { [index: string]: string[]; }; } export interface ResourceMetaActionStatus { loading: string[]; failed: string[]; completed: string[]; } export interface ResourceMetaActionType { many: ResourceMetaActionStatus; } export interface ResourceMetaActions { read: ResourceMetaActionType; } export interface ResourceMetaItem { read: ResourceMetaActionStatus; } export interface ResourceMetaItems { [index: string]: ResourceMetaItem; } export interface PaginationDetails { offset: number; size: number; total: number; start: number; } export interface PaginationMeta { loadedPages: string[]; current: { [index: string]: PaginationDetails; }; } export interface ResourceMetaState { status: string; items: ResourceMetaItems; actions: ResourceMetaActions; pagination: PaginationMeta; } export interface ResourceState<S = any> { [index: string]: { data: ResourceData<S>; idMap: ResourceIdMap; pagination: Pagination; order: ResourceOrder; meta: ResourceMetaState; }; } // status(): string // const a: ResourceState<any> = { // data: { // '1': { id: 'blah', title: 'title' }, // '2': { id: 'foo', title: 'title-2' }, // '3': { id: 'bar', title: 'title-3' } // }, // idMap: { // blah: '1', // foo: '2' // }, // order: { // 'order-id': ['2', '3'], // 'order-is': '1' // }, // pagination: { // 'size-20': { // 'total': 200, // 'pages': { // 'page-1': [ '2', '3' ] // } // } // }, // meta: { // pagination: { // initiator: { // offset: 20, // size: // } // } // actions: { // read: { // one: { // 'loading': [ 'initiator-id' ], // 'failed': [ 'initiator-id' ], // 'completed': [ 'initiator-id' ] // }, // many: { // 'loading': [ 'initiator-id' ], // 'failed': [ 'initiator-id' ], // 'completed': [ 'initiator-id' ] // } // }, // create: { // one: { // 'loading': [ 'initiator-id' ], // 'failed': [ 'initiator-id' ], // 'completed': [ 'initiator-id' ] // }, // many: { // 'loading': [ 'initiator-id' ], // 'failed': [ 'initiator-id' ], // 'completed': [ 'initiator-id' ] // } // } // }, // items: { // '1': { // log: { // action-id: { // result: {} // } // }, // create: { // 'loading': [ 'initiator-id' ], // 'failed': [ 'initiator-id' ], // 'completed': [ 'initiator-id' ] // }, // update: { // 'loading': [ 'initiator-id' ], // 'failed': [ 'initiator-id' ], // 'completed': [ 'initiator-id' ] // }, // remove: { // 'loading': [ 'initiator-id' ], // 'failed': [ 'initiator-id' ], // 'completed': [ 'initiator-id' ] // }, // read: { // 'loading': [ 'initiator-id' ], // 'failed': [ 'initiator-id' ], // 'completed': [ 'initiator-id' ] // } // } // } // } // }; // Assuming Optimistic Actions // create -> update ----> collect the results and apply oldest newest from server. // update -> update ----> collect the results and apply oldest newest from server. // create -> delete ----> deleted item is removed so cannot be updated. // update -> delete ----> deleted item is removed so cannot be updated. // read many ----> fails ----> return empty and status is to failed // create one ----> fails ----> optimistically added to // retry (action, id) ----> re-run clear the status - re-run the action //
Markdown
UTF-8
9,277
2.53125
3
[]
no_license
Use Amazon ECS Containers to setup (docker-based) elastic build executors. # About [Amazon EC2 Container Service (ECS)](https://aws.amazon.com/ecs/) is AWS' service for Docker container orchestration letting you deploy Docker based applications on a cluster. This plugin lets you use Amazon ECS Container Service to manage Jenkins cloud agents. Jenkins delegates to Amazon ECS the execution of the builds on Docker based agents. Each Jenkins build is executed on a dedicated Docker container that is wiped-out at the end of the build. The ECS cluster is composed of Amazon EC2 virtual machines instantiated within the boundaries the user's account (typically in an Amazon VPC). These virtual machines can be declared statically or can be managed dynamically by AWS ECS thanks to AWS Auto Scaling and AWS CloudFormation.  Jenkins agents are connected to the Jenkins master using the JNLP protocol. # Requirements - Jenkins version 1.609 or later - AWS account with permissions to create an ECS cluster # Installation Navigate to the "Plugin Manager" screen, install the "Amazon EC2 Container Service" plugin and restart Jenkins. ![](docs/images/01-plugin-install.png) # Configuration ## Amazon ECS cluster As a pre-requisite, you must have created an Amazon ECS cluster with associated ECS instances. These instances can be statically associated with the ECS cluster or can be dynamically created with Amazon Auto Scaling. The Jenkins Amazon EC2 Container Service plugin will use this ECS cluster and will create automatically the required Task Definition. ## Jenkins System Configuration Navigate to the "Configure System" screen. In the "Jenkins Location" section, ensure that the "Jenkins URL" is reachable from the the container instances of the Amazon ECS cluster. See the section "Network and firewalls" for more details. ![](docs/images/02-0-cfg-jenkins-location.png) If the global Jenkins URL configuration does not fit your needs (e.g. if your ECS agents must reach Jenkins through some kind of tunnel) you can also override the Jenkins URL in the [Advanced Configuration](http://localhost:8085/display/JENKINS/Amazon+EC2+Container+Service+Plugin#AmazonEC2ContainerServicePlugin-advancedconfig) of the ECS cloud. At the bottom of the screen, click on "Add a new Cloud" and select "Amazon EC2 Container Service Cloud". ![](docs/images/02-cfg-add-cloud.png) ### Amazon EC2 Container Service Cloud Then enter the configuration details of the Amazon EC2 Container Service Cloud: - Name: name for your ECS cloud (e.g. \`ecs-cloud\`) - Amazon ECS Credentials: Amazon IAM Access Key with privileges to create Task Definitions and Tasks on the desired ECS cluster - ECS Cluster: desired ECS cluster on which Jenkins will send builds as ECS tasks - ECS Template: click on "Add" to create the desired ECS template or templates Advanced Configuration - Tunnel connection through: tunnelling options (when Jenkins runs behind a load balancer...). - Alternative Jenkins URL: The URL used as the Jenkins URL within the ECS containers of the configured cloud. Can be used to override the default Jenkins URL from global configuration if needed.  ![](docs/images/04-cfg-ecs-add-template.png) ### ECS Agent Templates One or several ECS agent templates can be defined for the Amazon EC2 Container Service Cloud. The main reason to create more than one ECS agent template is to use several Docker image to perform build (e.g. java-build-tools, php-build-tools...) - Template name is used (prefixed with the cloud's name) for the task definition in ECS. - Label: agent labels used in conjunction with the job level configuration "Restrict where the project can be run / Label expression". ECS agent label could identify the Docker image used for the agent (e.g. \`docker\` for the [jenkinsci/jnlp-slave](https://hub.docker.com/r/jenkinsci/jnlp-slave/)). - Docker image: identifier of the Docker image to use to create the agents - Filesystem root: working directory used by Jenkins (e.g. \`/home/jenkins/\`). - Memory: number of MiB of memory reserved for the container. If your container attempts to exceed the memory allocated here, the container is killed. - The number of cpu units to reserve for the container. A container instance has 1,024 cpu units for every CPU core. **Advanced Configuration** - Override entrypoint: overwritten Docker image entrypoint. Container command can't be overriden as it is used to pass jenkins agent connection parameters. - JVM arguments: additional arguments for the JVM, such as \`-XX:MaxPermSize\` or GC options. ![](docs/images/2016092513_0831-ConfigureSystem_.png) ## Network and firewalls Running the Jenkins master and the ECS container instances in the same Amazon VPC and in the same subnet is the simplest setup and default settings will work out-of-the-box. ### Firewalls If you enable network restrictions between the Jenkins master and the ECS cluster container instances, - Fix the TCP listen port for JNLP agents of the Jenkins master (e.g. \`5000\`) navigating in the "Manage Jenkins / Configure Global Security" screen - Allow TCP traffic from the ECS cluster container instances to the Jenkins master on the listen port for JNLP agents (see above) and the HTTP(S) port. ![](docs/images/cfg-security-jnlp-listen-port.png) ### Network Address Translation and Reverse Proxies In case of Network Address Translation rules between the ECS cluster container instances and the Jenkins master, ensure that the JNLP agents will use the proper hostname to connect to the Jenkins master doing on of the following: - Define the proper hostname of the Jenkins master defining the system property \`hudson.TcpSlaveAgentListener.hostName\` in the launch command - Use the advanced configuration option "Tunnel connection through" in the configuration of the Jenkins Amazon EC2 Container Service Cloud (see above). ## IAM role We recommend you create a dedicated amazon IAM role to delegate Jenkins access to your ECS cluster. ecs:DescribeTaskDefinition [TABLE] Here is a sample policy file if you prefer using one  : { "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1452746887373", "Action": [ "ecs:RegisterTaskDefinition", "ecs:DeregisterTaskDefinition", "ecs:ListClusters", "ecs:DescribeContainerInstances", "ecs:ListTaskDefinitions", "ecs:DescribeTaskDefinition" ], "Effect": "Allow", "Resource": "*" }, { "Sid": "Stmt1452746887374", "Action": [ "ecs:StopTask", "ecs:ListContainerInstances" ], "Effect": "Allow", "Resource": "arn:aws:ecs:<region>:<accountId>:cluster/<clusterName>" }, { "Sid": "Stmt1452746887375", "Action": [ "ecs:RunTask" ], "Effect": "Allow", "Resource": "arn:aws:ecs:<region>:<accountId>:task-definition/jenkins-agent:*" }, { "Sid": "Stmt1452746887376", "Action": [ "ecs:StopTask", "ecs:DescribeTasks" ], "Effect": "Allow", "Resource": "arn:aws:ecs:<region>:<accountId>:task/*" } ] } # Usage The ECS agents can be used for any job and any type of job (Freestyle job, Maven job, Workflow job...), you just have to restrict the execution of the jobs on one of the labels used in the ECS Agent Template configuration. Sample with a label named \`docker\`: ![](docs/images/06-0-job-label.png) In the console output of the executed builds, you can verify that the build was performed on the ECS cluster checking the agent name that is composed of the ECS cloud name and of a random identifier. Sample console output of a build executed on a agent managed by an ECS cloud named \`ecs-cloud\`: ![](docs/images/06-job-build-logs.png) # Docker Images for ECS Agents The Jenkins Amazon EC2 Container Service Cloud can use for the agents all the Docker image designed to act as a Jenkins JNLP agent. Here is a list of compatible Docker images: - [jenkinsci/jnlp-slave](https://hub.docker.com/r/jenkinsci/jnlp-slave/): Jenkins CI official image to run Docker based JNLP agents - [cloudbees/jnlp-slave-with-java-build-tools](https://hub.docker.com/r/cloudbees/jnlp-slave-with-java-build-tools/): a Docker image designed by CloudBees with convenient tools to build java applications (openjdk8, maven, selenium, firefox, aws-cli...) You can easily extend one of these images to add tools or you can create your own Docker image. # Resources - [Youtube: Jenkins with Amazon ECS slaves](https://www.youtube.com/watch?v=v0b53cdrujs) # Versions see [Changelog](https://github.com/jenkinsci/amazon-ecs-plugin/blob/master/Changelog.md)
JavaScript
UTF-8
2,258
2.75
3
[]
no_license
const register = async () => { let linkedinEmail = document.getElementById('linkedinEmail').value; let twitterUsername = await document.getElementById('twitterUsername').value; window.localStorage.setItem('twitterUsername',twitterUsername); let response = await fetch('http://3.227.193.57:8001/applicants'); let data = await response.json(); var validate = true; for (let item of data) { if (item.linkedin_email == linkedinEmail || item.twitter_username == twitterUsername) { console.log(item.linkedin_email); validate = false; break; } } if (validate == false){ alert('Sudah pernah apply sebelumnya'); } else{ let linkedinEmailElem = document.getElementById('linkedinEmail'); let twitterUsernameElem = document.getElementById('twitterUsername'); console.log(JSON.stringify({ "linkedin_email": linkedinEmailElem.value , "twitter_username": twitterUsernameElem.value}) ) await fetch(`http://3.227.193.57:8001/applicants`, { method: 'POST', mode:'cors', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "linkedin_email": linkedinEmailElem.value , "twitter_username":twitterUsernameElem.value, }) }) } }; //convert image to Base64 function getBase64(file,cb){ var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(){ console.log(reader.result); cb(reader.result); }; reader.oneerror = function (error) { console.log('Error: ', error); } } const uploadPhoto = async(data) => { await fetch('http://3.227.193.57:10100/users/accounts/photo/'+localStorage.getItem('twitterUsername'),{ method: 'PUT', mode: 'cors', headers: { 'Content-Type':'application/json' }, body: JSON.stringify(data) }) } const uploadButton = async() => { var files = await document.getElementById("foto").files; var data = {}; if (files.length > 0){ getBase64(files[0], function(result){ data.Photo = result; console.log(data.Photo); uploadPhoto(data); console.log(data); }) } else { uploadPhoto(data); } }
Markdown
UTF-8
3,374
4.03125
4
[ "MIT" ]
permissive
Angular animation comes with a handy function called `animateChild()` which as the name suggests, executes the child’s animation. You might be asking why would we need this if we can execute the child’s animation independent of the parent? One of the common use case for this is when you have an `*ngIf` attached to the parent and each of the children has its own animation triggers attached to it with their own enter and leave animations. This is not a problem when the parent enters the DOM, all the children elements’ animation will be executed normally as they are added to the DOM. However, the `:leave` animation on the children elements doesn’t really work the same way. Because the `*ngIf` is on the parent, once that boolean becomes false, the children will immediately be removed from the DOM along with the parent without executing their animation and waiting for it to be done before removing it. A way to handle that scenario is to attach a trigger to the parent and querying the children as part of the parent’s animation. Below is an example of how we would use the parent’s animation to trigger its children’s animation. Let’s say we have a simple container with 2 children, each with its own set of animations (different triggers) with the following structure. ```markup <div *ngIf="”isDisplayed”" @container> <div @enterExitLeft></div> <div @enterExitRight></div> </div> ``` ```ts export const EnterExitLeft = [ trigger('enterExitLeft', [ transition(':enter', [ style({ opacity: 0, transform: 'translateX(-200px)' }), animate( '300ms ease-in', style({ opacity: 1, transform: 'translateX(0)' }) ), ]), transition(':leave', [ animate( '300ms ease-in', style({ opacity: 0, transform: 'translateX(-200px)' }) ), ]), ]), ]; export const EnterExitRight = [ trigger('enterExitRight', [ transition(':enter', [ style({ opacity: 0, transform: 'translateX(200px)' }), animate( '300ms ease-in', style({ opacity: 1, transform: 'translateX(0)' }) ), ]), transition(':leave', [ animate( '300ms ease-in', style({ opacity: 0, transform: 'translateX(200px)' }) ), ]), ]), ]; ``` To be able to trigger all the children’s animation using the parent container’s `*ngIf`, we will need to do a query with a wildcard to get all the children’s triggers, followed by the `animateChild()` function to tell Angular to execute the animation that it finds on the queried elements. ```ts export const Container = [ trigger('container', [ transition(':enter, :leave', [ query('@*', animateChild(), { optional: true }), ]), ]), ]; ``` What the code above does is it tells the parent to find all the children of the element with an animation trigger (anything that starts with `@`) attached to it, and run the animation as part of the parent’s animation sequence. In the code above, I used a wildcard prefixed with `@`, which returns all the children with an animation trigger. This might not be applicable to all use cases. For cases where you need to target specific children or maybe target different child or child animations depending on a certain condition, we can pass in a different target here instead of `@*` as the query parameter depending on your needs.
Python
UTF-8
259
2.984375
3
[]
no_license
S = input() k = input() result = list() if not k in S: print((-1, -1)) else: len0 = len(S) len1 = len(k) for i in range(len0): if S[i:i + len1] == k: result.append((i,i + len1 - 1)) for j in result: print(j)
C#
UTF-8
1,987
2.609375
3
[]
no_license
using masterCore.Entities; using masterCore.Interfaces; using masterInfrastructure.Data; using Microsoft.EntityFrameworkCore; using System; using System.Threading.Tasks; namespace masterInfrastructure.Repositories { public class MenuItemUserGroupRepo : IMenuItemUserGroupRepo { private readonly AppDbContext _context; public MenuItemUserGroupRepo(AppDbContext context) { _context = context; } public async Task<MenuItemUserGroup> GetMenuItemUserGroup(int id) { return await _context.MenuItemUserGroups.FirstOrDefaultAsync(x=>x.Id == id); } public async Task<responseData> PostMenuItemUserGroupRepo(MenuItemUserGroup menuItemUserGroup) { var responseData = new responseData(); try { _context.MenuItemUserGroups.Add(menuItemUserGroup); await _context.SaveChangesAsync(); responseData.data = menuItemUserGroup; } catch (Exception e) { responseData.error = true; responseData.errorValue = 2; responseData.description = e.Message; responseData.data = e; } return responseData; } public async Task<responseData> PutMenuItemUserGroup(MenuItemUserGroup menuItemUserGroup) { var responseData = new responseData(); try { _context.Entry(menuItemUserGroup).State = EntityState.Modified; await _context.SaveChangesAsync(); responseData.data = menuItemUserGroup; } catch (Exception e) { responseData.error = true; responseData.errorValue = 2; responseData.description = e.Message; responseData.data = e; } return responseData; } } }
Python
UTF-8
1,142
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- # !/usr/bin/env python3 """ @Author : ziheng.ni @Time : 2021/2/8 17:31 @Contact : nzh199266@163.com @Desc : """ from __future__ import annotations from abc import ABC, abstractmethod from create_mode.generator.product import Product1 class Builder(ABC): @property @abstractmethod def product(self) -> None: pass @property @abstractmethod def produce_part_1(self) -> None: pass @property @abstractmethod def produce_part_2(self) -> None: pass @property @abstractmethod def produce_part_3(self) -> None: pass class HouseBuilder(Builder): def __init__(self) -> None: self._product = None self.reset() def reset(self) -> None: self._product = Product1() @property def product(self) -> None: product = self._product self.reset() return product def produce_part_1(self) -> None: self._product.add("part 1") def produce_part_2(self) -> None: self._product.add("part 2") def produce_part_3(self) -> None: self._product.add("part 3")
C#
UTF-8
1,243
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Uppgift1 { class ShopStorage : ItemStorage<Item> { int sortIndex = 0; public ShopStorage() { Add(new Item { ID=1, Cat = Category.Food, Name = "Morot", Price = 2.50}); Add(new Item { ID = 2, Cat = Category.Food, Name = "Banan", Price = 1.00 }); Add(new Item { ID = 3, Cat = Category.Drinks, Name = "Kaffe", Price = 45.00 }); Add(new Item { ID = 4, Cat = Category.Clothes, Name = "Jeans", Price = 299.00 }); Add(new Item { ID = 5, Cat = Category.Drinks, Name = "CocaCola", Price = 12.50 }); Add(new Item { ID = 6, Cat = Category.Movies, Name = "Star Wars", Price = 199.90 }); Add(new Item { ID = 7, Cat = Category.Books, Name = "I Samlarens Spår", Price = 149.90 }); Add(new Item { ID = 8, Cat = Category.Clothes, Name = "T-shirt", Price = 2.50 }); Add(new Item { ID = 9, Cat = Category.Food, Name = "Lyxig Gurka", Price = 10.00 }); Add(new Item { ID = 10, Cat = Category.Movies, Name = "Pirates of the Caribbean", Price = 99.90 }); } } }
JavaScript
UTF-8
4,171
2.703125
3
[]
no_license
const low = require('lowdb') const FileSync = require('lowdb/adapters/FileSync') const adapter = new FileSync('db.json') const db = low(adapter) const writeToTerminal = require("./writeToTerminal") module.exports = { ValidateAccount : function ValidateAccount(cardType, cardNumber){ db.read() let validatedAccounts = [] let allPlayers = db.get('players').value() switch(cardType){ case "AccountNumber": { writeToTerminal("ValidateAccount: cardType = AccountNumber") allPlayers.forEach(player => { if(player.accountNumber === cardNumber){ validatedAccounts.push(player) } }); break } case "PhoneNumber": { writeToTerminal("ValidateAccount: cardType = PhoneNumber") allPlayers.forEach(player => { if(player.phoneNumber === cardNumber){ validatedAccounts.push(player) } }); break } case "CardNumber": { writeToTerminal("ValidateAccount: cardType = CardNumber") allPlayers.forEach(player => { if(player.cardNumber === cardNumber){ validatedAccounts.push(player) } }); break } } let PatronResponse = [] let oneAccountBlocked = false validatedAccounts.forEach(account => { //see if player is blocked let isBlocked = account.isInActive === "TRUE" || account.isPinLocked === "TRUE" || account.isBanned === "TRUE"; if(isBlocked) { oneAccountBlocked = true } PatronResponse.push({ ClubStateId: 40,//hardcoded for rn AccountNumber: account.accountNumber, FirstName: account.firstName, LastName: account.lastName, ClubState: account.tierLevel, DateOfBirth: account.dateOfBirth, PointsBalance: parseInt(account.pointBalance), PointsBalanceInDollars: (account.pointBalance/db.get('pointsToDollars').value()).toFixed(2), CompBalance: parseInt(account.compBalance), Promo2Balance: account.promo2Balance, IsInActive: account.isInActive, IsPinLocked: account.isPinLocked, IsBanned: account.isBanned, ResponseResult: { IsSuccess: !isBlocked, ErrorMessage: isBlocked ? generateErrorMessage(account) : "", ErrorCode: isBlocked ? "error" : "" } }) }); let ResponseStatus; if(validatedAccounts.length === 0){ writeToTerminal("ValidateAccount: No accounts found") ResponseStatus = { IsSuccess: false, ErrorMessage: "No accounts found", ErrorCode: "error" } } else if (oneAccountBlocked){ writeToTerminal("ValidateAccount: One of the collection failed, review the collection result") ResponseStatus = { IsSuccess: false, ErrorMessage: "One of the collection failed, review the collection result.", ErrorCode: "error" } } else { ResponseStatus = { IsSuccess: true, ErrorMessage: "", ErrorCode: "" } } return { PatronResponse, ResponseStatus } } } function generateErrorMessage(account){ let outString = "Player with Account # " + account.accountNumber if(account.isInActive === "TRUE"){ outString += " is inactive" } else if(account.isBanned === "TRUE"){ outString += " has been banned" } else if(account.isPinLocked === "TRUE"){ outString += " is pin locked" } return outString }
C++
UTF-8
2,108
2.5625
3
[ "MIT" ]
permissive
#define _CRT_SECURE_NO_WARNINGS #include<cstring> #include<iostream> #include<algorithm> #include<sstream> #include<string> #include<vector> #include<cmath> #include<cstdio> #include<cstdlib> #include<fstream> #include<cassert> #include<numeric> #include<set> #include<map> #include<queue> #include<list> #include<deque> #include<stack> #define INF 987654321 using namespace std; void dfs(int lo, int hi, int here, vector<vector<pair<int, int> > >& adj, vector<bool>& visited){ visited[here] = true; if (here == adj.size() - 1){ return; } //cout << lo << " " << hi << " " << here << endl; for (int i = 0; i < adj[here].size(); i++){ int next = adj[here][i].first; int val = adj[here][i].second; if (val<lo || val>hi){ continue; } if (!visited[next]){ dfs(lo, hi, next, adj, visited); } } } bool haspath(int lo, int hi, vector<vector<pair<int, int> > >& adj){ int N = adj.size(); vector<bool> visited(N, false); dfs(lo, hi, 0, adj, visited); return visited[N - 1]; } int solve1(int low, vector<int>& weights, vector<vector<pair<int, int> > >& adj){ } int solve2(vector<int>& weights, vector<vector<pair<int, int> > >& adj){ int ret = INF; for (int i = 0; i < weights.size(); i++) { ret = min(ret, solve1(i,weights,adj) - weights[i]); } return ret; } int solve3(vector<int>& weights, vector<vector<pair<int,int> > >& adj){ int lo = 0; int hi = 0; int ret = INF; while (true){ if (haspath(weights[lo], weights[hi], adj)){ ret = min(ret, weights[hi] - weights[lo]); lo++; } else{ if (hi == weights.size() - 1){ break; } hi++; } } return ret; } int main(){ int T; cin >> T; while (T--){ int N, M; cin >> N >> M; vector<vector<pair<int, int> > > adj; for (int i = 0; i < N; i++){ vector<pair<int, int> > vpbuf; adj.push_back(vpbuf); } vector<int> weights; for (int i = 0; i < M; i++){ int a, b, c; cin >> a >> b >> c; weights.push_back(c); adj[a].push_back(make_pair(b, c)); adj[b].push_back(make_pair(a, c)); } sort(weights.begin(), weights.end()); cout << solve3(weights, adj) << endl; } system("pause"); }
C#
UTF-8
575
2.734375
3
[]
no_license
namespace Domain { public class Sync { //class for syncing of timer threads private readonly object _syncObject = new object(); private bool _changeDetected = false; public bool WasChangeDetected() { lock (_syncObject) return _changeDetected; } public void RecordChangeDetected() { lock (_syncObject) _changeDetected = true; } public void Reset() { lock (_syncObject) _changeDetected = false; } } }
Python
UTF-8
558
2.640625
3
[]
no_license
class GameStats(): """game stats class for storing various statsitics concerning the flow of the game,like high score ,normal score,and ships reaming and level which the player is currently on TODO the high score hould be saved in a text file""" def __init__(self,def_settings): self.def_settings = def_settings self.reset_stats() self.score = 0 self.game_active = False self.high_score = 0 def reset_stats(self): self.ships_left = self.def_settings.ship_limit self.level = 1
PHP
UTF-8
1,522
3.078125
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { // Hacemos esto para indicar que este variable debe tomarlo como una instacia de carbon protected $dates = ['published_at']; // Creamos un nuevo metodo para crear la relacion post con categoria // como el post tiene una categoria le llamamos en singular es decir category // para luego cuando accedamos al post podamos acceder al nombre de la siguiente manera // $post->category->name public function category(){ // Aqui tenemos que retornar el objeto es decir el post actual con la siguiente instruccion // belongsTo() = pertecene a => y a quien pertenece en este caso a una Category::class // recuerda como estamos dentro de namespace no es necesario colocarle la direccion completa // es decir no es necesario colocar en la parte superior la siguiente instruccion // use App\Category; // Aqui estamos diciendo que el post pertence a la categoria pero en la migracion post // no hay ningun campo para referirnos a esa categoria, por lo tanto iremos // a la migraion del post para crear un campo que haga esa relacion. return $this->belongsTo(Category::class); } // Ahora para relacionar el post con la tabla post_tag crearemos una nueva relacion de muchos a muchos public function tags(){ // belongsToMany => significa pertence a muchos, y la relacion es con la clase Tag return $this->belongsToMany(Tag::class); } }
JavaScript
UTF-8
662
2.59375
3
[]
no_license
// mostly code from reactjs.org/docs/error-boundaries.html import React from 'react'; import {Link} from '@reach/router'; export default class ErrorBoundary extends React.Component { state = {hasError: false} static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, info) { console.error("ErrorBoundary has error", error, info); } render() { if(this.state.hasError) { return ( <h1> There was some error with this listing. <Link to="/">Click here</Link> to go back to homepage or wait for five seconds. </h1> ) } return this.props.children; } }
C++
UTF-8
1,379
3.015625
3
[]
no_license
#include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <sstream> #include <InetAddress.hpp> #include <Logging.hpp> namespace Net { InetAddressIPV4::InetAddressIPV4(uint16_t port, std::string address): port_(port), address_(address) {} InetAddressIPV4::InetAddressIPV4(sockaddr_in &socket_addr) { } std::string InetAddressIPV4::GetIPAndPort() const { std::ostringstream stream; stream << port_; return (address_ + " : " + stream.str()); } uint16_t InetAddressIPV4::GetPort() const { return port_; } sockaddr_in InetAddressIPV4::GetSocketAddr() const { sockaddr_in socket_ipv4; bzero(&socket_ipv4, sizeof(socket_ipv4)); socket_ipv4.sin_port = port_; socket_ipv4.sin_family = AF_INET; ::inet_pton(AF_INET, address_.c_str(), &socket_ipv4.sin_addr); return socket_ipv4; } Status SocketAddrToInetAddress(sockaddr_in &addr_in, InetAddressIPV4 *addr_out) { uint16_t port = ntohs(addr_in.sin_port); char buf[INET_ADDRSTRLEN]; const char *address = ::inet_ntop( AF_INET, reinterpret_cast<const void *>(&addr_in.sin_addr), buf, sizeof(buf)); if (NULL == address) { LOG_ERROR << "convert ip address failed."; return SOCKET_ADDRESS_CONVERT_FAILED; } *addr_out = InetAddressIPV4(port, std::string(address)); return SUCCESS; } }
Python
UTF-8
385
4
4
[]
no_license
print ('Aula 12: Condições Aninhadas') nome = str(input('Qual é o seu Nome: ')) if nome == 'Gustavo': print('Que nome bonito!') elif nome == 'Pedro' or nome == 'Paulo' or nome == 'Maria': print('Seu nome é bem popular no Brasil') elif nome in 'Jessica Marcia Ana Claudia': print ('Belo nome feminino') else: print('Seu nome é bem normal.') print ('Tenha um bom dia, {}!'.format(nome))
Markdown
UTF-8
1,239
3.078125
3
[]
no_license
# ModEarlyAccess *Namespace: [MSCLoader](API/MSCLoader.md)* ### Description Simple date handler for mods, with this you can time limit your mods, and optionally prevent the mod from loading if 'todays' date is outside a specified range. It can take both local time and online time. ### Static Functions Name | Description | Returns ---- | ----------- | ------- [CheckDateAndDisable](API/MSCLoader/ModEarlyAccess/Functions/CheckDateAndDisable.md) | Check if the current date is within specified range, and if not disable the mod and show a message. | <font color=#4170a7>void</font> [CheckDate](API/MSCLoader/ModEarlyAccess/Functions/CheckDate.md) | Check the current date, optionally opt for online checking only. | <font color=#4170a7>bool</font> [DisableMod](API/MSCLoader/ModEarlyAccess/Functions/DisableMod.md) | Completely disable a mod and show a message. | <font color=#4170a7>void</font> [GetDate](API/MSCLoader/ModEarlyAccess/Functions/GetDate.md) | Get the current date (online with backup local time). | <font color=#3ca486>DateTime</font> [GetOnlineDate](API/MSCLoader/ModEarlyAccess/Functions/GetOnlineDate.md) | Get the current date (online only, returns null if check failed). | <font color=#3ca486>DateTime</font>?
TypeScript
UTF-8
925
2.546875
3
[ "MIT" ]
permissive
import { FormControl, NG_VALIDATORS, Validator } from '@angular/forms'; import { Directive } from '@angular/core'; @Directive({ selector: '[FileTypeValidator]', providers: [ { provide: NG_VALIDATORS, useExisting: FileTypeValidator, multi: true } ] }) export class FileTypeValidator implements Validator { static validate(c: FormControl): { [key: string]: any } { if (c.value) { if (c.value[0]) { // console.log(c.value[0].size/1024/1024); return FileTypeValidator.checkExtension(c); }; } } private static checkExtension(c: FormControl) { let valToLower = c.value[0].name.toLowerCase(); let regex = new RegExp("(.*?)\.(jpg|png|jpeg)$"); let regexTest = regex.test(valToLower); return !regexTest ? { "notSupportedFileType": true } : null; } validate(c: FormControl): { [key: string]: any } { return FileTypeValidator.validate(c); } }
Python
UTF-8
5,580
2.828125
3
[]
no_license
# encoding=utf-8 import threading import time from lib.api.okex.spot_api import SpotApi from lib.api.okex.swap_api import SwapApi from lib.common import get_dict, TimeOperation from lib.trade.collection.volume_store import VolumeStore class CoinThread(threading.Thread): """ 成交数据采集 """ __trade_type = '' def __init__(self, thread_id, name, trade_type): threading.Thread.__init__(self, name=name) self.threadID = thread_id self.set_trade_type(trade_type) def set_trade_type(self, trade_type): """ 设置交易类别 spot | swap :param trade_type: :return: """ self.__trade_type = trade_type def get_trade_type(self): """ 交易类别 spot | swap :return: """ return self.__trade_type def get_api_trades(self): trade_type = self.get_trade_type() flag = True if trade_type == 'spot': data = SpotApi.get_trades(self.getName()) elif trade_type == 'swap': data = SwapApi.get_trades(self.getName()) else: data = None flag = False return data, flag def run(self): """ 线程入口 :return: """ while True: # 获取交易记录 trade_list, flag = self.get_api_trades() if not flag: continue if trade_list is None: continue # 交易记录条数 trade_len = len(trade_list) # 遍历交易记录,倒序读取 for index in range(trade_len - 1, 0, -1): trade_item = trade_list[index] # ISO8601 时间转换 # 转成北京时间 format_str = '%Y-%m-%dT%H:%M:%S.%fZ' time_array = TimeOperation.string2datetime(trade_item['timestamp'], format_str, hours=8) # 基准时间秒数(以5秒为单位的时间起点的时间戳) tm_second = time_array.second # 基准秒数(以基准秒数转换后的时间戳作为列表索引) # 5秒 temp = tm_second % 5 base_second = tm_second - temp # 分钟整点的datetime minute_array = TimeOperation.set_datetime(time_array, second=0) # 设置基准秒数 time_array = TimeOperation.set_datetime(time_array, second=base_second) # 设置基准时间戳 base_timestamp = TimeOperation.datetime2timestamp(time_array) trade_id = trade_item['trade_id'] price = float(trade_item['price']) size = float(trade_item['size']) volume = price * size # buy: 买入; sell: 卖出 side = trade_item['side'] ################# # 5秒钟交易量汇总 # ################# # if not VolumeStore.is_timestamp_in_dict(self.getName(), base_timestamp): # 初始化 # VolumeStore.init_dict_timestamp(self.getName(), base_timestamp) # trade_id 是否在列表中 # has_trade_id = True # 添加trade_id,累计成交量 # if trade_id not in VolumeStore.get_dict_one_timestamp(self.getName(), base_timestamp)['trade_ids']: # has_trade_id = False # 如果trade_id不在列表中,则添加 # VolumeStore.dict_append_trade_id(self.getName(), base_timestamp, trade_id) # 累加买卖交易量 # if side == 'buy': # VolumeStore.dict_add_buy_volume(self.getName(), base_timestamp, volume) # elif side == 'sell': # VolumeStore.dict_add_sell_volume(self.getName(), base_timestamp, volume) ########################## # 1分钟交易量汇总,准备入库 # ########################## base_minute_time = TimeOperation.datetime2timestamp(minute_array) # 初始化 if not VolumeStore.is_timestamp_in_volume(self.getName(), base_minute_time): # 初始化 VolumeStore.init_volume_timestamp(self.getName(), base_minute_time) # trade_id 是否在列表中 if trade_id not in VolumeStore.get_volume_one_timestamp(self.getName(), base_minute_time)['trade_ids']: if side == 'buy': VolumeStore.get_lock().acquire() try: VolumeStore.volume_set_volume(self.getName(), base_minute_time, buy_volume=volume, symbol='+') finally: VolumeStore.get_lock().release() elif side == 'sell': VolumeStore.get_lock().acquire() try: VolumeStore.volume_set_volume(self.getName(), base_minute_time, sell_volume=volume, symbol='+') finally: VolumeStore.get_lock().release() # total_dict = VolumeStore.get_total_dict()['BTC-USDT'] # for key, item in total_dict.items(): # print(item) # exit() # 等待500毫秒 time.sleep(0.2)
Java
UTF-8
1,441
2.734375
3
[]
no_license
package Thread_pool; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; //read .pre file and get seg,parse result public class ReadFile { public ArrayList<ArrayList<String>> seg_result; public ArrayList<ArrayList<String>> parse_result; public ReadFile() { this.seg_result = new ArrayList<ArrayList<String>>(); this.parse_result = new ArrayList<ArrayList<String>> (); } public void clear() { this.seg_result.clear(); this.parse_result.clear(); } public void ReadPre(String user_id) throws Exception { File file = new File(user_id+".pre"); if(!file.exists()) throw new Exception("pre file not found"); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8")); String line = ""; while((line = reader.readLine()) != null) { String[] items = line.split(":"); if(line.startsWith("f_seg")) { String f_seg = items[1]; String[] seg = f_seg.split("\t"); ArrayList<String> s = new ArrayList<String>(); for(String se:seg) s.add(se); this.seg_result.add(s); } else if(line.startsWith("parse_result")) { String p_re = items[1]; String[] par = p_re.split("\t"); ArrayList<String> p = new ArrayList<String>(); for(String pa:par) p.add(pa); this.parse_result.add(p); } } reader.close(); } }
JavaScript
UTF-8
2,827
2.75
3
[]
no_license
//dependency var db = require("../models"); //routes module.exports = function (app) { // get all the cases to be put on the main page app.get("/api/cases", function (req, res) { db.Employee.findAll({}).then(function (dbQuar) { res.json(dbQuar); }); }); // get all the employees with the status of [something] app.get("/api/cases/currentCondition/:currentCondition", function (req, res) { db.Quarantine.findAll({ where: { currentCondition: req.params.currentCondition, }, }).then(function (dbQuar) { res.json(dbQuar); }); }); //get a single table entry app.get("/api/cases/:id", function (req, res) { db.Quarantine.findAll({ where: { id: req.params.id, }, }).then(function (dbQuar) { res.json(dbQuar); }); }); //posting a new employee case FROM THE SUBMISSION FORM app.post("/api/cases", function (req, res) { console.log(req.body); // db.Quarantine.Create({ // firstName: req.body.firstName, // lastName: req.body.lastName, // quarantineStart: req.body.quarantineStart, // quarantineEnd: req.body.quarantineEnd, // covidConfirmed: req.body.covidConfirmed, // currentCondition: req.body.currentCondition, // }).then(function (dbQuar) { // res.json(dbQuar); // }); }); //"delete" route will just change the active status to false app.put("/api/cases/delete", function (req, res) { db.Quarantine.update( { activeStatus: false, }, { where: { id: req.body.id, }, } ) .then(function (dbQuar) { res.json(dbQuar); }) .catch(function (err) { res.json(err); }); }); //update route to update posts app.put("/api/cases", function (req, res) { db.Quarantine.update( { firstName: req.body.firstName, lastName: req.body.lastName, quarantineStart: req.body.quarantineStart, quarantineEnd: req.body.quarantineEnd, covidConfirmed: req.body.covidConfirmed, currentCondition: req.body.currentCondition, }, { where: { id: req.body.id, }, } ) .then(function (dbQuar) { res.json(dbQuar); }) .catch(function (err) { res.json(err); }); }); // Check if symptomatic app.get("/api/cases/symptomatic", function (req, res) { // db.Quarantine.findAll({currentCondition: "symptomatic"}).then(function (dbQuar) { // res.json(dbQuar); // }); var data = [ { firstName: "Joe", lastName: "Bob", }, { firstName: "Jill", lastName: "Bob", }, { firstName: "Billy", lastName: "Bob", }, ]; res.send("data"); }); };
Markdown
UTF-8
1,191
3.171875
3
[]
no_license
## Frontend-nanodegree-resume Project that programmatically fills in resume information. Description ----------- Project to write code that takes the given resume information, filters and formats it using a list of variables that contain the formatting for each of the sections and then places it in the index.html file for display. The project also shows how the re-usable code in the pre-formatted variables breaks down the process into smaller chunks facilitating the overall process. All the code in the resumeBuilder.js code was refactored from the initial materials given to separate the concerns into an Model, View, Presenter (MVP) format. Components ---------- index.html<br> js/resumeBuilder.js<br> js/jQuery.js<br> css/style.css<br> README.md Installation ------------ To install simply clone the repository. The 'resumeBuilder.js' file currently contains my resume information. To change the resume that is displayed, edit the 'resumeBuilder.js' file and add the new information. Running the code ---------------- To display the resume simply open the index.html file on a browser. Documentation ------------- The 'resumeBuilder.js' is documented throughout the code.
C++
UTF-8
509
2.75
3
[]
no_license
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if(n == 0) return 0; else if(n == 1) return nums[0]; else if(n == 2) return max(nums[0], nums[1]); int day_m1 = max(nums[0], nums[1]), day_m2 = nums[0], today; for(int i = 2; i < n; i++) { today = max(day_m1, day_m2 + nums[i]); day_m2 = day_m1; day_m1 = today; } return today; } };
C++
UTF-8
1,165
3.015625
3
[]
no_license
// Problem: STPAR - Street Parade // Link: https://www.spoj.com/problems/STPAR/ // Solution: Mai Thanh Hiep // Complexity: O(N) #include <iostream> #include <stack> using namespace std; #define MAX 1000 int arr[MAX]; int main() { int n; while (true) { cin >> n; if (n == 0) break; stack<int> mystack; int order = 1; int x; for (int i = 0; i < n; i++) { cin >> x; if (x != order) { // Check to pop in-order waiting trucks in stack while (!mystack.empty() && mystack.top() == order) { mystack.pop(); order++; // next order } mystack.push(x); // push this truck into waiting list } else { order++; // next order } } // Check to pop in-order waiting trucks in stack while (!mystack.empty() && mystack.top() == order) { mystack.pop(); order++; } cout << (mystack.empty() ? "yes" : "no") << endl; } return 0; }
SQL
UTF-8
147
2.609375
3
[]
no_license
CREATE PROCEDURE Billing.FeeGroupReadAll AS BEGIN SELECT Id, Name, FrequencyId, IsActive FROM Billing.FeeGroup WITH (NOLOCK) END
C#
UTF-8
8,808
2.515625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Leisn.UI.Xaml.Extensions; using System.Diagnostics; using Microsoft.UI.Xaml.Controls; using System.Collections.Specialized; namespace Leisn.UI.Xaml.Controls { public class AutoFillLayout : VirtualizingLayout { #region Properties public Thickness Padding { get { return (Thickness)GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } public static readonly DependencyProperty PaddingProperty = DependencyProperty.Register( nameof(Padding), typeof(Thickness), typeof(AutoFillLayout), new PropertyMetadata(default(Thickness), LayoutPropertyChanged)); public Orientation Orientation { get { return (Orientation)GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register( nameof(Orientation), typeof(Orientation), typeof(AutoFillLayout), new PropertyMetadata(Orientation.Horizontal, LayoutPropertyChanged)); public double HorizontalSpacing { get { return (double)GetValue(HorizontalSpacingProperty); } set { SetValue(HorizontalSpacingProperty, value); } } public static readonly DependencyProperty HorizontalSpacingProperty = DependencyProperty.Register( nameof(HorizontalSpacing), typeof(double), typeof(AutoFillLayout), new PropertyMetadata(4d, LayoutPropertyChanged)); public double VerticalSpacing { get { return (double)GetValue(VerticalSpacingProperty); } set { SetValue(VerticalSpacingProperty, value); } } public static readonly DependencyProperty VerticalSpacingProperty = DependencyProperty.Register( nameof(VerticalSpacing), typeof(double), typeof(AutoFillLayout), new PropertyMetadata(4d, LayoutPropertyChanged)); private static void LayoutPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { //Debug.WriteLine(e.Property + " changed"); if (d is AutoFillLayout ap) { ap.InvalidateMeasure(); ap.InvalidateArrange(); } } #endregion protected override void InitializeForContextCore(VirtualizingLayoutContext context) { context.LayoutState = new AutoFillLayoutState(context); base.InitializeForContextCore(context); } protected override void UninitializeForContextCore(VirtualizingLayoutContext context) { context.LayoutState = null; base.UninitializeForContextCore(context); } protected override void OnItemsChangedCore(VirtualizingLayoutContext context, object source, NotifyCollectionChangedEventArgs args) { var state = (AutoFillLayoutState)context.LayoutState; //Debug.WriteLine(args.Action); switch (args.Action) { case NotifyCollectionChangedAction.Add: state.RemoveItemsFrom(args.NewStartingIndex); break; case NotifyCollectionChangedAction.Move: state.RemoveItemsFrom(Math.Min(args.OldStartingIndex, args.NewStartingIndex)); state.RecycleElementAt(args.OldStartingIndex); state.RecycleElementAt(args.NewStartingIndex); break; case NotifyCollectionChangedAction.Remove: state.RemoveItemsFrom(args.OldStartingIndex); break; case NotifyCollectionChangedAction.Replace: state.RemoveItemsFrom(args.NewStartingIndex); state.RecycleElementAt(args.NewStartingIndex); break; case NotifyCollectionChangedAction.Reset: state.Reset(); break; } base.OnItemsChangedCore(context, source, args); } protected override Size MeasureOverride(VirtualizingLayoutContext context, Size availableSize) { var requiredSize = new Size(Padding.Left + Padding.Right, Padding.Top + Padding.Bottom); if (context.ItemCount == 0 || context.RealizationRect.Width == 0 || context.RealizationRect.Height == 0) return requiredSize; var state = (AutoFillLayoutState)context.LayoutState; var clientSize = new Size( availableSize.Width - Padding.Left - Padding.Right, availableSize.Height - Padding.Top - Padding.Bottom); //Save layout properties //If changed every thing need redo if (state.SavePropertiesIfChange(Orientation, Padding, HorizontalSpacing, VerticalSpacing, availableSize)) { state.Reset(); } if (!state.Initialized) { if (Orientation == Orientation.Horizontal) { state.Initialize( new Rect(Padding.Left, Padding.Top, clientSize.Width + HorizontalSpacing, double.PositiveInfinity) ); } else { state.Initialize( new Rect(Padding.Left, Padding.Top, double.PositiveInfinity, clientSize.Height + VerticalSpacing) ); } } for (int i = 0; i < context.ItemCount; i++) { var item = state.GetOrCreateItemAt(i); bool measured = false; if (item.Bounds.IsEmpty())//measure empty { item.Element = context.GetOrCreateElementAt(i); item.Element.Measure(clientSize); item.Width = item.Element.DesiredSize.Width; item.Height = item.Element.DesiredSize.Height; state.FitItem(item); measured = true; } item.ShouldDisplay = context.RealizationRect.IsIntersect(item.Bounds); if (!item.ShouldDisplay) { if (item.Element != null) { context.RecycleElement(item.Element); item.Element = null; } } else if (!measured)//measure in view rect { item.Element = context.GetOrCreateElementAt(i); item.Element.Measure(clientSize); var childSize = item.Element.DesiredSize; if (item.Width != childSize.Width || item.Height != childSize.Height) //size changed { item.Width = childSize.Width; item.Height = childSize.Height; state.RemoveItemsFrom(i + 1);//remove after this state.FitItem(item); } } } var size = state.GetTotalSize(); //var size = state.GetVirtualizedSize(); requiredSize.Width += size.Width; requiredSize.Height += size.Height; return requiredSize; } protected override Size ArrangeOverride(VirtualizingLayoutContext context, Size finalSize) { if (context.RealizationRect.Width == 0 || context.RealizationRect.Height == 0) return finalSize; var viewRect = context.RealizationRect; var state = (AutoFillLayoutState)context.LayoutState; Debug.Assert(context.ItemCount == state.ItemCount); for (int i = 0; i < context.ItemCount; i++) { var item = state[i]; var bounds = item.Bounds; if (viewRect.IsIntersect(bounds)) { var child = context.GetOrCreateElementAt(item.Index); item.Element = child; child.Arrange(bounds); } } return finalSize; } } }
C++
UTF-8
2,571
3.640625
4
[]
no_license
// leetcode_5350.cpp : This file contains the 'main' function. Program execution begins and ends there. // https://leetcode.com/contest/biweekly-contest-22/problems/sort-integers-by-the-power-value/ /* The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. Return the k-th integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in 32 bit signed integer. Input: lo = 12, hi = 15, k = 2 Output: 13 Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. Input: lo = 1, hi = 1, k = 1 Output: 1 Input: lo = 7, hi = 11, k = 4 Output: 7 Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. The interval sorted by power is [8, 10, 11, 7, 9]. The fourth number in the sorted array is 7. Input: lo = 10, hi = 20, k = 5 Output: 13 Input: lo = 1, hi = 1000, k = 777 Output: 570 Constraints: 1 <= lo <= hi <= 1000 1 <= k <= hi - lo + 1 */ #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int getKth(int lo, int hi, int k) { vector<int> dp(4000, -1); dp[1] = 0; for (int i = 2; i < 1001; ++i) { int now = i; int cnt = 0; while (now != 1) { if (now % 2) now = 3 * now + 1; else now /= 2; cnt++; } dp[i] = cnt; } vector<pair<int, int>> vec; for (int i = lo; i <= hi; ++i) vec.emplace_back(dp[i], i); sort(vec.begin(), vec.end()); return vec[k - 1].second; } }; int main() { std::cout << "Hello World!\n"; }
C++
UTF-8
1,671
2.546875
3
[]
no_license
#include "cute.h" #include "ide_listener.h" #include "xml_listener.h" #include "cute_runner.h" #include <sstream> #include "long_function.h" #include <fstream> #include <cstdio> void testWriting3Times() { std::ostringstream out; writeNTimesToStream(out,"hello",4); ASSERT_EQUAL("hello\nhello\nhello\n",out.str()); } void testWriting3TimesIfOk() { std::ostringstream out; bool ok = writeNTimesToStreamIfOk(out,"hello",4); ASSERTM("writing succeeded",ok); ASSERT_EQUAL("hello\nhello\nhello\n\n",out.str()); } void testWriting3TimesIfNotOk() { std::ostringstream out; out.clear(std::ios_base::badbit); bool ok = writeNTimesToStreamIfOk(out,"hello",3); ASSERTM("writing should have failed",not ok); ASSERT_EQUAL("",out.str()); } void testWrite2TimesToRealFile(){ std::string filename{"hello.txt"}; std::remove(filename.c_str()); bool ok= writeNTimesToFile3(filename,"hello",3); ASSERTM("writing should succeed",ok); std::ifstream in(filename); ASSERT(in.good()); std::ostringstream all; all<<in.rdbuf(); ASSERT_EQUAL("hello\nhello\n\n",all.str()); } void runAllTests(int argc, char const *argv[]){ cute::suite s; //TODO add your test here s.push_back(CUTE(testWriting3Times)); s.push_back(CUTE(testWriting3TimesIfOk)); s.push_back(CUTE(testWriting3TimesIfNotOk)); s.push_back(CUTE(testWrite2TimesToRealFile)); cute::xml_file_opener xmlfile(argc,argv); cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out); cute::makeRunner(lis,argc,argv)(s, "AllTests"); } int main(int argc, char const *argv[]){ using std::string; string s{"no std::"}; using str=std::string; str t{"short alias"}; runAllTests(argc,argv); return 0; }
C#
UTF-8
1,063
3.3125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sunglasses { class Sunglasses { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); char asteriks = '*'; char straightLine = '|'; char leanLine = '/'; Console.WriteLine("{0}{1}{0}",new string(asteriks, n*2),new string(' ',n)); for(int i = 0; i<n-2;i++) { if (i == n / 2-1) { Console.WriteLine("{0}{1}{0}{2}{0}{1}{0}", new string(asteriks, 1), new string(leanLine, n * 2 - 2), new string(straightLine, n)); } else { Console.WriteLine("{0}{1}{0}{2}{0}{1}{0}", new string(asteriks, 1), new string(leanLine, n * 2 - 2), new string(' ', n)); } } Console.WriteLine("{0}{1}{0}", new string(asteriks, n * 2), new string(' ', n)); } } }
C++
UTF-8
602
3
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; typedef long long int ll; void read_input(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif } int main(){ read_input(); int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int max_ind=0; int min_ind=0; for(int i=0;i<n;i++){ if (arr[max_ind]<arr[i]){ max_ind=i; } if (arr[min_ind]>arr[i]){ min_ind=i; } } cout<<" The maximum number is : "<<arr[max_ind]<<"\n"; cout<<" The minimum number is : "<<arr[min_ind]<<"\n"; return 0; }
Java
UTF-8
3,895
1.960938
2
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
package in.partake.controller.api.user; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import in.partake.base.DateTime; import in.partake.base.Pair; import in.partake.base.TimeUtil; import in.partake.controller.api.APIControllerTest; import in.partake.model.dto.Event; import in.partake.model.dto.EventTicket; import in.partake.model.dto.UserTicket; import in.partake.model.dto.auxiliary.AttendanceStatus; import in.partake.model.dto.auxiliary.EventCategory; import in.partake.model.dto.auxiliary.ModificationStatus; import in.partake.model.dto.auxiliary.ParticipationStatus; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.junit.Test; import com.opensymphony.xwork2.ActionProxy; public class GetTicketsAPITest extends APIControllerTest { @Test public void testGetEnrollments() throws Exception { List<Pair<UUID, String>> ids = prepareEvents(20); prepareEnrollment(DEFAULT_USER_ID, ids); ActionProxy proxy = getActionProxy("/api/user/tickets"); addParameter(proxy, "userId", DEFAULT_USER_ID); addParameter(proxy, "limit", "10"); proxy.execute(); assertResultOK(proxy); JSONObject obj = getJSON(proxy); assertThat(obj.getInt("totalTicketCount"), is(20)); JSONArray array = obj.getJSONArray("ticketStatuses"); assertThat(array.size(), is(5)); for (int i = 0; i < 5; ++i) { assertThat(array.getJSONObject(i).getJSONObject("ticket").getString("id"), is(ids.get(i * 2).getFirst().toString())); assertThat(array.getJSONObject(i).getString("status"), is("enrolled")); } } private List<Pair<UUID, String>> prepareEvents(int n) throws Exception { List<Pair<UUID, String>> ids = new ArrayList<Pair<UUID, String>>(); DateTime now = TimeUtil.getCurrentDateTime(); DateTime late = new DateTime(now.getTime() + 1000 * 3600); String category = EventCategory.getCategories().get(0).getKey(); for (int i = 0; i < n; ++i) { boolean isPrivate = i % 2 == 1; Event event = new Event(null, "title", "summary", category, late, late, "url", "place", "address", "description", "#hashTag", EVENT_OWNER_ID, EVENT_FOREIMAGE_ID, EVENT_BACKIMAGE_ID, isPrivate ? "passcode" : null, false, Collections.singletonList(EVENT_EDITOR_TWITTER_SCREENNAME), new ArrayList<String>(), null, now, now, -1); String eventId = storeEvent(event); UUID uuid = UUID.randomUUID(); EventTicket ticket = EventTicket.createDefaultTicket(uuid, eventId); storeEventTicket(ticket); ids.add(new Pair<UUID, String>(uuid, eventId)); } return ids; } private List<String> prepareEnrollment(String userId, List<Pair<UUID, String>> ids) throws Exception { List<String> userTicketIds = new ArrayList<String>(); for (int i = 0; i < ids.size(); ++i) { UUID ticketId = ids.get(i).getFirst(); String eventId = ids.get(i).getSecond(); ParticipationStatus status = ParticipationStatus.ENROLLED; ModificationStatus modificationStatus = ModificationStatus.CHANGED; AttendanceStatus attendanceStatus = AttendanceStatus.UNKNOWN; DateTime enrolleAt = new DateTime(TimeUtil.getCurrentTime() + (ids.size() - i) * 1000); UserTicket enrollment = new UserTicket(null, userId, ticketId, eventId, "comment", status, modificationStatus, attendanceStatus, null, enrolleAt, enrolleAt, enrolleAt); userTicketIds.add(storeEnrollment(enrollment)); } return userTicketIds; } }
Java
UTF-8
5,981
1.96875
2
[]
no_license
package com.qysd.lawtree.lawtreefragment; import android.content.Intent; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.TextView; import com.google.gson.Gson; import com.qysd.lawtree.R; import com.qysd.lawtree.lawtreeactivity.OrderDetailActivity; import com.qysd.lawtree.lawtreeadapter.MarketingManagementAdapter; import com.qysd.lawtree.lawtreeadapter.RepertoryListAdapter; import com.qysd.lawtree.lawtreebase.BaseFragment; import com.qysd.lawtree.lawtreebean.MarketingManagementBean; import com.qysd.lawtree.lawtreebean.RepertoryListBean; import com.qysd.lawtree.lawtreeutil.httputils.UserCallback; import com.qysd.lawtree.lawtreeutils.Constants; import com.qysd.lawtree.lawtreeutils.GetUserInfo; import com.zhy.http.okhttp.OkHttpUtils; import java.util.ArrayList; import java.util.List; public class MarketingManagementFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener{ private SwipeRefreshLayout refreshlayout; private RecyclerView recyclerview; private MarketingManagementAdapter examinendApproveListAdapter; private TextView noDataTv; private int num = 1;//页码 private int size = 6;//每一页显示个数 private int state = 0;//0 表示刷新 1表示加载更多 private LinearLayoutManager manager; private Gson gson; //数据 private List<MarketingManagementBean.Status> repertoryList = new ArrayList<>(); private MarketingManagementBean listBean; @Override protected int getLayoutId() { return R.layout.fragment_marketingmanagement; } @Override protected void initView() { noDataTv = (TextView) findViewById(R.id.noDataTv); refreshlayout = (SwipeRefreshLayout) findViewById(R.id.refreshlayout); recyclerview = (RecyclerView) findViewById(R.id.recyclerview); // 设置下拉刷新时的颜色值,颜色值需要定义在xml中 refreshlayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); } @Override protected void bindListener() { refreshlayout.setOnRefreshListener(this); } @Override protected void initData() { //加载数据 loadData(state); } @Override protected void initNav() { } @Override protected void loadData() { } /** * 请求网络数据 */ private void loadData(int state) { if (state == 0) { num = 1; } else if (state == 1) { num++; } gson = new Gson(); refreshlayout.setRefreshing(true); OkHttpUtils.get() .url(Constants.baseUrl + "/appsalesorder/selectList") .addParams("page", String.valueOf(num)) //.addParams("pageSize","10") .addParams("userId", GetUserInfo.getUserId(getActivity())) .addParams("compId", (String) GetUserInfo.getData(getActivity(),"conmpId","")) .addParams("type","0")//0.未完成 1已完成(必传) .build() .execute(new UserCallback() { @Override public void onResponse(String response, int id) { Log.e("songlonglong",response); if (num == 1){ repertoryList.clear(); } listBean = gson.fromJson(response,MarketingManagementBean.class); if ("1".equals(listBean.getCode())){ refreshlayout.setRefreshing(false); repertoryList.addAll(listBean.getStatus()); if (repertoryList.size()>0) { if (examinendApproveListAdapter == null) { setAdapter(repertoryList); } else { examinendApproveListAdapter.notifyDataSetChanged(); } } }else { refreshlayout.setRefreshing(false); } } }); } private void setAdapter(final List<MarketingManagementBean.Status> list) { manager = new LinearLayoutManager(getActivity()); recyclerview.setLayoutManager(manager); examinendApproveListAdapter = new MarketingManagementAdapter(list); recyclerview.setAdapter(examinendApproveListAdapter); //条目点击接口 examinendApproveListAdapter.setOnItemClickListener(new MarketingManagementAdapter.OnRecyclerViewItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(getActivity(), OrderDetailActivity.class); startActivity(intent); } }); /** * 滚动事件接口 */ recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { int lastVisiblePosition = manager.findLastVisibleItemPosition(); if (lastVisiblePosition >= manager.getItemCount() - 1) { state = 1; loadData(state); } } } }); } @Override public void onRefresh() { state = 0; loadData(state); } }
JavaScript
UTF-8
1,292
2.53125
3
[]
no_license
var React = require('react'); var ReactDOM = require('react-dom'); var TaskList = require('./TaskList.jsx'); var TaskItem = require('./TaskItem.jsx'); var GlobalSidebar = React.createClass({ getInitialState: function() { return { tasksInList: [], city: "Las Vegas", temperature: "" } }, componentDidMount: function() { $.ajax({ url: 'http://api.openweathermap.org/data/2.5/weather?q=' + this.state.city + '&appid=ce8b5f7c6fbfcba5e114640942ab7893', dataType: 'json', cache: false, success: function(data) { console.log(data.main.temp); // convert API response from Kelvin to Fahrenheit this.state.temperature = " | " + ((data.main.temp * 9 / 5) - 459.67).toFixed(0) + "°"; }.bind(this) }) }, render: function() { return ( <div className="sidebar"> <div className="twelve columns sidebar-height"> <div className="location-display"> <i className="fa fa-circle fa-paper-plane-o fa-5x"></i> <h5>{this.state.city} {this.state.temperature}</h5> </div> <hr /> <TaskList tasks={this.state.tasksInList} addNewTask={this.props.addNewTask} /> </div> </div> ) } }); module.exports = GlobalSidebar;
Java
UTF-8
4,045
1.539063
2
[]
no_license
package org.springframework.eam.dao; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.eam.domain.Personas; import org.springframework.eam.domain.ProActTar; import org.springframework.eam.domain.Usuarios; import org.springframework.eam.domain.Menues; import org.springframework.eam.domain.Turno; import org.springframework.eam.domain.Administrativos; import org.springframework.eam.domain.Servidor; import org.springframework.eam.domain.carreras; public interface AdministrarUsuariosDao { List getUsuariosPrograma(String id_programa) throws DataAccessException; int setRegistrarUsuariosAdm(Usuarios usuario) throws DataAccessException; int getId_usuario(String id_usuario) throws DataAccessException; int setRegistrarUsuariosRoles(Usuarios usuario) throws DataAccessException; //jes void setRegistrarUsuariosyRoles(Usuarios usuario) throws DataAccessException; int setActualizarUsuariosRoles(Usuarios usuario) throws DataAccessException; int setEliminarUsuariosRoles(Usuarios usuario) throws DataAccessException; int setRegistrarAdministrativo(Administrativos administrativo) throws DataAccessException; List getRolesUsuario(Usuarios usuario) throws DataAccessException; int getKeySecurity(Menues menu) throws DataAccessException; int setActualizarUsuarioAdm(Usuarios usuario) throws DataAccessException; int setActualizarAdministrativo(Administrativos administrativo) throws DataAccessException; void setBorrarRolesUsuario(Usuarios usuario) throws DataAccessException; void setBorrarLoginHistorico(Usuarios usuario) throws DataAccessException; // Actualizar Clave int setActualizarClaveKar(Usuarios usuario) throws DataAccessException; //_ Cambiar Turno void setCambiarTurno(Usuarios usuario) throws DataAccessException; //Fin _ Cambiar Turno //_ Turno Modulo void setTurno(Turno turno) throws DataAccessException; void setTurno2(Turno turno) throws DataAccessException; void setTurnoTmp(Turno turno) throws DataAccessException; int getTurnoActual(Usuarios usuario) throws DataAccessException; int getTurno(Usuarios usuario) throws DataAccessException; Turno getTurnoTmp(Usuarios usuario) throws DataAccessException; List getUsuariosTurno() throws DataAccessException; //String getEstadoTranscriptor(Usuarios usuario) throws DataAccessException; //Fin _ Turno Modulo Administrativos getAdministrativo(Administrativos administrativo) throws DataAccessException; Servidor getServidor(Servidor servidor) throws DataAccessException; List getListaServidores() throws DataAccessException; void setServidor(Servidor servidor) throws DataAccessException; void setCajaServidor(Servidor servidor) throws DataAccessException; void setDefaultServer(Servidor servidor) throws DataAccessException; Servidor getDefaultServer() throws DataAccessException; String getIdSrvByBoxName(String cod_img) throws DataAccessException; //jes List getListarTareas(ProActTar proActTar) throws DataAccessException; ProActTar getActividad(ProActTar tta) throws DataAccessException; ProActTar getTarea(ProActTar ttar) throws DataAccessException; void setCarreasRelacionUsuario(carreras relacion) throws DataAccessException; List getListaTareasUsuario(carreras relacion_usuario) throws DataAccessException; void setEliminaRelacionTareasUsuarios(carreras tareasUsuario) throws DataAccessException; void setEliminarLoginStatus(Usuarios us) throws DataAccessException; void setElimiarAdministrativo(Administrativos ads) throws DataAccessException; void setEliminaPersona(Personas per) throws DataAccessException; List getFuentesAndMontosEjecutadosByTarea() throws DataAccessException; List getListActividad() throws DataAccessException; List getListAllFuentesFinanciamiento() throws DataAccessException; List getListAllTareaByActividad(ProActTar actividad) throws DataAccessException; }
Python
UTF-8
1,313
3.453125
3
[]
no_license
with open("password_db.dat") as passwordData: passwordEntries = passwordData.read().split('\n') passwordOK = 0 passwordBad = 0 for entry in passwordEntries: charMin = int(entry.split('-')[0]) charMax = int(entry.split('-')[1].split(' ')[0]) char = entry.split(' ')[1].split(':')[0] password = entry.split(' ')[2] # print('Line: {} charMin: {} charMax: {} char: {} password: {}'.format(entry, charMin, charMax, char, password)) if(password.count(char) >= charMin and password.count(char) <= charMax): passwordOK += 1 else: passwordBad += 1 print('Good passwords: {} Bad passwords: {}'.format(passwordOK, passwordBad)) passwordOK = 0 passwordBad = 0 for entry in passwordEntries: charFirst = int(entry.split('-')[0]) charSecond = int(entry.split('-')[1].split(' ')[0]) char = entry.split(' ')[1].split(':')[0] password = entry.split(' ')[2] # print('Line: {} charMin: {} charMax: {} char: {} password: {}'.format(entry, charFirst, charSecond, char, password)) if((len(password) >= charFirst and password[charFirst - 1] == char) ^ (len(password) >= charSecond and password[charSecond - 1] == char)): passwordOK += 1 else: passwordBad += 1 print('Good passwords: {} Bad passwords: {}'.format(passwordOK, passwordBad))
C++
UTF-8
1,096
3.515625
4
[]
no_license
#include <iostream> #include <cstdio> using namespace std; struct node { int num; node* parent; node* left; node* right; }; node* create(int a) { node* temp = new node; temp->num = a; temp->left = NULL; temp->right = NULL; temp->parent = NULL; return temp; } void insert(node* n, int a) { if (n->num > a) { if (n->left == NULL) { node* temp = create(a); temp->parent = n; n->left = temp; } else insert(n->left, a); } else if (n->num < a) { if (n->right == NULL) { node* temp = create(a); temp->parent = n; n->right = temp; } else insert(n->right, a); } } void postorder(node* n) { if (n != NULL) { postorder(n->left); postorder(n->right); cout << n->num << "\n"; } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n = 0; node* root = NULL; int count = 0; while (scanf("%d", &n) == 1) { if (n > 0) { if (count == 0) { root = new node; root->num = n; root->left = NULL; root->right = NULL; } else insert(root, n); count++; } } postorder(root); return 0; }
Java
UTF-8
18,350
2.09375
2
[]
no_license
/* * Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package ws.daley.genealogy.laf.family; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.LayoutManager; import java.awt.Rectangle; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.Icon; import javax.swing.JInternalFrame; import javax.swing.JMenu; import javax.swing.JOptionPane; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import sun.swing.SwingUtilities2; /** * Class that manages a JLF title bar * * @author Steve Wilson * @author Brian Beck * @since 1.3 */ @SuppressWarnings("serial") public class FamilyInternalFrameTitlePane extends BasicInternalFrameTitlePane { protected boolean isPalette = false; protected Icon paletteCloseIcon; protected int paletteTitleHeight; private static final Border handyEmptyBorder = new EmptyBorder(0, 0, 0, 0); /** * Key used to lookup Color from UIManager. If this is null, * <code>getWindowTitleBackground</code> is used. */ private String selectedBackgroundKey; /** * Key used to lookup Color from UIManager. If this is null, * <code>getWindowTitleForeground</code> is used. */ private String selectedForegroundKey; /** * Key used to lookup shadow color from UIManager. If this is null, * <code>getPrimaryControlDarkShadow</code> is used. */ private String selectedShadowKey; /** * Boolean indicating the state of the <code>JInternalFrame</code>s closable * property at <code>updateUI</code> time. */ private boolean wasClosable; int buttonsWidth = 0; FamilyBumps activeBumps = new FamilyBumps(0, 0, FamilyLookAndFeel.getPrimaryControlHighlight(), FamilyLookAndFeel.getPrimaryControlDarkShadow(), (UIManager.get("InternalFrame.activeTitleGradient") != null) ? null : FamilyLookAndFeel.getPrimaryControl()); FamilyBumps inactiveBumps = new FamilyBumps(0, 0, FamilyLookAndFeel.getControlHighlight(), FamilyLookAndFeel.getControlDarkShadow(), (UIManager.get("InternalFrame.inactiveTitleGradient") != null) ? null : FamilyLookAndFeel.getControl()); FamilyBumps paletteBumps; private Color activeBumpsHighlight = FamilyLookAndFeel.getPrimaryControlHighlight(); private Color activeBumpsShadow = FamilyLookAndFeel.getPrimaryControlDarkShadow(); public FamilyInternalFrameTitlePane(JInternalFrame f) { super(f); } @Override public void addNotify() { super.addNotify(); // This is done here instead of in installDefaults as I was worried // that the BasicInternalFrameUI might not be fully initialized, and // that if this resets the closable state the BasicInternalFrameUI // Listeners that get notified might be in an odd/uninitialized state. updateOptionPaneState(); } @Override protected void installDefaults() { super.installDefaults(); setFont(UIManager.getFont("InternalFrame.titleFont")); this.paletteTitleHeight = UIManager.getInt("InternalFrame.paletteTitleHeight"); this.paletteCloseIcon = UIManager.getIcon("InternalFrame.paletteCloseIcon"); this.wasClosable = this.frame.isClosable(); this.selectedForegroundKey = this.selectedBackgroundKey = null; if (FamilyLookAndFeel.usingOcean()) setOpaque(true); } @Override protected void uninstallDefaults() { super.uninstallDefaults(); if (this.wasClosable != this.frame.isClosable()) this.frame.setClosable(this.wasClosable); } @Override protected void createButtons() { super.createButtons(); Boolean paintActive = this.frame.isSelected() ? Boolean.TRUE : Boolean.FALSE; this.iconButton.putClientProperty("paintActive", paintActive); this.iconButton.setBorder(handyEmptyBorder); this.maxButton.putClientProperty("paintActive", paintActive); this.maxButton.setBorder(handyEmptyBorder); this.closeButton.putClientProperty("paintActive", paintActive); this.closeButton.setBorder(handyEmptyBorder); // The palette close icon isn't opaque while the regular close icon is. // This makes sure palette close buttons have the right background. this.closeButton.setBackground(FamilyLookAndFeel.getPrimaryControlShadow()); if (FamilyLookAndFeel.usingOcean()) { this.iconButton.setContentAreaFilled(false); this.maxButton.setContentAreaFilled(false); this.closeButton.setContentAreaFilled(false); } } /** * Override the parent's method to do nothing. Family frames do not have * system menus. */ @Override protected void assembleSystemMenu() {} /** * Override the parent's method to do nothing. Family frames do not have * system menus. */ @Override protected void addSystemMenuItems(@SuppressWarnings("unused") JMenu systemMenu) {} /** * Override the parent's method to do nothing. Family frames do not have * system menus. */ @Override protected void showSystemMenu() {} /** * Override the parent's method avoid creating a menu bar. Family frames do * not have system menus. */ @Override protected void addSubComponents() { add(this.iconButton); add(this.maxButton); add(this.closeButton); } @Override protected PropertyChangeListener createPropertyChangeListener() { return new FamilyPropertyChangeHandler(); } @Override protected LayoutManager createLayout() { return new FamilyTitlePaneLayout(); } class FamilyPropertyChangeHandler extends BasicInternalFrameTitlePane.PropertyChangeHandler { @SuppressWarnings("synthetic-access") @Override public void propertyChange(PropertyChangeEvent evt) { String prop = evt.getPropertyName(); if (prop.equals(JInternalFrame.IS_SELECTED_PROPERTY)) { Boolean b = (Boolean) evt.getNewValue(); FamilyInternalFrameTitlePane.this.iconButton.putClientProperty("paintActive", b); FamilyInternalFrameTitlePane.this.closeButton.putClientProperty("paintActive", b); FamilyInternalFrameTitlePane.this.maxButton.putClientProperty("paintActive", b); } else if ("JInternalFrame.messageType".equals(prop)) { updateOptionPaneState(); FamilyInternalFrameTitlePane.this.frame.repaint(); } super.propertyChange(evt); } } class FamilyTitlePaneLayout extends TitlePaneLayout { @Override public void addLayoutComponent(@SuppressWarnings("unused") String name, @SuppressWarnings("unused") Component c) {} @Override public void removeLayoutComponent(@SuppressWarnings("unused") Component c) {} @Override public Dimension preferredLayoutSize(Container c) { return minimumLayoutSize(c); } @SuppressWarnings("synthetic-access") @Override public Dimension minimumLayoutSize(@SuppressWarnings("unused") Container c) { // Compute width. int width = 30; if (FamilyInternalFrameTitlePane.this.frame.isClosable()) width += 21; if (FamilyInternalFrameTitlePane.this.frame.isMaximizable()) width += 16 + (FamilyInternalFrameTitlePane.this.frame.isClosable() ? 10 : 4); if (FamilyInternalFrameTitlePane.this.frame.isIconifiable()) width += 16 + (FamilyInternalFrameTitlePane.this.frame.isMaximizable() ? 2 : (FamilyInternalFrameTitlePane.this.frame.isClosable() ? 10 : 4)); FontMetrics fm = FamilyInternalFrameTitlePane.this.frame.getFontMetrics(getFont()); String frameTitle = FamilyInternalFrameTitlePane.this.frame.getTitle(); int title_w = frameTitle != null ? SwingUtilities2.stringWidth(FamilyInternalFrameTitlePane.this.frame, fm, frameTitle) : 0; int title_length = frameTitle != null ? frameTitle.length() : 0; if (title_length > 2) { int subtitle_w = SwingUtilities2.stringWidth(FamilyInternalFrameTitlePane.this.frame, fm, FamilyInternalFrameTitlePane.this.frame.getTitle().substring(0, 2) + "..."); width += (title_w < subtitle_w) ? title_w : subtitle_w; } else width += title_w; // Compute height. int height; if (FamilyInternalFrameTitlePane.this.isPalette) height = FamilyInternalFrameTitlePane.this.paletteTitleHeight; else { int fontHeight = fm.getHeight(); fontHeight += 7; Icon icon = FamilyInternalFrameTitlePane.this.frame.getFrameIcon(); int iconHeight = 0; if (icon != null) // SystemMenuBar forces the icon to be 16x16 or less. iconHeight = Math.min(icon.getIconHeight(), 16); iconHeight += 5; height = Math.max(fontHeight, iconHeight); } return new Dimension(width, height); } @SuppressWarnings("synthetic-access") @Override public void layoutContainer(@SuppressWarnings("unused") Container c) { boolean leftToRight = FamilyUtils.isLeftToRight(FamilyInternalFrameTitlePane.this.frame); int w = getWidth(); int x = leftToRight ? w : 0; int y = 2; int spacing; // assumes all buttons have the same dimensions // these dimensions include the borders int buttonHeight = FamilyInternalFrameTitlePane.this.closeButton.getIcon().getIconHeight(); int buttonWidth = FamilyInternalFrameTitlePane.this.closeButton.getIcon().getIconWidth(); if (FamilyInternalFrameTitlePane.this.frame.isClosable()) if (FamilyInternalFrameTitlePane.this.isPalette) { spacing = 3; x += leftToRight ? -spacing - (buttonWidth + 2) : spacing; FamilyInternalFrameTitlePane.this.closeButton.setBounds(x, y, buttonWidth + 2, getHeight() - 4); if (!leftToRight) x += (buttonWidth + 2); } else { spacing = 4; x += leftToRight ? -spacing - buttonWidth : spacing; FamilyInternalFrameTitlePane.this.closeButton.setBounds(x, y, buttonWidth, buttonHeight); if (!leftToRight) x += buttonWidth; } if (FamilyInternalFrameTitlePane.this.frame.isMaximizable() && !FamilyInternalFrameTitlePane.this.isPalette) { spacing = FamilyInternalFrameTitlePane.this.frame.isClosable() ? 10 : 4; x += leftToRight ? -spacing - buttonWidth : spacing; FamilyInternalFrameTitlePane.this.maxButton.setBounds(x, y, buttonWidth, buttonHeight); if (!leftToRight) x += buttonWidth; } if (FamilyInternalFrameTitlePane.this.frame.isIconifiable() && !FamilyInternalFrameTitlePane.this.isPalette) { spacing = FamilyInternalFrameTitlePane.this.frame.isMaximizable() ? 2 : (FamilyInternalFrameTitlePane.this.frame.isClosable() ? 10 : 4); x += leftToRight ? -spacing - buttonWidth : spacing; FamilyInternalFrameTitlePane.this.iconButton.setBounds(x, y, buttonWidth, buttonHeight); if (!leftToRight) x += buttonWidth; } FamilyInternalFrameTitlePane.this.buttonsWidth = leftToRight ? w - x : x; } } public void paintPalette(Graphics g) { boolean leftToRight = FamilyUtils.isLeftToRight(this.frame); int width = getWidth(); int height = getHeight(); if (this.paletteBumps == null) this.paletteBumps = new FamilyBumps(0, 0, FamilyLookAndFeel.getPrimaryControlHighlight(), FamilyLookAndFeel.getPrimaryControlInfo(), FamilyLookAndFeel.getPrimaryControlShadow()); Color background = FamilyLookAndFeel.getPrimaryControlShadow(); Color darkShadow = FamilyLookAndFeel.getPrimaryControlDarkShadow(); g.setColor(background); g.fillRect(0, 0, width, height); g.setColor(darkShadow); g.drawLine(0, height - 1, width, height - 1); int xOffset = leftToRight ? 4 : this.buttonsWidth + 4; int bumpLength = width - this.buttonsWidth - 2 * 4; int bumpHeight = getHeight() - 4; this.paletteBumps.setBumpArea(bumpLength, bumpHeight); this.paletteBumps.paintIcon(this, g, xOffset, 2); } @Override public void paintComponent(Graphics g) { if (this.isPalette) { paintPalette(g); return; } boolean leftToRight = FamilyUtils.isLeftToRight(this.frame); boolean isSelected = this.frame.isSelected(); int width = getWidth(); int height = getHeight(); Color background = null; Color foreground = null; Color shadow = null; FamilyBumps bumps; String gradientKey; if (isSelected) { if (!FamilyLookAndFeel.usingOcean()) { this.closeButton.setContentAreaFilled(true); this.maxButton.setContentAreaFilled(true); this.iconButton.setContentAreaFilled(true); } if (this.selectedBackgroundKey != null) background = UIManager.getColor(this.selectedBackgroundKey); if (background == null) background = FamilyLookAndFeel.getWindowTitleBackground(); if (this.selectedForegroundKey != null) foreground = UIManager.getColor(this.selectedForegroundKey); if (this.selectedShadowKey != null) shadow = UIManager.getColor(this.selectedShadowKey); if (shadow == null) shadow = FamilyLookAndFeel.getPrimaryControlDarkShadow(); if (foreground == null) foreground = FamilyLookAndFeel.getWindowTitleForeground(); this.activeBumps.setBumpColors(this.activeBumpsHighlight, this.activeBumpsShadow, UIManager.get("InternalFrame.activeTitleGradient") != null ? null : background); bumps = this.activeBumps; gradientKey = "InternalFrame.activeTitleGradient"; } else { if (!FamilyLookAndFeel.usingOcean()) { this.closeButton.setContentAreaFilled(false); this.maxButton.setContentAreaFilled(false); this.iconButton.setContentAreaFilled(false); } background = FamilyLookAndFeel.getWindowTitleInactiveBackground(); foreground = FamilyLookAndFeel.getWindowTitleInactiveForeground(); shadow = FamilyLookAndFeel.getControlDarkShadow(); bumps = this.inactiveBumps; gradientKey = "InternalFrame.inactiveTitleGradient"; } if (!FamilyUtils.drawGradient(this, g, gradientKey, 0, 0, width, height, true)) { g.setColor(background); g.fillRect(0, 0, width, height); } g.setColor(shadow); g.drawLine(0, height - 1, width, height - 1); g.drawLine(0, 0, 0, 0); g.drawLine(width - 1, 0, width - 1, 0); int titleLength; int xOffset = leftToRight ? 5 : width - 5; String frameTitle = this.frame.getTitle(); Icon icon = this.frame.getFrameIcon(); if (icon != null) { if (!leftToRight) xOffset -= icon.getIconWidth(); int iconY = ((height / 2) - (icon.getIconHeight() / 2)); icon.paintIcon(this.frame, g, xOffset, iconY); xOffset += leftToRight ? icon.getIconWidth() + 5 : -5; } if (frameTitle != null) { Font f = getFont(); g.setFont(f); FontMetrics fm = SwingUtilities2.getFontMetrics(this.frame, g, f); @SuppressWarnings("unused") int fHeight = fm.getHeight(); g.setColor(foreground); int yOffset = ((height - fm.getHeight()) / 2) + fm.getAscent(); Rectangle rect = new Rectangle(0, 0, 0, 0); if (this.frame.isIconifiable()) rect = this.iconButton.getBounds(); else if (this.frame.isMaximizable()) rect = this.maxButton.getBounds(); else if (this.frame.isClosable()) rect = this.closeButton.getBounds(); int titleW; if (leftToRight) { if (rect.x == 0) rect.x = this.frame.getWidth() - this.frame.getInsets().right - 2; titleW = rect.x - xOffset - 4; frameTitle = getTitle(frameTitle, fm, titleW); } else { titleW = xOffset - rect.x - rect.width - 4; frameTitle = getTitle(frameTitle, fm, titleW); xOffset -= SwingUtilities2.stringWidth(this.frame, fm, frameTitle); } titleLength = SwingUtilities2.stringWidth(this.frame, fm, frameTitle); SwingUtilities2.drawString(this.frame, g, frameTitle, xOffset, yOffset); xOffset += leftToRight ? titleLength + 5 : -5; } int bumpXOffset; int bumpLength; if (leftToRight) { bumpLength = width - this.buttonsWidth - xOffset - 5; bumpXOffset = xOffset; } else { bumpLength = xOffset - this.buttonsWidth - 5; bumpXOffset = this.buttonsWidth + 5; } int bumpYOffset = 3; int bumpHeight = getHeight() - (2 * bumpYOffset); bumps.setBumpArea(bumpLength, bumpHeight); bumps.paintIcon(this, g, bumpXOffset, bumpYOffset); } public void setPalette(boolean b) { this.isPalette = b; if (this.isPalette) { this.closeButton.setIcon(this.paletteCloseIcon); if (this.frame.isMaximizable()) remove(this.maxButton); if (this.frame.isIconifiable()) remove(this.iconButton); } else { this.closeButton.setIcon(this.closeIcon); if (this.frame.isMaximizable()) add(this.maxButton); if (this.frame.isIconifiable()) add(this.iconButton); } revalidate(); repaint(); } /** * Updates any state dependant upon the JInternalFrame being shown in a * <code>JOptionPane</code>. */ private void updateOptionPaneState() { int type = -2; boolean closable = this.wasClosable; Object obj = this.frame.getClientProperty("JInternalFrame.messageType"); if (obj == null) // Don't change the closable state unless in an JOptionPane. return; if (obj instanceof Integer) type = ((Integer) obj).intValue(); switch(type) { case JOptionPane.ERROR_MESSAGE: this.selectedBackgroundKey = "OptionPane.errorDialog.titlePane.background"; this.selectedForegroundKey = "OptionPane.errorDialog.titlePane.foreground"; this.selectedShadowKey = "OptionPane.errorDialog.titlePane.shadow"; closable = false; break; case JOptionPane.QUESTION_MESSAGE: this.selectedBackgroundKey = "OptionPane.questionDialog.titlePane.background"; this.selectedForegroundKey = "OptionPane.questionDialog.titlePane.foreground"; this.selectedShadowKey = "OptionPane.questionDialog.titlePane.shadow"; closable = false; break; case JOptionPane.WARNING_MESSAGE: this.selectedBackgroundKey = "OptionPane.warningDialog.titlePane.background"; this.selectedForegroundKey = "OptionPane.warningDialog.titlePane.foreground"; this.selectedShadowKey = "OptionPane.warningDialog.titlePane.shadow"; closable = false; break; case JOptionPane.INFORMATION_MESSAGE: case JOptionPane.PLAIN_MESSAGE: this.selectedBackgroundKey = this.selectedForegroundKey = this.selectedShadowKey = null; closable = false; break; default: this.selectedBackgroundKey = this.selectedForegroundKey = this.selectedShadowKey = null; break; } if (closable != this.frame.isClosable()) this.frame.setClosable(closable); } }
Java
UTF-8
1,885
3.265625
3
[]
no_license
package models.spaceships.weapons; import models.spaceships.weapons.bullets.Bullet; import java.awt.*; import java.util.ArrayList; public abstract class Weapon { private ArrayList<Bullet> bulletsFired; private int damage; protected int cooldown; protected int cooldownCounter; protected boolean shootingRight; protected Weapon(int cooldown, boolean shootingRight, int damage) { this.bulletsFired = new ArrayList<>(); this.cooldown = cooldown; this.cooldownCounter = cooldown; this.shootingRight = shootingRight; this.damage = damage; } public ArrayList<Bullet> getBulletsFired() { return this.bulletsFired; } public int getDamage() { return this.damage; } public abstract void shoot(int x, int y); public void update() { this.cooldownCounter++; for (int i = 0; i < bulletsFired.size(); i++) { this.bulletsFired.get(i).update(); } this.checkForUnneededBullets(); } public void render(Graphics graphics) { for (int i = 0; i < bulletsFired.size(); i++) { this.bulletsFired.get(i).render(graphics); } } public void deactivateWeapon() { for (int i = 0; i < this.bulletsFired.size(); i++) { Bullet bullet = this.bulletsFired.get(i); bullet.deactivateBullet(); } } protected void addBullet(Bullet bullet) { this.bulletsFired.add(bullet); } private void checkForUnneededBullets() { ArrayList<Bullet> activeBullets = new ArrayList<>(); for (int i = 0; i < this.bulletsFired.size(); i++) { Bullet bullet = this.bulletsFired.get(i); if (bullet.getStatus()) { activeBullets.add(bullet); } } this.bulletsFired = activeBullets; } }
JavaScript
UTF-8
2,470
2.859375
3
[]
no_license
exports.fill = fill; var _ = require('./public/lib/underscore-min'), wordservice = require('./wordservice'), puz = require('./puzzle'); function randomMember (array) { return array[Math.floor(Math.random()*array.length)]; } function fill (puzzle, callback) { var firstSlot = randomMember(puzzle.slots); wordservice.matchWord(firstSlot.getQueryPattern(puzzle.grid), function (matches) { firstSlot.fillIn(randomMember(matches), puzzle.grid); fillRecursive(puzzle, function (completedPuzzle) { wordservice.areTheseWords(puzzle.slots.map(function (slot) {return slot.getQueryPattern(puzzle.grid)}), function (theyAre) { if (theyAre) { callback(completedPuzzle); } else { fill(new puz.Puzzle(puzzle.size), callback); } }); }); }); } function fillRecursive (puzzle, callback) { var slotsToFill = puzzle.slots.filter(function (slot) { var letters = slot.getQueryPattern(puzzle.grid).split(''); return letters.some(function (l) {return l == '_'}) && letters.some(function (l) {return l != '_'}); }); if (slotsToFill.length == 0) { callback(puzzle); } else { wordservice.matchWords(_.uniq(slotsToFill.map(function (slot) {return slot.getQueryPattern(puzzle.grid)})), function (patternsToMatches) { slotsToFill.sort(function (slotA, slotB) { var matchesA = patternsToMatches[slotA.getQueryPattern(puzzle.grid)]; var matchesB = patternsToMatches[slotB.getQueryPattern(puzzle.grid)]; return matchesA.length > matchesB.length ? 1 : -1; }); var mostConstrainedSlot = slotsToFill[0]; var matchOptions = patternsToMatches[mostConstrainedSlot.getQueryPattern(puzzle.grid)]; if (matchOptions.length > 0) { mostConstrainedSlot.fillIn(mostCompatible(matchOptions), puzzle.grid); fillRecursive(puzzle, callback); } else { callback(puzzle); } }); } } function mostCompatible (words) { return words.sort(function (wordA, wordB) { return compatibility(wordA) < compatibility(wordB) ? 1 : -1; })[0]; function compatibility (word) { return word.split('').filter(function (l) {return _.contains(['a', 'e', 'i', 'o', 'u'], l)}).length / word.length; } }
C++
UTF-8
1,717
2.703125
3
[]
no_license
#include "..\include\Enemy.h" using namespace std; void Enemy::switchFps() { if (anim.y > 3) anim.y = 0; if (!pony) { if (anim.x < 2) sprite.setTextureRect(sf::IntRect(100 * anim.x, 94 * anim.y, 100, 94)); else sprite.setTextureRect(sf::IntRect(86 + 57 * anim.x, 94 * anim.y, 57, 94)); } else { sprite.setTextureRect(sf::IntRect(100 * anim.x, 94 * anim.y, 100, 94)); } anim.y++; } Enemy::Enemy(sf::Texture &t, Resources &res, sf::Vector2f pos, TypeEnemy * Typenemy, int type, bool pony) : SpaceObject(t, res, 5, 3), compteurEnemy(1) { this->pony = pony; this->health = Typenemy->getLife(); this->rate = Typenemy->getRate(); this->speed = Typenemy->getSpeed(); this->laserSpeed = Typenemy->getLaserSpeed(); this->laserQty = Typenemy->getLaserQty(); this->dommage = Typenemy->getDommage(); this->anim = sf::Vector2i(type, 0); if (!pony) { if (anim.x < 2) sprite.setTextureRect(sf::IntRect(anim.x * 100, anim.y, 100, 94)); else sprite.setTextureRect(sf::IntRect(86 + anim.x * 57, anim.y, 57, 94)); } else { sprite.setTextureRect(sf::IntRect(anim.x * 100, anim.y, 100, 94)); } this->score = Typenemy->getScore(); sprite.setPosition(pos); } int Enemy::getScore() { return score; } void Enemy::move() { sprite.move(-speed, 0); } vector<Laser*> Enemy::shoot(sf::Texture &texture) { vector<Laser*> l; if (compteurEnemy == 60 / rate) { for (int i = 1; i <= laserQty; i++) l.push_back(new Laser(texture,i,this->laserQty,this->sprite, this->laserSpeed, this->dommage)); compteurEnemy = 1; return l; } else compteurEnemy++; return l; } Enemy::~Enemy() { std::cout << "Enemy died." << std::endl; } int Enemy::getDommage() { return this->dommage; }
Java
UTF-8
792
2.640625
3
[ "MIT" ]
permissive
package com.edicarlosls.rungoat.jogo; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Typeface; public class HDU { private int distancia = 0; private int moedas = 0; private Paint paint; private Moeda moeda; public HDU(){ paint = new Paint(); paint.setColor(0xffffffff); paint.setShadowLayer(2, 2, 2, 0xff444444); paint.setTypeface(Typeface.DEFAULT_BOLD); moeda = new Moeda(70, 40, 70, 70); } public void desenhaNo(Canvas canvas){ paint.setTextSize(60); canvas.drawText(String.valueOf(moedas), 145, 100, paint); paint.setTextSize(30); canvas.drawText(distancia + " m", 150, 140, paint); moeda.desenhaNo(canvas); } public void aumentaDistancia(){ distancia++; } public void aumentaMoedas(){ moedas++; } }
Python
UTF-8
729
2.515625
3
[]
no_license
#!/usr/local/bin/python3 #-*- coding: UTF-8 -*- """ Log setting. """ import os import logging import define def setLogger(loggername, level, formaterStr, dirpath): """ Set loger, using logging lib. """ if not os.path.isdir(dirpath): try: os.makedirs(dirpath) except: raise define.SpiderError("ERROR - can not create log dir.") try: loggerHandler = logging.FileHandler(dirpath + '/' + loggername + '.log') except: raise define.SpiderError("ERROR - can not create log file.") loggerHandler.setFormatter(logging.Formatter(formaterStr)) logger = logging.getLogger(loggername) logger.setLevel(level) logger.addHandler(loggerHandler)
Java
UTF-8
692
3.140625
3
[]
no_license
class Solution { public ListNode oddEvenList(ListNode head) { if(head == null) { return null; } ListNode dummy1 = new ListNode(0); ListNode dummy2 = new ListNode(0); dummy1.next = head; dummy2.next = head.next; ListNode headOdd = head; ListNode headEven = head.next; while((headOdd != null && headOdd.next != null) && (headEven != null && headEven.next != null)) { headOdd.next = headOdd.next.next; headEven.next = headEven.next.next; headOdd = headOdd.next; headEven = headEven.next; } headOdd.next = dummy2.next; return dummy1.next; } }
Python
UTF-8
618
4.0625
4
[]
no_license
#crie um programa que leia uma frase qualquer e diga se ela é um palindromo, desconsiderando os espaçõs. #ex: APOS A SOPA, A SACADA DA CASA, A TORRE DA DERROTA, O LOBO AMA O BOLO , ANOTARAM A DATA DA MARATONA import unicodedata print('*'*45,'\nVamos ver se essa frase é um palindromo.') f = input('Digite uma Frase. \n: ') f = unicodedata.normalize('NFD',f) f = f.encode("ascii", "ignore") f = f.decode("utf-8") f = f.replace(' ','') r = f.replace(' ','')[::-1] print(f'A Frase {f.title()} invertida fica {r}') if f == r: print('Essa frase é um palindromo') else: print('Essa frase não é um palindromo')
Python
UTF-8
788
2.9375
3
[ "MIT" ]
permissive
"""Lololo.""" from operator import itemgetter from itertools import groupby import json mylist = [ [ 30.0, "C", "Third", "0003", "First sensor", "Температура" ], [ 25.0, "C", "First", "0001", "First sensor", "Температура" ], [ 21.0, "Вт", "Second", "0002", "Second sensor", "Энергопотребление" ] ] def group_category(records): """Lololo.""" records.sort(key=itemgetter(5, 2)) result = { key: [*group] for key, group in groupby(records, key=itemgetter(5)) } return result print(json.dumps(group_category(mylist), indent=2, ensure_ascii=False))
Shell
UTF-8
337
3.171875
3
[]
no_license
#!/bin/sh # SPDX-License-Identifier: Apache-2.0 if ! grep -q operations/dns .gitreview 2>/dev/null; then echo "ERROR: must be executed from the DNS repo root" exit 2 fi (git --no-pager grep -P '\t') && HAS_TAB=1 || HAS_TAB=0 if [ $HAS_TAB -eq 1 ]; then echo "ERROR: Tabs found" else echo "OK: No tabs" fi exit $HAS_TAB
SQL
UTF-8
1,465
2.921875
3
[]
no_license
DROP DATABASE ItProfi IF EXISTS; CREATE DATABASE ItProfi; USE ItProfi; CREATE TABLE login ( Id Int(11) NOT NULL auto_increment, EMail VarChar(50) NOT NULL default '', Kennwort VarChar(50) NOT NULL default '', ProfilTyp VarCHar(50) NOT NULL default'', PRIMARY KEY (Id) ); CREATE TABLE register_personal ( Id Int(11) NOT NULL auto_increment, Anrede VarChar(10) NOT NULL default '', Nachname VarChar(50) NOT NULL default '', Vorname VarChar(50) NOT NULL default '', Geburtsdatum date NOT NULL, Nationalitaet VarChar(50) NOT NULL default '', EMail VarChar(100) NOT NULL default '', Passwort VarChar(50) NOT NULL default '', Telefon VarChar(50), Strasse VarChar(50) NOT NULL default '', PLZ Int(4) NOT NULL, Ort VarChar(50) NOT NULL default '', Berufsbezeichnung VarChar(50) NOT NULL default '', Arbeitgeber VarChar(50) NOT NULL default '', Ausbildung VarChar(50) NOT NULL default '', Student VarChar(50) NOT NULL default '', PRIMARY KEY (Id) ); CREATE TABLE register_company( Id Int(11) NOT NULL auto_increment, Name VarChar(50) NOT NULL default '', EMail VarChar(100) NOT NULL default '', Passwort VarChar(50) NOT NULL default '', Telefon VarChar(50) NOT NULL default '', Strasse VarChar(50) NOT NULL default '', PLZ Int(4) NOT NULL, Ort VarChar(50) NOT NULL default '', Dienstleistungen VarChar(50) NOT NULL default '', SucheNach VarChar(50) NOT NULL default '', PRIMARY KEY (Id) );
SQL
UTF-8
1,057
3.125
3
[]
no_license
-- pack_liste_situation_logiciel PL/SQL -- -- Equipe SOPRA -- cree le 15/03/1999 -- -- Objet : Permet la creation de la liste top amortissable dans top_amort -- Tables : type_amort -- Pour le fichier HTML : dccamo.htm -- Attention le nom du package ne peut etre le nom -- de la table... CREATE OR REPLACE PACKAGE pack_liste_top_amort AS PROCEDURE lister_top_amort( p_userid IN VARCHAR2, p_curseur IN OUT pack_liste_dynamique.liste_dyn ); END pack_liste_top_amort; / CREATE OR REPLACE PACKAGE BODY pack_liste_top_amort AS ----------------------------------- SELECT ----------------------------------- PROCEDURE lister_top_amort ( p_userid IN VARCHAR2, p_curseur IN OUT pack_liste_dynamique.liste_dyn ) IS BEGIN OPEN p_curseur FOR SELECT ctopact, libamort FROM type_amort ORDER BY ctopact; EXCEPTION WHEN OTHERS THEN raise_application_error(-20997, SQLERRM); END lister_top_amort; END pack_liste_top_amort; /
Java
UTF-8
299
3.109375
3
[ "MIT" ]
permissive
public class Item { String name; String type; double price; Item(String name,String type, double price){ this.type = type; this.name = name; this.price = price; } public String toString(){ return name+":"+type+":"+price; } }
PHP
UTF-8
1,561
3.375
3
[]
no_license
<?php function returnSeason($month){ switch($month) case "January": case "December": case "February": echo "Winter"; break; case "March": case "April": case "May": echo "Spring"; break; case "June": case "July": case "August": echo "summer"; break; case "September": case "October": case "November": echo "fall"; break; } $isClicked = FALSE; if ( $isClicked ) { $link_color = "aqua"; } else { $link_color = "gold"; } <?php function ternaryCheckout($items) { return $items <= 12 ? "express lane" : "regular lane"; } function ternaryVote ($age) { return $age >= 18 ? "yes" : "no"; } echo ternaryCheckout(1); echo "\n\n"; echo ternaryCheckout(13); echo "\n\n"; echo ternaryVote(19); echo "\n\n"; echo ternaryVote(13); <?php function truthyOrFalsy ($value) { if ($value){ return "True"; } else { return "False"; } } /* // Alternate version using ternary: function truthyOrFalsy ($value) { return $value ? "True" : "False"; } */ echo truthyOrFalsy(TRUE); echo "\n\n"; echo truthyOrFalsy(FALSE); echo "\n\n"; echo truthyOrFalsy("cat"); echo "\n\n"; echo truthyOrFalsy(""); echo "\n\n"; echo truthyOrFalsy("-10290192.871"); echo "\n\n"; echo truthyOrFalsy("0"); echo "\n\n"; <?php echo "Hello, there. What's your first name?\n"; $name = readline(">> "); $name_length = strlen($name); if ($name_length > 8) { echo "Hi, ${name}. That's a long name."; } elseif ($name_length > 3) { echo "Hi, ${name}."; } else { echo "Hi, ${name}. That's a short name."; }
Java
UTF-8
1,745
2.25
2
[]
no_license
package com.tsinghua.course.Base.CustomizedClass; import org.springframework.data.mongodb.core.mapping.Document; /** * @描述 一条评论的格式 */ @Document("CommentItem") public class CommentItem { // 评论id String commentId; // 用户名 String commentUsername; // 昵称 String commentNickname; // 备注 String commentRemark; // 内容 String commentContent; // 评论时间 String commentTime; // 是否是好友 boolean isFriend; public String getCommentId() { return commentId; } public void setCommentId(String commentId) { this.commentId = commentId; } public String getCommentUsername() { return commentUsername; } public void setCommentUsername(String commentUsername) { this.commentUsername = commentUsername; } public String getCommentNickname() { return commentNickname; } public void setCommentNickname(String commentNickname) { this.commentNickname = commentNickname; } public String getCommentRemark() { return commentRemark; } public void setCommentRemark(String commentRemark) { this.commentRemark = commentRemark; } public String getCommentContent() { return commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } public String getCommentTime() { return commentTime; } public void setCommentTime(String commentTime) { this.commentTime = commentTime; } public boolean isFriend() { return isFriend; } public void setFriend(boolean friend) { isFriend = friend; } }
C++
UTF-8
731
2.859375
3
[]
no_license
#include <iostream> #include "fit/infix.h" #include "fit/compose.h" #include "fit/lambda.h" #include "fit/placeholders.h" using namespace fit; struct increment { template<class T> T operator()(T x) const { return x + 1; } }; struct decrement { template<class T> T operator()(T x) const { return x - 1; } }; int main() { int r = compose(increment(), decrement(), increment())(3); auto cmps = infix([](auto x, auto y){return compose(x, y);}); //auto cmps = infix(compose); int k = (increment() <cmps> increment())(5); int k2 = (([](auto x) {return x + 10;}) <cmps> increment() <cmps> (_ + 50))(5); std::cout << r << " " << k << " " << k2; return 0; }
Java
UTF-8
1,626
2.515625
3
[]
no_license
package com.atlas.atlasEarth._VirtualGlobe.Source.Renderer; import android.graphics.Bitmap; import com.atlas.atlasEarth._VirtualGlobe.Source.Core.ByteFlags; import com.atlas.atlasEarth._VirtualGlobe.Source.Renderer.GL3x.NamesGL3x.TextureNameGL3x; /** * Class for a Texture for OpenGL, loaded by {@link com.atlas.atlasEarth._VirtualGlobe.Source.Renderer.GL3x.TextureLoaderGL3x} */ public class Texture extends TextureNameGL3x{ // TODO: 6/19/2017 ShineDamper and Reflectivity? private int resourceID = 0; private String url = ""; private Bitmap bitmap = null; private byte type = ByteFlags.NULL; /** * Load a texture out of a Resource folder * @param resourceID id for the Resource data */ public Texture(int resourceID, byte type) { this.resourceID = resourceID; this.type = type; } /** * Load a {@link Bitmap} Object to OpenGL * @param bitmap the Bitmap which should be loaded to OpenGL */ public Texture(Bitmap bitmap){ this.bitmap = bitmap; this.type = ByteFlags.GL_TEXTURE_2D; } /** * @param url the url of the Bitmap which should be loaded to OpenGL */ public Texture(String url){ this.url = url; this.type = ByteFlags.GL_TEXTURE_2D; } public int getResourceID() { return resourceID; } public String getUrl() { return url; } public Bitmap getBitmap(){ return bitmap; } public byte getType() { return type; } public int getTextureIDGl3x() { return super.getTextureIDGl3x(); } }
Java
UTF-8
916
2.265625
2
[]
no_license
package com.dell.tsp.admin.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "service_group") public class ServiceGroupEntity { public ServiceGroupEntity() { super(); } public ServiceGroupEntity(int serviceGroupId, String services) { super(); this.serviceGroupId = serviceGroupId; this.services = services; } private int serviceGroupId; private String services; @Id @Column(name="SERVICE_GROUP_ID", nullable = false) public int getServiceGroupId() { return serviceGroupId; } public void setServiceGroupId(int serviceGroupId) { this.serviceGroupId = serviceGroupId; } @Column(name="SERVICES", nullable = false) public String getServices() { return services; } public void setServices(String services) { this.services = services; } }
C++
UTF-8
543
3.09375
3
[]
no_license
class Solution { public: int countNumbersWithUniqueDigits(int n) { if (!n) return 1; if (n == 1) return 10; if (n == 2) return 91; vector<int> dp (n+1, 0); dp[1] = 10; dp[2] = 81; int res = dp[1] + dp[2]; for (int i = 3; i <= n; ++ i) { if (i >= 11) return res; dp[i] = dp[i-1] * (9-i+2); res += dp[i]; } return res; } }; /* the idea: math combination question: * for n-digit number, the unique number counter: 9 * 9 * 8 * 7... * NOTICE the limit is 11, were there is no more unique number further * /
Python
UTF-8
2,738
4.03125
4
[]
no_license
# This is my first try at a tic tac toe game with a 1v1 system import random from os import system import time board = [] def setup(): global board board = [' ']*10 def get_letter(): letter = input("What letter do you want to be? (X/O): ").upper() while not (letter == "X" or letter == "O"): letter = input("Either the letter 'x' or 'o': ").upper() return letter def det_first_player(): choice = get_letter() if choice == "X": global player1 player1 = "X" system('cls') print("You go first!") time.sleep(1) get_player_move() else: global player2 player2 = "O" system('cls') print("Computer goes first!") time.sleep(1) def show_board(): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') def get_player_move(): show_board() valid = False while valid is not True: move = input("Where do want to move on? (1-9)") if move not in '1 2 3 4 5 6 7 8 9'.split(): print('You can only move on squares 1 to 9') elif not is_space_free(move) is True: print('This square has already been filled') else: valid = True else: make_move("X", int(move)) def is_space_free(number): if board[int(number)] != " ": return False else: return True def make_move(player, move): board.pop(move) board.insert(move, player) show_board() get_comp_move() setup() get_player_move() def check_won(bo, le): return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal (bo[9] == le and bo[5] == le and bo[1] == le)) def is_board_full(): for i in range(0, 10): if is_space_free(i): return False else: return True
TypeScript
UTF-8
29,168
2.546875
3
[]
no_license
import { HttpRedirect, HttpRequest, HttpResponse, JavascriptCookieRecord, JavascriptOperation, Navigation, UiInteraction, UiState, } from "../shared-resources/openwpm-webext-instrumentation"; import { CapturedContent, LogEntry } from "./OpenWpmPacketHandler"; import { isoDateTimeStringsWithinFutureSecondThreshold } from "./lib/dateUtils"; import { captureExceptionWithExtras, Sentry, } from "../shared-resources/ErrorReporting"; import { browser } from "webextension-polyfill-ts"; export interface NavigationBatch { navigationEnvelope: OpenWpmPayloadEnvelope; childEnvelopes: OpenWpmPayloadEnvelope[]; httpRequestCount: number; httpResponseCount: number; httpRedirectCount: number; javascriptOperationCount: number; capturedContentCount: number; uiInteractionCount: number; uiStateCount: number; } export interface TrimmedNavigationBatch extends NavigationBatch { trimmedHttpRequestCount: number; trimmedHttpResponseCount: number; trimmedHttpRedirectCount: number; trimmedJavascriptOperationCount: number; trimmedCapturedContentCount: number; trimmedUiInteractionCount: number; trimmedUiStateCount: number; } export interface TrimmedNavigationBatchesByUuid { [navigationUuid: string]: TrimmedNavigationBatch; } export type OpenWPMType = | "navigations" | "navigation_batches" | "trimmed_navigation_batches" | "http_requests" | "http_responses" | "http_redirects" | "javascript" | "javascript_cookies" | "openwpm_log" | "openwpm_captured_content" | "ui_interactions" | "ui_states"; type OpenWPMPayload = | Navigation | NavigationBatch | TrimmedNavigationBatch | HttpRequest | HttpResponse | HttpRedirect | JavascriptOperation | JavascriptCookieRecord | LogEntry | CapturedContent | UiInteraction | UiState; type BatchableChildOpenWPMPayload = | HttpRequest | HttpResponse | HttpRedirect | JavascriptOperation | CapturedContent | UiInteraction | UiState; /** * An envelope that allows for grouping of different * types of OpenWPM packets together while maintaining * type checking */ export interface OpenWpmPayloadEnvelope { type: OpenWPMType; navigation?: Navigation; navigationBatch?: NavigationBatch; trimmedNavigationBatch?: TrimmedNavigationBatch; httpRequest?: HttpRequest; httpResponse?: HttpResponse; httpRedirect?: HttpRedirect; javascriptOperation?: JavascriptOperation; javascriptCookieRecord?: JavascriptCookieRecord; logEntry?: LogEntry; capturedContent?: CapturedContent; uiInteraction?: UiInteraction; uiState?: UiState; } export const batchableChildOpenWpmPayloadFromOpenWpmPayloadEnvelope = ( openWpmPayloadEnvelope: OpenWpmPayloadEnvelope, ): BatchableChildOpenWPMPayload => { switch (openWpmPayloadEnvelope.type) { case "http_requests": return openWpmPayloadEnvelope.httpRequest as HttpRequest; case "http_responses": return openWpmPayloadEnvelope.httpResponse as HttpResponse; case "http_redirects": return openWpmPayloadEnvelope.httpRedirect as HttpRedirect; case "javascript": return openWpmPayloadEnvelope.javascriptOperation as JavascriptOperation; case "openwpm_captured_content": return openWpmPayloadEnvelope.capturedContent as CapturedContent; case "ui_interactions": return openWpmPayloadEnvelope.uiInteraction as UiInteraction; case "ui_states": return openWpmPayloadEnvelope.uiState as UiState; } throw new Error(`Unexpected type supplied: '${openWpmPayloadEnvelope.type}'`); }; export const openWpmPayloadEnvelopeFromOpenWpmTypeAndPayload = ( type: OpenWPMType, payload: OpenWPMPayload, ): OpenWpmPayloadEnvelope => { const openWpmPayloadEnvelope: OpenWpmPayloadEnvelope = { type, navigation: type === "navigations" ? (payload as Navigation) : undefined, navigationBatch: type === "navigation_batches" ? (payload as NavigationBatch) : undefined, trimmedNavigationBatch: type === "trimmed_navigation_batches" ? (payload as TrimmedNavigationBatch) : undefined, httpRequest: type === "http_requests" ? (payload as HttpRequest) : undefined, httpResponse: type === "http_responses" ? (payload as HttpResponse) : undefined, httpRedirect: type === "http_redirects" ? (payload as HttpRedirect) : undefined, javascriptOperation: type === "javascript" ? (payload as JavascriptOperation) : undefined, javascriptCookieRecord: type === "javascript_cookies" ? (payload as JavascriptCookieRecord) : undefined, logEntry: type === "openwpm_log" ? (payload as LogEntry) : undefined, capturedContent: type === "openwpm_captured_content" ? (payload as CapturedContent) : undefined, uiInteraction: type === "ui_interactions" ? (payload as UiInteraction) : undefined, uiState: type === "ui_states" ? (payload as UiState) : undefined, }; return openWpmPayloadEnvelope; }; const removeItemFromArray = (ar, el) => { ar.splice(ar.indexOf(el), 1); }; const setEnvelopeCounts = $navigationBatch => { $navigationBatch.httpRequestCount = $navigationBatch.childEnvelopes.filter( env => env.type === "http_requests", ).length; $navigationBatch.httpResponseCount = $navigationBatch.childEnvelopes.filter( env => env.type === "http_responses", ).length; $navigationBatch.httpRedirectCount = $navigationBatch.childEnvelopes.filter( env => env.type === "http_redirects", ).length; $navigationBatch.javascriptOperationCount = $navigationBatch.childEnvelopes.filter( env => env.type === "javascript", ).length; $navigationBatch.capturedContentCount = $navigationBatch.childEnvelopes.filter( env => env.type === "openwpm_captured_content", ).length; $navigationBatch.uiInteractionCount = $navigationBatch.childEnvelopes.filter( env => env.type === "ui_interactions", ).length; $navigationBatch.uiStateCount = $navigationBatch.childEnvelopes.filter( env => env.type === "ui_states", ).length; }; interface NavigationBatchPreprocessorOptions { navigationAgeThresholdInSeconds: number; navigationBatchChildEnvelopeAgeThresholdInSeconds: number; orphanAgeThresholdInSeconds: number; } /** * Groups incoming payloads by navigation. * The strange implementation of the processing is mainly * due to the flexible ordering of the incoming payloads, * eg payloads related to a specific navigation may arrive before * the corresponding navigation. */ export class NavigationBatchPreprocessor { public navigationAgeThresholdInSeconds: number; public navigationBatchChildEnvelopeAgeThresholdInSeconds: number; public orphanAgeThresholdInSeconds: number; constructor(options: NavigationBatchPreprocessorOptions) { const { navigationAgeThresholdInSeconds, navigationBatchChildEnvelopeAgeThresholdInSeconds, orphanAgeThresholdInSeconds, } = options; this.navigationAgeThresholdInSeconds = navigationAgeThresholdInSeconds; this.navigationBatchChildEnvelopeAgeThresholdInSeconds = navigationBatchChildEnvelopeAgeThresholdInSeconds; this.orphanAgeThresholdInSeconds = orphanAgeThresholdInSeconds; } /** * Method that is meant to be overridden and implement trimming of * navigation batches at the end of the processing flow. */ public processedNavigationBatchTrimmer: ( navigationBatch: NavigationBatch | TrimmedNavigationBatch, ) => TrimmedNavigationBatch = ( navigationBatch: TrimmedNavigationBatch, ): TrimmedNavigationBatch => { return { ...navigationBatch, trimmedHttpRequestCount: -1, trimmedHttpResponseCount: -1, trimmedHttpRedirectCount: -1, trimmedJavascriptOperationCount: -1, trimmedCapturedContentCount: -1, trimmedUiInteractionCount: -1, trimmedUiStateCount: -1, }; }; public openWpmPayloadEnvelopeProcessQueue: OpenWpmPayloadEnvelope[] = []; public navigationBatchesByNavigationUuid: TrimmedNavigationBatchesByUuid = {}; async submitOpenWPMPayload(type: OpenWPMType, payload: any) { // console.log({ type, payload }); const openWpmPayloadEnvelope: OpenWpmPayloadEnvelope = { ...openWpmPayloadEnvelopeFromOpenWpmTypeAndPayload(type, payload), }; return this.queueOrIgnore(openWpmPayloadEnvelope); } private async queueOrIgnore(openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) { // Any http or javascript packet with window, tab and frame ids are // sent for batching by corresponding navigation // or dropped (if no corresponding navigation showed up) if (this.shouldBeBatched(openWpmPayloadEnvelope)) { this.queueForProcessing(openWpmPayloadEnvelope); return; } // Ignoring non-batchable payloads currently // return this.foo(openWpmPayloadEnvelope); } public queueForProcessing(openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) { this.openWpmPayloadEnvelopeProcessQueue.push(openWpmPayloadEnvelope); } public shouldBeBatched(openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) { if (openWpmPayloadEnvelope.type === "navigations") { return true; } return ( this.batchableChildOpenWpmType(openWpmPayloadEnvelope.type) && this.childCanBeMatchedToWebNavigationFrame( batchableChildOpenWpmPayloadFromOpenWpmPayloadEnvelope( openWpmPayloadEnvelope, ), ) ); } private batchableChildOpenWpmType(type: OpenWPMType) { return [ "http_requests", "http_responses", "http_redirects", "javascript", "openwpm_captured_content", "ui_interactions", "ui_states", ].includes(type); } private childCanBeMatchedToWebNavigationFrame( payload: BatchableChildOpenWPMPayload, ) { return ( payload.extension_session_uuid && payload.window_id > -1 && payload.tab_id > -1 && payload.frame_id > -1 && payload.event_ordinal && payload.time_stamp ); } private alarmName: string; public async run( onAfterQueueProcessed: ( navigationBatchesByUuid: TrimmedNavigationBatchesByUuid, ) => Promise<void>, ) { this.alarmName = `${browser.runtime.id}:queueProcessorAlarm`; const alarmListener = async _alarm => { if (_alarm.name !== this.alarmName) { return false; } console.info( `Processing ${this.openWpmPayloadEnvelopeProcessQueue.length} study payloads to group by navigation`, ); try { await this.processQueue(); await onAfterQueueProcessed(this.navigationBatchesByNavigationUuid); } catch (error) { captureExceptionWithExtras(error, { msg: "Error encountered during periodic queue processing", }); console.error( "Error encountered during periodic queue processing", error, ); } }; browser.alarms.onAlarm.addListener(alarmListener); browser.alarms.create(this.alarmName, { periodInMinutes: 1, // every minute }); } public async cleanup() { if (this.alarmName) { await browser.alarms.clear(this.alarmName); } this.reset(); } public reset() { this.openWpmPayloadEnvelopeProcessQueue = []; this.navigationBatchesByNavigationUuid = {}; } /** * Removes study payload envelopes from the queue, grouped by their presumed * originating web navigations * @param nowDateTime */ public async processQueue(nowDateTime: Date = new Date()) { // Flush current queue for processing (we will later put back // elements that should be processed in an upcoming iteration) const { openWpmPayloadEnvelopeProcessQueue } = this; this.openWpmPayloadEnvelopeProcessQueue = []; await this.sortEnvelopesIntoBatchesAndPurgeOldEnoughEnvelopes( nowDateTime, openWpmPayloadEnvelopeProcessQueue, ); this.detectAndMoveStrayHttpRequestEnvelopesToTheBatchOfItsResponse( openWpmPayloadEnvelopeProcessQueue, ); await this.dropOldOrphanedEnvelopes( nowDateTime, openWpmPayloadEnvelopeProcessQueue, ); } public async sortEnvelopesIntoBatchesAndPurgeOldEnoughEnvelopes( nowDateTime: Date, openWpmPayloadEnvelopeProcessQueue: OpenWpmPayloadEnvelope[], ) { // Navigations ... const webNavigationOpenWpmPayloadEnvelopes = openWpmPayloadEnvelopeProcessQueue.filter( (openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) => { return openWpmPayloadEnvelope.type === "navigations"; }, ); // ... that are more than navigationAgeThresholdInSeconds seconds old const navigationIsOldEnoughToBePurged = (navigation: Navigation) => { return !isoDateTimeStringsWithinFutureSecondThreshold( navigation.committed_time_stamp, nowDateTime.toISOString(), this.navigationAgeThresholdInSeconds, ); }; const navigationBatchChildEnvelopeIsOldEnoughToBePurged = ( navigationBatchChildPayload: BatchableChildOpenWPMPayload, ) => { return !isoDateTimeStringsWithinFutureSecondThreshold( navigationBatchChildPayload.time_stamp, nowDateTime.toISOString(), this.navigationBatchChildEnvelopeAgeThresholdInSeconds, ); }; const sameFrame = ( subject: BatchableChildOpenWPMPayload | Navigation, navigation: Navigation, ) => { return ( subject.extension_session_uuid === navigation.extension_session_uuid && subject.window_id === navigation.window_id && subject.tab_id === navigation.tab_id && subject.frame_id === navigation.frame_id ); }; const withinNavigationEventOrdinalBounds = ( eventOrdinal: number, fromEventOrdinal: number, toEventOrdinal: number, ) => { return fromEventOrdinal < eventOrdinal && eventOrdinal < toEventOrdinal; }; // console.debug("debug processQueue", "this.openWpmPayloadEnvelopeProcessQueue.length", this.openWpmPayloadEnvelopeProcessQueue.length, "openWpmPayloadEnvelopeProcessQueue.length", openWpmPayloadEnvelopeProcessQueue.length, "webNavigationOpenWpmPayloadEnvelopes.length", webNavigationOpenWpmPayloadEnvelopes.length); // console.debug("JSON.stringify(openWpmPayloadEnvelopeProcessQueue)", JSON.stringify(openWpmPayloadEnvelopeProcessQueue)); // For each navigation... const reprocessingQueue: OpenWpmPayloadEnvelope[] = []; await Promise.all( webNavigationOpenWpmPayloadEnvelopes.map( async (webNavigationOpenWpmPayloadEnvelope: OpenWpmPayloadEnvelope) => { const navigation: Navigation = webNavigationOpenWpmPayloadEnvelope.navigation; const purge = navigationIsOldEnoughToBePurged(navigation); // console.log(`Purge check for navigation with uuid ${navigation.uuid}`, {purge, navigation}); const navigationBatch: NavigationBatch = { navigationEnvelope: webNavigationOpenWpmPayloadEnvelope, childEnvelopes: [], httpRequestCount: 0, httpResponseCount: 0, httpRedirectCount: 0, javascriptOperationCount: 0, capturedContentCount: 0, uiInteractionCount: 0, uiStateCount: 0, }; // Remove navigation envelope from this run's processing queue removeItemFromArray( openWpmPayloadEnvelopeProcessQueue, webNavigationOpenWpmPayloadEnvelope, ); // ... but be sure to re-add it afterwards to ensure that the navigation // stays available for processing of future payloads (until the // navigation is old enough to be purged / ignored) if (!purge) { reprocessingQueue.push(webNavigationOpenWpmPayloadEnvelope); } // Find potential subsequent same-frame navigations const subsequentNavigationsMatchingThisNavigationsFrame = openWpmPayloadEnvelopeProcessQueue.filter( (openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) => { switch (openWpmPayloadEnvelope.type) { case "navigations": return ( sameFrame(openWpmPayloadEnvelope.navigation, navigation) && withinNavigationEventOrdinalBounds( openWpmPayloadEnvelope.navigation .before_navigate_event_ordinal !== undefined ? openWpmPayloadEnvelope.navigation .before_navigate_event_ordinal : openWpmPayloadEnvelope.navigation .committed_event_ordinal, navigation.before_navigate_event_ordinal !== undefined ? navigation.before_navigate_event_ordinal : navigation.committed_event_ordinal, Number.MAX_SAFE_INTEGER, ) ); } return false; }, ); // console.log("subsequentNavigationsMatchingThisNavigationsFrame.length", subsequentNavigationsMatchingThisNavigationsFrame.length,); // Assign matching children to this navigation const fromEventOrdinal = navigation.before_navigate_event_ordinal !== undefined ? navigation.before_navigate_event_ordinal : navigation.committed_event_ordinal; const toEventOrdinal = subsequentNavigationsMatchingThisNavigationsFrame.length === 0 ? Number.MAX_SAFE_INTEGER : subsequentNavigationsMatchingThisNavigationsFrame[0].navigation .before_navigate_event_ordinal !== undefined ? subsequentNavigationsMatchingThisNavigationsFrame[0].navigation .before_navigate_event_ordinal : subsequentNavigationsMatchingThisNavigationsFrame[0].navigation .committed_event_ordinal; // Only non-navigations can be assigned navigation parents const childCandidates = openWpmPayloadEnvelopeProcessQueue.filter( (openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) => { return this.batchableChildOpenWpmType( openWpmPayloadEnvelope.type, ); }, ); // console.log("childCandidates.length", childCandidates.length, {fromEventOrdinal, toEventOrdinal}); // Assign children to this navigation batch if relevant childCandidates.forEach( (openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) => { // Which are found in the same frame and navigation event ordinal bounds const payload: BatchableChildOpenWPMPayload = batchableChildOpenWpmPayloadFromOpenWpmPayloadEnvelope( openWpmPayloadEnvelope, ) as BatchableChildOpenWPMPayload; const isSameFrame = sameFrame(payload, navigation); const isWithinNavigationEventOrdinalBounds = withinNavigationEventOrdinalBounds( payload.event_ordinal, fromEventOrdinal, toEventOrdinal, ); const isWithinNavigationEventAgeThreshold = isoDateTimeStringsWithinFutureSecondThreshold( navigation.before_navigate_time_stamp !== undefined ? navigation.before_navigate_time_stamp : navigation.committed_time_stamp, payload.time_stamp, this.navigationAgeThresholdInSeconds, ); // console.debug({type: openWpmPayloadEnvelope.type, event_ordinal: payload.event_ordinal, isSameFrame, isWithinNavigationEventOrdinalBounds, isWithinNavigationEventAgeThreshold}); if (isSameFrame && isWithinNavigationEventOrdinalBounds) { if (isWithinNavigationEventAgeThreshold) { navigationBatch.childEnvelopes.push(openWpmPayloadEnvelope); setEnvelopeCounts(navigationBatch); } // Remove from queue since it has been adopted by a navigation batch removeItemFromArray( openWpmPayloadEnvelopeProcessQueue, openWpmPayloadEnvelope, ); } }, ); // console.log("navigationBatch.childEnvelopes.length", navigationBatch.childEnvelopes.length); if (purge) { // Remove from navigationBatchesByNavigationUuid // console.log(`Removing expired navigation with uuid ${navigation.uuid}`); delete this.navigationBatchesByNavigationUuid[navigation.uuid]; } else { // Update navigationBatchesByNavigationUuid let updatedNavigationBatch; if (this.navigationBatchesByNavigationUuid[navigation.uuid]) { const existingNavigationBatch = this .navigationBatchesByNavigationUuid[navigation.uuid]; updatedNavigationBatch = { ...existingNavigationBatch, childEnvelopes: existingNavigationBatch.childEnvelopes.concat( navigationBatch.childEnvelopes, ), }; setEnvelopeCounts(updatedNavigationBatch); } else { updatedNavigationBatch = navigationBatch; } // Only include young enough child envelopes updatedNavigationBatch.childEnvelopes = updatedNavigationBatch.childEnvelopes.filter( openWpmPayloadEnvelope => { const payload: BatchableChildOpenWPMPayload = batchableChildOpenWpmPayloadFromOpenWpmPayloadEnvelope( openWpmPayloadEnvelope, ) as BatchableChildOpenWPMPayload; return !navigationBatchChildEnvelopeIsOldEnoughToBePurged( payload, ); }, ); // Run the general callback for trimming navigation batches further updatedNavigationBatch = this.processedNavigationBatchTrimmer( updatedNavigationBatch, ); this.navigationBatchesByNavigationUuid[ navigation.uuid ] = updatedNavigationBatch; } }, ), ); // Restore relevant items to the processing queue reprocessingQueue.reverse().map(openWpmPayloadEnvelope => { this.openWpmPayloadEnvelopeProcessQueue.unshift(openWpmPayloadEnvelope); }); } public detectAndMoveStrayHttpRequestEnvelopesToTheBatchOfItsResponse( openWpmPayloadEnvelopeProcessQueue: OpenWpmPayloadEnvelope[], ) { const navUuids = Object.keys(this.navigationBatchesByNavigationUuid); navUuids.map(navUuid => { const currentNavigationBatch = this.navigationBatchesByNavigationUuid[ navUuid ]; const httpResponseEnvelopes: OpenWpmPayloadEnvelope[] = currentNavigationBatch.childEnvelopes.filter( (openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) => openWpmPayloadEnvelope.type === "http_responses", ); const httpRequestEnvelopes: OpenWpmPayloadEnvelope[] = currentNavigationBatch.childEnvelopes.filter( (openWpmPayloadEnvelope: OpenWpmPayloadEnvelope) => openWpmPayloadEnvelope.type === "http_requests", ); // console.debug({ httpResponseEnvelopes, httpRequestEnvelopes }); // Sometimes http request envelopes were created within the lifespan of a previous webNavigation // thus we need to check for http responses without http request counterparts httpResponseEnvelopes.forEach( (currentHttpResponseEnvelope: OpenWpmPayloadEnvelope) => { const httpRequestEnvelopeMatcher = childEnvelope => childEnvelope.type === "http_requests" && childEnvelope.httpRequest.request_id === currentHttpResponseEnvelope.httpResponse.request_id; const httpRequestEnvelope = httpRequestEnvelopes.find( httpRequestEnvelopeMatcher, ); if (!httpRequestEnvelope) { // console.debug("move the stray http request envelope to the same batch where their response envelope is", {currentHttpResponseEnvelope}); let correspondingHttpRequest; // console.debug("check other navigation batches for the stray envelope"); const navUuidsToCheck = Object.keys( this.navigationBatchesByNavigationUuid, ).filter(navUuidToCheck => navUuidToCheck !== navUuid); navUuidsToCheck.some(navUuidToCheck => { const candidateNavigationBatch = this .navigationBatchesByNavigationUuid[navUuidToCheck]; const matchingHttpRequestEnvelope = candidateNavigationBatch.childEnvelopes .reverse() .find(httpRequestEnvelopeMatcher); if (matchingHttpRequestEnvelope) { correspondingHttpRequest = matchingHttpRequestEnvelope; // remove from candidateNavigationBatch removeItemFromArray( candidateNavigationBatch.childEnvelopes, matchingHttpRequestEnvelope, ); setEnvelopeCounts(candidateNavigationBatch); return true; } return false; }); if (!correspondingHttpRequest) { // console.debug("check the unprocessed queue for the stray envelopes"); const matchingHttpRequestEnvelope = openWpmPayloadEnvelopeProcessQueue .reverse() .find(httpRequestEnvelopeMatcher); if (matchingHttpRequestEnvelope) { correspondingHttpRequest = matchingHttpRequestEnvelope; // remove from the unprocessed queue removeItemFromArray( openWpmPayloadEnvelopeProcessQueue, matchingHttpRequestEnvelope, ); } } if (correspondingHttpRequest) { // console.debug("adding the stray envelope to this navigation batch since it was found"); currentNavigationBatch.childEnvelopes.unshift( correspondingHttpRequest, ); setEnvelopeCounts(currentNavigationBatch); } else { console.error( `The matching httpRequestEnvelope was not found for request id ${currentHttpResponseEnvelope.httpResponse.request_id}`, { currentHttpResponseEnvelope, }, ); captureExceptionWithExtras( new Error( `The matching httpRequestEnvelope was not found for request id ${currentHttpResponseEnvelope.httpResponse.request_id}`, ), { request_id: currentHttpResponseEnvelope.httpResponse.request_id, }, Sentry.Severity.Warning, ); // remove the http response since it will cause issues downstream if it is kept // (developer note: comment out the removal code below to be able to collect // a relevant fixture to debug this issue, which most often occurs in conjunction // with extension reloads, but may possibly occur in other contexts as well. // Note that tests will fail as long as the code below is commented out) removeItemFromArray( currentNavigationBatch.childEnvelopes, currentHttpResponseEnvelope, ); setEnvelopeCounts(currentNavigationBatch); } } }, ); }); } public async dropOldOrphanedEnvelopes( nowDateTime: Date, openWpmPayloadEnvelopeProcessQueue: OpenWpmPayloadEnvelope[], ) { // Drop old orphaned items (assumption: whose navigation batches have already // been purged and thus not sorted into a queued navigation event above) const childIsOldEnoughToBeAnOrphan = ( payload: BatchableChildOpenWPMPayload, ) => { return !isoDateTimeStringsWithinFutureSecondThreshold( payload.time_stamp, nowDateTime.toISOString(), this.orphanAgeThresholdInSeconds, ); }; const openWpmPayloadEnvelopesWithoutMatchingNavigations = openWpmPayloadEnvelopeProcessQueue; const orphanedOpenWpmPayloadEnvelopes = []; openWpmPayloadEnvelopesWithoutMatchingNavigations .reverse() .forEach(openWpmPayloadEnvelope => { const payload: BatchableChildOpenWPMPayload = batchableChildOpenWpmPayloadFromOpenWpmPayloadEnvelope( openWpmPayloadEnvelope, ); if (!childIsOldEnoughToBeAnOrphan(payload)) { this.openWpmPayloadEnvelopeProcessQueue.unshift( openWpmPayloadEnvelope, ); } else { orphanedOpenWpmPayloadEnvelopes.unshift(openWpmPayloadEnvelope); } }); // console.debug("Orphaned items debug", orphanedOpenWpmPayloadEnvelopes); } }
Markdown
UTF-8
4,734
2.6875
3
[ "Apache-2.0" ]
permissive
import {useState} from 'react'; import { Meta, Story, Preview, Props } from '@storybook/addon-docs/blocks'; import AppWrapper from '.'; <Meta title="AppWrapper" parameters={{ info: { disable: true }}} /> # AppWrapper AppWrapper manages the width and containment of your application. ## Contents - [Quick Start](#quick-start) - [Examples](#examples) - [Props](#props) ## Quick Start ```javascript import AppWrapper from "carbon-react/lib/components/app-wrapper"; ``` ## Examples ### Default <Preview> <Story name="default"> <AppWrapper> <div> Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar. The Big Oxmox advised her not to do so, because there were thousands of bad Commas, wild Question Marks and devious Semikoli, but the Little Blind Text didn’t listen. She packed her seven versalia, put her initial into the belt and made herself on the way. When she reached the first hills of the Italic Mountains, she had a last view back on the skyline of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, the Line Lane. </div> </AppWrapper> </Story> </Preview> ### Default without AppWrapper <Preview> <Story name="without AppWrapper"> <div> Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar. The Big Oxmox advised her not to do so, because there were thousands of bad Commas, wild Question Marks and devious Semikoli, but the Little Blind Text didn’t listen. She packed her seven versalia, put her initial into the belt and made herself on the way. When she reached the first hills of the Italic Mountains, she had a last view back on the skyline of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, the Line Lane. </div> </Story> </Preview> ### Default with Background Colour For the purposes of this demonstration, the AppWrapper has been given a colour to stand out so you can clearly see the component. <Preview> <Story name="with Background Colour"> <AppWrapper style={{backgroundColor: 'rgba(0,0,0,0.25)'}}> <div style={{marginBottom: '16px'}}> The Story of Carbon </div> <div> Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar. The Big Oxmox advised her not to do so, because there were thousands of bad Commas, wild Question Marks and devious Semikoli, but the Little Blind Text didn’t listen. She packed her seven versalia, put her initial into the belt and made herself on the way. When she reached the first hills of the Italic Mountains, she had a last view back on the skyline of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, the Line Lane. </div> </AppWrapper> </Story> </Preview> ## Props ### AppWrapper <Props of={AppWrapper} />
Java
UTF-8
2,142
3.734375
4
[]
no_license
package edu.ncsu.csc316.grocerystore2.map; import java.util.Iterator; import edu.ncsu.csc316.grocerystore2.list.LinkedList; import edu.ncsu.csc316.grocerystore2.order.Product; /** * Dictionary to find products * @author Eric Mcallister * */ public class ProductDictionary { /** Array of linked list */ private LinkedList<Product>[] dict; /** The max capacity for the array*/ public final static int CAPACITY = 10000; /** The current amount of items in the array*/ private int size; /** * Constructor for the product dictionary */ @SuppressWarnings("unchecked") public ProductDictionary() { dict = new LinkedList[CAPACITY]; for(int i = 0; i < CAPACITY; i++) { dict[i] = new LinkedList<Product>(); } size = 0; } /** * Adds a product to the dictionary * @param p - the product to add */ public void add(Product p) { if(p.getPosition() > CAPACITY) { throw new IllegalArgumentException(); } if(dict[p.getPosition()].size() == 0) { dict[p.getPosition()].add(p); size = size + 1; } else { LinkedList<Product> list = dict[p.getPosition()]; Iterator<Product> itr = list.iterator(); boolean spotFound = false; while(!spotFound) { Product found = itr.next(); if(p.compareTo(found) == 0) { found.incrementFrequency(); size = size + 1; spotFound = true; } else if(!itr.hasNext()){ dict[p.getPosition()].add(p); spotFound = true; size = size + 1; } } } } /** * Returns a product from the dictionary given it's brand and description * @param brand - the name of the product * @param description - the product's description * @return - the product information */ public Product get(String brand, String description) { Product search = new Product(brand, description); LinkedList<Product> list = dict[search.getPosition()]; Iterator<Product> itr = list.iterator(); while(itr.hasNext()) { Product found = itr.next(); if(found.compareTo(search) == 0) { return found; } } return null; } /** * Returns the size of the dictionary * @return - the size */ public int size() { return size; } }
Go
UTF-8
1,956
3.015625
3
[]
no_license
package controller import ( "errors" "io/ioutil" "net/http" "strings" "testing" meetupmanager "github.com/lucas-dev-it/62252aee-9d11-4149-a0ea-de587cbcd233" "github.com/lucas-dev-it/62252aee-9d11-4149-a0ea-de587cbcd233/business" "github.com/stretchr/testify/assert" ) type uService struct{} func (u *uService) TokenIssue(ti *business.TokenIssue) (*business.AccessToken, error) { if ti.Password == "wronglyTyped" { return nil, errors.New("heads up bro") } if ti.Password == "" && ti.Username == "" { return nil, errors.New("heads up bro") } return &business.AccessToken{ AccessToken: "token", ExpiresAt: 1, }, nil } func Test_userHandler_TokenIssue(t *testing.T) { jn := `{"username":"lucas","password":"pass"}` r := &http.Request{ Body: ioutil.NopCloser(strings.NewReader(jn)), } handler := userHandler{userService: &uService{}} result, err := handler.TokenIssue(nil, r) if err != nil { t.Error("unexpected error") } assert.Equal(t, 200, int(result.status)) token, ok := result.body.(*business.AccessToken) if !ok { t.Error("unexpected error from type conversion") } assert.Equal(t, "token", token.AccessToken, ) assert.Equal(t, 1, int(token.ExpiresAt)) } func Test_userHandler_TokenIssue_WrongPass(t *testing.T) { jn := `{"username":"lucas","password":"wronglyTyped"}` r := &http.Request{ Body: ioutil.NopCloser(strings.NewReader(jn)), } handler := userHandler{userService: &uService{}} result, err := handler.TokenIssue(nil, r) if err == nil && result != nil { t.Error("expected error") } } func Test_userHandler_TokenIssue_EmptyFields(t *testing.T) { jn := `{"username":"","password":""}` r := &http.Request{ Body: ioutil.NopCloser(strings.NewReader(jn)), } handler := userHandler{userService: &uService{}} result, err := handler.TokenIssue(nil, r) if err == nil && result != nil { t.Error("expected error") } assert.IsType(t, meetupmanager.CustomError{}, err) }
Python
UTF-8
5,427
2.625
3
[ "BSD-3-Clause" ]
permissive
''' Populates the SQLite database with a user and a sequence with three components. ''' import json from pyelixys.web.database.model import session from pyelixys.web.database.model import Roles from pyelixys.web.database.model import User from pyelixys.web.database.model import Sequence from pyelixys.web.database.model import Component from pyelixys.web.database.model import Reagents from pyelixys.web.database.model import metadata # Import hashing library for pw hash import hashlib def create_role(): # Create admin role role = Roles('Administrator', 255) session.add(role) session.commit() return role def get_default_user_client_state(): """ Silly work around for current webserver """ #TODO Remove client default state server dependency return ({"sequenceid": 0, "runhistorysort": {"column": "date&time", "type": "sort", "mode": "down"}, "lastselectscreen": "SAVED", "selectsequencesort": {"column": "name", "type": "sort", "mode": "down"}, "prompt": { "show": False, "screen": "", "text2": "", "text1": "", "edit2default": "", "buttons": [], "title": "", "edit1validation": "", "edit1": False, "edit2": False, "edit1default": "", "edit2validation": "", "type": "promptstate"}, "screen": "HOME", "type": "clientstate", "componentid": 0}) def get_default_component_state(cassette, reactor_count): ''' Silly work around for the current webserver ''' #TODO Remove Component state/details dependency # Create a dictionary and append to it the # details needed details_dict = {} details_dict['note'] = cassette.Note details_dict['sequenceid'] = cassette.SequenceID details_dict['reactor'] = reactor_count details_dict['validationerror'] = False details_dict['componenttype'] = cassette.Type details_dict['type'] = 'component' details_dict['id'] = cassette.ComponentID # For all the cassette's reagents, append their ids details_dict['reagent'] = [] for reagent in cassette.reagents: details_dict['reagent'].append(reagent.ReagentID) return details_dict def create_user(role_id): # Let's create a default user # Encrypt the password using md5 and reutrn as hex new_user = User() new_user.Username = 'devel' new_user.Password = hashlib.md5('devel').hexdigest() new_user.FirstName = 'Sofiebio' new_user.LastName = 'Developer' new_user.Email = 'developer@sofiebio.com' new_user.RoleID = role_id new_user.ClientState = json.dumps( get_default_user_client_state()) session.add(new_user) session.commit() return new_user def create_sequence(user_id): # Create a new sequence for the user new_seq = Sequence() new_seq.Name = 'Sequence 1' new_seq.Component = 'Test Sequence' new_seq.Type = 'Saved' new_seq.UserID = user_id session.add(new_seq) session.commit() return new_seq def create_cassette_components(sequence_id): # Create a new set of component cassettes cass_list = [] for cass_count in range(1,4): new_comp = Component() new_comp.SequenceID = sequence_id new_comp.Type = 'CASSETTE' new_comp.Note = '' # Leave details empty, update later new_comp.Details = '' session.add(new_comp) session.commit() cass_list.append(new_comp) return cass_list def create_reagents(sequence_id, cassettes): # Let's create some empty reagents # For each of the 3 cassettes, create # 12 reagents for cassette in cassettes: for reg_count in range(1,13): reagent = Reagents() reagent.SequenceID = sequence_id reagent.Position = reg_count reagent.component = cassette reagent.ComponentID = cassette.ComponentID session.add(reagent) session.commit() def update_sequence_details(sequence): # Update the first component id and # component count of the sequence's fields # Query for the first component matched component_id = session.query(Component).filter_by( SequenceID = sequence.SequenceID).first().ComponentID sequence.FirstComponentID = component_id sequence.ComponentCount = 3 sequence.Valid = 1 session.commit() def update_component_details(cassettes): # Update the details field of each new # cassette component # Keep a reactor count reactor_count = 1 for cassette in cassettes: cassette.Details = json.dumps( get_default_component_state( cassette, reactor_count)) session.commit() reactor_count += 1 if __name__ == '__main__': ''' Running this file as a script shall execute the following which will create a new role and user. The script shall also create a default sequence with three cassettes that contain no reagents. ''' metadata.create_all(checkfirst=True) role = create_role() user = create_user(role.RoleID) sequence = create_sequence(user.UserID) cassettes = create_cassette_components(sequence.SequenceID) create_reagents(sequence.SequenceID, cassettes) update_sequence_details(sequence) update_component_details(cassettes) from IPython import embed embed()
C#
UTF-8
663
2.640625
3
[]
no_license
using UnityEngine; using System.Collections; public static class EventLog{ //Here we simply print to Console public static void Log_Message(string message) { UnityEngine.Debug.Log(message); } public static void Draw_Square(Vector3 botLeft, Vector3 topRight, Color color) { //Bottom Line UnityEngine.Debug.DrawLine(botLeft, new Vector3(topRight.x,0,botLeft.z), color); UnityEngine.Debug.DrawLine(botLeft, new Vector3(botLeft.x,0,topRight.z), color); //Top Line UnityEngine.Debug.DrawLine(topRight, new Vector3(botLeft.x,0,topRight.z), color); UnityEngine.Debug.DrawLine(topRight, new Vector3(topRight.x,0,botLeft.z), color); } }
Java
UTF-8
630
3.46875
3
[]
no_license
package com.riverlcn.proxy; /** * 静态代理的例子. * 代理的目的,在调用具体方法前,可以预处理或者后处理一些信息,对处理方法进行条件过滤等操作. * * @author river */ public class HelloProxy implements HelloInterface { protected HelloInterface hello = new Hello(); @Override public void sayHello() { System.out.println("Before say hello"); hello.sayHello(); System.out.println("After say hello"); } public static void main(String[] args) { HelloProxy helloProxy = new HelloProxy(); helloProxy.sayHello(); } }
Python
UTF-8
3,174
2.953125
3
[]
no_license
import numpy as np class FCMeans(object): def __init__(self, n_clusters=3, n_iter=300, fuzzy_c=2, tolerance=0.001): self.n_clusters = n_clusters self.n_iter = n_iter self.fuzzy_c = fuzzy_c self.tolerance = tolerance self.run = False def fit(self, x): self.run = True self.centroids = {} if len(x.shape) < 1: raise Exception("DataException: Dataset must contain more examples" + "than the required number of clusters!") for k in range(self.n_clusters): self.centroids[k] = np.random.random(x.shape[1]) self.degree_of_membership = np.zeros((x.shape[0], self.n_clusters)) for idx_ in self.centroids: for idx, xi in enumerate(x): updated_degree_of_membership = 0.0 norm = np.linalg.norm(xi - self.centroids[idx_]) all_norms = [norm / np.linalg.norm(xi - self.centroids[c]) for c in self.centroids] all_norms = np.power(all_norms, 2 / (self.fuzzy_c - 1)) updated_degree_of_membership = 1 / sum(all_norms) self.degree_of_membership[idx][idx_] = updated_degree_of_membership for iteration in range(self.n_iter): powers = np.power(self.degree_of_membership, self.fuzzy_c) for idx_ in self.centroids: centroid = [] sum_membeship = 0 for idx, xi in enumerate(x): centroid.append(powers[idx][idx_] * np.array(xi)) sum_membeship += powers[idx][idx_] centroid = np.sum(centroid, axis=0) centroid = centroid / sum_membeship self.centroids[idx_] = centroid max_episilon = 0.0 for idx_ in self.centroids: for idx, xi in enumerate(x): updated_degree_of_membership = 0.0 norm = np.linalg.norm(xi - self.centroids[idx_]) all_norms = [norm / np.linalg.norm(xi - self.centroids[c]) for c in self.centroids] all_norms = np.power(all_norms, 2 / (self.fuzzy_c - 1)) updated_degree_of_membership = 1 / sum(all_norms) diff = updated_degree_of_membership - self.degree_of_membership[idx][idx_] self.degree_of_membership[idx][idx_] = updated_degree_of_membership if diff > max_episilon: max_episilon = diff if max_episilon <= self.tolerance: break def predict(self, x): if self.run: if len(x.shape) > 1: class_ = [] for c in self.centroids: class_.append(np.sum((x - self.centroids[c]) ** 2, axis=1)) return np.argmin(np.array(class_).T, axis=1) else: dist = [np.linalg.norm(x - self.centroids[c]) for c in self.centroids] class_ = dist.index(min(dist)) return class_ else: raise Exception("NonTrainedModelException: You must fit data first!")
Java
UTF-8
2,129
2.015625
2
[]
no_license
package br.com.unip.stan.resourceserver.adapter.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.unip.stan.resourceserver.adapter.persistence.jpa.entity.veiculo.Abastecimento; import br.com.unip.stan.resourceserver.port.in.veiculo.CriarAbastecimentoService; import br.com.unip.stan.resourceserver.port.in.veiculo.ObterDetalheAbastecimentoService; @CrossOrigin() @RestController @RequestMapping({ "/api/abastecimentos" }) public class AbastecimentoController { @Autowired private ObterDetalheAbastecimentoService obterDetalheAbastecimentoService; @Autowired private CriarAbastecimentoService criarAbastecimentoService; @GetMapping(path = "/{cnpj-empresa}") @Secured({"ROLE_USER", "ROLE_ADMIN"}) public List<Abastecimento> obterAbastecimentos(@PathVariable("cnpj-empresa") String cnpj) { return obterDetalheAbastecimentoService.obterTodos(cnpj); } @GetMapping(path = "/{cnpj-empresa}/{id}") @Secured({"ROLE_USER", "ROLE_ADMIN"}) public Abastecimento obterAbastecimentos(@PathVariable("cnpj-empresa") String cnpj, @PathVariable("id") Long id) { return obterDetalheAbastecimentoService.obter(cnpj, id); } @PostMapping() @Secured({"ROLE_USER", "ROLE_ADMIN"}) public Abastecimento criarAbastecimento(@RequestBody Abastecimento abastecimento) { return criarAbastecimentoService.criar(abastecimento); } @PostMapping("/{id}") @Secured({"ROLE_USER", "ROLE_ADMIN"}) public Abastecimento atualizarAbastecimento(@PathVariable("id") Long id, @RequestBody Abastecimento abastecimento) { return criarAbastecimentoService.criar(abastecimento); } }
C#
UTF-8
1,369
3.046875
3
[]
no_license
/*######################################################## *# InternalLib.dll # *# Copyright 2018 by WesTex Enterprises # *########################################################*/ using System; using System.Text.RegularExpressions; //3rd party using NLog; namespace InternalLib { public static class PhoneNumberHelper { private readonly static Logger logger = LogManager.GetCurrentClassLogger(); /// <summary> /// Clean phone number /// </summary> /// <param name="phoneNumber">Number to clean</param> public static string CleanPhoneNumber(string phoneNumber) { string result = ""; try { //Create string pattern string pattern = @"[\!\@\#\$\%\\^\&\*()\-\\_\+\=//\\\[\]\.\,\:\;//""\'\?\<\>\|\`\~]"; //Create RegEx object Regex regex = new Regex(pattern); //Clean string result = regex.Replace(phoneNumber, ""); result = result.Replace(" ", ""); } catch (Exception ex) { logger.Error("Error processing cleaning a phone number : " + ex); } return result; } } }
Java
UTF-8
599
1.890625
2
[ "Apache-2.0" ]
permissive
package com.city.phonemall.ware.feign; import com.city.common.utils.R; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; /** * @author liuZhongKun * @email 1071607950@qq.com * @date 2021-05-05 10:46:28 **/ @FeignClient("phonemall-member") public interface MemberFeignService { /** * 根据id获取用户地址信息 * @param id * @return */ @RequestMapping("/member/memberreceiveaddress/info/{id}") R info(@PathVariable("id") Long id); }
Python
UTF-8
837
3.828125
4
[]
no_license
class User: def __init__(self, name): self.name = name self.account_balance = 0 def make_deposit(self, amount): self.account_balance += amount def make_withdrawal(self, amount): self.account_balance -= amount def display_user_balance(self): print(f"User: {self.name}, Balance: {self.account_balance}") def transfer_money(self, other_user, amount): self.account_balance -= amount other_user.account_balance += amount lana = User("Lana") lana.make_deposit(1000) lana.make_deposit(9720) lana.make_withdrawal(50) lana.display_user_balance() nizam = User("nizam") nizam.make_deposit(1720) nizam.make_deposit(2050) nizam.make_withdrawal(720) nizam.display_user_balance() nizam.transfer_money(lana, 1200) lana.display_user_balance() nizam.display_user_balance()
Go
UTF-8
1,464
2.890625
3
[ "MIT" ]
permissive
package filters import ( "math" "github.com/bspaans/bleep/audio" ) type FlangerFilter struct { Time float64 Factor float64 LFORate float64 LeftDelayed []float64 RightDelayed []float64 Phase int } func NewFlangerFilter(time, factor, rate float64) *FlangerFilter { return &FlangerFilter{ Time: time, Factor: factor, LFORate: rate, LeftDelayed: nil, RightDelayed: nil, } } func (f *FlangerFilter) Filter(cfg *audio.AudioConfig, samples []float64) []float64 { time := int(float64(cfg.SampleRate) * f.Time) if f.LeftDelayed == nil { f.LeftDelayed = make([]float64, time) f.RightDelayed = make([]float64, time) } n := len(samples) if cfg.Stereo { n = n / 2 } stepSize := (f.LFORate * math.Pi) / float64(cfg.SampleRate) result := make([]float64, len(samples)) for i := 0; i < n; i++ { ix := i if cfg.Stereo { ix *= 2 } currentDelay := time - int(math.Ceil(float64(time)*math.Abs(math.Sin(float64(f.Phase)*stepSize)))) delayedIx := f.Phase - currentDelay if delayedIx < 0 { delayedIx += time } f.LeftDelayed[f.Phase] = samples[ix] if cfg.Stereo { f.RightDelayed[f.Phase] = samples[ix+1] } result[ix] = (1.0-f.Factor)*samples[ix] + f.Factor*f.LeftDelayed[delayedIx] if cfg.Stereo { result[ix+1] = (1.0-f.Factor)*samples[ix+1] + f.Factor*f.RightDelayed[delayedIx] } f.Phase += 1 if f.Phase >= len(f.LeftDelayed) { f.Phase = 0 } } return result }
C#
UTF-8
3,888
3.578125
4
[]
no_license
using System; using System.Linq; using System.Text.RegularExpressions; using Utils.Encryption; namespace Utils { public enum EncryptionMode { SHA_256, SHA_512 } public static class StringExtensions { /// <summary> /// check if string is number /// </summary> /// <returns></returns> public static bool IsNumber(this string inputString) { int result; return int.TryParse(inputString, out result); } /// <summary> /// convert string to number /// </summary> /// <returns></returns> public static int ToNumber(this string inputString) { int result; if (!int.TryParse(inputString, out result)) { throw new InvalidOperationException("string is not a number"); } return result; } /// <summary> /// allows to check if string is a valid email /// </summary> /// <param name="inputString"></param> /// <returns></returns> public static bool IsEmail(this string inputString) { try { var addr = new System.Net.Mail.MailAddress(inputString); return addr.Address == inputString; } catch { return false; } } /// <summary> /// transform string to hashed string whith sha 256 /// </summary> /// <param name="inputString"></param> /// <returns></returns> public static string Encrypt(this string inputString, EncryptionMode mode = EncryptionMode.SHA_256) { string encrypt = string.Empty; if (mode == EncryptionMode.SHA_256) { encrypt = Sha.GenerateSHA256String(inputString); } if (mode == EncryptionMode.SHA_512) { encrypt = Sha.GenerateSHA512String(inputString); } return encrypt; } private static Random random = new Random(); public static string Random(this string inputString,int length, string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") { return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } /// <summary> /// allows to check if string contains pattern string /// </summary> /// <param name="inputString"></param> /// <returns></returns> public static bool IsMatch(this string inputString, string pattern) { return inputString.Contains(pattern); } /// <summary> /// allows to check if string contains regex /// </summary> /// <param name="inputString"></param> /// <returns></returns> public static bool IsMatchRegex(this string inputString, Regex reg) { return reg.IsMatch(inputString); } /// <summary> /// allows to check if string contains regex string /// </summary> /// <param name="inputString"></param> /// <returns></returns> public static bool IsMatchRegexString(this string inputString, string regexString) { return new Regex(regexString).IsMatch(inputString); } /// <summary> /// allows to split with string /// </summary> /// <param name="inputString"></param> /// <param name="regexString"></param> /// <returns></returns> public static string [] Split(this string inputString, string regexString) { return inputString.Split(new[] { regexString }, StringSplitOptions.None); } } }
Java
WINDOWS-1250
3,298
4.8125
5
[]
no_license
package algorithm.number; /* * Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation. */ public class NextSmallestAndLargest { /* * The Brute Force Approach: An easy approach is simply brute force: count * the number of 1s in n, and then increment (or decrement) until you !nd a * number with the same number of 1s. Easy - but not terribly interesting. * Can we do something a bit more optimal? Yes! Number Properties Approach * for Next Number Observations: If we turn on a 0, we need to turn o# * a 1 If we turn on a 0 at bit i and turn o# a 1 at bit j, the number * changes by 2^i - 2^j. If we want to get a bigger number with the same * number of 1s and 0s, i must be bigger than j. Solution: * * 1. Traverse from right to left. Once weve passed a 1, turn on the next * 0. Weve now increased the number by 2^i. Yikes! Example: xxxxx011100 * becomes xxxxx111100 * * 2. Turn o# the one thats just to the right side of that. Were now * bigger by 2^i - 2^(i-1) Example: xxxxx111100 becomes xxxxx101100 * * 3. Make the number as small as possible by rearranging all the 1s to be * as far right as possible: Example: xxxxx101100 becomes xxxxx100011 * * To get the previous number, we do the reverse. * * 1. Traverse from right to left. Once weve passed a zero, turn o# the * next 1. Example: xxxxx100011 becomes xxxxx000011. * * 2. Turn on the 0 that is directly to the right. Example: xxxxx000011 * becomes xxxxx010011. * * 3. Make the number as big as possible by shifting all the ones as far to * the left as possible. Example: xxxxx010011 becomes xxxxx011100 . And now, * for the code. Note the emphasis on pulling common code out into a * reusable function. Your interviewer will look for clean code like this. */ public static boolean GetBit(int n, int index) { return ((n & (1 << index)) > 0); } public static int SetBit(int n, int index, boolean b) { if (b) { return n | (1 << index); } else { int mask = ~(1 << index); return n & mask; } } public static int GetNext_NP(int n) { if (n <= 0) return -1; int index = 0; int countOnes = 0; while (!GetBit(n, index)) index++; // Turn on next zero. while (GetBit(n, index)) { index++; countOnes++; } n = SetBit(n, index, true); // Turn off previous one index--; n = SetBit(n, index, false); countOnes--; // Set zeros for (int i = index - 1; i >= countOnes; i--) { n = SetBit(n, i, false); } // Set ones for (int i = countOnes - 1; i >= 0; i--) { n = SetBit(n, i, true); } return n; } public static int GetPrevious_NP(int n) { if (n <= 0) return -1; // Error int index = 0; int countZeros = 0; while (GetBit(n, index)) index++; // Turn off next 1. while (!GetBit(n, index)) { index++; countZeros++; } n = SetBit(n, index, false); // Turn on previous zero index--; n = SetBit(n, index, true); countZeros--; // Set ones for (int i = index - 1; i >= countZeros; i--) { n = SetBit(n, i, true); } // Set zeros for (int i = countZeros - 1; i >= 0; i--) { n = SetBit(n, i, false); } return n; } }
Java
UTF-8
2,572
4.03125
4
[]
no_license
package com.lec.java.for01; /* * ■ 순환문(loop) * - for * - while * - do ~ while * * ■ for 순환문 구문 * * for(①초기식; ②조건식; ④증감식){ * ③수행문; * .. * } * ①초기식 : 최초에 단한번 수행 * ②조건식 : true / false 결과값 * 위 조건식의 결과가 false 이면 for문 종료 * ③수행문 : 위 조건식이 true 이면 수행 * ④증감식 : 수행문이 끝나면 증감식 수행 * 증감식이 끝나면 다시 ②조건식 으로.. * * 순환문을 작성시 내가 만드는 순환문에 대해 다음을 확실하게 인지하고 작성해야 한다 * 1. 몇번 순환하는 가? * 2. 순환중에 사용된 인덱스값의 시작값과 끝값은? * 3. 순환문이 끝난뒤 인덱스값은? * * for문 작성시 TIP 1) n번 순환 하는 경우 (즉 횟수가 촛점인 경우) for(int i = 0; i < n; i++){ .. } 2) a ~ b 까지 순환하는 경우 (즉 시작값과 끝값이 중요한 경우) for(int i = a; i <= b; i++){ .. } */ public class For01Main { public static void main(String[] args) { System.out.println("for 반복문"); System.out.println("Hello Java 1"); System.out.println("Hello Java 2"); System.out.println("Hello Java 3"); System.out.println(); for(int count = 1; count <= 3; count++) { System.out.println("Hello Java " + count); } // end for // 1 ~ 10 까지 for 사용하여 출력 for(int count = 1; count <= 10; count++) { System.out.print(count + " "); } System.out.println(); // 10 ~ 1 까지 출력 for (int count = 10; count >= 1; count--) { System.out.println(count + " "); } // local variable : 블럭 { } 안에서 선언되는 변수 // 블럭 안에서만 유효하고, 블럭 종료하면 소멸된다 int x = 200; { int aaa = 100; // 블럭 안에서 선언된 지역변수 aaa System.out.println("블럭안 : x = " + x + "aaa = " + aaa); } // 블럭이 끝나면 aaa는 소멸된다. System.out.println("블럭밖 : x = " + x); // 변수(이름)가 유효한 범위 ==> scope // 초기식과 증감식에 식을 여러개 사용 가능! System.out.println(); int i, j; for(i = 0, j = 10; i < j; i++, j -= 2) { System.out.println("i:" + i + " j:"); } System.out.println("for 종료 후 i : " + i + "j : " + j); } // end main() } // end class For01Main
TypeScript
UTF-8
1,524
2.796875
3
[]
no_license
import { ofType } from 'redux-observable'; import { switchMap, map, tap } from 'rxjs/operators'; import { BehaviorSubject } from 'rxjs'; import { wait } from './wait'; export class IteratorBehaviorSubject<T> extends BehaviorSubject<T | undefined> { constructor(private iterator: any) { super(undefined); this.iterator = iterator; this.push(undefined); } public push = async (pushValue: T | undefined): Promise<void> => { const { done, value } = await this.iterator.next(pushValue); if (done && value === undefined) { this.complete(); } else { await this.next(value); } }; } async function* asyncGenerator() { for (let i = 0; i <= 10; i++) { yield new Promise((resolve) => { setTimeout(() => { console.log(`asyncGenerator promise ${i} resolved`); resolve(i); }, 1000); }); } } const iterator$ = new IteratorBehaviorSubject(asyncGenerator()); export function epic(action$: any): any { return action$.pipe( ofType('TAKE_EPIC'), switchMap(() => { return iterator$.pipe( tap((value) => console.log('EPIC: INCOMING VALUE', value)), tap(() => wait(1000)), // Some hard calculations here tap((value) => console.log('EPIC: DONE PROCESSING VALUE', value)), tap({ next: iterator$.push, complete: () => { console.log('EPIC: DONE PROCESSING ALL VALUES'); }, }) ); }), map((value) => ({ type: 'PUT_EPIC', payload: value })) ); }
Swift
UTF-8
438
3.046875
3
[]
no_license
// // Question.swift // DbzTrivia // // Created by Anthony Torres on 5/18/19. // Copyright © 2019 Anthony Torres. All rights reserved. // import Foundation class Question { var question: String var player1: Character var player2: Character var answer: Bool init(q:String,p1:Character,p2:Character,a:Bool) { self.question = q self.player1 = p1 self.player2 = p2 self.answer = a } }
C#
UTF-8
9,487
3.15625
3
[]
no_license
using System; using System.Threading; //* Implement the "Falling Rocks" game in the text console. //A small dwarf stays at the bottom of the screen and can move //left and right (by the arrows keys). //A number of rocks of different sizes and forms constantly fall //down and you need to avoid a crash. //Rocks are the symbols ^, @, *, &, +, %, $, #, !, ., ;, //distributed with appropriate density. The dwarf is (O). //Ensure a constant game speed by Thread.Sleep(150). //Implement collision detection and scoring system. public struct Stone { public char stoneType; public ConsoleColor color; } class FallingRocks { const string dwarf = "(0)"; static int consoleHeight = Console.WindowHeight; static int consoleWidth = Console.WindowWidth; static int dwarfPositionX = (consoleWidth/2 - 1); static ConsoleKeyInfo KeyPressed; static Random stoneGenerator = new Random(); static Stone[,] stonesOnScreen = new Stone[1,1] ; static bool exitFlag = true; static float levelTimeout = 150f; static ulong scores = 0L; static int lives = 3; static string stoneSymbols = "^@*&+-%$#!.;,"; static int gameLevel = 1; static string[] colorNames = ConsoleColor.GetNames(typeof(ConsoleColor)); static int numColors = colorNames.Length; static void Main() { FixConsoleScreen(); InicializeScreen(); while (exitFlag) { if (Console.KeyAvailable) { KeyPressed = Console.ReadKey(); if (KeyPressed.Key == ConsoleKey.Escape) { exitFlag = false; DrawGoodbuyScreen(); break; } else if (KeyPressed.Key == ConsoleKey.LeftArrow) { MoveDwardLeft(); } else if (KeyPressed.Key == ConsoleKey.RightArrow) { MoveDwarRight(); } } PopulateFirstLine(); CalculateScore(); RedrawScreen(); ClearKeyBuffer(); Thread.Sleep((int)levelTimeout); } } private static void CalculateScore() { // TODO: Game score calculation if ((stonesOnScreen[consoleHeight - 5, dwarfPositionX].stoneType == ' ')&& (stonesOnScreen[consoleHeight - 5, dwarfPositionX + 1].stoneType == ' ')&& ((stonesOnScreen[consoleHeight - 5, dwarfPositionX + 2].stoneType == ' ')|| (stonesOnScreen[consoleHeight - 5, dwarfPositionX + 2].stoneType == '\0'))) { scores ++; if (scores > (ulong)gameLevel*1000) { gameLevel++; levelTimeout -= gameLevel * 0.5f; } } else { lives--; if (lives > 0) { DrawLooseLive(); } else { DrawGoodbuyScreen(); exitFlag = false; } } } private static void DrawLooseLive() { string message = "You Loose a Live!!!"; Console.SetCursorPosition(((consoleWidth - message.Length) / 2), ((consoleHeight / 2) + 2)); Console.Write("************************"); Console.SetCursorPosition(((consoleWidth - message.Length) / 2), ((consoleHeight / 2) + 3)); Console.Write("*{0,21} *", message); Console.SetCursorPosition(((consoleWidth - message.Length) / 2), ((consoleHeight / 2) + 4)); Console.Write("************************"); Thread.Sleep(3000); } private static void PopulateFirstLine() { // TODO: Populating First line with random symbols int count = 0; if (gameLevel > 10) { count = 6; } else { count = (gameLevel / 3) + 2; } int StonesCount = stoneGenerator.Next(count); ShiftRowsDown(); for (int i = 0; i < stonesOnScreen.GetLength(1) - 1; i++) { stonesOnScreen[0, i].stoneType = ' '; } for (int i = 0; i < StonesCount ; i++) { int stoneSyze = stoneGenerator.Next(gameLevel+1); int stonePosition = stoneGenerator.Next((stonesOnScreen.GetLength(1) - 1) - stoneSyze); int stoneType = stoneGenerator.Next(stoneSymbols.Length-1); for (int j = 0; j < stoneSyze; j++) { stonesOnScreen [0,stonePosition+j].stoneType = Convert.ToChar(stoneSymbols.Substring(stoneType,1)) ; // Get random ConsoleColor string string colorName = colorNames[stoneGenerator.Next(1,numColors)]; // Get ConsoleColor from string name stonesOnScreen[0, stonePosition + j].color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorName); } } } private static void ShiftRowsDown() { for (int i = stonesOnScreen.GetLength(0)-1 ; i > 0; i--) { for (int j = 0; j < stonesOnScreen.GetLength(1)-1 ; j++) { stonesOnScreen[i, j] = stonesOnScreen[i - 1, j]; } } } private static void ClearKeyBuffer() { // Clearing Console Input buffer while (Console.KeyAvailable) { Console.ReadKey(false); } } private static void MoveDwarRight() { // Moving dward to the Right if (dwarfPositionX < consoleWidth-4) { dwarfPositionX = dwarfPositionX + 1; } } private static void MoveDwardLeft() { // Moving dward to the Left if (dwarfPositionX > 0) { dwarfPositionX = dwarfPositionX - 1; } } private static void DrawGoodbuyScreen() { // Goodbuy Screen string message = " GAME OVER!!! "; Console.SetCursorPosition(((consoleWidth - message.Length) / 2), ((consoleHeight / 2) + 2)); Console.Write("************************"); Console.SetCursorPosition(((consoleWidth - message.Length) / 2), ((consoleHeight / 2) + 3)); Console.Write("*{0,21} *", message); Console.SetCursorPosition(((consoleWidth - message.Length) / 2), ((consoleHeight / 2) + 4)); Console.Write("************************"); Thread.Sleep(3000); } private static void RedrawScreen() { // Redraw screen on every loop RedrawStones(); RedrawDwarf(); RedrawScore(); } private static void RedrawDwarf() { // Clearing old dwarf Console.SetCursorPosition(0, consoleHeight - 1); Console.Write("".PadLeft((stonesOnScreen.GetLength(1)), ' ')); // clear dwarf // Redrawing dward Console.ForegroundColor = ConsoleColor.White; Console.SetCursorPosition(dwarfPositionX, consoleHeight - 1); Console.Write(dwarf); } private static void RedrawScore() { // Redraw score board Console.ForegroundColor = ConsoleColor.White; Console.SetCursorPosition(0, 0); Console.Write(" SCORE:"); Console.SetCursorPosition(0, 1); Console.Write("============"); Console.SetCursorPosition(0, 2); Console.Write("|{0,10}|", scores); Console.SetCursorPosition(0, 3); Console.Write("============"); Console.SetCursorPosition(consoleWidth - 13, 0); Console.Write(" LEVEL:"); Console.SetCursorPosition(consoleWidth - 13, 1); Console.Write("============"); Console.SetCursorPosition(consoleWidth - 13, 2); Console.Write("|{0,10}|", gameLevel); Console.SetCursorPosition(consoleWidth - 13, 3); Console.Write("============"); } private static void RedrawStones() { //Redrawing Stones for background ClearStones(); for (int i = 0; i < stonesOnScreen.GetLength(0) - 1; i++) { for (int j = 0; j < stonesOnScreen.GetLength(1) - 1; j++) { if (stonesOnScreen[i, j].stoneType != ' ') { Console.ForegroundColor = stonesOnScreen[i, j].color; Console.SetCursorPosition(j, i + 4); Console.Write(stonesOnScreen[i, j].stoneType); } } } } private static void ClearStones() { Console.SetCursorPosition(0, 4); for (int i = 0; i < stonesOnScreen.GetLength(0) - 1; i++) { Console.WriteLine("".PadLeft((stonesOnScreen.GetLength(1) - 1),' ')); } } private static void InicializeScreen() { for (int i = 0; i < stonesOnScreen.GetLength(0) - 1; i++) { for (int j = 0; j < stonesOnScreen.GetLength(1) - 1; j++) { stonesOnScreen[i, j].stoneType = ' '; } } } private static void FixConsoleScreen() { Console.WindowHeight = 40; consoleHeight = Console.WindowHeight; stonesOnScreen = new Stone[consoleHeight - 4, consoleWidth - 1]; Console.BufferHeight = Console.WindowHeight; Console.BufferWidth = Console.WindowWidth; } }
Java
UTF-8
1,105
3.484375
3
[ "MIT" ]
permissive
package Utils; import Model.Chromosome; public class MergeSort { public static void sort(Chromosome[] a, int n) { if (n < 2) { return; } int mid = n / 2; Chromosome[] l = new Chromosome[mid]; Chromosome[] r = new Chromosome[n - mid]; for (int i = 0; i < mid; i++) { l[i] = a[i]; } for (int i = mid; i < n; i++) { r[i - mid] = a[i]; } sort(l, mid); sort(r, n - mid); merge(a, l, r, mid, n - mid); } public static void merge( Chromosome[] a, Chromosome[] l, Chromosome[] r, int left, int right ) { int i = 0, j = 0, k = 0; while (i < left && j < right) { if (l[i].getFitness() > r[j].getFitness()) { a[k++] = l[i++]; } else { a[k++] = r[j++]; } } while (i < left) { a[k++] = l[i++]; } while (j < right) { a[k++] = r[j++]; } } }