text
stringlengths
1
1.04M
language
stringclasses
25 values
<filename>app/data/seed/users/5b01683c-1408-464b-8a40-63acb0d72deb.json {"id":"5b01683c-1408-464b-8a40-63acb0<PASSWORD>deb","firstName":"Fermin","lastName":"Mohr","email":"<EMAIL>","username":"<EMAIL>","password":"<PASSWORD>","organisations":[{"id":"<PASSWORD>","code":"13J","name":"Yorkshire Anglican Learning and Education Partnership","permissions":[],"notifications":["course_published","course_changed","course_withdrawn","course_vacancies_changed"]}],"createdAt":"2022-03-07T12:35:12.756Z","updatedAt":"2022-03-08T20:09:44.661Z","active":true}
json
<gh_stars>10-100 // Copyright (c) 2016 <NAME>, Inc. // Use of this source code is governed by the Apache License 2.0 // that can be found in the COPYING file. // +build !linux package netns // stub: close closes the file descriptor mapped to a network namespace func (h nsHandle) close() error { return nil } // stub: fd returns the handle as a uintptr func (h nsHandle) fd() int { return 0 } // stub: getNs returns a file descriptor mapping to the given network namespace var getNs = func(nsName string) (handle, error) { return nsHandle(1), nil } // stub: setNs sets the process's network namespace var setNs = func(fd handle) error { return nil }
go
from abc import ABC, abstractmethod import numpy as np class Regularizer(ABC): @abstractmethod def regularize(self, weights: np.ndarray) -> None: pass
python
package ch.hslu.sw07.join; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class JoinAndSleep implements Runnable { private static final Logger LOG = LogManager.getLogger(JoinAndSleep.class); private int sleepTime; private Thread thread; private Thread prev; @Override public void run() { this.thread = Thread.currentThread(); try { if (this.prev != null) { LOG.info(this.thread.getName() + " wartet auf " + this.prev.getName()); this.prev.join(); LOG.info(this.thread.getName() + " schläft für " + this.sleepTime + "ms"); Thread.sleep(this.sleepTime); } else { LOG.info(this.thread.getName() + " schläft für " + this.sleepTime + "ms"); Thread.sleep(this.sleepTime); } } catch (InterruptedException e) { e.printStackTrace(); } finally { if (this.thread != null) { LOG.info(this.thread.getName() + " beendet."); this.thread.interrupt(); } } } public static void main(String[] args) { JoinAndSleep join3 = new JoinAndSleep(4000, null); Thread t3 = new Thread(join3, "Thread 3"); JoinAndSleep join2 = new JoinAndSleep(3000, t3); Thread t2 = new Thread(join2, "Thread 2"); JoinAndSleep join1 = new JoinAndSleep(2000, t2); Thread t1 = new Thread(join1, "Thread 1"); t1.start(); t2.start(); t3.start(); } public JoinAndSleep(final int sleepTime, final Thread prev) { this.sleepTime = sleepTime; this.prev = prev; } }
java
<filename>examples/reason-react-app/package.json { "private": true, "name": "@phenomic/example-reason-react-app", "devDependencies": { "@moox/bs-react-helmet": "^1.0.0", "@phenomic/cli": "^1.0.0-beta.9", "@phenomic/core": "^1.0.0-beta.9", "@phenomic/preset-react-app": "^1.0.0-beta.9", "bs-platform": "^4.0.8", "npm-run-all": "^4.0.2", "react": "^16.3.0", "react-dom": "^16.3.0", "react-helmet": "^5.2.0", "react-router": "^3.2.0", "reason-react": "^0.5.3" }, "scripts": { "reason:cleanup": "bsb -clean-world", "reason:compile": "bsb -make-world", "prepare": "yarn reason:cleanup && yarn reason:compile", "start": "yarn reason:cleanup && npm-run-all --parallel start:*", "start:js": "phenomic start", "start:reason": "yarn reason:compile -w", "build": "yarn reason:compile && phenomic build" }, "phenomic": { "presets": [ "@phenomic/preset-react-app" ] }, "version": "1.0.0-beta.9" }
json
<filename>react_frontend/node_modules/.cache/babel-loader/49d824d5dd7df01f3e552505a36d0117.json {"ast":null,"code":"import _classCallCheck from \"C:\\\\Users\\\\Vivi-ROG1070\\\\Desktop\\\\themeforest-ttyOtuIW-easypro-developer-friendly-react-bootstrap-4-admin-template\\\\themeforest\\\\new-seed\\\\node_modules\\\\babel-preset-react-app\\\\node_modules\\\\@babel\\\\runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"C:\\\\Users\\\\Vivi-ROG1070\\\\Desktop\\\\themeforest-ttyOtuIW-easypro-developer-friendly-react-bootstrap-4-admin-template\\\\themeforest\\\\new-seed\\\\node_modules\\\\babel-preset-react-app\\\\node_modules\\\\@babel\\\\runtime/helpers/esm/createClass\";\nimport _possibleConstructorReturn from \"C:\\\\Users\\\\Vivi-ROG1070\\\\Desktop\\\\themeforest-ttyOtuIW-easypro-developer-friendly-react-bootstrap-4-admin-template\\\\themeforest\\\\new-seed\\\\node_modules\\\\babel-preset-react-app\\\\node_modules\\\\@babel\\\\runtime/helpers/esm/possibleConstructorReturn\";\nimport _getPrototypeOf from \"C:\\\\Users\\\\Vivi-ROG1070\\\\Desktop\\\\themeforest-ttyOtuIW-easypro-developer-friendly-react-bootstrap-4-admin-template\\\\themeforest\\\\new-seed\\\\node_modules\\\\babel-preset-react-app\\\\node_modules\\\\@babel\\\\runtime/helpers/esm/getPrototypeOf\";\nimport _inherits from \"C:\\\\Users\\\\Vivi-ROG1070\\\\Desktop\\\\themeforest-ttyOtuIW-easypro-developer-friendly-react-bootstrap-4-admin-template\\\\themeforest\\\\new-seed\\\\node_modules\\\\babel-preset-react-app\\\\node_modules\\\\@babel\\\\runtime/helpers/esm/inherits\";\nimport { PureComponent } from 'react';\nimport { withRouter } from 'react-router-dom';\nimport PropTypes from 'prop-types';\n\nvar ScrollToTop =\n/*#__PURE__*/\nfunction (_PureComponent) {\n _inherits(ScrollToTop, _PureComponent);\n\n function ScrollToTop() {\n _classCallCheck(this, ScrollToTop);\n\n return _possibleConstructorReturn(this, _getPrototypeOf(ScrollToTop).apply(this, arguments));\n }\n\n _createClass(ScrollToTop, [{\n key: \"componentDidUpdate\",\n value: function componentDidUpdate(prevProps) {\n var location = this.props.location;\n\n if (location.pathname !== prevProps.location.pathname) {\n window.scrollTo(0, 0);\n }\n }\n }, {\n key: \"render\",\n value: function render() {\n var children = this.props.children;\n return children;\n }\n }]);\n\n return ScrollToTop;\n}(PureComponent);\n\nScrollToTop.propTypes = {\n location: PropTypes.shape({\n pathname: PropTypes.string\n }).isRequired,\n children: PropTypes.element.isRequired\n};\nexport default withRouter(ScrollToTop);","map":{"version":3,"sources":["C:/Users/Vivi-ROG1070/Desktop/themeforest-ttyOtuIW-easypro-developer-friendly-react-bootstrap-4-admin-template/themeforest/new-seed/src/containers/App/ScrollToTop.jsx"],"names":["PureComponent","withRouter","PropTypes","ScrollToTop","prevProps","location","props","pathname","window","scrollTo","children","propTypes","shape","string","isRequired","element"],"mappings":";;;;;AAAA,SAASA,aAAT,QAA8B,OAA9B;AACA,SAASC,UAAT,QAA2B,kBAA3B;AACA,OAAOC,SAAP,MAAsB,YAAtB;;IAEMC,W;;;;;;;;;;;;;uCAQeC,S,EAAW;AAAA,UACpBC,QADoB,GACP,KAAKC,KADE,CACpBD,QADoB;;AAE5B,UAAIA,QAAQ,CAACE,QAAT,KAAsBH,SAAS,CAACC,QAAV,CAAmBE,QAA7C,EAAuD;AACrDC,QAAAA,MAAM,CAACC,QAAP,CAAgB,CAAhB,EAAmB,CAAnB;AACD;AACF;;;6BAEQ;AAAA,UACCC,QADD,GACc,KAAKJ,KADnB,CACCI,QADD;AAEP,aAAOA,QAAP;AACD;;;;EAlBuBV,a;;AAApBG,W,CACGQ,S,GAAY;AACjBN,EAAAA,QAAQ,EAAEH,SAAS,CAACU,KAAV,CAAgB;AACxBL,IAAAA,QAAQ,EAAEL,SAAS,CAACW;AADI,GAAhB,EAEPC,UAHc;AAIjBJ,EAAAA,QAAQ,EAAER,SAAS,CAACa,OAAV,CAAkBD;AAJX,C;AAoBrB,eAAeb,UAAU,CAACE,WAAD,CAAzB","sourcesContent":["import { PureComponent } from 'react';\nimport { withRouter } from 'react-router-dom';\nimport PropTypes from 'prop-types';\n\nclass ScrollToTop extends PureComponent {\n static propTypes = {\n location: PropTypes.shape({\n pathname: PropTypes.string,\n }).isRequired,\n children: PropTypes.element.isRequired,\n };\n\n componentDidUpdate(prevProps) {\n const { location } = this.props;\n if (location.pathname !== prevProps.location.pathname) {\n window.scrollTo(0, 0);\n }\n }\n\n render() {\n const { children } = this.props;\n return children;\n }\n}\n\nexport default withRouter(ScrollToTop);\n"]},"metadata":{},"sourceType":"module"}
json
import * as mongoose from 'mongoose'; export const UserSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true }, password: { type: String, required: true }, firstName: { type: String, required: true }, lastName: { type: String, required: true }, dateCreated: String, }); UserSchema.methods.toJSON = function () { let userObject = this.toObject(); delete userObject.password; return userObject; };
typescript
// // Cone2DParticleEmitter.cpp // Chilli Source // Created by <NAME> on 03/12/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitter.h> #include <ChilliSource/Core/Math/Random.h> #include <ChilliSource/Rendering/Particle/ParticleEffect.h> #include <ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitterDef.h> #include <cmath> namespace ChilliSource { namespace Rendering { namespace { //---------------------------------------------------------------- /// Generates a 2D direction within the given angle range with even /// distribution. /// /// @author <NAME> /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GenerateDirectionWithinAngle(f32 in_angle) { f32 angle = Core::MathUtils::k_pi * 0.5f + Core::Random::GenerateNormalised<f32>() * in_angle - 0.5f * in_angle; Core::Vector2 direction(std::cos(angle), std::sin(angle)); return direction; } //---------------------------------------------------------------- /// Generates a direction with the given angle with even /// distribution. /// /// @author <NAME> /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GenerateDirectionWithAngle(f32 in_angle) { f32 angle = 0.0f; if (Core::Random::Generate<u32>(0, 1) == 0) { angle = Core::MathUtils::k_pi * 0.5f - 0.5f * in_angle; } else { angle = Core::MathUtils::k_pi * 0.5f + 0.5f * in_angle; } Core::Vector2 direction(std::cos(angle), std::sin(angle)); return direction; } //---------------------------------------------------------------- /// Generates a position in a unit 2D cone with the given angle, with /// even distribution. /// /// @author <NAME> /// /// @param The angle. /// /// @return The position. //---------------------------------------------------------------- Core::Vector2 GeneratePositionInUnitCone2D(f32 in_angle) { f32 dist = std::sqrt(Core::Random::GenerateNormalised<f32>()); return GenerateDirectionWithinAngle(in_angle) * dist; } //---------------------------------------------------------------- /// Generates a position on a the surface of a unit 2D cone with the /// given angle, with even distribution. /// /// @author <NAME> /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GeneratePositionOnUnitCone2D(f32 in_angle) { f32 dist = std::sqrt(Core::Random::GenerateNormalised<f32>()); return GenerateDirectionWithAngle(in_angle) * dist; } } //---------------------------------------------------------------- //---------------------------------------------------------------- Cone2DParticleEmitter::Cone2DParticleEmitter(const ParticleEmitterDef* in_particleEmitter, Core::dynamic_array<Particle>* in_particleArray) : ParticleEmitter(in_particleEmitter, in_particleArray) { //Only the sphere emitter def can create this, so this is safe. m_coneParticleEmitterDef = static_cast<const Cone2DParticleEmitterDef*>(in_particleEmitter); } //---------------------------------------------------------------- //---------------------------------------------------------------- void Cone2DParticleEmitter::GenerateEmission(f32 in_normalisedEmissionTime, Core::Vector3& out_position, Core::Vector3& out_direction) { f32 radius = m_coneParticleEmitterDef->GetRadiusProperty()->GenerateValue(in_normalisedEmissionTime); f32 angle = m_coneParticleEmitterDef->GetAngleProperty()->GenerateValue(in_normalisedEmissionTime); //calculate the position. switch (m_coneParticleEmitterDef->GetEmitFromType()) { case Cone2DParticleEmitterDef::EmitFromType::k_inside: out_position = Core::Vector3(GeneratePositionInUnitCone2D(angle) * radius, 0.0f); break; case Cone2DParticleEmitterDef::EmitFromType::k_edge: out_position = Core::Vector3(GeneratePositionOnUnitCone2D(angle) * radius, 0.0f); break; case Cone2DParticleEmitterDef::EmitFromType::k_base: out_position = Core::Vector3::k_zero; break; default: CS_LOG_FATAL("Invalid 'Emit From' type."); break; } //calculate the direction. switch (m_coneParticleEmitterDef->GetEmitDirectionType()) { case Cone2DParticleEmitterDef::EmitDirectionType::k_random: out_direction = Core::Vector3(GenerateDirectionWithinAngle(angle), 0.0f); break; case Cone2DParticleEmitterDef::EmitDirectionType::k_awayFromBase: if (out_position != Core::Vector3::k_zero) { out_direction = Core::Vector3(Core::Vector2::Normalise(out_position.XY()), 0.0f); } else { out_direction = Core::Vector3(GenerateDirectionWithinAngle(angle), 0.0f); } break; default: CS_LOG_FATAL("Invalid 'Emit Direction' type."); break; } } } }
cpp
<filename>src/server/usersDb.js import low from 'lowdb'; import underscoreDb from 'underscore-db'; low.mixin(underscoreDb); let db = low('users.json'); class UserModel { static getAll() { return db('users'); } static get(id) { return db('users').find({id : id}); } static remove(id) { db('users').remove(id); } static getByUsername(username) { return db('users').find({username : username}); } static create(username, password, email) { let user = { username : username, password : password, email : email }; return db('users').insert(user); } static update(id, username, password, email) { let user = { username : username, password : password, email : email }; return db('users') .chain() .find({id : id}) .assign(user) .value(); } } export default UserModel
javascript
Candidates can apply for the vacancies on the official website at opsc. gov. in till June 29. Increasing women representation in the Services will be the crucial metric in bridging gender inequities and empowering women to smash the glass ceilings. Eligible and interested candidates can submit their forms up to June 15 on agniveernavy. cdac. in. The fellowship amount will be ₹31,000 per month for the first two years and ₹35,000 per month for subsequent years. AIIMS Deoghar Recruitment 2023: Candidates can visit aiimsdeoghar. edu. in for detailed information and the application link. Jharkhand HC Recruitment 2023: Eligible and interested candidates can apply on jhc. org. in or jharkhandhighcourt. nic. in up to June 24. Candidates can apply online through the official website at rac. gov. in. Candidates can apply for the vacancies on the official website jkpsc. nic. in. Candidates can apply online through the official website at www. mstcindia. co. in till June 11. ISRO will recruit candidates for Scientist/ Engineer posts. Eligible candidates can apply at isro. gov. in. Indian Navy will recruit candidates for Agniveer posts. The registration process will begin on May 29, 2023. Candidates can apply online through the official website at pfcindia. com. NTPC will recruit candidates for Assistant Manager posts. Eligible candidates can apply online through the official site of NTPC at careers. ntpc. co. in. UPSC will recruit candidates for Assistant Engineer and other posts. Eligible candidates can apply at upsc. gov. in. IDBI will recruit candidates for Executive posts. Candidates can apply for 1036 posts at idbibank. in. Candidates can apply through the official website at dfccil. com. India Post will recruit candidates for GDS posts. Eligible candidates can apply online at indiapostgdsonline. gov. in. Indian Bank will recruit candidates for Specialist posts. Eligible candidates can apply at indianbank. in. DRDO will recruit candidates for Apprentice posts. Candidates can apply online through the official site of MHRD at mhrdnats. gov. in. Candidates can apply online through the official website at joinindiannavy. gov. in. IOCL has invited applications for 65 Non-Executive posts. APSC has invited applications for the Urban Technical Officer (Junior Grade-III) posts. Interested candidates can apply for the posts on the official website apsc. nic. in from May 16. UPSC will recruit candidates for Medical Officers and other posts. Eligible candidates can apply at upsc. gov. in. NPCIL has invited applications for Deputy Manager and other posts. HP TET June 2023 application process commenced at hpbose. org. Interested candidates can apply for the vacancies on the official website opsc. gov. in till June 8. OPTCL has invited applications for 50 Management Trainee(Electrical) posts. NPCIL has invited applications for Deputy Manager and Junior Hindi Translator posts. TNUSRB to recruit Sub Inspector posts. Candidates can apply online from June 1, 2023 onwards.
english
Two days after she shared a video of her interaction with her Saans co-star Kanwaljit Singh, Neena Gupta shared yet another video with him and hinted that they are shooting something new. In the video, Neena and Kanwaljit were seen standing in a luxury home, waiting for the crew to set up the scene. While Neena and Kanwaljit did not reveal details about their shoot, they were seen admiring the view from the house. “Ye hota hai ji flat, kya view hai! Par hum isse afford nahi kar sakte bus sirf yaha par shooting kar sakte hai. Hain na, Kuku ji? (This is called a flat, what a view! But we cannot afford this. We can only shoot here)," Neena said, addressing Kanwaljit. Kanwaljit added, “Kamsekam shooting mein ye humara ghar ho sakta hai! (At least we can consider this as our home while shooting)". Neena agreed, “Haan, chalo shooting mein hi sahi, isko enjoy kar lete hai do chaar din ke liye. (Yes, even if it is for shooting purposes, let’s enjoy the house for a few days). " Neena shared the video with the caption, “Yeh hai Mumbai Meri Jaan @kanwaljit19 #Mumbai #Shoottime. " The video prompted reactions from many fans of the actors. “My most fav onscreen couple," a fan said. “The all-time perfect duo," added another. “What a view! So happy to see you both together," a third fan said. “So happy to see you both together. Reminds me of Saans," a fourth fan said. Although several years have passed, fans still remember Neena and Kanwaljit for their outstanding work in Saans. The actors shouldered a mature romantic drama show for the small screen. In 2019, fans were surprised to see that Neena slipped into the shoes of Kanwaljit’s on-screen mother in the film Sardar Ka Grandson. The movie starred Arjun Kapoor in the lead. Read all the Latest News , Breaking News and IPL 2022 Live Updates here.
english
import { keyframes } from 'styled-components'; const backgroundChange = keyframes` 0% { background-color: #52bad5; } 5% { background-color: #2980b9; } 10% { background-color: #5ce5b4; } 15% { background-color: #73a84f; } 20% { background-color: #9b59b6; } 25% { background-color: #cb92e2; } 30% { background-color: #1c128b; } 35% { background-color: #d8e33d; } 40% { background-color: #e2b618; } 45% { background-color: #d35400; } 50% { background-color: #ba1616; } 55% { background-color: #52bad5; } 60% { background-color: #2980b9; } 65% { background-color: #5ce5b4; } 70% { background-color: #73a84f; } 75% { background-color: #9b59b6; } 80% { background-color: #cb92e2; } 85% { background-color: #1c128b; } 90% { background-color: #e3b63d; } 95% { background-color: #d8e33d; } 100% { background-color: #52bad5; } `; export default backgroundChange;
typescript
ఆ దినములలో అహీ తోపెలు చెప్పిన యే యాలోచనయైనను ఒకడు దేవుని యొద్ద విచారణచేసి పొందిన ఆలోచనయైనట్టుగా ఉండెను; దావీదును అబ్షాలోమును దానిని అట్లే యెంచుచుండిరి. aa dinamulalō ahee thoopelu cheppina yē yaalōchanayainanu okaḍu dhevuni yoddha vichaaraṇachesi pondina aalōchanayainaṭṭugaa uṇḍenu; daaveedunu abshaalōmunu daanini aṭlē yen̄chuchuṇḍiri. Now in those days the advice Ahithophel gave was like that of one who enquires of God. That was how both David and Absalom regarded all of Ahithophel-s advice. उन दिनों जो सम्मति अहीतोपेल देता था, वह ऐसी होती थी कि मानो कोई परमेश्वर का वचन पूछलेता हो; अहीतोपेल चाहे दाऊद को चाहे अबशलोम को, जो जो सम्मति देता वह ऐसी ही होती थी। அந்நாட்களில் அகித்தோப்பேல் சொல்லும் ஆலோசனை தேவனுடைய வாக்கைப்போல இருந்தது; அப்படி அகித்தோப்பேலின் ஆலோசனையெல்லாம் தாவீதுக்கும் இருந்தது, அப்சலோமுக்கும் அப்படியே இருந்தது. ಆ ದಿವಸಗಳಲ್ಲಿ ಅಹೀತೋಫೆಲನು ಆಲೋಚಿಸಿದ ಆಲೋಚನೆಯು ಒಬ್ಬನು ದೈವೋಕ್ತಿಗಳನ್ನು ವಿಚಾರಿಸುವ ಹಾಗೆ ಇತ್ತು. ಅಹೀತೋಫೆಲನ ಆಲೋಚನೆಯೆಲ್ಲಾ ದಾವೀದನಿಗೂ ಅಬ್ಷಾಲೋಮನಿಗೂ ಹಾಗೆಯೇ ಇತ್ತು. And the counsel of Ahithophel, which he counseled in those days, was as if a man had inquired at the oracle of God; so was all the counsel of Ahithophel both with David and with Absalom.
english
The primary question that almost every investor has in mind is what instrument will get me the maximum rate of returns? But, is it the right question to ask? The basic tenets of personal finance advise individuals to start with introspection. One should start with one’s financial goals than looking for high paying investments. The financial goals clearly define what you intend to achieve and you can accordingly plan your journey—where to invest, how much to invest and set your expectations right. Clearly defined financial goals or smart financial goals help you make a sound financial plan and ensure better execution of the same to achieve your goals. Here is how you can frame a SMART financial goal: The financial goal must be clear in the minds of the individual. Buying a house is a very vague goal, for example. However, if one says arranging down payment for a one bedroom hall kitchen (1BHK) home in a gated community in Mumbai Suburbs, then it makes more sense. Specific goals ensure that there is an emotional connect with the financial goals and such goals are more likely to be achieved. The goal should have a money value ascribed to it, among other factors. It helps the individual to understand where he wants to go clearly. Going by the example mentioned above, one would say that he would end up buying a home priced at Rs 70 lakh. The down payment at 20 percent works out to Rs 14 lakh. The money value lets you adjust your goals depending on the extent of money you saved and the changes in the price of the financial goals. For example, you may have a target of raising Rs 14 lakh but the prices go above your expectations, then the same need to be factored into your financial plan. The financial goal must be achievable. Sometimes the goals are not achievable in a near future. However one may want to use time on his side to make goals achievable. Goals that look not achievable for individuals with a very low-risk profile, may become achievable if some allocation is made to risky assets offering high returns. For example, in the above example, for an individual with a monthly salary of Rs 1 lakh and monthly saving of Rs 30,000, the goal appears to be impossible if one wants to raise the desired amount of money by end of the financial year. However, if the person takes a bit longer term, then his goal becomes achievable. If you have to accumulate a corpus of Rs 14 lakh at the end of five years from now and the expected rate of return is 12 percent per annum, then you should be investing approximately Rs 17,150 per month. These numbers make it achievable in the given context mentioned above. The financial goal must be realistic. If an individual with a monthly salary of Rs 1 lakh decides to build a multi-storied mansion in the plush localities in South Mumbai, then it would look impossible in the given context of high property prices and inadequate income. Only some miracle can help in such circumstances. Even if you stick to your goal of buying 1BHK, but try to achieve it in a short span of time along with other goals such as going on a foreign vacation and arranging down payment for a luxury sports utility vehicle, then it will become unrealistic. The financial goal must be expressed in the context of the time. Each financial goal comes with a price tag. But inflation ensures that the price tag changes with the time involved. For example, in the above example if we assume inflation at 5 percent, then the same house will be available at Rs 89. 34 lakh five years from now and at Rs 98. 5 lakh at the end of the seventh year. If we have to write the abovementioned goal in SMART words then it would read: Arranging down payment of Rs 19. 7 lakh for a 1BHK home in a gated community in Mumbai Suburbs priced at Rs 98. 5 lakh seven years from now. Clearly defining financial goal makes it easy to draw a financial plan. A saving and investment action can be prescribed with more clarity if the individual knows what he wants.
english
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Runs tempest tests This command is used for running the tempest tests Test Selection ============== Tempest run has several options: * **--regex/-r**: This is a selection regex like what testr uses. It will run any tests that match on re.match() with the regex * **--smoke/-s**: Run all the tests tagged as smoke There are also the **--blacklist-file** and **--whitelist-file** options that let you pass a filepath to tempest run with the file format being a line separated regex, with '#' used to signify the start of a comment on a line. For example:: # Regex file ^regex1 # Match these tests .*regex2 # Match those tests The blacklist file will be used to construct a negative lookahead regex and the whitelist file will simply OR all the regexes in the file. The whitelist and blacklist file options are mutually exclusive so you can't use them together. However, you can combine either with a normal regex or the *--smoke* flag. When used with a blacklist file the generated regex will be combined to something like:: ^((?!black_regex1|black_regex2).)*$cli_regex1 When combined with a whitelist file all the regexes from the file and the CLI regexes will be ORed. You can also use the **--list-tests** option in conjunction with selection arguments to list which tests will be run. You can also use the **--load-list** option that lets you pass a filepath to tempest run with the file format being in a non-regex format, similar to the tests generated by the **--list-tests** option. You can specify target tests by removing unnecessary tests from a list file which is generated from **--list-tests** option. Test Execution ============== There are several options to control how the tests are executed. By default tempest will run in parallel with a worker for each CPU present on the machine. If you want to adjust the number of workers use the **--concurrency** option and if you want to run tests serially use **--serial/-t** Running with Workspaces ----------------------- Tempest run enables you to run your tempest tests from any setup tempest workspace it relies on you having setup a tempest workspace with either the ``tempest init`` or ``tempest workspace`` commands. Then using the ``--workspace`` CLI option you can specify which one of your workspaces you want to run tempest from. Using this option you don't have to run Tempest directly with you current working directory being the workspace, Tempest will take care of managing everything to be executed from there. Running from Anywhere --------------------- Tempest run provides you with an option to execute tempest from anywhere on your system. You are required to provide a config file in this case with the ``--config-file`` option. When run tempest will create a .testrepository directory and a .testr.conf file in your current working directory. This way you can use testr commands directly to inspect the state of the previous run. Test Output =========== By default tempest run's output to STDOUT will be generated using the subunit-trace output filter. But, if you would prefer a subunit v2 stream be output to STDOUT use the **--subunit** flag Combining Runs ============== There are certain situations in which you want to split a single run of tempest across 2 executions of tempest run. (for example to run part of the tests serially and others in parallel) To accomplish this but still treat the results as a single run you can leverage the **--combine** option which will append the current run's results with the previous runs. """ import io import os import sys import tempfile import threading from cliff import command from os_testr import regex_builder from os_testr import subunit_trace from oslo_serialization import jsonutils as json import six from testrepository.commands import run_argv from tempest import clients from tempest.cmd import cleanup_service from tempest.cmd import init from tempest.cmd import workspace from tempest.common import credentials_factory as credentials from tempest import config CONF = config.CONF SAVED_STATE_JSON = "saved_state.json" class TempestRun(command.Command): def _set_env(self, config_file=None): if config_file: CONF.set_config_path(os.path.abspath(config_file)) # NOTE(mtreinish): This is needed so that testr doesn't gobble up any # stacktraces on failure. if 'TESTR_PDB' in os.environ: return else: os.environ["TESTR_PDB"] = "" # NOTE(dims): most of our .testr.conf try to test for PYTHON # environment variable and fall back to "python", under python3 # if it does not exist. we should set it to the python3 executable # to deal with this situation better for now. if six.PY3 and 'PYTHON' not in os.environ: os.environ['PYTHON'] = sys.executable def _create_testrepository(self): if not os.path.isdir('.testrepository'): returncode = run_argv(['testr', 'init'], sys.stdin, sys.stdout, sys.stderr) if returncode: sys.exit(returncode) def _create_testr_conf(self): top_level_path = os.path.dirname(os.path.dirname(__file__)) discover_path = os.path.join(top_level_path, 'test_discover') file_contents = init.TESTR_CONF % (top_level_path, discover_path) with open('.testr.conf', 'w+') as testr_conf_file: testr_conf_file.write(file_contents) def take_action(self, parsed_args): returncode = 0 if parsed_args.config_file: self._set_env(parsed_args.config_file) else: self._set_env() # Workspace execution mode if parsed_args.workspace: workspace_mgr = workspace.WorkspaceManager( parsed_args.workspace_path) path = workspace_mgr.get_workspace(parsed_args.workspace) if not path: sys.exit( "The %r workspace isn't registered in " "%r. Use 'tempest init' to " "register the workspace." % (parsed_args.workspace, workspace_mgr.path)) os.chdir(path) # NOTE(mtreinish): tempest init should create a .testrepository dir # but since workspaces can be imported let's sanity check and # ensure that one is created self._create_testrepository() # Local execution mode elif os.path.isfile('.testr.conf'): # If you're running in local execution mode and there is not a # testrepository dir create one self._create_testrepository() # local execution with config file mode elif parsed_args.config_file: self._create_testr_conf() self._create_testrepository() else: print("No .testr.conf file was found for local execution") sys.exit(2) if parsed_args.state: self._init_state() else: pass if parsed_args.combine: temp_stream = tempfile.NamedTemporaryFile() return_code = run_argv(['tempest', 'last', '--subunit'], sys.stdin, temp_stream, sys.stderr) if return_code > 0: sys.exit(return_code) regex = self._build_regex(parsed_args) if parsed_args.list_tests: argv = ['tempest', 'list-tests', regex] returncode = run_argv(argv, sys.stdin, sys.stdout, sys.stderr) else: options = self._build_options(parsed_args) returncode = self._run(regex, options) if returncode > 0: sys.exit(returncode) if parsed_args.combine: return_code = run_argv(['tempest', 'last', '--subunit'], sys.stdin, temp_stream, sys.stderr) if return_code > 0: sys.exit(return_code) returncode = run_argv(['tempest', 'load', temp_stream.name], sys.stdin, sys.stdout, sys.stderr) sys.exit(returncode) def get_description(self): return 'Run tempest' def _init_state(self): print("Initializing saved state.") data = {} self.global_services = cleanup_service.get_global_cleanup_services() self.admin_mgr = clients.Manager( credentials.get_configured_admin_credentials()) admin_mgr = self.admin_mgr kwargs = {'data': data, 'is_dry_run': False, 'saved_state_json': data, 'is_preserve': False, 'is_save_state': True} for service in self.global_services: svc = service(admin_mgr, **kwargs) svc.run() with open(SAVED_STATE_JSON, 'w+') as f: f.write(json.dumps(data, sort_keys=True, indent=2, separators=(',', ': '))) def get_parser(self, prog_name): parser = super(TempestRun, self).get_parser(prog_name) parser = self._add_args(parser) return parser def _add_args(self, parser): # workspace args parser.add_argument('--workspace', default=None, help='Name of tempest workspace to use for running' ' tests. You can see a list of workspaces ' 'with tempest workspace list') parser.add_argument('--workspace-path', default=None, dest='workspace_path', help="The path to the workspace file, the default " "is ~/.tempest/workspace.yaml") # Configuration flags parser.add_argument('--config-file', default=None, dest='config_file', help='Configuration file to run tempest with') # test selection args regex = parser.add_mutually_exclusive_group() regex.add_argument('--smoke', '-s', action='store_true', help="Run the smoke tests only") regex.add_argument('--regex', '-r', default='', help='A normal testr selection regex used to ' 'specify a subset of tests to run') list_selector = parser.add_mutually_exclusive_group() list_selector.add_argument('--whitelist-file', '--whitelist_file', help="Path to a whitelist file, this file " "contains a separate regex on each " "newline.") list_selector.add_argument('--blacklist-file', '--blacklist_file', help='Path to a blacklist file, this file ' 'contains a separate regex exclude on ' 'each newline') list_selector.add_argument('--load-list', '--load_list', help='Path to a non-regex whitelist file, ' 'this file contains a seperate test ' 'on each newline. This command' 'supports files created by the tempest' 'run ``--list-tests`` command') # list only args parser.add_argument('--list-tests', '-l', action='store_true', help='List tests', default=False) # execution args parser.add_argument('--concurrency', '-w', help="The number of workers to use, defaults to " "the number of cpus") parallel = parser.add_mutually_exclusive_group() parallel.add_argument('--parallel', dest='parallel', action='store_true', help='Run tests in parallel (this is the' ' default)') parallel.add_argument('--serial', '-t', dest='parallel', action='store_false', help='Run tests serially') parser.add_argument('--save-state', dest='state', action='store_true', help="To save the state of the cloud before " "running tempest.") # output args parser.add_argument("--subunit", action='store_true', help='Enable subunit v2 output') parser.add_argument("--combine", action='store_true', help='Combine the output of this run with the ' "previous run's as a combined stream in the " "testr repository after it finish") parser.set_defaults(parallel=True) return parser def _build_regex(self, parsed_args): regex = '' if parsed_args.smoke: regex = 'smoke' elif parsed_args.regex: regex = parsed_args.regex if parsed_args.whitelist_file or parsed_args.blacklist_file: regex = regex_builder.construct_regex(parsed_args.blacklist_file, parsed_args.whitelist_file, regex, False) return regex def _build_options(self, parsed_args): options = [] if parsed_args.subunit: options.append("--subunit") if parsed_args.parallel: options.append("--parallel") if parsed_args.concurrency: options.append("--concurrency=%s" % parsed_args.concurrency) if parsed_args.load_list: options.append("--load-list=%s" % parsed_args.load_list) return options def _run(self, regex, options): returncode = 0 argv = ['tempest', 'run', regex] + options if '--subunit' in options: returncode = run_argv(argv, sys.stdin, sys.stdout, sys.stderr) else: argv.append('--subunit') stdin = io.StringIO() stdout_r, stdout_w = os.pipe() subunit_w = os.fdopen(stdout_w, 'wt') subunit_r = os.fdopen(stdout_r) returncodes = {} def run_argv_thread(): returncodes['testr'] = run_argv(argv, stdin, subunit_w, sys.stderr) subunit_w.close() run_thread = threading.Thread(target=run_argv_thread) run_thread.start() returncodes['subunit-trace'] = subunit_trace.trace( subunit_r, sys.stdout, post_fails=True, print_failures=True) run_thread.join() subunit_r.close() # python version of pipefail if returncodes['testr']: returncode = returncodes['testr'] elif returncodes['subunit-trace']: returncode = returncodes['subunit-trace'] return returncode
python
The 2012 London Olympics have already become India’s best Olympic performance. At the time of writing, India have already won a Silver and two Bronzes, thanks to Vijay Kumar (Men’s 25m Rapid Fire Pistol), Gagan Narang (Men’s 10m Air Gun), and Saina Nehwal (Women’s Badminton Singles) respectively. And considering we are assured of another medal from Mary Kom, who’s just entered the Women’s 51 Kg Boxing Semi Finals, it takes India’s medal count to four, one more than Beijing 2008. It’s a reason to celebrate. Despite the fact that we as a nation technically trail behind the likes of Chinshanlo Zulfiya of Kazakhstan and Kim Un Guk of North Korea on the medals tally, unless our boxers and wrestlers bring back the much elusive Gold medal, it’s still an improvement. The country could have easily won one more medal when Joydeep Karmarkar missed a Bronze by a fraction of an inch, quite literally. However, come 2020 and the number of Indians who’ll remember Karmarkar’s 4thplace in 50m Rifle Prone will be far lesser than those who’ll remember Rajesh Chauhan’s last over six against Pakistan in an ODI at Karachi. And therein lies a lesson. No, seriously. How many of you remember the name of the Badminton player from India who almost made it to the quarters of the Barcelona Olympics? I certainly don’t. Clearly, Indian cricket has become the Microsoft of Indian sports. Nobody seems to appreciate what it’s managed to achieve, even though nobody can imagine life without it. True story. Surely, the BCCI has managed to do something that other sporting bodies in India have failed to do. They’ve managed to create a loyalty among fans, even without their knowledge. Sample the cases stated below: Broadcast: As a kid, I grew up watching Sachin Tendulkar make piles of money when he won matches, while Mohammed Azharuddin matched the little master’s earnings by losing them. But I couldn’t say the same about badminton, which was never really telecast on national TV. So, watching countless fixed fixtures at Sharjah was more memorable than growing up watching Vijayalakshmi auntie and Ananthapadmanabhan uncle play ‘shuttlecock’! Victory Celebration: We never really celebrated when Jaspal Rana won a Gold medal at the Asian Games at Hiroshima in 1994. Yet, we took a family picture around our old Nelco Blue Diamond TV when India won the Asia Cup in 1995 at Sharjah. Sex Appeal: When Hrishikesh Kanitkar scored a match-winning boundary against Pakistan at the Bangabandu Stadium to help India win the Coca Cola Independence Cup in 1998, he instantly became India’s most eligible bachelor, getting proposals from North Indians, South Indians and even West Indians (One woman named Sanya Rambally who lived on the outskirts of Georgetown, Guyana actually believed that Kanitkar had the sexiest forward defence, second only to Shivnaraine Chanderpaul). However, not too many women gave Bajrang Lal Takhar a second glance after he won a Men’s Single Sculls Gold at the Asian Games in 2010 in Guangzhou. Publicity: If you were shown photos of two similar sounding sportsmen named Raman Lamba and Limba Ram, who are you likely to recognize? The one holding the cricket bat, obviously! Clearly, much has worked in favour of cricket, thanks to its fans, who may even recall the bowling action of Bhupinder Singh Sr with moist eyes, but couldn’t recognize Ajit Pal Singhs from their Ajit Singhs. Why, even Ajit Agarkar would have a bigger fan club than his two equally illustrious namesakes. So guys, don’t blame one game for the country’s failures in other fields (and not just sporting ones). If you feel so strongly about sports in India, do more than worshipping one set of medal winners and forgetting the rest until it’s time for the next Olympics four years later. Follow them. Encourage them. And if nothing else, stop blaming cricket the next time an Indian athlete fails to win a Bronze. (P. S. : If you agree with what the author says, first memorise the names of the Men’s and Women’s Kabaddi squads who won the World Cup in 2011 and then forward this article to 10 other friends. If you do so immediately, India will surely win another medal before the Olympics ends. )
english
Morgan Stanley Capital International (MSCI) recently re-balanced its India index under its semi-annual review. Of the eight additions it did to the index, two belong to the insurance sector – SBI Life and ICICI Prudential Life Insurance, possibly underlining brighter prospects in the segment. “Insurance as a sector is a must have in an investor’s portfolio because of the potential the sector has in terms of penetration. Two reasons why the sector is bound to see an uptick is because firstly, more and more people are getting insurance done, and secondly, the value for which you get the policy done is rising, leading to higher premium incomes for the companies,” says Dharmesh Kant, Head of Retail Research at IndiaNivesh Securities. According to a report by Edelweiss Securities, insurance premiums are likely to grow by 16 per cent over the next decade despite 30 per cent annual projected growth for pure protection. TO READ THE FULL STORY, SUBSCRIBE NOW NOW AT JUST RS 249 A MONTH. What you get on Business Standard Premium? - Unlock 30+ premium stories daily hand-picked by our editors, across devices on browser and app. - Pick your 5 favourite companies, get a daily email with all news updates on them. - Full access to our intuitive epaper - clip, save, share articles from any device; newspaper archives from 2006. - Preferential invites to Business Standard events. - Curated newsletters on markets, personal finance, policy & politics, start-ups, technology, and more.
english
Na vosa e a yaco vei Jeremaia mai vei Jiova, ka vaka, 2 "Mo tu cake, ka lako sobu ki na nona vale na dautuli bilo, ia Au na tukuna vei iko mai keya na Noqu vosa." 3 Au a qai lako sobu ki na nona vale na dautulituli, ka raica, sa ia tiko e dua na cakacaka e na kenai tutu-wiri. 4 A sa cataki na bilo tete sa cakava tiko, e na liga i koya na dautulituli; ka sa baci cakava tale me bilo tani, me vaka sa vinaka vua na dautulituli me cakava. 5 Sa qai yaco vei au na vosa i Jiova, ka vaka: 6 "Me'u sega beka ni veitalia vei kemudou, na mataqali i Isireli, me vaka taki koya na dautulituli oqo?" Sa tukuna o Jiova, "Raica, me vaka na tete e na liga i koya na dautulituli, sa vakakina oi kemudou e na Ligaqu, na mataqali i Isireli! 7 "Na tiki-ni-siga Au na vosa e na vuku ni dua na vanua, se dua na matanitu, Me'u cavuta, ka basuka, ka vakarusa, 8 "Kevaka ena lesu na vanua o ya mai na nodra ca, Au a lewa me ra ca kina, Au na qai veivutunitaka na vinaka, Au a tukuna Me'u cakava me ra vinaka kina. 9 "Ia na tiki-ni-siga Au na vosa e na vuku ni dua na vanua, se dua na matanitu, me'u tara, ka tea, 10 "Kevaka ena caka ca e Mataqu, me sega ni vakarorogo ki na domoqu, Au na qai veivutunitaka na vinaka, Ka'u a tukuna Me'u cakava me ra vinaka kina. 11 "Ia oqo, mo vosa vei ira na Juta, kei na lewe i Jerusalemi, ka vaka, 'Sa tukuna vakaoqo o Jiova; "Raica, Au sa tulia na ca kivei kemudou, ia Au sa vakananuma e dua na lewa e na vukumudou, dou dui lesu mada mai na nomudou i tovo ca, ka vakavinakataka na nomudou i tovo kei na nomudoui valavala."'" 12 Era sa tukuna, "Sa sega sara ni rawa! Keimami na muria ga na neimami lewa, ia na nanuma ni lomai keimami ca keimami na dui cakava." 13 O koya oqo sa tukuna kina o Jiova; "Dou vakataroga mada vei ira na veimatanitu, se o cei sa rogoca na ka vakaoqo; Sa dua na ka rerevaki sara sa cakava o koya na goneyalewa ni Isireli." 14 E dua li me vakalaiva na uca-vulavula ni Lepanoni me kenai sosomi na wai mai na uluvatu ni vanua? se me biu beka na wai liliwa sa drodro tu me kenai sosomi na wai ni dua na tikina tani? 15 "Ka ni ra sa guilecavi Au na Noqu tamata, ia era sa vakama kina na ka boi vinaka ki na ka lasu, ka ra sa vakatarabetaki ira e na nodra sala, ka sa biu ga nai lakolako makawa, me ra lako vakatikitiki e na sala sa sega ni buluti, 16 me ra vakavuna na kena vakalalataki na nodra vanua, ka me vakasiusiutaki ka sega ni mudu; o ira kece era lako voli yani era na kidacalataka, ka kurea na uludra. 17 Au na vakatolosevi ira e na mata ni meca me vaka e na cagi mai na vualiku; Au na vakanadakui ira e na siga ni nodra rarawa ka sega ni vakanamata vei ira." 18 Era sa qai tukuna, "Me da mai bukia na vere kei Jeremaia, ni na sega ni yali na vunau mai vua na bete, se nai vakavuvuli mai vua na vuku, se na vosa mai vua na parofita. Me da mai vakacataki koya e na yameda, ia me da kakua ni vakarorogo ki na dua na nona vosa." 19 Ni golevi au mai, Jiova, ka rogoca na domodra era veileti kei au! 20 Me saumi beka na vinaka e na ca? Ni ra a kelia nai keli me'u mate kina. Mo ni nanuma ni'u a tu e Matamuni me'u vosa vinaka e na vukudra, ka me'u saumaka tani na Nomuni cudru mai vei ira. 21 O koya mo ni solia kina na luvedra me ra viakana, ka vakadavea na kedra dra e na kaukauwa ni seleiwau; ia me yali vei ira na watidra na luvedra, ka me ra yada talega; ka me ra vakamatei na nodra tagane; ia na nodra cauravou, me ra mate e nai seleiwau e nai valu. 22 Me rogo mai na nodra veivale na tagi, ni Kemuni sa vakauta nai valu me sikiti ira: ni ra sa kelia nai keli me rawai au; ia era sa vunia nai cori me tacori kina na yavaqu. 23 Io, oi Kemuni, Jiova, o Ni sa kila kece na nodra veretaki au me'u mate. Mo ni kakua ni buluta na nodra caka cala, ia na nodra i valavala ca mo ni kakua ni bokoca tani mai na Matamuni, ia me ra vakabalei sobu ga e matamuni; Mo Ni vakayacora vei ira e na gauna ni Nomuni cudru.
english
Farhan Akhtar's daughters Akira and Shakya had a gala time at their father's wedding with Shibani Dandekar. In one of the photos, they can be seen beaming with joy. Farhan and Adhuna had met during the filming of Dil Chahta Hai. Bhabani who is now dating Dino Morea's brother Nicolo Morea made her debut with this film as hairstylist. She has worked as a hairstylist in many other projects that include Dil Dhadakne Do, Zindagi Na Milegi Dobara, Dangal, Raaes and many more. Adhuna launched her own hairstyling brand, BBlunt in 2004. While rumours had claimed that Farhan and Adhuna broke up because the former was dating Aditi Rao Hydari during the shooting of Wazir, Aditi Rao Hydari had however rubbished claims. "It's part of our job. . . Some days, I am irritated for five minutes, and then we all laugh and get on with our work. I actually find it entertaining," she said. Farhan Akhtar and Adhuna Bhabani parted ways in 2017. In a joint statement, they both said, "This is to announce that we, Adhuna and Farhan, have mutually and amicably decided to separate. Our children remain our priority and it is immensely important to us, as responsible parents, that they be protected from unwarranted speculation and public glare. We sincerely request that we are given the privacy that is required at this time to move forward in a dignified manner. " (For more news and updates from the world of celebrities from Bollywood and Hollywood, keep reading Indiatimes Entertainment, and let us know your thoughts on this story in the comments below. )
english
Slide # / Relevance 3-5 Objectives for years 1-3 (assumed) 6-11 5-Steps to prepare the NRA 12 Qualitative funding breakdown 13,14 Possible Program position by year-1 end 15,16 Questions that should have answers by the end of the 3rd year 17 Action Items (Pre-NRA) Year-1 Strategic Objectives • Establish a foundation for future decision making. • Gather knowledge about issues related to the development and operation of a space fusion propulsion plant. • Preliminarily assess the benefit of fusion over alternate propulsion systems for possible future space missions. • Develop a relationship with fusion-energy players, such as the DOE, fusion community, et al. Year-1 Key Tactical Objectives • Upgrade systems integration for manypropulsion concepts (paper studies). • Develop tools that enable transparent, fair, and objective assessment of fusion and non-fusion propulsion to accomplish specific arduous space missions. Year-2 & 3 Macro Objectives • Continue upgrading paper studies where warranted, and building a knowledge base to support next-level funding decisions and program directions. • For each concept, address industrial base readiness; programmatic technology, infrastructure technology, and material resource needs; gross cost estimate; political and social commitment requirements; environmental and safety considerations; and other special features. • Select key systems for proof of principle technology development, if warranted (risk mitigation mind set). 1a. Describe Standards forVehicle Definition Rationale: These standards describe what’s needed for fair, transparent, and objective comparison of propulsion system performance (independent of space mission, payload, politics, cost, ...) Define: • terminology, • units, and • figures of merit Define minimum consideration in: • subsystem thoroughness and • engine-absorbed waste heat. Deadline: living draft available online prior to NRA release. Action: place earlier draft definitions online now (C. Williams et al.), and solicit comments from the Working Group for upgrades. Funded recipients need this information by the time of NRA release. 1b. Describe ReferenceSpace Missions Rationale: Reference space missions are needed to evaluate return-on-investment (ROI) for competing fusion, fission, chemical, and other devices over a variety of mission classes that may be needed in the future. Define reference missions and classes: • human mars and outer solar system, • robotic mass-moving, • multi-mission-engine classes, ... Define: • terminology, • units, and • figures of merit Deadline: living draft available online prior to NRA release. Action: solicit mission definitions from the Working Group now, put them online ASAP; prior to NRA release, organize them into a living draft of a broad range of classes with key reference missions. 1c. Describe Assessment ToolNeeds Rationale: To facilitate transparent, fair, and objective comparisons requires user-friendly, easily-accessible trade-study tools. Define assessment tool needs: • common platform for model intercomparisons (EXCEL?), • impulse and continuous thrust astrodynamic navigation, • mission-window and payload tracking, ... Deadline: living draft available online prior to NRA release. Action: solicit trade-study tool needs from the Working Group now, put them online ASAP; prior to NRA release, organize them into a living draft of a broad range of tool needs. 2a. Request Proposals for Propulsion Concept Paper Studies Rationale: To provide nominal support to bring many fusion propulsion concepts up to minimum standards required for transparent, fair, and objective assessment. Define selection & submission criteria: • NASA to describe programmatic needs & submission reqmnts, • Proposer to identify their concept’s missing subsystems, • Proposer to identify tentative technology status, ... Deadline: NASA part available online as part of the NRA release. Action: Solicit suggestions from the Working Group for defining the “Proposer Request for Funding” part of the NRA. Put suggestions online now for comment by the Working Group. 2b. Request Proposals for Assessment-Tool Development Rationale: To provide nominal support to develop user-friendly trade-study tools for eventual use by participants, management, and the public for assessing fusion-engine/space-mission benefit. Define selection & submission criteria: • NASA to describe programmatic needs & submission reqmnts, • Proposer to describe the benefit of their assessment tool, • Proposer to describe user-friendliness and portability, ... Deadline: NASA part available online as part of the NRA release. Action: Solicit suggestions from the Working Group for defining the “Proposer Request for Funding” part of the NRA. Put suggestions online now for comment by the Working Group. Possible Program Position by Year-1 End(detail on next slide) A Growing Number of Dynamic Transparent Modules The Model Owner retains their specific platform, butto keep it simple and transparent for the Program, all models are translated to a Common Platform (say EXCEL Spreadsheet Modules). - This probably needs more explanation. Questions that may be Answered during Years 1-3 NASA can facilitate a worldwide consortium of government, university, industry, and public partners to find answer's to the following questions. 1. Can mission-capability per unit-cost be improved through fusion propulsion? 2. What space missions could benefit, or require, fusion propulsion? 3. Which fusion power plant concepts are adaptable for propulsion in space? 4. What is the status of fusion-technology on Earth? 5. What are the special adaptations required for space-based fusion systems? 6. How can existing candidate space-based fusion concepts be brought up to standards useful for a fair comparison? 7. What are the categories of figure-of-merits (FOMs) needed for comparison? 8. What subsystems must be considered for a fair concept comparison? 9. What tools are needed to perform subsystem/space-mission trades? (continued on next slide) Questions that may be Answered during Years 1-3 (continued) 10. What tools are needed for comparison to non-fusion propulsion concepts? 11. What tools are needed to assess the space-mission capability of specific fusion concepts, taking into account mission window and planet alignment? 12. What tools are needed to easily determine astrodynamic flight path? 13. What tools are needed for multi-mission payload tracking? 14. What are the special operating concerns of fusion-propulsion concepts? 15. What are the logical parking orbits and construction orbits? 16. What infrastructure is required to support launch, construction, and operations? 17. What are the knowledge-based tools needed to manage and to keep the participants, the public, and government informed of the issues and progress of the project? Action Items (Pre-NRA) • Establish 6 new topical message boards dedicated to gathering information, by the Working Group, that is required for NRA release: 1. Suggested “Vehicle Definition” Standards 2. Suggested Reference Space Missions 3. Suggested Software Tool Development to Facilitate Transparent, Fair, and Objective Engine/Mission-Capability Comparisons 4. NRA selection & submission criteria for Fusion Engine Paper Studies 5. NRA selection & submission criteria for Assessment-Tool Development 6. Ask questions that need answering during Phase-I of the fusion program (Years 1-3?) • Use the Planned October Workshop to abridge, articulate, and finalize the issues discovered in the Message Boards above. Yellow brick roadmap. Spectacular Event Roadmap. Business Roadmap.
english
Kagiso Rabada has rattled the Australian top order in the semi-final of the ICC Under-19 World Cup 2014. Chasing 231 to win the game, Rabada snared three early wickets to dent Australia’s charge. It has been a great exhibition of bowling by the seamer. Australia are 40 for three in 11 overs. Matthew Short was the first to go when one ball climbed on him and he edged it while pulling it. Then, Damien Mortimer was castled by one that came in and he was beaten all ends up. Then the big wicket, as Jaron Morgan inside-edged one onto his stumps in the ninth over. Rabada has been quick and has surprised the top order. It has been a truly inspiring spell by him. This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful. Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings. If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.
english
<reponame>ofZach/landlinesApp {"id":1133,"line-1":"Coquimbo Region","line-2":"Chile","attribution":"©2014 Cnes/Spot Image, DigitalGlobe","url":"https://www.google.com/maps/@-29.593162,-70.333056,16z/data=!3m1!1e3"}
json
package io.bootique.tools.release.controller; import com.fasterxml.jackson.databind.ObjectMapper; import io.bootique.tools.release.model.github.Organization; import io.bootique.tools.release.model.github.Repository; import io.bootique.tools.release.model.maven.Project; import io.bootique.tools.release.service.content.ContentService; import io.bootique.tools.release.service.git.GitService; import io.bootique.tools.release.service.github.GitHubApi; import io.bootique.tools.release.service.maven.MavenService; import io.bootique.tools.release.service.preferences.PreferenceService; import java.io.IOException; import java.util.List; import javax.inject.Inject; abstract class BaseController { @Inject PreferenceService preferences; @Inject GitHubApi gitHubApi; @Inject MavenService mavenService; @Inject ObjectMapper objectMapper; @Inject GitService gitService; @Inject ContentService contentService; List<Project> getSelectedProjects(String selectedProjects) throws IOException { List selectedProjectsId = objectMapper.readValue(selectedProjects, List.class); Organization organization = gitHubApi.getCurrentOrganization(); return mavenService.getProjects(organization, project -> selectedProjectsId.contains(project.getRepository().getName())); } List<Project> getAllProjects() { Organization organization = gitHubApi.getCurrentOrganization(); return mavenService.getProjects(organization, project -> true); } boolean haveMissingRepos(Organization organization) { for(Repository repository : organization.getRepositoryCollection().getRepositories()) { if (preferences.have(GitService.BASE_PATH_PREFERENCE)) { if(gitService.status(repository) == GitService.GitStatus.MISSING) { return true; } } } return false; } }
java
<reponame>chartjes/chartjes.github.io <!DOCTYPE html> <html> <head lang="en"> <title>Home &mdash; At The Keyboard &mdash; <NAME> sharing grumpy wisdom since 2005</title> <meta charset="utf-8"> <meta name="theme-color" content="#ffffff"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="robots" content="noindex, follow"> <link rel="stylesheet" href="/build/app.css"> <link rel="apple-touch-startup-image" href="/build/2048x2048.png"> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="shortcut icon" sizes="76x76" href="/build/jackson/76x76.png"> <link rel="shortcut icon" sizes="120x120" href="/build/jackson/120x120.png"> <link rel="shortcut icon" sizes="128x128" href="/build/jackson/128x128.png"> <link rel="shortcut icon" sizes="152x152" href="/build/jackson/152x152.png"> <link rel="shortcut icon" sizes="196x196" href="/build/jackson/196x196.png"> <link rel="shortcut icon" sizes="512x512" href="/build/jackson/512x512.png"> <link rel="shortcut icon" sizes="1024x1024" href="/build/jackson/1024x1024.png"> <link rel="shortcut icon" sizes="2048x2048" href="/build/jackson/2048x2048.png"> <link rel="apple-touch-icon" sizes="76x76" href="/build/jackson/76x76.png"> <link rel="apple-touch-icon" sizes="120x120" href="/build/jackson/120x120.png"> <link rel="apple-touch-icon" sizes="128x128" href="/build/jackson/128x128.png"> <link rel="apple-touch-icon" sizes="152x152" href="/build/jackson/152x152.png"> <link rel="apple-touch-icon" sizes="196x196" href="/build/jackson/196x196.png"> <link rel="apple-touch-icon" sizes="512x512" href="/build/jackson/512x512.png"> <link rel="apple-touch-icon" sizes="1024x1024" href="/build/jackson/1024x1024.png"> <link rel="apple-touch-icon" sizes="2048x2048" href="/build/jackson/2048x2048.png"> <link rel="alternate" type="application/atom+xml" href="/atom.xml" title="At The Keyboard activity feed" /> </head> <body> <header> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container"> <a class="navbar-brand" href="/">At The Keyboard</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item"><a class="nav-link" href="/blog">Posts Archive</a></li> <li class="nav-item"><a class="nav-link" href="/blog/categories">Categories</a></li> <li class="nav-item"><a class="nav-link" href="/blog/tags">Tags</a></li> <li class="nav-item"><a class="nav-link" href="/about">About</a></li> </ul> </div> </div> </nav> </header> <main role="main" class="container"> <div class="row"> <div class="col-sm-8"> <article> <header> <h2><a href="/2008/01/29/whats-in-chris-brain-january-2008-edition/">What&#039;s In Chris&#039; Brain: January 2008 Edition</a></h2> </header> <div> <p> Not a lot going on, it's time for a quick round-up post <ul> <li>I'm speaking at <a href='http://www.cakefest.org'>CakeFest</a>, so I'm working on my presentation. Since I'm going to be a combination of slides and actual demonstrations of the Cake console, I'm going to be using <a href="http://meyerweb.com/eric/tools/s5/">S5</a> to run the slideshow, then switching to a terminal and my IDE to show people the results</li> <li>I've run into a weird bug in working with Cake and Postgres, where the code works okay in PHP 5 + Postgres + OS-X, but erroring out in PHP 4 + Postgres + Linux. If I could figure out a test to recreate the bug, that would be a good step forward. In a nutshell, for some reason CakePHP is not determining the correct name of the sequence (it's what Postgres uses when determining auto-incremented ID's for a table) in the PHP 4 + Postgres + Linux environment. It's very weird and I have no idea what might be happening here. Given that I can't submit a ticket without a test proving the problem, and then figuring out what code to change, this could cause me some headaches.</li> <li>I suck at writing screen scrapers, which is what I need to make one of my side projects work</li> <li>Via the ever-increasingly-useful Miro, I have started watching a presentation on <a href="http://research.sun.com/projects/lively/">the Lively Kernel</a>. For some more info about it, check out this post about how <a href="http://bitworking.org/news/290/JavaScript-is-the-new-Smalltalk">Javascript is the new Smalltalk</a></li> <li>I've been playing around with different themes for this blog, but nothing seems to work as well as my current setup. Interesting...</li> <li>I also experimented with adding some more advertising but that got me nothing in the way of revenue. Maybe I didn't give it enough time or something. My current set of advertisers (thank you very much, guys and gals) make this blog pay for itself, so I consider that a major accomplishment. </li> </ul></p> </div> </article> <article> <header> <h2><a href="/2008/01/22/simple-user-registration-in-cakephp-12-part-ii/">Simple User Registration in CakePHP 1.2, Part II</a></h2> </header> <div> <p>I got a question in the comments about my previous post on simple user registration about how to do some of the necessary validation for registration in the model. I thought I'd show some code I did to do exactly that. </p> <p> The key to all this stuff is using a second form field for doing the validation. Here's some sample code for you, based on the latest straight-from-svn version of Cake PHP 1.2 (r6402) <br /><br /> ~~~ <?php /** * Class used for user authentication on the league website * */ class User extends AppModel { var $name = 'User'; var $validate = array( 'id' => array('rule' => 'blank', 'on' => 'create'), 'username' => array('rule' => 'alphanumeric', 'required' => true, 'message' => 'Please enter a username'), 'password' => array('rule' => array('confirmPassword', 'password'), 'message' => 'Passwords do not match'), 'password_confirm' => array('rule' => 'alphanumeric', 'required' => true) ); function confirmPassword($data) { $valid = false; if ($data['password'] == Security::hash(Configure::read('Security.salt') . $this->data['User']['password_confirm'])) { $valid = true; } return $valid; } } ?> ~~~ </p> <p> So, let's talk about what's in there. <ul> <li>make sure that the username is alphanumeric and has been entered</li> <li>make sure the password exists and run the custom validation function 'confirmPassword' on the data being posted in</li> <li>make sure that our confirm password field exists and is alphanumeric</li> </ul> </p> <p> The only tricky thing when I made this was figuring out how to compare the two password fields, and where to get the proper hashing from. Initially I thought that I could somehow import the Auth component in there but a quick chat with gwoo showed me how stupid that was when I could just duplicate how the component itself is hashing the password field. That's what is going in with the use of Security::hash(...). </p> <p> Hope that helps. </p> </div> </article> <article> <header> <h2><a href="/2008/01/21/going-to-cakefest/">Going To CakeFest!</a></h2> </header> <div> <p> Yes, it's been confirmed: I will be attending <a href='http://www.cakefest.org'>CakeFest</a> down in Orlando Feb. 6 to 8. I'll be giving a talk entitled "Fake It Until You Make It" about how to use the Cake console tools to speed up your development. I use the Cake console for all my CakePHP projects, since it helps me quickly create the code for models, controllers (love being able to have all those admin methods already baked in) and I hope to show those who might be a little shy of using the command line what they are missing out on. </p> <p> I'm going to be flying down Tuesday night, getting in around midnight and flying out Friday morning (it's looking like a 10:30 departure). So that's two full days at the conference, which is okay. Now, if anyone is going down there and could use a roomie to help cut down on costs let me know. </p> </div> </article> <nav> <a href="/page/95">Newer Posts</a><br /> <a href="/page/97">Older Posts</a><br /> </nav> </div> <div class="col-sm-4 sidebar"> <div class="card bg-light"> <div class="card-header">At The Keyboard</div> <div class="card-body"> <small><NAME> sharing grumpy wisdom since 2005</small> </div> </div> <div class="card bg-light sidebar-nav"> <section> <h3>Contact me</h3> <ul> <li>Email me at <EMAIL></li> <li>Find me on Twitter as <a href="https://twitter.com/grmpyprogrammer">@grmpyprogrammer</a></li> </ul> </section> <section> <h3>Sponsor me</h3> <p>If you like the work I do on <a href="https://github.com/opencfp/opencfp/">OpenCFP</a> you can become a sponsor via my <a href="https://github.com/sponsors/chartjes">GitHub sponsors</a> page. Your sponsorship allows me to spend more time on open source and less time writing books and training material.</p> </section> <section> <h3>Books</h3> <ul> <li><a href="https://leanpub.com/grumpy-guide">The Grumpy Programmer's Guide To Testing PHP Applications (currently pre-ordering)</a></li> <li><a href="https://leanpub.com/test-driven">Building Test-Driven Developers</a></li> <li><a href="https://leanpub.com/minimumviabletests">Minimum Viable Tests</a></li> <li><a href="https://leanpub.com/grumpy-phpunit">The Grumpy Programmer's PHPUnit Cookbook</a></li> </ul> </section> </div> </div> </div> </main> <footer class="container"> <span class="text-muted">&copy; 2020 At The Keyboard</span> </footer> <script src="/build/app.js"></script> </body> </html>
html
from plenum.test.bls.helper import check_bls_multi_sig_after_send from plenum.test.pool_transactions.conftest import looper, clientAndWallet1, \ client1, wallet1, client1Connected nodeCount = 4 nodes_wth_bls = 0 def test_each_node_has_bls(txnPoolNodeSet): for node in txnPoolNodeSet: assert node.bls_bft assert node.replicas[0]._bls_bft_replica def test_send_txns_no_bls(looper, txnPoolNodeSet, client1, client1Connected, wallet1): check_bls_multi_sig_after_send(looper, txnPoolNodeSet, client1, wallet1, saved_multi_sigs_count=0)
python
<filename>eki/raw/g/9971014.json {"station_g":[{"pref_cd":34,"line_cd":99710,"line_name":"広電1号線(宇品線)","station_cd":9971014,"station_name":"鷹野橋"},{"pref_cd":34,"line_cd":99712,"line_name":"広電3号線","station_cd":9971214,"station_name":"鷹野橋"},{"pref_cd":34,"line_cd":99715,"line_name":"広電7号線","station_cd":9971513,"station_name":"鷹野橋"}]}
json
Not only did Loyola and Duquesne have to contend with each other in Wednesday night’s college basketball match-up, they also had to ignore the temptation of grabbing a quick McDonald’s. Early in the second half of Duquesne’s 72-58 victory, an Uber Eats delivery person appeared to wander on to court with a bag of McDonald’s. Play was stopped while security staff ushered the man off court. The video screens at UPMC Cooper Fieldhouse later showed a happy conclusion to the story: a student in the crowd was shown cheering as he tucked into his delivery. Duquesne coach Keith Dambrot complimented the delivery person on his commitment to his craft. On Thursday, after the footage went viral and was featured on ESPN’s Sportscenter, the Pittsburgh university’s media relations team confirmed it was a staged prank. “As you would probably expect, we strive to provide a safe and enjoyable environment for guests and participants at all events on our campus. We also rely on common courtesy and the civility of those in attendance to adhere to the guidelines that are in place. Everyone keeps asking me what happened with the door dash guy on the court at tonights game. Here was my angle. “This was a prank, planned in advance, done for internet exposure. We determined that the individual was wearing a mic while someone filmed him as he walked on to the court during active play. While the incident may have seemed funny at the time, and no harm was done, we are mindful that incidents like this can put players and officials at risk.
english
<filename>scripts/select_ref_by_ANI/parse_closest_ANI.py import sys counter = 0 matrix = [] with open(sys.argv[1], 'r') as inf: for line in inf: thisline = line.strip().split("\t") matrix.append(thisline) # for i,x in enumerate(thisline): # if x == "contigs" or x == "scaffolds": # print(i + 2) # unix indexes at 1, and line starts with a blak tab # sys.exit() # raise ValueError("contigs not found in header") # just start by getting the first forward comparison (ie, the vertical part of the matrix # we assume rthere is just one entry # lets transpose this tmatrix = list(map(list, zip(*matrix))) # print(tmatrix) # get the index of the row/column with id "contigs* contigs_idx = [i for i, x in enumerate(tmatrix) if x[0].startswith("contigs") or x[0].startswith("run")][0] # print(contigs_idx) # select our headers headers = matrix[0] # note here that we have to trim the first column from the row of interest, we have one less header column than the rest of the rows, cause the first one is empty line_of_interest = sorted(zip(headers, tmatrix[contigs_idx][1:]), key=lambda x: x[1], reverse=True) # print(line_of_interest) # bam # we need to do this stupid loop thing because if there is a score tie, the contigs # entry won't neccesdarily be first. So, we go through the line, printing the first entry that doesnt start with "contigs" and isn't identical (probably an artifact) for pair in line_of_interest: # the new version appends _## to the names if not (pair[0].startswith("contigs") or pair[0].startswith("run")) and pair[1] != "1": closest_id = "_".join(pair[0].split("_")[0:-1]) closest_id_perc = pair[1] print("{0}\t{1}".format(closest_id, closest_id_perc)) sys.exit(0) # print(line_of_interest[1][0])
python
/* * Copyright 2019 <NAME> (github.com/mP1) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package walkingkooka.j2cl.maven; import walkingkooka.collect.set.Sets; import walkingkooka.text.CharSequences; import java.io.File; import java.nio.file.Path; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Predicate; /** * If the dependency source has a shade file, create an output directory with selected shaded class files combined * with the other class files changed. */ abstract class J2clStepWorkerShade extends J2clStepWorker2 { /** * Package private to limit sub classing. */ J2clStepWorkerShade() { super(); } @Override final J2clStepResult execute1(final J2clDependency artifact, final J2clStepDirectory directory, final J2clLinePrinter logger) throws Exception { J2clStepResult result = null; if (artifact.isIgnored()) { result = J2clStepResult.SKIPPED; } else { logger.indent(); { logger.printLine(J2clPath.SHADE_FILE); logger.indent(); { final Map<String, String> shadeMappings = artifact.shadeMappings(); if (!shadeMappings.isEmpty()) { this.copyAndShade(artifact, artifact.step(this.step()).output(), shadeMappings, directory.output(), logger); result = J2clStepResult.SUCCESS; } else { logger.printLine("Not found"); result = J2clStepResult.SKIPPED; } } logger.outdent(); } logger.outdent(); } return result; } abstract J2clStep step(); /** * Performs two copy passes, the first will shade any files during the copy process, the second will simply * copy the files to the destination. */ private void copyAndShade(final J2clDependency artifact, final J2clPath root, final Map<String, String> shade, final J2clPath output, final J2clLinePrinter logger) throws Exception { final BiFunction<byte[], J2clPath, byte[]> contentShader = (content, path) -> shade(content, shade); final Predicate<Path> filter = this.fileExtensionFilter(); final Set<J2clPath> files = root.gatherFiles(J2clPath.ALL_FILES.and(filter)); final Set<J2clPath> possibleFiles = Sets.sorted(); possibleFiles.addAll(files); final Set<J2clPath> nonShadedFiles = Sets.sorted(); nonShadedFiles.addAll(files); logger.indent(); { for (final Entry<String, String> mapping : shade.entrySet()) { final String find = mapping.getKey(); final String replace = mapping.getValue(); final J2clPath shadeDirectory = replace.isEmpty() ? output : output.append(replace.replace('.', File.separatorChar)); final Set<J2clPath> shadedFiles = Sets.sorted(); final J2clPath shadedRoot = root.append(find.replace('.', File.separatorChar)); // filter only files belonging to and under shade source root possibleFiles.stream() .filter(f -> f.path().startsWith(shadedRoot.path())) .forEach(shadedFiles::add); possibleFiles.removeAll(shadedFiles); // else files will be copied below if (find.equals(replace)) { logger.printLine("Skipping shade package " + CharSequences.quote(find)); } else { logger.printLine("Shading package from " + CharSequences.quote(find) + " to " + CharSequences.quote(replace)); logger.indent(); { // copy and shade java source and copy other files to output. shadeDirectory.copyFiles(shadedRoot, shadedFiles, contentShader, logger); nonShadedFiles.removeAll(shadedFiles); } logger.outdent(); } } logger.printLine("Copying other files"); logger.indent(); { // copy all other files verbatim. output.copyFiles(root, nonShadedFiles, contentShader, logger); this.postCopyAndShade(artifact, output, logger); } logger.outdent(); } logger.outdent(); } /** * A filter that only tests the file extension. It does not test if the file actually exists. */ abstract Predicate<Path> fileExtensionFilter(); /** * Reads the file and shades the source text or class file type references. */ abstract byte[] shade(final byte[] content, final Map<String, String> mappings); /** * This is invoked after and files are copy and shaded, the primary use case is copying javascript files * after java files have been shaded. */ abstract void postCopyAndShade(final J2clDependency artifact, final J2clPath output, final J2clLinePrinter logger) throws Exception; }
java
<reponame>tigeeer/pms package com.wangjx.pms.security; import com.wangjx.common.web.exception.LoginException; import com.wangjx.common.web.util.CookieUtil; import com.wangjx.pms.service.AuthenticationService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.json.JSONObject; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.stereotype.Component; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.stream.Collectors; /** * Created by IntelliJ IDEA. * User: tigeeer * Date: 2016/12/29 * Time: 16:36 */ @Component public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private static final Log logger = LogFactory.getLog(CustomUsernamePasswordAuthenticationFilter.class); private AuthenticationService authenticationService; public CustomUsernamePasswordAuthenticationFilter(AuthenticationService authenticationService) { this.authenticationService = authenticationService; } @Override protected String obtainPassword(HttpServletRequest request) { return null; } @Override protected String obtainUsername(HttpServletRequest request){ return null; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { String username, password, imageCode; if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) { try { String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator())); JSONObject parmas = new JSONObject(body); username = parmas.getString("username"); password = parmas.getString("password"); imageCode = parmas.getString("imageCode"); } catch (IOException | JSONException e) { throw new LoginException("用户名或密码错误"); } } else { username = request.getParameter("username"); password = request.getParameter("password"); imageCode = request.getParameter("imageCode"); } if (imageCode == null) { throw new LoginException("验证码错误"); } Cookie cookie = CookieUtil.get(request.getCookies(), AuthenticationFactory.COOKIE_NAME); if (cookie == null) { throw new LoginException("验证码错误"); } if (!authenticationService.verifyImageCode(imageCode, cookie.getValue())) { throw new LoginException("验证码错误"); } if (username == null || password == null) { throw new LoginException("用户名或密码错误"); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, password); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } }
java
<reponame>JeongJaeWook/python-for-text-analysis {"published": "2015-09-01T08:38:49Z", "media-type": "Blog", "title": "Zam: Umno can save gov\u2019t if Najib quits", "id": "8ac3f468-4b2e-45e0-b088-fc685204cf62", "content": "KUALA LUMPUR: A former Information Minister has urged the Umno Supreme Council, scheduled to meet on September 9, to work out an honourable exit strategy for Prime Minister Najib Abdul Razak in the wake of the massive Bersih 4 rallies over the weekend. \u201cFormer Prime Minister <NAME> himself had to go down to the streets in Kuala Lumpur to meet with the people at Bersih 4 to tell them that he only wants Najib to resign as Prime Minister, as they were demanding, but he wants the Barisan Nasional (BN) to remain the government in Putrajaya.\u201d \n \n\u201cBersih 4 means that the MCA was dead and was just waiting to be buried come the 14th General Election in 2018.\u201d \n \nZainuddin Maidin reckons that it\u2019s too late for Najib to play the politics of race and win back Malay support in order to hang onto power amidst Tunku Abdul Aziz pushing the line, too late, that the DAP was the real enemy of the Malays. \u201cHowever, it\u2019s not too late for Najib to withdraw as Prime Minister so that Umno and the government headed by it in Putrajaya can be saved.\u201d \n \n\u201cBersih 4 is the clearest indication that efforts by the late Tun Ismail, Deputy Prime Minister under Prime Minister Abdul Razak, to protect MIC and MCA have been buried by Razak\u2019s son, Najib, the current Prime Minister.\u201d \n \nThe destruction of MIC and MCA, warned Zainuddin, has opened the way for DAP to dismantle the Malay Government in Putrajaya. \u201cHow will the Malays and the non-Malays alike ever respect a leader like Najib? The Chinese, as witnessed during Bersih 4, want a new government to follow Najib\u2019s departure. They no longer want the old politics of race. This is a message to Umno to re-configure their politics based on Malays dealing with non-Malays.\u201d \n \n\u201cThe Chinese have looked at Najib as a weak leader, a coward, ever since he blamed the narrow BN win in 2013 on them and called it a Chinese tsunami. He has not repeated his allegations after being advised by his people.\u201d \n \nIn tearing into Najib, Zainuddin pointed out that no Prime Minister has showed himself as having so little dignity and this he added was evident in the RM2.6 billion donation which in Najib\u2019s own words was from a foreign power. \u201cHe has admitted in his own words to being a tool of foreigners.\u201d \n \n\u201cAt the same time, he has humiliated government servants and dragged them down through transfers and removals, arrests and investigations.\u201d \n \nZainuddin appeared to accept the NGO Bersih 2.0\u2019s figures that 500,000 people turned up in Kuala Lumpur alone for the weekend Bersih 4 rallies. The Bersih 4 rallies were held in Kuala Lumpur, Kota Kinabalu, Kuching and 70 cities worldwide.", "source": "Free Malaysia Today"}
json
<filename>src/reducers/loadingReducer.ts export type TLoadingState = boolean; const loadingReducer = ( state = false, { type }: { type: string } ): TLoadingState => { switch (type) { case "START_LOADING": return true; case "FINISH_LOADING": return false; } return state; }; export default loadingReducer;
typescript
.TrackItem { display: grid; grid-template-columns: auto minmax(120px, 1fr) auto; grid-gap: 1rem; align-items: center; width: 100%; } .TrackItem h2, .TrackItem p { font-size: 0.8125rem; margin-bottom: 0; user-select: none; } .TrackItem h2 { color: var(--text); } .TrackItem p { color: var(--text-secondary); } .TrackPlayerContainer { height: 3rem; width: 3rem; border-radius: 8px; overflow: hidden; } .TrackInformation { overflow: hidden; color: var(--text); } .TrackInformation > * { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } @media all and (min-width: 768px) { .TrackItem h2, .TrackItem p { font-size: 1rem; } .TrackPlayerContainer { height: 3.5rem; width: 3.5rem; } }
css
Thursday July 22, 2021, Online trucking startuphas raised Series E funding of $67 million. With this funding, the startup's valuation is now over $1 billion. The round was led by Tribe Capital, IFC Emerging Asia Fund, and VEF. Existing investors Wellington Management, Sands Capital, and International Finance Corporation also participated in this round of funding. The company stated that it will use these funds to further penetrate the market and launch new service offerings for its customer base. It plans to invest heavily in product and data science capabilities, with the aim of enabling more efficient freight matching for the Indian trucking ecosystem. Rajesh Yabaji, Co-Founder and CEO of BlackBuck, said, The startup stated it currently drives over 90 percent of the market share of all online trucking activity. BlackBuck digitises fleet operations for truckers and helps match trucks with relevant loads through its marketplace. The platform has close to 700,000+ truckers and over 1.2 million trucks on its platform, and it sees over $15 million in monthly transactions. BlackBuck has over 1.2 million trucks on its platform, operating pan India across 700+ districts and 1,000+ industrial hubs, enabling smooth and efficient trucking operations. Currently, the company has over 10,000 customers, including SMEs and large corporates such as Hindustan Unilever, Reliance, Coca Cola, Asian Paints, Tata, Vedanta, L&T, and Jindal. Saadia Khairi, Fund Head, IFC Emerging Asia Fund said,
english
Angelo Mathews has time and again been Sri Lanka's savior but was unable to guide them to the semi-final of the ICC World T20 2016. Mathews is gifted with the abilities of picking up wickets at crucial junctures as well, making him one of the most complete players of his side by a long margin. His ability to read the game is also commendable. Sri Lanka do possess some talented players and they will only get better with time. There is no need to press the panic button for Sri Lanka as yet. But it is necessary to groom the talent at their disposal in the right direction. For now, Mathews remains their only bright hope amidst all the gloom that surrounds Sri Lanka. Things will get tougher for Sri Lanka in the upcoming months, but it will make them only stronger and with Mathews as their leader, they will only get better. (Pramod Ananth is a reporter at CricketCountry. He has represented Karnataka table tennis under-15, and is a hardcore supporter of Liverpool FC. His Twitter handle is @pramz)
english
<gh_stars>0 .back1{ background-size: 80% ; background-repeat: no-repeat; background-position: 15rem -5rem } .pl-3, .px-3 { padding-left: 1rem !important; } .pb-2, .py-2 { padding-bottom: 0.5rem !important; } .pl-4, .dataTables_wrapper .dataTables_length, .px-4, .dataTables_wrapper .dataTables_info { padding-left: 1.5rem !important; } .mt-4, .my-4 { margin-top: 1.5rem !important; } .fw-normal { font-weight: normal; } .text-muted, input[type="radio"]:disabled + label, input[type="checkbox"]:disabled + label { color: #6c757d !important; } .pl-4, .dataTables_wrapper .dataTables_length, .px-4, .dataTables_wrapper .dataTables_info { padding-left: 1.5 rem !important; } .mt-4, .my-4 { margin-top: 1.5rem !important; } .row { display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } .border-warning-light { border-color: #fce384 !important; } .bg-warning-light { background-color: #fce384 !important; } .p-2 { padding: 0.5rem !important; } h3 { font-size: 2.75rem !important; font-weight: 500 !important; padding-top: 10px; padding-bottom: 30px; } h4 { font-size: 2.7rem !important; padding-bottom: 41px; } .list-group-item { padding:3.5rem 1rem !important; } span.d-block.mb-2.fw-bold { padding-bottom: 26px; font-size: 2.2rem; } p { font-size: 1.6rem; } a.btn.btn-link.text-primary.pl-0 { FONT-SIZE: 1.8rem; } select.form-control:not([size]):not([multiple]), .dataTables_wrapper .dataTables_length label select:not([size]):not([multiple]) { height: calc(4.25rem + 2px) !important; } small.fw-bold.mx-4 { font-size: 2.2rem; line-height: 33px; font-weight: 500 !important; } span { font-size: 2rem; } h5.mt-2 { font-size: 2rem; } .btn-link { font-size: 1.5rem; } label.col-sm-4.col-form-label.p-1.pt-2 { width: 25%; margin-left: 47px; font-size: 1.8rem; } form.form-horizontal.row-separator.d-flex.flex-wrap.w-100 { padding-top: 30px; } .form-group { padding-bottom: 37px; border-bottom: 1ps; } span.Polaris-Banner__Text { font-size: 1.2rem; } button.Polaris-Banner__Button { font-size: 1.2rem; } .planeLevel{ margin-top: 0 px ; font-weight: bold; text-align: center; } a.Polaris-Link { font-size: 1rem; font-weight: 600; } span.Polaris-Button__Text { font-size: 11px; } button.Polaris-Button { min-height: 2rem; } .Polaris-Heading { font-size: 1.2rem; } p { font-size: 1.1rem; } img.img1 { width: 95%; }
css
<filename>tokens/ethereum/mainnet/details/0xfF18DBc487b4c2E3222d115952bABfDa8BA52F5F.json<gh_stars>0 {"name":"LIFE","symbol":"LIFE","address":"0xfF18DBc487b4c2E3222d115952bABfDa8BA52F5F","decimals":18,"type":"ERC20"}
json
# Generated by Django 2.1.7 on 2019-03-26 08:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('count', '0007_wxuserstatistics_user_total'), ] operations = [ migrations.AddField( model_name='orderstatistics', name='qrpay_num', field=models.PositiveIntegerField(default=0, verbose_name='扫码支付订单数量'), ), migrations.AddField( model_name='turnoversstatistics', name='qrpay_turnovers', field=models.DecimalField(decimal_places=2, default=0, max_digits=15, verbose_name='扫码支付订单总销售额'), ), migrations.AlterField( model_name='turnoversstatistics', name='sub_turnovers', field=models.DecimalField(decimal_places=2, max_digits=15, verbose_name='订阅订单总销售额'), ), ]
python
Actor Akanksha Puri, who was recently eliminated from Bigg Boss OTT season two, recently said that her relationship with former Bigg Boss contestant and TV actor, Paras Chhabra, “broke” her so much that she never fell in love again. She also spoke about her relationship with Sidharth Shukla, where both of them “friend-zoned” each other. Akanksha said she and Sidharth never ‘hated’ each other. “The first relationship, we friend-zoned it mutually. With him (Sidharth), I maintained a good relationship till the very end. We never became enemies. He always stayed my very good friend,” the actor told Siddharth Kanan in a new interview. Paras Chhabra fell in love with Mahira Sharma on Bigg Boss (2019), and publicly called off his relationship on the show with Akanksha Puri. After the fiasco, Akanksha entered the TV reality show Mika Di Vohti as a wild card contestant. She became the winner of the show but she and Mika Singh maintained they are ‘just friends’ and are not involved romantically.
english
<div class="view__row"> <section class="recall-teaser"> <div class="recall-teaser__grid recall-teaser__grid--2col"> <div class="recall-teaser__left"> <div class="recall-teaser__tags"> <span class="tag tag--active">045-2011</span> <a class="tag tag--high - class i" href="/taxonomy/term/9">High - Class I</a> <a class="tag tag--reason" href="/taxonomy/term/16">Product Contamination</a> </div> <h3 class="recall-teaser__title"><a href="/recalls-alerts/new-jersey-firm-recalls-imported-ham-products-due-potential-listeria-contamination">New Jersey Firm Recalls Imported Ham Products Due To Potential Listeria Contamination</a></h3> <span class="recall-teaser__establishment"></span> </div> <div class="recall-teaser__right"> <div class="recall-teaser__status"> <span class="tag tag--closed">Closed</span> </div> <div class="recall-teaser__date"> Wed, 06/22/2011 - Sat, 06/02/2012 </div> </div> </div> <div class="recall-teaser__summary"><p>WASHINGTON, June 24, 2011- Specialities Agro Alimentation, a Millington, N.J. establishment, is recalling approximately 5,700 pounds of imported boneless Serrano ham products that may be contaminated with Listeria monocytogenes, the U.S. Department of Agriculture's Food Safety and Inspection Service announced today. The following products are...</p> </div> <div class="recall-teaser__products"> <h5>Impacted Products</h5> <span>Approximately 11 lb. cases of "Noel Jamón Serrano Boneless Spanish Dry-Cured Ham" and "Bloc Noel Serrano Ham," with production codes "11000481" or "11000119" on the shipping container and the label on the ham.</span> </div> <div class="recall-teaser__products"> <h5>Quantity Recovered</h5> 2,684 pounds </div> <div class="recall-teaser__language"></div> </section> </div>
html
import re import datetime from Constants import * from ..Hashes import * from StringUtils import * from TimeZoneUtils import * from ..ScheduleEvent import * from .Scraper import * def SupplementSchedule(sched, navigator, sport, league, season): supplement = ScrapeAllStarGame(sport, league, season) for key in supplement.keys(): supplementalEvent = supplement[key] if not supplementalEvent: continue eventId = int(key) if key > 100: eventId = int(key) // 100 # Find event in original schedule eligible = __find_events(sched, eventId) if eligible: foundEligible = False for eligibleEvent in eligible: isMatching = __is_matching_game(season, eligibleEvent, supplementalEvent, navigator) if isMatching: foundEligible = True __merge_events(navigator, sport, league, season, eligibleEvent, supplementalEvent, eventId) if not foundEligible: # Add Event __create_and_add_event(sched, navigator, sport, league, season, supplementalEvent, eventId) else: # Add Event __create_and_add_event(sched, navigator, sport, league, season, supplementalEvent, eventId) pass def __is_matching_game(season, eligibleEvent, supplementalEvent, navigator): if supplementalEvent.get("game") and eligibleEvent.game and supplementalEvent["game"] == eligibleEvent.game: return True homeTeam = navigator.GetTeam(season, fullName=eligibleEvent.homeTeamName, key=eligibleEvent.homeTeam) awayTeam = navigator.GetTeam(season, fullName=eligibleEvent.awayTeamName, key=eligibleEvent.awayTeam) winner = navigator.GetTeam(season, fullName=supplementalEvent.get("winner"), name=supplementalEvent.get("winner"), abbreviation=supplementalEvent.get("winner"), city=supplementalEvent.get("winner")) loser = navigator.GetTeam(season, fullName=supplementalEvent.get("loser"), name=supplementalEvent.get("loser"), abbreviation=supplementalEvent.get("loser"), city=supplementalEvent.get("loser")) if homeTeam and winner and homeTeam.key == winner.key: if awayTeam and loser and awayTeam.key == loser.key: return True if homeTeam and loser and homeTeam.key == loser.key: if awayTeam and winner and awayTeam.key == winner.key: return True return False def __create_and_add_event(sched, navigator, sport, league, season, supplementalEvent, eventId): newEvent = __convert_supplement(navigator, sport, league, season, supplementalEvent, eventId) if not newEvent.get("date"): return AddOrAugmentEvent(sched, ScheduleEvent(**newEvent), 0) pass def __find_events(sched, eventId): qualifyingEvents = [] for augmentationKey in sched.keys(): # Hashed augmentation keys for subkey in sched[augmentationKey].keys(): # Augmentation subkeys (hours) evt = sched[augmentationKey][subkey] if evt.eventindicator == eventId: qualifyingEvents.append(evt) return qualifyingEvents def __convert_supplement(navigator, sport, league, season, augmentEvent, eventId): date = augmentEvent.get("date") if isinstance(date, datetime.datetime): pass elif isinstance(date, datetime.date): pass elif isinstance(date, basestring): if IsISO8601DateWithoutTime(date): date = ParseISO8601Date(date).date() elif IsISO8601Date(date): date = ParseISO8601Date(date) augmentHomeTeam = deunicode(augmentEvent.get("homeTeam") if augmentEvent.get("homeTeam") else augmentEvent.get("loser")) homeTeamKey = None homeTeamName = None homeTeamDisplay = None if augmentHomeTeam: discoveredHomeTeam = navigator.GetTeam(season, fullName=augmentHomeTeam, name=augmentHomeTeam, abbreviation=augmentHomeTeam, city=augmentHomeTeam) if discoveredHomeTeam: homeTeamKey = discoveredHomeTeam.key homeTeamDisplay = discoveredHomeTeam.fullName else: homeTeamName = augmentHomeTeam homeTeamDisplay = augmentHomeTeam augmentAwayTeam = deunicode(augmentEvent.get("awayTeam") if augmentEvent.get("awayTeam") else augmentEvent.get("winner")) awayTeamKey = None awayTeamName = None awayTeamDisplay = None if augmentAwayTeam: discoveredAwayTeam = navigator.GetTeam(season, fullName=augmentAwayTeam, name=augmentAwayTeam, abbreviation=augmentAwayTeam, city=augmentHomeTeam) if discoveredAwayTeam: awayTeamKey = discoveredAwayTeam.key awayTeamDisplay = discoveredAwayTeam.fullName else: awayTeamName = augmentAwayTeam awayTeamDisplay = augmentAwayTeam game = augmentEvent.get("game") enhancedEvent = { "sport": sport, "league": league, "season": season, "eventindicator": eventId, "eventTitle": deunicode(augmentEvent.get("caption")), "description": augmentEvent.get("description"), "date": date, "game": game } if homeTeamKey: enhancedEvent["homeTeam"] = homeTeamKey if homeTeamName: enhancedEvent["homeTeamName"] = homeTeamName if awayTeamKey: enhancedEvent["awayTeam"] = awayTeamKey if awayTeamName: enhancedEvent["awayTeamName"] = awayTeamName vs = None if homeTeamDisplay and awayTeamDisplay: vs = "%s vs. %s" % (homeTeamDisplay, awayTeamDisplay) enhancedEvent.setdefault("vs", vs) assets = {} if augmentEvent.get("logo"): assets[ASSET_TYPE_THUMBNAIL] = [{"source": ASSET_SOURCE_WIKIPEDIA, "url": deunicode(augmentEvent["logo"])}] pass if assets: enhancedEvent.setdefault("assets", assets) networks = [] if augmentEvent.get("networks"): for network in augmentEvent["networks"]: networks.append(deunicode(network)) if networks: enhancedEvent.setdefault("networks", networks) gameKeyPart = (".%s" % game) if game else "" enhancedEvent["identity"] = {"WikipediaID": "%s.%s.%s%s" % (league, season, eventId, gameKeyPart)} return enhancedEvent def __merge_events(navigator, sport, league, season, evt, augmentEvent, eventId): enhancedEvent = __convert_supplement(navigator, sport, league, season, augmentEvent, eventId) evt.augment(**enhancedEvent) if enhancedEvent.get("eventTitle") and evt.eventTitle and evt.eventTitle == evt.eventTitle.upper(): # Existing event title is from ESPN API. Overwrite it. evt.eventTitle = enhancedEvent["eventTitle"] pass
python
The windows may not retract properly when they detect an obstruction while closing. Tesla is recalling just over 1 million of its vehicles because their windows may pinch a person's fingers when they roll up. The window automatic reversal system may not react correctly after detecting an obstruction, according to documents posted Sept. 19 on the National Highway Traffic Safety Administration's website. This issue could cause a window to pinch a person's fingers if they're on top of a window as it rises, "increasing the risk of injury," the NHTSA said. The recall covers model years 2017-2022 for Model 3 , 2020-2021 for Model Y and 2021-2022 for Model S and Model X vehicles. Tesla will fix the issue with a free over-the-air software update. Owners will be notified by mail in mid-November, but can also contact Tesla for assistance at 877-798-3752.
english
import { Metrics as DataModel } from '../DataModel/Metrics'; import { MetricsValue as Entity } from '../../Entity/MetricsValue'; import { MetricsType } from '../../Entity/MetricsType'; export class MetricsValue { to(dataModel: DataModel) { return new Entity(MetricsType.castAs(dataModel.type), dataModel.value); } }
typescript
<gh_stars>1-10 package org.hbird.core.commons.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.util.BitSet; import org.hbird.core.commons.util.exceptions.BitSetOperationException; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BitSetUtilityTest { private static final Logger LOG = LoggerFactory.getLogger(BitSetUtilityTest.class); private static final String BIT_STR_BE_123 = "01111011"; private static BitSet BITSET_BE_123; private static final int BITSET_BE_123_DEC_BYTE_REP = 123; private static final byte[] BYTES_BE_123 = new byte[] { 123 }; private static final String BIT_STR_LE_123 = "1101111"; private static BitSet BITSET_LE_123; private static final String BIT_STR_BE_999 = "01111100111"; private static BitSet BITSET_BE_999; private static final String BIT_STR_LE_999 = "11100111110"; private static BitSet BITSET_LE_999; private static final String BIT_STR_BE_69BIT = "110000000000000000000000000000000000000000000000000000000000000000001"; private static BitSet BITSET_BE_69BIT; private static final String BIT_STR_FLOAT32_NEG1658_035 = "11000100110011110100000100011111"; private static BitSet BITSET_FLOAT32_NEG1658_035; private static final String BIT_STR_FLOAT64_89433_23532268 = "0100000011110101110101011001001111000011111000011011011011101010"; private static BitSet BITSET_FLOAT64_89433_23532268; private final static String MULTI_BYTE_STRING = "00000000000100000000000000000000000000000000000000000000000000011110011101110100000000000000000000011110"; private final static byte[] MULTI_BYTE_ARRAY = new byte[] { 0, 16, 0, 0, 0, 0, 0, 1, -25, 116, 0, 0, 30 }; private static BitSet MULTI_BYTE_BITSET; @BeforeClass public static void setUpBeforeClass() throws Exception { LOG.info("############ Setting up before all tests #################"); BITSET_BE_123 = new BitSet(BIT_STR_BE_123.length()); BITSET_BE_123.set(1, 5); BITSET_BE_123.set(6, 8); String expected = BitSetUtility.bitSetToBinaryString(BITSET_BE_123, true); assertEquals(expected, BIT_STR_BE_123); BITSET_LE_123 = new BitSet(BIT_STR_LE_123.length()); BITSET_LE_123.set(0, 2); BITSET_LE_123.set(3, 7); assertEquals(BIT_STR_LE_123, BitSetUtility.bitSetToBinaryString(BITSET_LE_123, true)); BITSET_BE_999 = new BitSet(BIT_STR_BE_999.length()); BITSET_BE_999.set(1, 6); BITSET_BE_999.set(8, 11); assertEquals(BIT_STR_BE_999, BitSetUtility.bitSetToBinaryString(BITSET_BE_999, true)); BITSET_LE_999 = new BitSet(BIT_STR_LE_999.length()); BITSET_LE_999.set(0, 3); BITSET_LE_999.set(5, 10); assertEquals(BIT_STR_LE_999, BitSetUtility.bitSetToBinaryString(BITSET_LE_999, BIT_STR_LE_999.length())); BITSET_BE_69BIT = new BitSet(BIT_STR_BE_69BIT.length()); BITSET_BE_69BIT.set(0, 2); BITSET_BE_69BIT.set(68); assertEquals(BIT_STR_BE_69BIT, BitSetUtility.bitSetToBinaryString(BITSET_BE_69BIT, BIT_STR_BE_69BIT.length())); BITSET_FLOAT32_NEG1658_035 = new BitSet(BIT_STR_FLOAT32_NEG1658_035.length()); BITSET_FLOAT32_NEG1658_035 = BitSetUtility.stringToBitSet(BIT_STR_FLOAT32_NEG1658_035, true, true); assertEquals(BIT_STR_FLOAT32_NEG1658_035, BitSetUtility.bitSetToBinaryString(BITSET_FLOAT32_NEG1658_035, Float.SIZE)); BITSET_FLOAT64_89433_23532268 = new BitSet(BIT_STR_FLOAT64_89433_23532268.length()); BITSET_FLOAT64_89433_23532268 = BitSetUtility.stringToBitSet(BIT_STR_FLOAT64_89433_23532268, true, true); assertEquals(BIT_STR_FLOAT64_89433_23532268, BitSetUtility.bitSetToBinaryString(BITSET_FLOAT64_89433_23532268, Double.SIZE)); MULTI_BYTE_BITSET = new BitSet(MULTI_BYTE_STRING.length()); MULTI_BYTE_BITSET = BitSetUtility.stringToBitSet(MULTI_BYTE_STRING, true, true); assertEquals(MULTI_BYTE_STRING, BitSetUtility.bitSetToBinaryString(MULTI_BYTE_BITSET, MULTI_BYTE_STRING.length())); } @SuppressWarnings("static-method") @Test public final void testStringToBitSetBE69BIT() throws BitSetOperationException { LOG.info("############ Starting test #################"); final BitSet actual = BitSetUtility.stringToBitSet(BIT_STR_BE_69BIT, true, true); assertEquals(BITSET_BE_69BIT, actual); } @SuppressWarnings("static-method") @Test public final void testStringToBitSetBE123() throws BitSetOperationException { final BitSet actual = BitSetUtility.stringToBitSet(BIT_STR_BE_123, true, true); assertEquals(BITSET_BE_123, actual); } @SuppressWarnings("static-method") @Test public final void testStringToBitSetLE123() throws BitSetOperationException { final BitSet actual = BitSetUtility.stringToBitSet(BIT_STR_LE_123, false, false); assertEquals(BITSET_LE_123, actual); } @SuppressWarnings("static-method") @Test public final void testStringToBitSetBE999() throws BitSetOperationException { LOG.debug("############ Starting test #################"); final BitSet actual = BitSetUtility.stringToBitSet(BIT_STR_BE_999, true, true); assertEquals(BITSET_BE_999, actual); } @SuppressWarnings("static-method") @Test public final void testStringToBitSetLE999() throws BitSetOperationException { LOG.debug("############ Starting test #################"); final BitSet actual = BitSetUtility.stringToBitSet(BIT_STR_LE_999, false, false); assertEquals(BITSET_LE_999, actual); } @SuppressWarnings("static-method") @Test public final void testBitSetToBinaryStringFixedSize() { LOG.debug("############ Starting test #################"); String actual = BitSetUtility.bitSetToBinaryString(BITSET_BE_123, 1); assertEquals(BIT_STR_BE_123.subSequence(0, 1), actual); actual = BitSetUtility.bitSetToBinaryString(BITSET_BE_123, 5); assertEquals(BIT_STR_BE_123.subSequence(0, 5), actual); actual = BitSetUtility.bitSetToBinaryString(BITSET_BE_123, 8); assertEquals(BIT_STR_BE_123, actual); } @SuppressWarnings("static-method") @Test public final void testPadStringFromTheBack() { LOG.debug("############ Starting test #################"); final String actual = BitSetUtility.padStringFromTheBack(BIT_STR_BE_123, 25); assertEquals(25, actual.length()); final StringBuilder expected = new StringBuilder(); expected.append(BIT_STR_BE_123); expected.append("00000000000000000"); assertEquals(expected.toString(), actual); } @SuppressWarnings("static-method") @Test public final void testStringLittleToBigEndian() throws BitSetOperationException { LOG.debug("############ Starting test #################"); final BitSet actual = BitSetUtility.stringToBitSet(BIT_STR_LE_999, false, true); assertEquals(BITSET_BE_999, actual); } @SuppressWarnings("static-method") @Test public final void testStringBigToLittleEndian() throws BitSetOperationException { LOG.debug("############ Starting test #################"); final BitSet actual = BitSetUtility.stringToBitSet(BIT_STR_BE_999, true, false); assertEquals(BITSET_LE_999, actual); } @SuppressWarnings("static-method") @Test(expected = BitSetOperationException.class) public final void testInvalidBitString() throws BitSetOperationException { LOG.debug("############ Starting test #################"); BitSetUtility.stringToBitSet("16783287467823", false, true); } @SuppressWarnings("static-method") @Test public final void testBitSetToBinaryStringNotLogicalSize() { LOG.debug("############ Starting test #################"); final String actual = BitSetUtility.bitSetToBinaryString(BITSET_BE_123, false); final String expected = "0111101100000000000000000000000000000000000000000000000000000000"; assertEquals(expected, actual); } @SuppressWarnings("static-method") @Test public final void toFloat() { LOG.debug("############ Starting test #################"); final float actual = BitSetUtility.toFloat(BITSET_FLOAT32_NEG1658_035); // TODO Does anybody know what an appropriate delta is? assertEquals(-1658.035f, actual, 0.000000000000000001); } @SuppressWarnings("static-method") @Test public final void toDouble() { LOG.debug("############ Starting test #################"); final double actual = BitSetUtility.toDouble(BITSET_FLOAT64_89433_23532268); // TODO Does anybody know what an appropriate delta is? assertEquals(89433.23532268d, actual, 0.000000000000000001); } @SuppressWarnings("static-method") @Test public final void toByteArraySingleByteRequired() { LOG.debug("############ Starting test #################"); final byte[] actual = BitSetUtility.toByteArray(BITSET_BE_123, 8); final byte[] expected = new byte[] { BITSET_BE_123_DEC_BYTE_REP }; assertArrayEquals(expected, actual); } @SuppressWarnings("static-method") @Test public final void toByteArrayTwoBytesRequired() { LOG.debug("############ Starting test #################"); final byte[] actual = BitSetUtility.toByteArray(BITSET_BE_999, 11); final byte[] expected = new byte[] { 0x3, (byte) 0xE7 }; assertArrayEquals(expected, actual); } @SuppressWarnings("static-method") @Test public final void fromByteArray() { LOG.debug("############ Starting test #################"); final BitSet actual = BitSetUtility.fromByteArray(BYTES_BE_123); assertEquals(BITSET_BE_123, actual); } @SuppressWarnings("static-method") @Test public final void fromByteArrayMultiByte() { LOG.debug("############ Starting test #################"); final BitSet actual = BitSetUtility.fromByteArray(MULTI_BYTE_ARRAY); LOG.debug(BitSetUtility.binDump(actual)); assertEquals(MULTI_BYTE_BITSET, actual); } }
java
<reponame>LaudateCorpus1/oci-typescript-sdk /** * Core Services API * Use the Core Services API to manage resources such as virtual cloud networks (VCNs), compute instances, and block storage volumes. For more information, see the console documentation for the [Networking](/iaas/Content/Network/Concepts/overview.htm), [Compute](/iaas/Content/Compute/Concepts/computeoverview.htm), and [Block Volume](/iaas/Content/Block/Concepts/overview.htm) services. * OpenAPI spec version: 20160918 * * * NOTE: This class is auto generated by OracleSDKGenerator. * Do not edit the class manually. * * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ import * as model from "../model"; import common = require("oci-common"); export interface UpdateDrgAttachmentDetails { /** * A user-friendly name. Does not have to be unique, and it's changeable. * Avoid entering confidential information. * */ "displayName"?: string; /** * The [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the DRG route table that is assigned to this attachment. * <p> The DRG route table manages traffic inside the DRG. * <p> You can't remove a DRG route table from a DRG attachment, but you can reassign which * DRG route table it uses. * */ "drgRouteTableId"?: string; "networkDetails"?: model.VcnDrgAttachmentNetworkUpdateDetails; /** * Defined tags for this resource. Each key is predefined and scoped to a * namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). * <p> Example: `{\"Operations\": {\"CostCenter\": \"42\"}}` * */ "definedTags"?: { [key: string]: { [key: string]: any } }; /** * Free-form tags for this resource. Each tag is a simple key-value pair with no * predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). * <p> Example: `{\"Department\": \"Finance\"}` * */ "freeformTags"?: { [key: string]: string }; /** * The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the export route distribution used to specify how routes in the assigned DRG route table * are advertised out through the attachment. * If this value is null, no routes are advertised through this attachment. * */ "exportDrgRouteDistributionId"?: string; /** * This is the [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the route table that is used to route the traffic as it enters a VCN through this attachment. * <p> For information about why you would associate a route table with a DRG attachment, see: * <p> * [Transit Routing: Access to Multiple VCNs in Same Region](https://docs.cloud.oracle.com/iaas/Content/Network/Tasks/transitrouting.htm) * * [Transit Routing: Private Access to Oracle Services](https://docs.cloud.oracle.com/iaas/Content/Network/Tasks/transitroutingoracleservices.htm) * */ "routeTableId"?: string; } export namespace UpdateDrgAttachmentDetails { export function getJsonObj(obj: UpdateDrgAttachmentDetails): object { const jsonObj = { ...obj, ...{ "networkDetails": obj.networkDetails ? model.DrgAttachmentNetworkUpdateDetails.getJsonObj(obj.networkDetails) : undefined } }; return jsonObj; } export function getDeserializedJsonObj(obj: UpdateDrgAttachmentDetails): object { const jsonObj = { ...obj, ...{ "networkDetails": obj.networkDetails ? model.DrgAttachmentNetworkUpdateDetails.getDeserializedJsonObj(obj.networkDetails) : undefined } }; return jsonObj; } }
typescript
He suffered a run of low scores, however, managing 91 runs in three Tests on the 2014-15 tour of South Africa and 92 runs in a similar three-Test series during England’s tour of the Caribbean last April. In the two series prior, he compiled 270 runs in two Tests against Bangladesh without being dismissed and averaged 48 in three Tests against touring New Zealand. Despite the dip in form, Chanderpaul believed he still had more Tests runs in him. Chanderpaul, who made his debut as a 19-year-old 22 years ago against England in his hometown Georgetown, said his career had been a rewarding one. “It probably could have been better in some areas but my career has been great since I was a school kid. Then there were things you expect from certain people but sometimes you have to put things behind and look ahead,” he noted. “I don’t know (if there are any regrets). I have always played the game with passion. I have enjoyed it. I don’t know if I have any regrets,”said Chanderpaul. Chanderpaul is here to play in the inaugural Masters Champions League where he will turn out for Gemini Arabians. Lara is also participating in the tournament as captain of Leon Lions, with past stars such as Australian Adam Gilchrist, Muttiah Muralitharan and Jacques Kallis also involved. “It’s been great. All these guys from different part of the world are here and most of them are legends, some really good players and I am happy to play alongside them,” said Chanderpaul. This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful. Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings. If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.
english
#[cfg(feature = "timely-next")] use crate::dataflow::reachability::TrackerEvent; use crate::dataflow::{operators::CrossbeamPusher, PROGRAM_NS_GRANULARITY}; use anyhow::{Context, Result}; use crossbeam_channel::Sender; use ddshow_sink::{EventWriter, DIFFERENTIAL_ARRANGEMENT_LOG_FILE, TIMELY_LOG_FILE}; use ddshow_types::{ differential_logging::DifferentialEvent, progress_logging::TimelyProgressEvent, timely_logging::TimelyEvent, WorkerId, }; use differential_dataflow::{ difference::Semigroup, lattice::Lattice, operators::{ arrange::{Arranged, TraceAgent}, Consolidate, }, trace::implementations::ord::{OrdKeySpine, OrdValSpine}, Collection, ExchangeData, Hashable, }; use indicatif::ProgressBar; use std::{ convert::TryFrom, fs::{self, File}, io::BufWriter, num::Wrapping, ops::Range, path::{Path, PathBuf}, time::{Duration, SystemTime}, }; use timely::dataflow::{ operators::{capture::Event, Capture, Probe}, ProbeHandle, Scope, ScopeParent, Stream, }; pub(crate) type Diff = isize; pub(crate) type Time = Duration; pub(crate) type ArrangedVal<S, K, V, D = Diff> = Arranged<S, TraceAgent<OrdValSpine<K, V, <S as ScopeParent>::Timestamp, D>>>; pub(crate) type ArrangedKey<S, K, D = Diff> = Arranged<S, TraceAgent<OrdKeySpine<K, <S as ScopeParent>::Timestamp, D>>>; pub type TimelyLogBundle<Id = WorkerId, Event = TimelyEvent> = (Time, Id, Event); pub type DifferentialLogBundle<Id = WorkerId, Event = DifferentialEvent> = (Time, Id, Event); pub type ProgressLogBundle<Id = WorkerId> = (Time, Id, TimelyProgressEvent); #[cfg(feature = "timely-next")] pub type ReachabilityLogBundle<Id = WorkerId> = (Time, Id, TrackerEvent); /// Puts timestamps into non-overlapping buckets that contain /// the timestamps from `last_bucket..PROGRAM_NS_GRANULARITY` /// to reduce the load on timely pub(crate) fn granulate(&time: &Duration) -> Duration { let timestamp = time.as_nanos(); let window_idx = (timestamp / PROGRAM_NS_GRANULARITY) + 1; let minted = Duration::from_nanos((window_idx * PROGRAM_NS_GRANULARITY) as u64); debug_assert_eq!( u64::try_from(window_idx * PROGRAM_NS_GRANULARITY).map(|res| res as u128), Ok(window_idx * PROGRAM_NS_GRANULARITY), ); debug_assert!(time <= minted); minted } #[allow(clippy::type_complexity)] pub(super) fn channel_sink<S, D, R>( collection: &Collection<S, D, R>, probe: &mut ProbeHandle<S::Timestamp>, channel: Sender<Event<S::Timestamp, (D, S::Timestamp, R)>>, should_consolidate: bool, ) where S: Scope, S::Timestamp: Lattice, D: ExchangeData + Hashable, R: Semigroup + ExchangeData, { let collection = if should_consolidate { collection.consolidate() } else { collection.clone() }; collection .inner .probe_with(probe) .capture_into(CrossbeamPusher::new(channel)); tracing::debug!( "installed channel sink on worker {}", collection.scope().index(), ); } /// Store all timely and differential events to disk pub(super) fn logging_event_sink<S>( save_logs: &Path, scope: &mut S, timely_stream: &Stream<S, (Duration, WorkerId, TimelyEvent)>, probe: &mut ProbeHandle<Duration>, differential_stream: Option<&Stream<S, (Duration, WorkerId, DifferentialEvent)>>, ) -> Result<()> where S: Scope<Timestamp = Duration>, { // Create the directory for log files to go to fs::create_dir_all(&save_logs).context("failed to create `--save-logs` directory")?; let timely_path = log_file_path(TIMELY_LOG_FILE, save_logs, scope.index()); tracing::debug!( "installing timely file sink on worker {} pointed at {}", scope.index(), timely_path.display(), ); let timely_file = BufWriter::new( File::create(timely_path).context("failed to create `--save-logs` timely file")?, ); timely_stream .probe_with(probe) .capture_into(EventWriter::new(timely_file)); if let Some(differential_stream) = differential_stream { let differential_path = log_file_path(DIFFERENTIAL_ARRANGEMENT_LOG_FILE, save_logs, scope.index()); tracing::debug!( "installing differential file sink on worker {} pointed at {}", scope.index(), differential_path.display(), ); let differential_file = BufWriter::new( File::create(differential_path) .context("failed to create `--save-logs` differential file")?, ); differential_stream .probe_with(probe) .capture_into(EventWriter::new(differential_file)); } Ok(()) } /// Constructs the path to a logging file for the given worker pub(super) fn log_file_path(file_prefix: &str, dir: &Path, worker_id: usize) -> PathBuf { dir.join(format!( "{}.replay-worker-{}.ddshow", file_prefix, worker_id, )) } pub(crate) fn set_steady_tick(progress: &ProgressBar, delta: usize) { let time = SystemTime::UNIX_EPOCH.elapsed().map_or_else( |err| { tracing::error!("failed to get system time for seeding generator: {:?}", err); Pcg64::new(delta as u128).next_u64() as u128 }, |time| time.as_nanos(), ); let mut rng = Pcg64::new(time); rng.advance(delta as u128); progress.enable_steady_tick(rng.gen_range(50..500)); } pub(crate) struct Pcg64 { state: Wrapping<u128>, increment: Wrapping<u128>, } impl Pcg64 { const MULTIPLIER: Wrapping<u128> = Wrapping(6_364_136_223_846_793_005); const DEFAULT_INCREMENT: Wrapping<u128> = Wrapping(1_442_695_040_888_963_407); pub fn new(seed: u128) -> Self { Self::with_increment(Wrapping(seed), Self::DEFAULT_INCREMENT) } pub fn with_increment(seed: Wrapping<u128>, mut increment: Wrapping<u128>) -> Self { if increment % Wrapping(2) != Wrapping(0) { increment += Wrapping(1); } let mut gen = Self { state: seed + increment, increment, }; gen.next_u64(); gen } /// Advances the generator `delta` steps in `log(delta)` time pub fn advance(&mut self, delta: u128) { self.state = self.jump_lcg128(delta); } fn jump_lcg128(&self, mut delta: u128) -> Wrapping<u128> { let mut current_multiplier = Self::MULTIPLIER; let mut current_plus = self.increment; let mut accumulated_multiplier = Wrapping(1); let mut accumulated_plus = Wrapping(0); while delta > 0 { if (delta & 1) > 0 { accumulated_multiplier *= current_multiplier; accumulated_plus = (accumulated_plus * current_multiplier) + current_plus; } current_plus = (current_multiplier + Wrapping(1)) * current_plus; current_multiplier *= current_multiplier; delta /= 2; } (accumulated_multiplier * self.state) + accumulated_plus } pub fn next_u64(&mut self) -> u64 { let x = self.state; let count = (x >> 122).0 as u32; self.state = x * Self::MULTIPLIER + self.increment; let x = (x ^ (x >> 64)).0 as u64; x.rotate_right(count) } pub fn gen_range(&mut self, range: Range<u64>) -> u64 { range.start + self.next_u64() % (range.end - range.start) } }
rust
<reponame>Ryebread4/Rustionary<filename>en/fovilla.json {"word":"fovilla","definition":"One of the fine granules contained in the protoplasm of a pollen grain."}
json
var bLoginTriggered = false; $(document).ready(function() { $('button.stop, a.stop, input.stop, [type="submit"].stop, select.stop').click(function(e) { e.preventDefault(); e.returnValue = false; $("select.stop").prop("disabled", true); $(this).blur(); return false; }); if (checkCookie('prev_latlng') == false && oUser == false && oSegments[1] != 'register') { $(window).on('scroll load', function() { if (($('#login_modal').data('bs.modal') || {}).isShown) { return false; } else { $('#check_loc_modal').modal('show'); } }); $('#login_modal').on('hidden.bs.modal', function () { if (checkCookie('prev_latlng') == false) { $('#check_loc_modal').modal('show'); } else { reloadState(); } }); } $('[js-event="farmMenuTrigger"]').click(function(e) { e.stopPropagation(); $(this).toggleClass('active'); $('[js-event="navbarFarmMenuContainer"]').toggleClass('active'); }); if ($('.g-recaptcha').length) downloadJSAtOnload(); if ($('.toggle-password').length) { $('.toggle-password').bind('click', function (e) { var password = $(this).parent().find('input').get(0); const type = password.getAttribute('type') === 'password' ? 'text' : 'password'; password.setAttribute('type', type); $(this).removeClass('bi-eye bi-eye-slash'); if (type == 'text') { $(this).addClass('bi-eye'); } else { $(this).addClass('bi-eye-slash'); } }); } if ($('a[loader="1"]').length) { $('a[loader="1"]').bind('click', function(e) { e.stopPropagation(); var oThis = $(this), origText = oThis.html(); oThis.addClass('stop').html('<span class="spinner-border spinner-border-sm"></span> '+origText); }); } }); window.onpopstate = function(e) { if (mobileAndTabletCheck()) { if (e.target.location.hash != '#m' && bLoginTriggered == false) { if ($('.modal').length) $('.modal').modal('hide'); } else if (bLoginTriggered) { setTimeout(function() { window.location.reload(true); }, 1); } } }; function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function checkCookie(cname) { var cookie = getCookie(cname); if (cookie != "") { return true; } else { return false; } } function modalCallbacks() { if (window.location.hash == '#m') window.history.replaceState({}, document.title, '/'); $('div.modal').on('show.bs.modal', function(e) { if (mobileAndTabletCheck()) window.location.hash = 'm'; switch (e.target.id) { case 'farm_location_modal': // console.log($(e.relatedTarget)); var input = $('<input />', {type: 'hidden', name: 'loc_input', value: '#'+e.relatedTarget.id}); $(e.target).find('form').prepend(input); if (map != undefined) { $('#shipping-id').remove(); var dataLocation = $(e.relatedTarget).next('input:hidden').val(); if (dataLocation.length) { var oData = $.parseJSON(dataLocation), oThisLatLong = {lat: parseFloat(oData.lat), lng: parseFloat(oData.lng)}; // console.log(oData); resetMap(oThisLatLong); $('#address_1').val(oData.address_1); } else { resetMap({lat: parseFloat(oUser.lat), lng: parseFloat(oUser.lng)}); $('#address_1').val(''); setTimeout(function() { $('#address_2').val(''); }, 500); } setTimeout(function() { google.maps.event.trigger(map, "contextmenu"); }, 1000); } break; case 'media_modal': if ($(e.relatedTarget).data('change-ui').length) { var value = $(e.relatedTarget).data('change-ui'); $(e.target).find('form').prepend($('<input />', {type: 'hidden', name: 'ui', value: value})); var field = $(e.relatedTarget).data('field'); $(e.target).find('form').prepend($('<input />', {type: 'hidden', name: 'col', value: field})); } break; case 'ff_invoice_modal': // console.log($(e.relatedTarget).data('basket-merge-id')); var merge_id = $(e.relatedTarget).data('basket-merge-id'); $(e.target).find('p[js-data="loader"]').removeClass('hide'); simpleAjax('api/set_invoice_html/invoice_middle_body', {table:'baskets_merge', data:{id: merge_id}, row: true, identifier:merge_id}, $(e.relatedTarget)); break; case 'check_loc_modal': var input = $('#check-place').get(0); // input.focus(); var i = setInterval(function() { if (typeof google != 'undefined') { clearInterval(i); var autocomplete = new google.maps.places.Autocomplete(input, { componentRestrictions: {country: "ph"}, }); var execLocation = function(latlng) { var geocoder = new google.maps.Geocoder(); geocoder.geocode({ latLng: latlng }, function(results, status) { // console.log(results); if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { var arVal = []; var city = null; var c, lc, component; for (var r = 0, rl = results.length; r < rl; r += 1) { var result = results[r]; if (!city && result.types[0] === 'locality') { for (c = 0, lc = result.address_components.length; c < lc; c += 1) { component = result.address_components[c]; if (component.types[0] === 'locality') { city = component.long_name; arVal.push(city); break; } } } if (city) break; } if (city) { $('#check-place').prop('value', city).val(city); // console.log("City: " + city, arVal); var oDataLatLng = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng(), city: city, }; simpleAjax('api/fetch_coordinates', oDataLatLng); } } } }); } google.maps.event.addListener(autocomplete, 'place_changed', function() { var place = autocomplete.getPlace(); // console.log(place.geometry.location.lat(), place.geometry.location.lng()); execLocation(place.geometry.location); }); var oGeoLatLong = oLatLong; // console.log(oGeoLatLong); $('#my-curr-loc').tooltip().focus(); $('#my-curr-loc').off('click').on('click', function() { execLocation(oGeoLatLong); }); } }, 1000); break; case 'login_modal': $('.ask-sign-in').click(); $('form.sign-in-form').bind('submit', function(e) { if ($(this).find('.error').length == 0) { bLoginTriggered = true; } }); break; case 'reply_modal': var oReply = JSON.parse($(e.relatedTarget).attr('data-reply')); var oFeedback = JSON.parse($(e.relatedTarget).attr('data-feedback')); // console.log(oReply, oFeedback); if (Object.keys(oFeedback).length) { // $('#buyer_photo').attr('src', oFeedback.profile.photo_url); $('#buyer_fullname').text(oFeedback.profile.firstname+' '+oFeedback.profile.lastname); // $('#buyer_date').text($.format.date(oFeedback.added, "- ddd, MMMM d, yyyy | hh:ss p")); timeLapseString(oFeedback.added, function(sDate) { $('#buyer_date').text(sDate); }) $('#buyer_comments').text(oFeedback.content); $('#to_id').val(oFeedback.from_id); $('#under').val(oFeedback.id); $('#page_id').val(oFeedback.page_id); $('#entity_id').val(oFeedback.entity_id); } if (oReply == false) { $('#reply_box').removeClass('hide'); $('#seller_content').addClass('hide'); $('#seller_buyer_date').text(''); $('#seller_comments').text(''); } else { if (oReply == true) { $('#reply_modalLabel').text('Last Response:'); $('#reply_box').addClass('hide'); $('#seller_content').addClass('hide'); $('#buyer_fullname').text(oFeedback.farm.name); $('#is_seller').text((oFeedback.from_id == oUser.id ? '(You)' : '')); } else { /*already replied*/ $('#reply_modalLabel').text('Last Conversations:'); $('#reply_box').addClass('hide'); $('#seller_content').removeClass('hide'); $('#seller_content').find('img.media-object').attr('src', oReply.farm.profile_pic); // $('#seller_buyer_date').text($.format.date(oReply.added, "- ddd, MMMM d, yyyy | hh:ss p")); $('#seller_farm_name').text(oReply.farm.name); timeLapseString(oReply.added, function(sDate) { $('#seller_buyer_date').text(sDate); }); $('#seller_comments').text(oReply.content); $('#is_seller').text((oReply.from_id == oUser.id ? '(You)' : '')); } } break; case 'ff_received_modal': // console.log($(e.relatedTarget).data('basket-merge-id')); var merge_id = $(e.relatedTarget).data('basket-merge-id'); $(e.target).find('p[js-data="loader"]').removeClass('hide'); simpleAjax('api/set_invoice_html/invoice_middle_body', {table:'baskets_merge', data:{id: merge_id}, row: true, identifier:merge_id}, $(e.relatedTarget)); break; } }).on('hide.bs.modal', function(e) { // console.log(e); if (window.location.hash == '#m') window.history.replaceState({}, document.title, '/'); switch (e.target.id) { case 'farm_location_modal': $(e.target).find('form input[name="loc_input"]').remove(); break; case 'media_modal': $(e.target).find('form input[name="ui"]').remove(); $(e.target).find('form input[name="col"]').remove(); var html = $(e.target).find('form .preview_images_list').html(); $(e.target).find('form .preview_images_list').html(''); html = $(html).find('input:radio').attr('name', 'selected').removeAttr('data-upload').removeAttr('checked').parent('li'); $(html).find('input:radio').each(function(i, elem) { var oThis = $(elem); elem.value = oThis.data('url-path'); }); $(e.target).find('form .preview_images_selected').append(html); $(e.target).find('form').find('input:file').prop('value', '').val('');; break; case 'ff_invoice_modal': $(e.target).find('p[js-data="loader"]').addClass('hide'); $(e.target).find('[js-element="invoice-body"]').html(''); break; case 'login_modal': setTimeout(function() { $('#login_body').find('.login-with-social').removeClass('hide'); $('#login_body').find('.fb-login-panel').addClass('hide'); $('#login_body').find('.fb-signing-in').addClass('hide'); $('#login_body').find('.invalid-fb-email').addClass('hide'); $('#login_body').find('.ask-sign-in').click(); $('#login_body').find('[name="email_address"]').removeClass('error'); $('#login_body').find('[name="email"]').removeClass('error'); $('#login_body').find('[name="password"]').removeClass('error').val(''); $('#login_body').find('[name="password"]').parents('form').find('.toggle-password').removeClass('invalid'); if ($('#login_body').find('[name="password"]').attr('type') === 'text') { $('#login_body').find('[name="password"]').parents('form').find('.toggle-password').click(); } }, 1000); break; case 'reply_modal': $('#reply_modal').find('form [name][required]').removeClass('error'); $('#seller_reply').val(''); break; } }); } function loadMore(ui, method) { if (ui != undefined && ui.length && ui.data('url') != undefined) { ui.on('click', function() { var ids = []; if ($(ui.data('items')).length) { $(ui.data('items')).map(function(i, elem) { ids.push($(elem).data('id')); }); } // console.log(ids); $.ajax({ url: ui.data('url'), type: 'post', data: {'not_ids': ids}, dataType: 'json', success: function(data) { // console.log(data); if (data.success) { $(ui.data('items')).parent().append(data.html); } if ($(ui.data('items')).length == data.count) ui.hide(); } }); }); } } var reloadState = function(data) { // window.location.reload(true); setTimeout(function() { /*$.ajax({ url: '/', success: function(html) { var new_document = document.open('text/html', 'replace'); new_document.write(html); new_document.close(); } });*/ window.location.reload(true); }, 300); } // Add a script element as a child of the body var downloadJSAtOnload = function() { var element = document.createElement("script"); element.src = "https://www.google.com/recaptcha/api.js?onload=runReCaptchaOnLoad&render=explicit"; document.body.appendChild(element); } window.runReCaptchaOnLoad = function() { $(document).find('form').each(function() { var form = $(this); runGRecaptchaChallenge(form.find('.g-recaptcha'), form); }); // runGRecaptchaChallenge($('.login-with-social .g-recaptcha')); }; var fbWidgetId; var runGRecaptchaChallenge = function(recaptcha, form) { if (recaptcha != undefined) { if (recaptcha.length) { if (recaptcha.data('size') === 'invisible') { if (form != undefined) { var widgetId = grecaptcha.render(recaptcha.get(0), { callback: function(challenge) { // console.log(challenge); if ($.trim(challenge).length) { form.off('submit').submit(); } } }); form.bind('submit', function(e) { grecaptcha.reset(); if (form.find('[name]').hasClass('error') == false) { grecaptcha.execute(widgetId); } }); } else { fbWidgetId = grecaptcha.render(recaptcha.get(0)); } } else { grecaptcha.render(recaptcha.get(0)); } } } } var timeZoneFormatDate = function(sDate, options) { if (options == undefined) { options = { timeZone: TIMEZONE, weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' }; } var oObject = new Date(sDate), sNewDate = oObject.toLocaleString('en-US', options); return sNewDate; } var timeLapseString = function(sDate, callback) { var sNewDate = timeZoneFormatDate(sDate); var oSettings = { url: 'support/helper/time_elapsed_string', type: 'post', data: {'data': sDate}, dataType: 'json', success: function(data) { if (data) { callback(data); } else { callback(sNewDate); } }, error: function() { callback(sNewDate); } }; $.ajax(oSettings); } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } var closeModals = function() { $('.modal').modal('hide'); } var ucWords = function(str) { str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) { return letter.toUpperCase(); }); return str; }
javascript
The opposition to penal provisions like heavy fines and even a jail term for builders and promoters who fail to deliver on their promises and the clamour for leaving commercial properties out of the purview of the Real Estate (Regulation and Development) Bill, 2012, could pave way for alterations in the law which the Ministry of Housing and Urban Poverty Alleviation (HUPA) is keen on tabling in the budget session of Parliament. Following a protracted tussle between the industry and the HUPA, and the intervention of the Urban Development Ministry, changes are now being considered to make the Bill more acceptable to the industry. Informed sources told The Hindu that commercial properties could be taken out of the Bill’s mandate and the other changes would be about the penal provisions. “The industry has been protesting that the Bill is unduly harsh on them. So it is now being proposed that the penalties and punishment will be fleshed out so that there is clarity on what transgressions will invoke action,” a source said. The sources indicated that the real estate industry managed to get the Urban Development Ministry’s support for its demand to keep shops and office spaces out of the Bill’s mandate. As for other changes, “it is being proposed that the Union Urban Development Ministry will appoint the regulatory authority for Delhi. Since the Bill proposes the setting up of a regulatory authority in each State, it has come as a surprise that the UD Ministry wants to exert its control over the Delhi authority,” said the source. The appointment of the national regulatory body, headed by a chairman, will be a matter of mutual decision involving both the Urban Development Ministry and the HUPA. The Bill, touted as the first of its kind to regulate the real estate sector and protect he consumer, has in place checks to prevent builders from making false and exaggerated claims; overcharging consumers and diverting funds for newer projects, which sometimes leads to delays.
english
{ "basepath": "/", "url": "https://devfest-2018-9690d.firebaseapp.com/", "analytics": "UA-109989027-1", "prefix": "/", "firebase": { "apiKey": "<KEY>", "authDomain": "devfest-2018-9690d.firebaseapp.com", "databaseURL": "https://devfest-2018-9690d.firebaseio.com", "projectId": "devfest-2018-9690d", "storageBucket": "devfest-2018-9690d.appspot.com", "messagingSenderId": "516409946568" }, "googleMapApiKey": "<KEY>" }
json
Eighth seed Hubert Hurkacz and Nick Kyrgios will lock horns in a highly-anticipated quarterfinal contest at the 2022 Canadian Open. Ahead of the encounter, Andy Roddick spoke about the keys for both players in an interview with the Tennis Channel. Highlighting Kyrgios' win over Daniil Medvedev, the American former World No.1 said Hurkacz will need to be wary of not making the same mistake as Medvedev — playing defensively as that, according to him, allows Kyrgios time to work his "magic". "I don't think he can kind of go way back and react to Kyrgios. I think he actually has to just completely thump when he gets the chance and make Kyrgios steal his power," Roddick said. "Listen, Medvedev is a great player. No. 1 in the world, better than I would have ever been in my life, but he gives Kyrgios time to work his magic, Hubert Hukracz has to take that time away." Roddick also spoke about the significance of serving numbers for both players, saying it will be especially important for Hurkacz to defend his serve well and at least push for a tie-breaker. "Yeah, Nick straight out-served him in Halle and actually get itnto those tie-breakers where anything could go, right?" Roddick said. "But listen Kyrgios is a different player than he was in Halle where he was actually in-form as well." "If you're Hubert Hurkacz, you know that you have to thump any ball you get that you have two feet under because you don't want Nick Kyrgios to start going mad magician, on you rightKnocking down that back and coming in and Hurkacz, I think he has to step in on second serve returns," he added. Kyrgios and Hurkacz will face off on Center Court in the morning session on Friday. Nick Kyrgios' inconsistent results prior to Wimbledon had adversely affected his world ranking. And with the Wimbledon Championships not awarding any ranking points this year, reaching the final at the All England Club did not do his ranking any favors. The Aussie, however, has seemingly struck form in the weeks since and is steadily climbing the ranking ladder. He is currently ranked at No. 37, but his solid showing in Montreal will see him go up at least 10 spots. Kyrgios has now moved up to World No. 27 in the ATP Live Rankings, a rank that’ll ensure he’s seeded at the US Open later this month.
english
{"text":"\n     Any member of the Retirement System under Sections \nA8.509, \nA8.584 and \nA8.587 of the Charter, who elects, pursuant to Section \n16.55-2 to make contributions and receive credit as miscellaneous City and County service for all or any part of the time he or she was in public service, shall contribute to the Retirement Fund an amount equal to the product of: \n     (a)     the monthly compensation earnable by said member on the date he or she makes a lump sum payment to purchase the prior public service credit or delivers to the Retirement System a signed installment payment agreement to purchase the prior public service credit, multiplied by \n     (b)     the normal cost percentage of the applicable miscellaneous plan as published in the most recent actuarial valuation adopted by the Retirement Board, multiplied by \n     (c)     the number of months of prior public service being purchased.\n     (d)     In addition, members who make payment by other than lump sum payment shall pay interest on the unpaid balance of the amount payable into the Retirement Fund under this Section, commencing on the date of the member's election to make such contributions, at the rate of interest currently being used from time to time under the Retirement System. \n     Payment of the contributions required by this Section shall be made in a lump sum or by installment payments. Installment payments shall be made at times and in a manner fixed by the Retirement Board; provided, that the period for completion of such payments shall not exceed five years. All payments required by this Section must be received by the Retirement System before the date the member files the application to retire or the effective date of the member's retirement, whichever is later. \n     Any member who elects to purchase credit for prior public service by installment payments may, at any time during the period for making such installment payments, complete the purchase by lump sum payment. \n     Except as prohibited by the Internal Revenue Service, any member who elects to purchase credit for prior public service by installment payments may, at any time prior to completion of payment for such purchase, revoke his or her election. Such revocation shall be in writing and shall be effective only if filed with the Retirement System. Upon such revocation of election, the member shall have the option to receive a refund of all of the contributions which he or she has made pursuant to such election or to receive credit for the prior public service purchased up to the date of the revocation. If said member elects to receive a refund, then he or she shall thereafter not have the right to elect to receive credit for the public service which was the subject of said revoked election. \n     All contributions made pursuant to this Section, and the interest thereon shall be considered to be and shall be administered as contributions of the member; provided that only the share of said contributions representing the member's contributions, including interest, shall he considered when calculating benefits payable pursuant to Sections \nA8.509(f), \nA8.584-6 and \nA8.587-6 of the Charter. \n(Added by Ord. 171-70, App. 5/28/70; amended by Ord. 308-08, File No. 080379, App. 12/16/2008)\n\n","heading":{"title":"16","chaptersection":"55-3","identifier":"16.55-3","catch_text":"CONTRIBUTIONS FOR PUBLIC SERVICE CREDIT."}}
json
import { HttpErrorResponse } from '@angular/common/http'; import { Component, Input, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MatSnackBar } from '@angular/material/snack-bar'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { ChangeProfilePictureDialogComponent } from 'src/app/modules/profile-picture/components/change-profile-picture-dialog/change-profile-picture-dialog.component'; import { ProfilePictureService } from 'src/app/modules/profile-picture/profile-picture.service'; import { CurrentUserService } from 'src/app/services/api/current-user.service'; @Component({ selector: 'app-change-profile-picture', templateUrl: './change-profile-picture.component.html', styleUrls: ['./change-profile-picture.component.scss'] }) export class ChangeProfilePictureComponent implements OnInit { @Input() public userId: string; public currentUserId: string = ''; public uploading = false; constructor( private profilePictureService: ProfilePictureService, private currentUserService: CurrentUserService, private snackBar: MatSnackBar, private dialog: MatDialog, private i18n: I18n ) {} public ngOnInit() { this.currentUserService.getCurrentUserId().subscribe( id => { this.currentUserId = id; }, error => { // do nothing, as the id will never be '' } ); } public isVisible(): boolean { return this.userId.toLowerCase() === this.currentUserId.toLowerCase(); } public uploadFile(event: Event) { this.dialog .open(ChangeProfilePictureDialogComponent, {}) .afterClosed() .subscribe(upload => { if (upload) { this.uploading = true; // This is import because of firefox https://stackoverflow.com/questions/5301643/how-can-i-make-event-srcelement-work-in-firefox-and-what-does-it-mean const eventElement = event.target || event.srcElement; const files = (eventElement as HTMLInputElement).files; if (files != null && files.length > 0) { const file: File = files[0]; const fileSize: number = file.size; (eventElement as HTMLInputElement).value = ''; if (fileSize <= 52428800) { this.profilePictureService.uploadUserPicture(file).subscribe( success => { this.snackBar.open( this.i18n({ meaning: 'ChangeProfilePictureComponent', description: 'Success Message if profile picture was updated', id: 'ChangeProfilePictureComponentSuccessUpdate', value: 'Updated your Profile Picture!' }), '', { duration: 3000 } ); this.profilePictureService.reload.emit(this.userId); this.uploading = false; }, (error: HttpErrorResponse) => { if (error.status === 400) { this.snackBar .open( this.i18n({ meaning: 'ChangeProfilePictureComponent', description: 'Error Message if wrong File Type is supplied', id: 'ChangeProfilePictureComponentErrorWrongFileType', value: `The File Type is not supported.` }), this.i18n({ meaning: 'ChangeProfilePictureComponent', description: 'Button on Error Message if wrong File Type is supplied', id: 'ChangeProfilePictureComponentErrorWrongFileTypeButton', value: 'I want to add more support!' }), { duration: 3000 } ) .onAction() .subscribe(clicked => { window.open('https://github.com/T-Systems-MMS/phonebook/issues/2', '_blank'); }); return; } this.snackBar.open( this.i18n({ meaning: 'GeneralErrorMessage', description: 'A general Error message, that can be displayed everywhere', id: 'GeneralErrorMessage', value: 'Something went wrong. Please try again.' }), '', { duration: 3000 } ); this.uploading = false; } ); } else { this.snackBar.open( this.i18n({ meaning: 'ChangeProfilePictureComponent', description: 'Error Message if supplied file size is to big (without size and unit)', id: 'ChangeProfilePictureComponentErrorFileSize', value: 'Your file is too big! It should be smaller than' }) + ' 50MB.', '', { duration: 3000 } ); } } (eventElement as HTMLInputElement).value = ''; } }); } public deleteProfilePicture() { this.profilePictureService.deleteUserPicture().subscribe( success => { this.snackBar.open( this.i18n({ meaning: 'ChangeProfilePictureComponent', description: 'Success Message if user deleted its profile picture', id: 'ChangeProfilePictureComponentSuccessDelete', value: 'Your profile picture was deleted!' }), '', { duration: 3000 } ); this.profilePictureService.reload.emit(this.userId); }, error => { this.snackBar.open( this.i18n({ id: 'GeneralErrorMessage', value: 'Something went wrong. Please try again.' }), '', { duration: 3000 } ); } ); } }
typescript
<reponame>efimovad/2019_2_Comandus package sqlstore import "github.com/go-park-mail-ru/2019_2_Comandus/internal/model" const ( ContractListByCompany = "company" ContractListByFreelancer = "freelancer" ) type ContractRepository struct { store *Store } func (r *ContractRepository) Create(contract *model.Contract) error { return r.store.db.QueryRow( "INSERT INTO contracts (responseId, companyId, freelancerId, startTime, endTime, status, grade" + "paymentAmount) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING accountId", contract.ResponseID, contract.CompanyID, contract.FreelancerID, contract.StartTime, contract.EndTime, contract.Status, contract.Grade, contract.PaymentAmount, ).Scan(&contract.ID) } func (r *ContractRepository) Find(id int64) (*model.Contract, error) { c := &model.Contract{} if err := r.store.db.QueryRow( "SELECT id, responseId, companyId, freelancerId, startTime, endTime, status, grade, " + "paymentAmount FROM contracts WHERE id = $1", id, ).Scan( &c.ID, &c.ResponseID, &c.CompanyID, &c.FreelancerID, &c.StartTime, &c.EndTime, &c.Status, &c.Grade, &c.PaymentAmount, ); err != nil { return nil, err } return c, nil } func (r *ContractRepository) Edit(c * model.Contract) error { return r.store.db.QueryRow("UPDATE contracts SET freelancerId = $1, startTime = $2, " + "endTime = $3, status = $4, grade = $5, paymentAmount = $6 WHERE id = $7 RETURNING id", c.FreelancerID, c.StartTime, c.EndTime, c.Status, c.Grade, c.PaymentAmount, c.ID, ).Scan(&c.ID) } func (r *ContractRepository) List(id int64, mode string) ([]model.Contract, error) { var contracts []model.Contract var query string if mode == ContractListByCompany { query = "SELECT id, responseId, companyId, freelancerId, startTime, endTime, status, grade, " + "paymentAmount FROM contracts WHERE companyId = $1" } else if mode == ContractListByFreelancer { query = "SELECT id, responseId, companyId, freelancerId, startTime, endTime, status, grade, " + "paymentAmount FROM contracts WHERE freelancerId = $1" } rows, err := r.store.db.Query(query, id) if err != nil { return nil, err } for rows.Next() { c := model.Contract{} err := rows.Scan(&c.ID, &c.ResponseID, &c.CompanyID, &c.FreelancerID, &c.StartTime, &c.EndTime, &c.Status, &c.Grade, &c.PaymentAmount) if err != nil { return nil , err } contracts = append(contracts , c) } if err := rows.Close(); err != nil { return nil, err } return contracts, nil }
go
# Third-party import astropy.units as u import numpy as np import pymc3 as pm from pymc3.distributions import generate_samples import aesara_theano_fallback.tensor as tt import exoplanet.units as xu __all__ = ['UniformLog', 'FixedCompanionMass'] class UniformLog(pm.Continuous): def __init__(self, a, b, **kwargs): """A distribution over a value, x, that is uniform in log(x) over the domain :math:`(a, b)`. """ self.a = float(a) self.b = float(b) assert (self.a > 0) and (self.b > 0) self._fac = np.log(self.b) - np.log(self.a) shape = kwargs.get("shape", None) if shape is None: testval = 0.5 * (self.a + self.b) else: testval = 0.5 * (self.a + self.b) + np.zeros(shape) kwargs["testval"] = kwargs.pop("testval", testval) super(UniformLog, self).__init__(**kwargs) def _random(self, size=None): uu = np.random.uniform(size=size) return np.exp(uu * self._fac + np.log(self.a)) def random(self, point=None, size=None): return generate_samples( self._random, dist_shape=self.shape, broadcast_shape=self.shape, size=size, ) def logp(self, value): return -tt.as_tensor_variable(value) - np.log(self._fac) class FixedCompanionMass(pm.Normal): r""" A distribution over velocity semi-amplitude, :math:`K`, that, at fixed primary mass, is a fixed Normal distribution in companion mass. This has the form: .. math:: p(K) \propto \mathcal{N}(K \,|\, \mu_K, \sigma_K) \sigma_K = \sigma_{K, 0} \, \left(\frac{P}{P_0}\right)^{-1/3} \, \left(1 - e^2\right)^{-1} where :math:`P` and :math:`e` are period and eccentricity, and ``sigma_K0`` and ``P0`` are parameters of this distribution that must be specified. """ @u.quantity_input(sigma_K0=u.km/u.s, P0=u.day, max_K=u.km/u.s) def __init__(self, P, e, sigma_K0, P0, mu=0., max_K=500*u.km/u.s, K_unit=None, **kwargs): self._sigma_K0 = sigma_K0 self._P0 = P0 self._max_K = max_K if K_unit is not None: self._sigma_K0 = self.sigma_K0.to(K_unit) self._max_K = self._max_K.to(self._sigma_K0.unit) if hasattr(P, xu.UNIT_ATTR_NAME): self._P0 = self._P0.to(getattr(P, xu.UNIT_ATTR_NAME)) sigma_K0 = self._sigma_K0.value P0 = self._P0.value sigma = tt.min([self._max_K.value, sigma_K0 * (P/P0)**(-1/3) / np.sqrt(1-e**2)]) super().__init__(mu=mu, sigma=sigma) class Kipping13Long(pm.Beta): def __init__(self): r""" The inferred long-period eccentricity distribution from Kipping (2013). """ super().__init__(1.12, 3.09) class Kipping13Short(pm.Beta): def __init__(self): r""" The inferred short-period eccentricity distribution from Kipping (2013). """ super().__init__(0.697, 3.27) class Kipping13Global(pm.Beta): def __init__(self): r""" The inferred global eccentricity distribution from Kipping (2013). """ super().__init__(0.867, 3.03)
python
<filename>README.md<gh_stars>1-10 ### The code and datasets for the manuscript: # EnsembleMerge: Integration of single cell RNA-seq datasets using an ensemble approach The R package EnsembleMerge can be found at https://github.com/erikjskie/ensemblemerge ## Processed datasets | | Dataset | Format | Script | | --- | --- | --- | --- | | Fig 1| [link](https://s3.msi.umn.edu/skiex003/datasets/EnsembleMerge/fig1.csv) | csv | [R](https://github.com/erikjskie/ensemblemerge_manuscript/blob/main/Figure1.R) | | latent ensemblemerge | [link](https://s3.msi.umn.edu/skiex003/datasets/EnsembleMerge/latent_ensemblemerge.csv) | csv | [R](https://github.com/erikjskie/ensemblemerge_manuscript/blob/main/Figure6.R) | | scVI ensemblemerge | [link](https://s3.msi.umn.edu/skiex003/datasets/EnsembleMerge/SCVI_ensemblemerge.csv) | csv | [R](https://github.com/erikjskie/ensemblemerge_manuscript/blob/main/Figure7.R) | | CLR ensemblemerge | [link](https://s3.msi.umn.edu/skiex003/datasets/EnsembleMerge/CLR_normalization.csv) | csv | [R](https://github.com/erikjskie/ensemblemerge_manuscript/blob/main/Figure8.R) | | fastMNN ensemblemerge | [link](https://s3.msi.umn.edu/skiex003/datasets/EnsembleMerge/Methods_EnsembleMerge.csv) | csv | [R](https://github.com/erikjskie/ensemblemerge_manuscript/blob/main/Figure10.R) | | Fig 9 | [link](https://s3.msi.umn.edu/skiex003/datasets/EnsembleMerge/fig9.csv) | csv | [R](https://github.com/erikjskie/ensemblemerge_manuscript/blob/main/Figure9.R) | | fastMNN | [link](https://s3.msi.umn.edu/skiex003/datasets/EnsembleMerge/fastMNN.csv) | csv | [R](https://github.com/erikjskie/ensemblemerge_manuscript/blob/main/fastMNN.R) | | scVI | [link](https://s3.msi.umn.edu/skiex003/datasets/EnsembleMerge/scVI.csv) | csv | [R](https://github.com/erikjskie/ensemblemerge_manuscript/blob/main/scVI.R) || ## Data Sources Datasets sourced from public data | | Dataset | Format | Script | | --- | --- | --- | --- | | Villani 2017 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_1.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | Han 2018 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_2.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | <NAME> | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_4.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | PBMC | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_5.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | 293t_Jurkat | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_6.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | <NAME> | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_7.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | Saunders 2018 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_8.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | HCA Blood | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_9.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | Paul 2015 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_10.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | Zillionis 2019 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_12.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | Shekhar 2016 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_13.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | Nestorowa 2016 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_14.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | Polanski 2019 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_15.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | Zheng 2017 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_16.rds) | SummarizedExperiment | [Source](https://hub.docker.com/r/jinmiaochenlab/batch-effect-removal-benchmarking) | | HBDC | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=20211008a/dataset_17.rds) | SummarizedExperiment | [Source](https://github.com/satijalab/seurat-data) | | Panc8 | [link](https://s3.msi.umn.edu/skiex003/datasets/dataset=JC_benchmark_scRNAseq_version=2021219a/dataset_4_seurat_panc8.rds) | SummarizedExperiment | [Source](https://github.com/satijalab/seurat-data) || # Notebooks | Description | link | | --- | --- | | Figure 1 | [[preview](Fig1.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Fig1.ipynb)]| | Supplementary Figure 3 | [[preview](Supplementary_Fig3.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Supplementary_Fig3.ipynb)]| | Supplementary Figure 4 | [[preview](Supplementarty_Fig4.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Supplementarty_Fig4.ipynb)]| | Supplementary Figure 5 | [[preview](supplementary_Fig5.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/supplementary_Fig5.ipynb)]| | Supplementary Figure 6 | [[preview](Supplementary_Fig6.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Supplementary_Fig6.ipynb)]| | Supplementary Figure 7 | [[preview](Supplementary_Fig7.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Supplementary_Fig7.ipynb)]| | Supplementary Figure 8 | [[preview](Supplementary_Fig8.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Supplementary_Fig8.ipynb)]| | Supplementary Figure 9 | [[preview](Supplementary_Fig9.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Supplementary_Fig9.ipynb)]| | Supplementary Figure 10 | [[preview](Supplementary_Fig10.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Supplementary_Fig10.ipynb)]| | Supplementary Figure 11 | [[preview](Supplementary_Fig11.ipynb)] [[colab](https://colab.research.google.com/github/erikjskie/ensemblemerge_manuscript/blob/main/Supplementary_Fig11.ipynb)]| ## Instructions for generating the intermediate results * Intermediate results are generating using R version 4.0.4 with the following packages * [EnsembleMerge](https://github.com/erikjskie/ensemblemerge) * [SingleCellExperiment](https://bioconductor.org/packages/release/bioc/html/SingleCellExperiment.html) * [Seurat](https://cran.r-project.org/web/packages/Seurat/index.html) * [Seurat Wrappers](https://github.com/satijalab/seurat-wrappers) * [Liger](https://github.com/welch-lab/liger) * [Harmony](https://github.com/immunogenomics/harmony) * [bbknn](https://github.com/Teichlab/bbknn) * [scVI](https://scvi-tools.org/) * [Scanorama](https://github.com/brianhie/scanorama) * [fastMNN](https://github.com/LTLA/batchelor) * [magrittr](https://cran.r-project.org/web/packages/magrittr/index.html) * [dplyr](https://cran.r-project.org/web/packages/dplyr/index.html) * The scripts used to generate the data for each figure are named as ```FigureX.R```. * The scripts will pull all the needed data from AWS storage if they are not already in current directory. * By default the script runs for ensemblemerge and produces the results in .csv format with the same name as the script in the current directory. * scripts can be run by: * ```Rscript Figure1.R``` * ```Rscript Figure6.R``` * ```Rscript Figure7.R``` * ```Rscript Figure8.R``` * ```Rscript Figure9.R``` * ```Rscript Figure10.R```
markdown
{ "Name": "Crash-Axt", "ShortName": "SCA", "Description": "Als Werkzeug für die Arbeit an harten Oberflächen entwickelt. Das Material und der Aufbau wurden für einen optimalen Einschlag und Stärkeübertragung ausgewählt. Der Axtkopf besteht aus 6AL4V Titanium, mit einer Stärke von 2,85 Zoll." }
json
1 Torbanitsi shintso aawots, sanbata gudots, maar goyo b́ maat'fetse, Megdeli datstsu Mariyam Iyesus doowomants biami, manok b bodtsok'on doowo bin ipets shútso doowman fengeshatse k'aztuut b́ befere bek'b́k'ri. 2 Mansh bi Simon P'et'rosnat Iyesus b́ shunf b́ danifok wos'fere amaat, «Doonzo dowootse kishdek'wutsernee, aawok bogedtsok'o danatsone» bieti. 3 Manorowere P'et'rosnat b́ danif ikmann kesht dowomand boami. 4 Gitetswotswere towatni bowos'iri, ernmó b́ danif k'oshman P'et'rosiyere bogo káárt wos'fere amt shino dowok b́bodi. 5 Dashan tuumt doowots b́s'iltsok'on duuni taho manoke b́befere b́bek'i, ernmó gitsomaand kindratse. 6 Simon P'et'roswere b́shuutso waat́ doowots b́ kindi, bíwere duuno bín t'at'ets taho manoke b́ befere b́ bek'i. 7 Iyesus tooko bín s'as'ets taho b́ duuni tahonton b́ woterawo bíaali k'oshoke k'odeyat b́ beyirwok'o bek'b́k'ri. 8 Maniyere il, shin shino waabodts b́ danifman doowi gitsots kindt bek't bíamani. 9 «K'irtswotsitse tuwo geyife bísha» etts aap'o S'ayin mas'afotstso t'iwintsde'afa'no botesh. 10 Maniyere il b́ danif gitetsmanots aanat bogalomand boami. 11 Megdel dats ashu Mariyam eepfetsat, dowoniyere úratse ned'dek'atni b́tesh, eepfetsatnwere tuumdek'at doowots b́ s'iili. 12 Iyesus duuno b́ teshts beyoke nas' tah tahtdek'ts melaki gitetsuwotsi iko s'olotse iko k'oyoke bobefere bbek'i. 13 Bowere Mariyamsh, «Nee máátsune! eegishe niepiri?» boeti. Biwere, «T doonzi dek'wutserne, eewk bogedtsok'onowere danatse» bíet. 14 Manowere etaat b shutsomand wongr biettsok'on Iyesus b́ need'efere bek'bk'ri, Iyesusi b́wottsok'onowere danatsane. 15 Iyesus, «Máátsune neena eegoshe niepiri, kone ngeyirwoni?» bí eti. Bíwere manoki mitwotsitse finirwo bish bíartsotse, «Doonzono! nee bín dek'ri wotiyal, eewk ngedtsok'owo oona neesha taash keewwe, taa were k'aaúdek'etuwe» bieti. 16 Iyesuswere, «Mariyame!» bí eti. Biwere b́maants wongr etaat Ibrayist'i noon keewu keewon, «Rebuni!» bí eti. Man etonwere, «Danifono!» etee. 17 Iyesus, «Tiyats borr taan detsk'aye taahe andoor tnihok damb keyafa'e, ernmó tieshwotsok amr ‹Taahe ti nihnat it nihok, ti Ik'onat it Ik'ok damb bíyok keshetwe etfe› err boosh keewwe» bíet. 18 Mann Megdel datstsu Mariyam b́ danifwotsok amaat «Doonzo bek're!» etaat bish eeg bíettsok'onowere boosh b keewi. 19 Manoori ik gawiymanitsi shints aaw sanbata gudots kooc' b́ danifwots ayhudi naashwotsi bo shattsotse, bo maa fengesho is'dek't́ moots kakwedek'tni botesh, maa fengesho is'etsok'on b́ befere Iyesus b́ danifwots kakwed'ek't bobeyiru moots b́ kindi, bo dagots need'dek't, «Jeeno itsh wotowe!» bíet. 20 Man ett b́ kishonat b́ lalk'on boosh b́ kits, b́ danifuwotswere doonzo bobek'tsok'on geneúbowutsi. 21 Maniyere il Iyesus aaniy, «Jeeno itsh wotowe! taan niho b́ woshtsok'o taawere iti woshitwe» bíet. 22 Man eton bo aats úff ett, «S'ayin shayiro de'ere, 23 20:23 Mat. 16:19; 18:18 ashuwots morrosh orowe it etal boosh bo morro orowa etetuwe, it ashuwots morro orowa eto it k'azal boosh orowa eteeratse» bíet. 24 Iyesus b́ danifwotsok b́ woor tatse gitetsuwotsitse iko, Didimosi eteefo Tomas bowoke aali b́tesh. 25 Mansh b́ danif k'oshuwots Tomassh «Doonzone bek'rone» boet. Bímó «Mismaron koshets b́ kishuwotsi be'er tjabuwotsi msmaron koshets manotsits tgerawo, t kishonowere b́ lalk'i gaawots t gedala bako b́jamon amaneratse» bí eti. 26 Shimt aawoniyere hakon b́danfuwots aaniy mootsna botesh, Tomasuwere bontini b́tesh, maa fengesho is'etsok'on b́befere Iyesus waa bo dagotse need'dek't́, «Jeeno itsh wotowe!» bíet. 27 Maniyere il Tomassh, «N jaabo hakan doyir tkishwotsi s'iile, nkishonowere dewar t lalk'ots geere, amantso wotowe bako, amanerawo wotk'aye» bí et. 28 Tomaswere, «T doonzo! tiko Izar Izewero!» ett bísh bíaani. 29 Iyesuswere Tomassh, «Neyere taan nbek'tsosha taan niamaniye, taan bo be aawon taan amanituwots údeknee» bíet. 30 Iyesus mas'afanitse guut't gederawo k'osh ay aditso b́ danifúwots shinatse finere, 31 Ernmó Iyesus Krstos Ik'o naayi b́wottsok'owo it amanituwok'o, amanar b́shutson dúre dúri kasho it datsitwok'owa han b́ guut'iyi.
english
<reponame>eitherother/css-animations<gh_stars>0 .bars { height: 56px; margin-left:auto; margin-right:auto; transform: rotate(180deg); width: 81px; } .bar { animation: sound 0ms 0ms linear alternate infinite; animation-duration: 8000ms; animation-fill-mode: backwards; background: #000077; display:inline-block; height: 40px; padding-top:6px; position: absolute; width: 3px; } @keyframes sound { 0% { height: 3px; opacity: 0.25; } 15% { height: 16px; opacity: 0.5; } 25% { height: 10px; } 35% { height: 16px; opacity: 0.7; } 50% { height: 8px; opacity: 0.4; } 70% { height: 18px; } 85% { height: 14px; } 100% { height: 28px; opacity: 0.6; } } .bar:nth-child(1) { left: 1px; animation-delay: 0ms; } .bar:nth-child(2) { left: 5px; animation-delay: 400ms; } .bar:nth-child(3) { left: 9px; animation-delay: 800ms; } .bar:nth-child(4) { left: 13px; animation-delay: 1200ms; } .bar:nth-child(5) { left: 17px; animation-delay: 1600ms; } .bar:nth-child(6) { left: 21px; animation-delay: 2000ms; } .bar:nth-child(7) { left: 25px; animation-delay: 2400ms; } .bar:nth-child(8) { left: 29px; animation-delay: 2800ms; } .bar:nth-child(9) { left: 33px; animation-delay: 3200ms; } .bar:nth-child(10) { left: 37px; animation-delay: 3600ms; } .bar:nth-child(11) { left: 41px; animation-delay: 4000ms; } .bar:nth-child(12) { left: 45px; animation-delay: 4400ms; } .bar:nth-child(13) { left: 49px; animation-delay: 4800ms; } .bar:nth-child(14) { left: 53px; animation-delay: 5200ms; } .bar:nth-child(15) { left: 57px; animation-delay: 5600ms; } .bar:nth-child(16) { left: 61px; animation-delay: 6000ms; } .bar:nth-child(17) { left: 65px; animation-delay: 6400ms; } .bar:nth-child(18) { left: 69px; animation-delay: 6800ms; } .bar:nth-child(19) { left: 73px; animation-delay: 7200ms; } .bar:nth-child(20) { left: 77px; animation-delay: 7600ms; }
css
The calendar is insisting that spring is coming. Even in Calgary. The evenings get longer (too bad we have to lose an hour of sleep for that) and the weather could start warming up soon. And many schools have a week off! Check out some fun events in Calgary during March 2023. Symphony Sundays with the Calgary Philharmonic Orchestra brings you Beethoven Lives Upstairs on March 5, 2023. This is a fabulous and fun introduction to classical music. Arts Commons Presents has terrific, educational shows for the whole family, like their National Geographic Live series. On March 12 – 13, 2023, get your tickets for Jasper Doest: A Voice for Nature. Jasper Doest is a photographer, but his goal isn’t just to create fantastic, memorable images. Photography is his way of giving a voice to the wildlife with whom we share the planet. His photographs are visual stories that explore the relationship between humans and nature. Get out of the house every Wednesday morning with Story Time at Heritage Park. You’ll enjoy favourite stories at favourite places and can pick up a craft to take home, too. The Cineplex Family Favourites are such a great way to enjoy an outing without breaking the bank. Every Saturday in March, your family can head to the theatre for the low price of $2.99 per ticket. That might even leave enough left over to share popcorn! Get a little free crafting fun at Michaels Make Break events, every Sunday afternoon in March. It’s time to plan an adventure with the Outdoor Adventure and Travel Show! There are fun activities and things to see for the whole family from March 18 – 19, 2023. Catch dinner (lunch) and a show! Jubilations Jr. is presenting Freakish Friday until March 25, 2023. Besides enjoying your meal, you’ll also appreciate the amazing and all-Canadian show; it’s a 2-act musical comedy, with world-famous, interactive character servers. It’s entertaining for the adults and the kids. Spring break is right around the corner. If you’re looking for a more structured plan for March 27 – 31, 2023, we’re working hard on building a convenient guide to spring break camp ideas in Calgary this year. Even if Mom and Dad don’t have to work, camp is just plain fun. If you want awesome playtime and March break fun over the school break, be sure to take a look at our March Break Events Guide. End the month with the Calgary Rock N’ Gem Show. It begins on March 30, 2023, and it’s an amazing display of gemstones, minerals, fossils and so much more. There are lots of other events happening during the month of March. Calgary is a great place for families to enjoy activities together. Be sure to check out our calendar to find more family fun. You can also submit your family-friendly event to us; just fill out our event submission form. Don’t forget to check out our new contests! Enjoy the month, Calgary! Sign up for the monthly Family Fun Calgary e-newsletter. We give you a peek at all of the great, upcoming, family-friendly activities scheduled in Calgary. Don’t forget to connect with us on Facebook and Instagram too!
english
.spinnerContainer { height: 100vh; width: 100%; display: flex; justify-content: center; align-items: center; } .loading-indicator:before { content: ""; background: #000000cc; position: fixed; width: 100%; height: 100%; top: 0; left: 0; z-index: 1000; } .loading-indicator:after { content: "\f1ce"; font-family: FontAwesome; position: fixed; width: 100%; top: 50%; left: 0; z-index: 1001; color: white; text-align: center; font-weight: 100; font-size: 4rem; -webkit-animation: fa-spin 1s infinite linear; animation: fa-spin 1s infinite linear; }
css
class EfficiencyMeasurement(): # input_voltage = None # input_current = None # output_voltage = None # output_current = None # input_power = None # output_power = None # loss_power = None # efficiency = None def __init__(self, input_voltage: float, input_current: float, output_voltage: float, output_current: float): self.input_voltage = input_voltage self.input_current = input_current self.output_voltage = output_voltage self.output_current = output_current self.input_power = calc_power(voltage = input_voltage, current = input_current) self.output_power = calc_power(voltage = output_voltage, current = output_current) self.loss_power = calc_loss_power(input_power=self.input_power, ouput_power=self.output_power) class TsetPoint(): setup = None measurement = None #EfficiencyMeasurement() class TestSet_Efficiency(): def __init__(self, s: dict): self.source_bias = s['source_bias'] self.dut = s['powertrain'] self.load = s['load']
python
<filename>src/main/java/org/codelibs/fess/indexer/IndexUpdater.java /* * Copyright 2012-2021 CodeLibs Project and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.codelibs.fess.indexer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.codelibs.core.lang.StringUtil; import org.codelibs.core.lang.ThreadUtil; import org.codelibs.fesen.action.search.SearchRequestBuilder; import org.codelibs.fesen.index.query.QueryBuilder; import org.codelibs.fesen.index.query.QueryBuilders; import org.codelibs.fesen.search.sort.SortOrder; import org.codelibs.fess.Constants; import org.codelibs.fess.crawler.Crawler; import org.codelibs.fess.crawler.entity.AccessResult; import org.codelibs.fess.crawler.entity.AccessResultData; import org.codelibs.fess.crawler.entity.EsAccessResult; import org.codelibs.fess.crawler.entity.EsUrlQueue; import org.codelibs.fess.crawler.service.DataService; import org.codelibs.fess.crawler.service.UrlFilterService; import org.codelibs.fess.crawler.service.UrlQueueService; import org.codelibs.fess.crawler.service.impl.EsDataService; import org.codelibs.fess.crawler.transformer.Transformer; import org.codelibs.fess.crawler.util.EsResultList; import org.codelibs.fess.es.client.SearchEngineClient; import org.codelibs.fess.es.log.exbhv.ClickLogBhv; import org.codelibs.fess.es.log.exbhv.FavoriteLogBhv; import org.codelibs.fess.exception.ContainerNotAvailableException; import org.codelibs.fess.exception.FessSystemException; import org.codelibs.fess.helper.IndexingHelper; import org.codelibs.fess.helper.IntervalControlHelper; import org.codelibs.fess.helper.SearchLogHelper; import org.codelibs.fess.helper.SystemHelper; import org.codelibs.fess.ingest.IngestFactory; import org.codelibs.fess.ingest.Ingester; import org.codelibs.fess.mylasta.direction.FessConfig; import org.codelibs.fess.util.ComponentUtil; import org.codelibs.fess.util.DocList; import org.codelibs.fess.util.MemoryUtil; import org.codelibs.fess.util.ThreadDumpUtil; public class IndexUpdater extends Thread { private static final Logger logger = LogManager.getLogger(IndexUpdater.class); protected List<String> sessionIdList; @Resource protected SearchEngineClient searchEngineClient; @Resource protected DataService<EsAccessResult> dataService; @Resource protected UrlQueueService<EsUrlQueue> urlQueueService; @Resource protected UrlFilterService urlFilterService; @Resource protected ClickLogBhv clickLogBhv; @Resource protected FavoriteLogBhv favoriteLogBhv; @Resource protected SystemHelper systemHelper; @Resource protected IndexingHelper indexingHelper; protected boolean finishCrawling = false; protected long executeTime; protected long documentSize; protected int maxIndexerErrorCount = 0; protected int maxErrorCount = 2; protected List<String> finishedSessionIdList = new ArrayList<>(); private final List<DocBoostMatcher> docBoostMatcherList = new ArrayList<>(); private List<Crawler> crawlerList; private IngestFactory ingestFactory = null; public IndexUpdater() { // nothing } @PostConstruct public void init() { if (logger.isDebugEnabled()) { logger.debug("Initialize {}", this.getClass().getSimpleName()); } if (ComponentUtil.hasIngestFactory()) { ingestFactory = ComponentUtil.getIngestFactory(); } } @PreDestroy public void destroy() { if (!finishCrawling) { if (logger.isInfoEnabled()) { logger.info("Stopping all crawler."); } forceStop(); } } public void addFinishedSessionId(final String sessionId) { synchronized (finishedSessionIdList) { finishedSessionIdList.add(sessionId); } } private void deleteBySessionId(final String sessionId) { try { urlFilterService.delete(sessionId); } catch (final Exception e) { logger.warn("Failed to delete url filters: {}", sessionId, e); } try { urlQueueService.delete(sessionId); } catch (final Exception e) { logger.warn("Failed to delete url queues: {}", sessionId, e); } try { dataService.delete(sessionId); } catch (final Exception e) { logger.warn("Failed to delete data: {}", sessionId, e); } } @Override public void run() { if (dataService == null) { throw new FessSystemException("DataService is null."); } if (logger.isDebugEnabled()) { logger.debug("Starting indexUpdater."); } executeTime = 0; documentSize = 0; final FessConfig fessConfig = ComponentUtil.getFessConfig(); final long updateInterval = fessConfig.getIndexerWebfsUpdateIntervalAsInteger().longValue(); final int maxEmptyListCount = fessConfig.getIndexerWebfsMaxEmptyListCountAsInteger(); final IntervalControlHelper intervalControlHelper = ComponentUtil.getIntervalControlHelper(); try { final Consumer<SearchRequestBuilder> cb = builder -> { final QueryBuilder queryBuilder = QueryBuilders.boolQuery().filter(QueryBuilders.termsQuery(EsAccessResult.SESSION_ID, sessionIdList)) .filter(QueryBuilders.termQuery(EsAccessResult.STATUS, org.codelibs.fess.crawler.Constants.OK_STATUS)); builder.setQuery(queryBuilder); builder.setFrom(0); final int maxDocumentCacheSize = fessConfig.getIndexerWebfsMaxDocumentCacheSizeAsInteger(); builder.setSize(maxDocumentCacheSize <= 0 ? 1 : maxDocumentCacheSize); builder.addSort(EsAccessResult.CREATE_TIME, SortOrder.ASC); }; final DocList docList = new DocList(); final List<EsAccessResult> accessResultList = new ArrayList<>(); long updateTime = System.currentTimeMillis(); int errorCount = 0; int emptyListCount = 0; long cleanupTime = -1; while (!finishCrawling || !accessResultList.isEmpty()) { try { final int sessionIdListSize = finishedSessionIdList.size(); intervalControlHelper.setCrawlerRunning(true); updateTime = System.currentTimeMillis() - updateTime; final long interval = updateInterval - updateTime; if (interval > 0) { // sleep ThreadUtil.sleep(interval); // 10 sec (default) } systemHelper.calibrateCpuLoad(); docList.clear(); accessResultList.clear(); intervalControlHelper.delayByRules(); if (logger.isDebugEnabled()) { logger.debug("Processing documents in IndexUpdater queue."); } updateTime = System.currentTimeMillis(); List<EsAccessResult> arList = getAccessResultList(cb, cleanupTime); if (arList.isEmpty()) { emptyListCount++; } else { emptyListCount = 0; // reset } long hitCount = ((EsResultList<EsAccessResult>) arList).getTotalHits(); while (hitCount > 0) { if (arList.isEmpty()) { ThreadUtil.sleep(fessConfig.getIndexerWebfsCommitMarginTimeAsInteger().longValue()); cleanupTime = -1; } else { processAccessResults(docList, accessResultList, arList); cleanupTime = cleanupAccessResults(accessResultList); } arList = getAccessResultList(cb, cleanupTime); hitCount = ((EsResultList<EsAccessResult>) arList).getTotalHits(); } if (!docList.isEmpty()) { indexingHelper.sendDocuments(searchEngineClient, docList); } synchronized (finishedSessionIdList) { if (sessionIdListSize != 0 && sessionIdListSize == finishedSessionIdList.size()) { cleanupFinishedSessionData(); } } executeTime += System.currentTimeMillis() - updateTime; if (logger.isDebugEnabled()) { logger.debug("Processed documents in IndexUpdater queue."); } // reset count errorCount = 0; } catch (final Exception e) { if (errorCount > maxErrorCount) { throw e; } errorCount++; logger.warn("Failed to access data. Retry to access it {} times.", errorCount, e); } finally { if (systemHelper.isForceStop()) { finishCrawling = true; if (logger.isDebugEnabled()) { logger.debug("Stopped indexUpdater."); } } } if (emptyListCount >= maxEmptyListCount) { if (logger.isInfoEnabled()) { logger.info("Terminating indexUpdater. emptyListCount is over {}.", maxEmptyListCount); } // terminate crawling finishCrawling = true; forceStop(); if (fessConfig.getIndexerThreadDumpEnabledAsBoolean()) { ThreadDumpUtil.printThreadDump(); } org.codelibs.fess.exec.Crawler.addError("QueueTimeout"); } if (!ComponentUtil.available()) { logger.info("IndexUpdater is terminated."); forceStop(); break; } } if (logger.isDebugEnabled()) { logger.debug("Finished indexUpdater."); } } catch (final ContainerNotAvailableException e) { if (logger.isDebugEnabled()) { logger.error("IndexUpdater is terminated.", e); } else if (logger.isInfoEnabled()) { logger.info("IndexUpdater is terminated."); } forceStop(); } catch (final Throwable t) { if (ComponentUtil.available()) { logger.error("IndexUpdater is terminated.", t); } else if (logger.isDebugEnabled()) { logger.error("IndexUpdater is terminated.", t); org.codelibs.fess.exec.Crawler.addError(t.getClass().getSimpleName()); } else if (logger.isInfoEnabled()) { logger.info("IndexUpdater is terminated."); org.codelibs.fess.exec.Crawler.addError(t.getClass().getSimpleName()); } forceStop(); } finally { intervalControlHelper.setCrawlerRunning(true); } if (logger.isInfoEnabled()) { logger.info("[EXEC TIME] index update time: {}ms", executeTime); } } private void processAccessResults(final DocList docList, final List<EsAccessResult> accessResultList, final List<EsAccessResult> arList) { final FessConfig fessConfig = ComponentUtil.getFessConfig(); final long maxDocumentRequestSize = Long.parseLong(fessConfig.getIndexerWebfsMaxDocumentRequestSize()); for (final EsAccessResult accessResult : arList) { if (logger.isDebugEnabled()) { logger.debug("Indexing {}", accessResult.getUrl()); } accessResult.setStatus(Constants.DONE_STATUS); accessResultList.add(accessResult); if (accessResult.getHttpStatusCode() != 200) { // invalid page if (logger.isDebugEnabled()) { logger.debug("Skipped. The response code is {}.", accessResult.getHttpStatusCode()); } continue; } final long startTime = System.currentTimeMillis(); final AccessResultData<?> accessResultData = accessResult.getAccessResultData(); if (accessResultData != null) { accessResult.setAccessResultData(null); try { final Transformer transformer = ComponentUtil.getComponent(accessResultData.getTransformerName()); if (transformer == null) { // no transformer logger.warn("No transformer: {}", accessResultData.getTransformerName()); continue; } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) transformer.getData(accessResultData); if (map.isEmpty()) { // no transformer logger.warn("No data: {}", accessResult.getUrl()); continue; } if (Constants.FALSE.equals(map.get(Constants.INDEXING_TARGET))) { if (logger.isDebugEnabled()) { logger.debug("Skipped. This document is not a index target. "); } continue; } else { map.remove(Constants.INDEXING_TARGET); } updateDocument(map); docList.add(ingest(accessResult, map)); final long contentSize = indexingHelper.calculateDocumentSize(map); docList.addContentSize(contentSize); final long processingTime = System.currentTimeMillis() - startTime; docList.addProcessingTime(processingTime); if (logger.isDebugEnabled()) { logger.debug("Added the document({}, {}ms). The number of a document cache is {}.", MemoryUtil.byteCountToDisplaySize(contentSize), processingTime, docList.size()); } if (docList.getContentSize() >= maxDocumentRequestSize) { indexingHelper.sendDocuments(searchEngineClient, docList); } documentSize++; if (logger.isDebugEnabled()) { logger.debug("The number of an added document is {}.", documentSize); } } catch (final Exception e) { logger.warn("Could not add a doc: {}", accessResult.getUrl(), e); } } else if (logger.isDebugEnabled()) { logger.debug("Skipped. No content. "); } } } protected Map<String, Object> ingest(final AccessResult<String> accessResult, final Map<String, Object> map) { if (ingestFactory == null) { return map; } Map<String, Object> target = map; for (final Ingester ingester : ingestFactory.getIngesters()) { try { target = ingester.process(target, accessResult); } catch (final Exception e) { logger.warn("Failed to process Ingest[{}]", ingester.getClass().getSimpleName(), e); } } return target; } protected void updateDocument(final Map<String, Object> map) { final FessConfig fessConfig = ComponentUtil.getFessConfig(); if (fessConfig.getIndexerClickCountEnabledAsBoolean()) { addClickCountField(map); } if (fessConfig.getIndexerFavoriteCountEnabledAsBoolean()) { addFavoriteCountField(map); } float documentBoost = 0.0f; for (final DocBoostMatcher docBoostMatcher : docBoostMatcherList) { if (docBoostMatcher.match(map)) { documentBoost = docBoostMatcher.getValue(map); break; } } if (documentBoost > 0) { addBoostValue(map, documentBoost); } if (!map.containsKey(fessConfig.getIndexFieldDocId())) { map.put(fessConfig.getIndexFieldDocId(), systemHelper.generateDocId(map)); } ComponentUtil.getLanguageHelper().updateDocument(map); } protected void addBoostValue(final Map<String, Object> map, final float documentBoost) { final FessConfig fessConfig = ComponentUtil.getFessConfig(); map.put(fessConfig.getIndexFieldBoost(), documentBoost); if (logger.isDebugEnabled()) { logger.debug("Set a document boost ({}).", documentBoost); } } protected void addClickCountField(final Map<String, Object> doc) { final FessConfig fessConfig = ComponentUtil.getFessConfig(); final String url = (String) doc.get(fessConfig.getIndexFieldUrl()); if (StringUtil.isNotBlank(url)) { final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper(); final int count = searchLogHelper.getClickCount(url); doc.put(fessConfig.getIndexFieldClickCount(), count); if (logger.isDebugEnabled()) { logger.debug("Click Count: {}, url: {}", count, url); } } } protected void addFavoriteCountField(final Map<String, Object> map) { final FessConfig fessConfig = ComponentUtil.getFessConfig(); final String url = (String) map.get(fessConfig.getIndexFieldUrl()); if (StringUtil.isNotBlank(url)) { final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper(); final long count = searchLogHelper.getFavoriteCount(url); map.put(fessConfig.getIndexFieldFavoriteCount(), count); if (logger.isDebugEnabled()) { logger.debug("Favorite Count: {}, url: {}", count, url); } } } private long cleanupAccessResults(final List<EsAccessResult> accessResultList) { if (!accessResultList.isEmpty()) { final long execTime = System.currentTimeMillis(); final int size = accessResultList.size(); dataService.update(accessResultList); accessResultList.clear(); final long time = System.currentTimeMillis() - execTime; if (logger.isDebugEnabled()) { logger.debug("Updated {} access results. The execution time is {}ms.", size, time); } return time; } return -1; } private List<EsAccessResult> getAccessResultList(final Consumer<SearchRequestBuilder> cb, final long cleanupTime) { if (logger.isDebugEnabled()) { logger.debug("Getting documents in IndexUpdater queue."); } final long execTime = System.currentTimeMillis(); final List<EsAccessResult> arList = ((EsDataService) dataService).getAccessResultList(cb); final FessConfig fessConfig = ComponentUtil.getFessConfig(); if (!arList.isEmpty()) { final long commitMarginTime = fessConfig.getIndexerWebfsCommitMarginTimeAsInteger().longValue(); for (final AccessResult<?> ar : arList.toArray(new AccessResult[arList.size()])) { if (ar.getCreateTime().longValue() > execTime - commitMarginTime) { arList.remove(ar); } } } final long totalHits = ((EsResultList<EsAccessResult>) arList).getTotalHits(); if (logger.isInfoEnabled()) { final StringBuilder buf = new StringBuilder(100); buf.append("Processing "); if (totalHits > 0) { buf.append(arList.size()).append('/').append(totalHits).append(" docs (Doc:{access "); } else { buf.append("no docs in indexing queue (Doc:{access "); } buf.append(System.currentTimeMillis() - execTime).append("ms"); if (cleanupTime >= 0) { buf.append(", cleanup ").append(cleanupTime).append("ms"); } buf.append("}, "); buf.append(MemoryUtil.getMemoryUsageLog()); buf.append(')'); logger.info(buf.toString()); } final long unprocessedDocumentSize = fessConfig.getIndexerUnprocessedDocumentSizeAsInteger().longValue(); final IntervalControlHelper intervalControlHelper = ComponentUtil.getIntervalControlHelper(); if (totalHits > unprocessedDocumentSize && intervalControlHelper.isCrawlerRunning()) { if (logger.isInfoEnabled()) { logger.info("Stopped all crawler threads. You have {} (>{}) unprocessed docs.", totalHits, unprocessedDocumentSize); } intervalControlHelper.setCrawlerRunning(false); } return arList; } private void cleanupFinishedSessionData() { final long execTime = System.currentTimeMillis(); // cleanup for (final String sessionId : finishedSessionIdList) { final long execTime2 = System.currentTimeMillis(); if (logger.isDebugEnabled()) { logger.debug("Deleting document data: {}", sessionId); } deleteBySessionId(sessionId); if (logger.isDebugEnabled()) { logger.debug("Deleted {} documents. The execution time is {}ms.", sessionId, (System.currentTimeMillis() - execTime2)); } } finishedSessionIdList.clear(); if (logger.isInfoEnabled()) { logger.info("Deleted completed document data. The execution time is {}ms.", (System.currentTimeMillis() - execTime)); } } private void forceStop() { systemHelper.setForceStop(true); for (final Crawler crawler : crawlerList) { crawler.stop(); } } public long getExecuteTime() { return executeTime; } public List<String> getSessionIdList() { return sessionIdList; } public void setSessionIdList(final List<String> sessionIdList) { this.sessionIdList = sessionIdList; } public void setFinishCrawling(final boolean finishCrawling) { this.finishCrawling = finishCrawling; } public long getDocumentSize() { return documentSize; } @Override public void setUncaughtExceptionHandler(final UncaughtExceptionHandler eh) { super.setUncaughtExceptionHandler(eh); } public static void setDefaultUncaughtExceptionHandler(final UncaughtExceptionHandler eh) { Thread.setDefaultUncaughtExceptionHandler(eh); } public void setMaxIndexerErrorCount(final int maxIndexerErrorCount) { this.maxIndexerErrorCount = maxIndexerErrorCount; } public void addDocBoostMatcher(final DocBoostMatcher rule) { docBoostMatcherList.add(rule); } public void setCrawlerList(final List<Crawler> crawlerList) { this.crawlerList = crawlerList; } }
java
const {User, Thought} = require('../models') module.exports = { //gets all users in database getAllUsers: async (req, res) => { try { const document = await User.find({}).select('-__v') if (!document) { return res.status(500).json({message: 'no users found'}) } return res.json(document) }catch (e) { res.status(500).json({message: e}) } }, //Creates a new users and adds it in the database newUser: async ({body}, res) => { try{ const document = await User.create(body) if(!document){ return res.status(500).json({message: 'User was not created'}) } return res.json(document) }catch (e) { res.status(500).json({message: e}) } }, //returns user by user ID getUserById: async ({params}, res) => { const userId = params._id try{ const document = await User.findById({_id:userId}).populate([{path:'thoughts',select:'-__v'},{path:'friends',select:'-__v'}]).select('-__v') if(!document){ return res.status(500).json({message: 'User was not found'}) } return res.json(document) }catch (e) { res.status(500).json({message: e}) } }, //updates existing user based on id updateUserById: async ({params, body}, res) => { const userId = params._id try{ const document = await User.findByIdAndUpdate({_id:userId},body,{new:true, runValidators:true}) if(!document){ return res.status(500).json({message: 'User was not found || Error updating user'}) } return res.json(document) }catch (e) { res.status(500).json({message: e}) } }, //Removes a user from the database by id deleteUserById: async ({params}, res) => { const userId = params._id try{ const document = await User.findByIdAndDelete({_id:userId}) if(!document){ return res.status(500).json({message: 'User was not found || Error deleting user'}) } const otherUsers = await User.updateMany({$in:{friends:userId}},{$pull:{friends:userId}},{new:true,runValidators:true}) if(!otherUsers){ return res.status(500).json({message: 'Error deleting user from others friends list'}) } const thoughts = await Thought.deleteMany({username:document.username}) if(!thoughts){ return res.status(500).json({message: 'Error deleting user thoughts'}) } return res.json(document) }catch (e) { res.status(500).json({message: e}) } }, //adds the userId to the other user friends array as well as adds the other persons user id to the users friend array addNewFriendToUser: async ({params}, res) => { const {userId, friendId} = params try{ const doesUserExist = await User.exists({_id:userId}) const doestFriendExist = await User.exists({_id:friendId}) if(!doestFriendExist || !doesUserExist){ return res.status(500).json({message: 'This is not a valid Friend id or not a valid User id'}) } const friendDocument = await User.findByIdAndUpdate({_id:friendId},{$push:{friends:userId}},{new:true,runValidators:true}) if(!friendDocument){ return res.status(500).json({message: 'Error adding user to proposed friend'}) } const document = await User.findByIdAndUpdate({_id:userId},{$push:{friends:friendId}},{new:true,runValidators:true}) if(!document){ return res.status(500).json({message: 'Error adding proposed friend to user'}) } return res.json(document) }catch (e) { res.status(500).json({message: e}) } }, //removes the userId for both the friend and the user in each others array of friend ids removeFriendFromUser: async ({params}, res) => { const {userId, friendId} = params try{ const doesUserExist = await User.exists({_id:userId}) const doestFriendExist = await User.exists({_id:friendId}) if(!doestFriendExist || !doesUserExist){ return res.status(500).json({message: 'This is not a valid Friend id or not a valid User id'}) } const friendDocument = await User.findByIdAndUpdate({_id:friendId},{$pull:{friends:userId}},{new:true,runValidators:true}) if(!friendDocument){ return res.status(500).json({message: 'Error removing friend from the users friend'}) } const document = await User.findByIdAndUpdate({_id:userId},{$pull:{friends:friendId}},{new:true,runValidators:true}) if(!document){ return res.status(500).json({message: 'Error removing friend from user'}) } return res.json(document) }catch (e) { res.status(500).json({message: e}) } } }
javascript
.switch { position: relative; display: inline-block; width: 34px; height: 20px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 13px; width: 13px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #32CD32; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(13px); -ms-transform: translateX(13px); transform: translateX(13px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } .bootstrap-switch .bootstrap-switch-handle-on, .bootstrap-switch .bootstrap-switch-handle-off, .bootstrap-switch .bootstrap-switch-label{ height: unset!important; } /* TAP toggle */ .tap-toggle { margin-bottom: 20px; background-position: center; transition: background 0.8s; -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; cursor: pointer; user-select: none; width: 42px; height: 20px; position: relative; /* border: 1px solid grey; */ background: rgb(226, 226, 226) 0% 0% no-repeat padding-box; /* padding: 1px; */ /* background-color: white; */ border-radius: 14px; opacity: 1; } .tap-toggle.disabled { user-select: none; opacity: .5; pointer-events: none !important; } .tp-checked { background: #32CD32 0% 0% no-repeat padding-box; } .tap-toggle::after { content: ""; border-radius: 14px; position: absolute; /* width: 17px; */ animation: .1s linear 0s slide-right; z-index: 9999; /* height: 17px; */ background: #FCFCFC 0% 0% no-repeat padding-box; /* box-shadow: 0px 2px 5px #00000029; */ /* opacity: 1; */ height: 13px; width: 13px; bottom: 4px; margin-left: 4px; /* left: 4px; */ background-color: white; -webkit-transition: .4s; transition: .4s; } .tap-toggle.tp-checked::after { right: 4px; animation: .1s linear 0s slide-left; } @keyframes slide-left { from { right: 20px; } to { right: 0; } } @keyframes slide-right { from { left: 20px; } to { left: 0px; } }
css
<gh_stars>1-10 """ ------------- | CTF Ware | ------------ | CHMODER | ----------- """ import main import Error_Handler from time import sleep # ---- Defining Functions ---- # The Title : CHMODER def title(): print("""" __ __ __ __ __ / |__||\/|/ \| \|_ |__) \__| || |\__/|__/|__| \ ---------------------------------------------------- | Helps you figure out the CHMOD permissions code. | ---------------------------------------------------- """) sleep(2) # Calling the menu options. chmod_menu() # The CHMOD Options Function def chmod_menu(): print("\n-----------------------" "\nChoose The Permissions" "\n-----------------------" "\n1: Execute [--x ]" "\n2: Write [ -w- ]" "\n3: Execute & Write [ -wx ]" "\n4: Read [ r-- ]" "\n5: Read & Execute [ r-x ]" "\n6: Read & Write [ rw- ]" "\n7: Read, Write, & Execute [ rwx ]" "\n") # Permission for USER. u = input("What is your choice for USER: ") # Send to The Checker for Error Handling # Re-assign the User's input with the value returned from The Checker u = Error_Handler.the_checker(u) # Process based on the value assigned by The Checker. if u == -1: chmod_menu() elif u == -2: chmod_menu() elif int(u) > 7: print("No such option. \nTry Again") sleep(2) chmod_menu() else: pass # Permission for GROUP. g = input("What is your choice for GROUP: ") # Send to The Checker for Error Handling # Re-assign the User's input with the value returned from The Checker g = Error_Handler.the_checker(g) # Process based on the value assigned by The Checker. if g == -1: chmod_menu() elif g == -2: chmod_menu() elif int(g) > 7: print("No such option. \nTry Again") sleep(2) chmod_menu() else: pass # Permission for EVERYONE. e = input("What is your choice for EVERYONE: ") # Send to The Checker for Error Handling # Re-assign the User's input with the value returned from The Checker e = Error_Handler.the_checker(e) # Process based on the value assigned by The Checker. if e == -1: chmod_menu() elif e == -2: chmod_menu() elif int(e) > 7: print("No such option. \nTry Again") sleep(2) chmod_menu() else: pass # Concacting the code uicode = str(u)+str(g)+str(e) code = uicode vcode = (u, g, e) # Dispalying the numeric results print("\nThis is your numeric CHMOD code: "+ code) # Call the visual function visual(vcode) # Creating the Visuals of the permissions chosen def visual(vcode): print("This will be your file's permissions: ", end="") for x in vcode: if (x == '1'): print("--x", end="") elif (x == '2'): print("-w-", end="") elif (x == '3'): print("-wx", end="") elif (x == '4'): print("r--", end="") elif (x == '5'): print("r-x", end="") elif (x == '6'): print("rw-", end="") elif (x == '7'): print("rwx", end="") else: print("Invalid Option") # Call the again function internal_loop() #-- Internal Loop Function def internal_loop(): loop_answer = input("\n\nBack to the CHMODER? [y/n] : ") if loop_answer.lower()== 'y': chmod_menu() else: main.mini_menu() # ----- End of Defining Functions ---- # The Main Guard in ALL the files please. '''------------------ CALLING THE FUNCTIONS ----------------------''' #-- Using a Main Guard to prevent it from running when Imported. if __name__ == '__main__': title() # Calling the title.
python
/*! * Copyright 2016 The ANTLR Project. All rights reserved. * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. */ import { ATN } from './atn/ATN'; import { ATNState } from './atn/ATNState'; import { BitSet } from './misc/BitSet'; import { DecisionState } from './atn/DecisionState'; import { InterpreterRuleContext } from './InterpreterRuleContext'; import { Parser } from './Parser'; import { ParserRuleContext } from './ParserRuleContext'; import { RecognitionException } from './RecognitionException'; import { Token } from './Token'; import { TokenStream } from './TokenStream'; import { Vocabulary } from './Vocabulary'; /** A parser simulator that mimics what ANTLR's generated * parser code does. A ParserATNSimulator is used to make * predictions via adaptivePredict but this class moves a pointer through the * ATN to simulate parsing. ParserATNSimulator just * makes us efficient rather than having to backtrack, for example. * * This properly creates parse trees even for left recursive rules. * * We rely on the left recursive rule invocation and special predicate * transitions to make left recursive rules work. * * See TestParserInterpreter for examples. */ export declare class ParserInterpreter extends Parser { protected _grammarFileName: string; protected _atn: ATN; /** This identifies StarLoopEntryState's that begin the (...)* * precedence loops of left recursive rules. */ protected pushRecursionContextStates: BitSet; protected _ruleNames: string[]; private _vocabulary; /** This stack corresponds to the _parentctx, _parentState pair of locals * that would exist on call stack frames with a recursive descent parser; * in the generated function for a left-recursive rule you'd see: * * private EContext e(int _p) { * ParserRuleContext _parentctx = _ctx; // Pair.a * int _parentState = state; // Pair.b * ... * } * * Those values are used to create new recursive rule invocation contexts * associated with left operand of an alt like "expr '*' expr". */ protected readonly _parentContextStack: [ParserRuleContext, number][]; /** We need a map from (decision,inputIndex)->forced alt for computing ambiguous * parse trees. For now, we allow exactly one override. */ protected overrideDecision: number; protected overrideDecisionInputIndex: number; protected overrideDecisionAlt: number; protected overrideDecisionReached: boolean; /** What is the current context when we override a decisions? This tells * us what the root of the parse tree is when using override * for an ambiguity/lookahead check. */ protected _overrideDecisionRoot?: InterpreterRuleContext; protected _rootContext: InterpreterRuleContext; /** A copy constructor that creates a new parser interpreter by reusing * the fields of a previous interpreter. * * @param old The interpreter to copy * * @since 4.5 */ constructor(old: ParserInterpreter); constructor(grammarFileName: string, vocabulary: Vocabulary, ruleNames: string[], atn: ATN, input: TokenStream); reset(resetInput?: boolean): void; readonly atn: ATN; readonly vocabulary: Vocabulary; readonly ruleNames: string[]; readonly grammarFileName: string; /** Begin parsing at startRuleIndex */ parse(startRuleIndex: number): ParserRuleContext; enterRecursionRule(localctx: ParserRuleContext, state: number, ruleIndex: number, precedence: number): void; protected readonly atnState: ATNState; protected visitState(p: ATNState): void; /** Method visitDecisionState() is called when the interpreter reaches * a decision state (instance of DecisionState). It gives an opportunity * for subclasses to track interesting things. */ protected visitDecisionState(p: DecisionState): number; /** Provide simple "factory" for InterpreterRuleContext's. * @since 4.5.1 */ protected createInterpreterRuleContext(parent: ParserRuleContext | undefined, invokingStateNumber: number, ruleIndex: number): InterpreterRuleContext; protected visitRuleStopState(p: ATNState): void; /** Override this parser interpreters normal decision-making process * at a particular decision and input token index. Instead of * allowing the adaptive prediction mechanism to choose the * first alternative within a block that leads to a successful parse, * force it to take the alternative, 1..n for n alternatives. * * As an implementation limitation right now, you can only specify one * override. This is sufficient to allow construction of different * parse trees for ambiguous input. It means re-parsing the entire input * in general because you're never sure where an ambiguous sequence would * live in the various parse trees. For example, in one interpretation, * an ambiguous input sequence would be matched completely in expression * but in another it could match all the way back to the root. * * s : e '!'? ; * e : ID * | ID '!' * ; * * Here, x! can be matched as (s (e ID) !) or (s (e ID !)). In the first * case, the ambiguous sequence is fully contained only by the root. * In the second case, the ambiguous sequences fully contained within just * e, as in: (e ID !). * * Rather than trying to optimize this and make * some intelligent decisions for optimization purposes, I settled on * just re-parsing the whole input and then using * {link Trees#getRootOfSubtreeEnclosingRegion} to find the minimal * subtree that contains the ambiguous sequence. I originally tried to * record the call stack at the point the parser detected and ambiguity but * left recursive rules create a parse tree stack that does not reflect * the actual call stack. That impedance mismatch was enough to make * it it challenging to restart the parser at a deeply nested rule * invocation. * * Only parser interpreters can override decisions so as to avoid inserting * override checking code in the critical ALL(*) prediction execution path. * * @since 4.5 */ addDecisionOverride(decision: number, tokenIndex: number, forcedAlt: number): void; readonly overrideDecisionRoot: InterpreterRuleContext | undefined; /** Rely on the error handler for this parser but, if no tokens are consumed * to recover, add an error node. Otherwise, nothing is seen in the parse * tree. */ protected recover(e: RecognitionException): void; protected recoverInline(): Token; /** Return the root of the parse, which can be useful if the parser * bails out. You still can access the top node. Note that, * because of the way left recursive rules add children, it's possible * that the root will not have any children if the start rule immediately * called and left recursive rule that fails. * * @since 4.5.1 */ readonly rootContext: InterpreterRuleContext; }
typescript
<gh_stars>1-10 {"appid": 601580, "name": "The Onion Knights", "windows": true, "mac": false, "linux": false, "early_access": false, "lookup_time": 1491011256}
json
Saudi Arabia: Karnataka’s one of the reputed Islamic education institution Darunnoor Education Centre Kashipatna’s Riyadh – Saudi Arabia committee annual meet was held recently at the Zam Zam Hotel Auditorium Riyadh. Maulana Arif Baqavi Nelyadi of Payakki Ustad Islamic Academy led the prayers, the world-renowned Pattikkad Jamiya Nuria Arabic College Professor Maulana Liayuddin Faizy inaugurated the function. Committee president D Mohammed Shereef Thodar presided. General Secretary Shafi Thodar presented the annual report and Treasurer Hasan Arkana presented the annual financial report. Sayed Shaul Hameed Thangala and Sayed Abdul Latif Badravathi were present in the dais. Secretary Siraj Thodar welcomed and Basheer Aramboor delivered the vote of thanks. Darunnoor Education Centre is pioneered by reputed Islamic scholars who have contributed socially and educationally in various spheres of the society. The Institute is providing professional and religious education which is hosted under Shaheed C. M. Abdulla Musliyar Foundation Karnataka® established at Kashipatna, a sub-urban enclave 16 KMs from Moodbidri town on the way to Belthangady. Darunnoor Education Centre is set to establish a widespread campus of 12 acres which will provide a healthy learning ambiance to approximately 5000 deserving students, who will pursue their respective professional courses along with strong religious education. The new committee formed for the year 2018 – 19: President: Vice Presidents: General Secretary: Secretaries: Org. Secretaries: Treasurer: Auditor: Advisors: Executive Committee Members:
english
{"meta":{"generated_at":"2015-11-26T19:01:10.778Z","location":"Singapore","api_version":"v1","total_events":2},"events":[{"id":"226415322","name":"Building Castles in the Air - Cybersecurity and the Cloud","description":"In collaboration with HGP Asia, we bring you a very special event on Cyber Security and Cloud Computing, for a series of presentations from industry professionals on cyber security, information risk management, and cloud implementation strategies, now open for our meetup members! \n\n\nThe purpose? Create better awareness of how you can protect valuable corporate data assets that are threatened by cyber attacks improve understanding of the benefits and risks of today's information landscape where cloud solutions become an everyday part of our business A practical understanding of key considerations and strategies for how to adopt Cloud solutions to your organisation \n\n\nSpeakers: <NAME>, Director, HGP Asia <NAME>, Partner, HGP <NAME>, Chief Security Officer Asia, Microsoft Corporation <NAME>, Partner &amp; Senior Consultant, HGP Management Consulting <NAME>, Senior Consultant, HGP Asia \n\n\nNecessary refreshments provided, and we can head off for an informal drink and get-together after the end of the event around 5pm. How's that? :-) Cheers, Ee Bin Organizer Health 2.0 Singapore","location":"Hotel Meritus Mandarin Orchard, 333 Orchard Road, Singapore 238867","latitude":1.302208,"longitude":103.836441,"rsvp_count":4,"url":"http://www.meetup.com/Health-2-0-Singapore/events/226415322/","group_id":7421142,"group_name":"Health 2.0 Singapore","group_url":"http://meetup.com/Health-2-0-Singapore","formatted_time":"27 Nov 2015, Fri, 9:00 am","start_time":"2015-11-27T01:00:00.000Z","end_time":"2015-11-27T10:00:00.000Z","yes_rsvp_count":4},{"id":"226392762","name":"<NAME>","description":"Agenda:  1. Introduce the new PUGS committee members and a word of appreciation for the old exco, Mr. Neo and his team. 2. To discuss PUGS events for the upcoming year (people are welcome to come over and request for training and stuff). Discussion of PyConSG 2016 conference content and committee. ","location":"PayPal office, 5 Temasek Blvd, Suntec Tower Five, Level 7, Singapore","latitude":1.352083,"longitude":103.819839,"rsvp_count":85,"url":"http://www.meetup.com/Singapore-Python-User-Group/events/226392762/","group_id":18417697,"group_name":"Singapore Python User Group","group_url":"http://meetup.com/Singapore-Python-User-Group","formatted_time":"27 Nov 2015, Fri, 7:00 pm","start_time":"2015-11-27T11:00:00.000Z","end_time":"2015-11-27T13:00:00.000Z","yes_rsvp_count":85}]}
json
import type * as core from '../../../core/lib' const BlockItems: { [item: string]: core.FullResourceLocation[] } = { // Coral fans. 'minecraft:brain_coral_fan': [ 'minecraft:brain_coral_fan', 'minecraft:brain_coral_wall_fan', ], 'minecraft:bubble_coral_fan': [ 'minecraft:bubble_coral_fan', 'minecraft:bubble_coral_wall_fan', ], 'minecraft:fire_coral_fan': [ 'minecraft:fire_coral_fan', 'minecraft:fire_coral_wall_fan', ], 'minecraft:horn_coral_fan': [ 'minecraft:horn_coral_fan', 'minecraft:horn_coral_wall_fan', ], 'minecraft:tube_coral_fan': [ 'minecraft:tube_coral_fan', 'minecraft:tube_coral_wall_fan', ], // Heads and skulls. 'minecraft:creeper_head': [ 'minecraft:creeper_head', 'minecraft:creeper_wall_head', ], 'minecraft:dragon_head': [ 'minecraft:dragon_head', 'minecraft:dragon_wall_head', ], 'minecraft:player_head': [ 'minecraft:player_head', 'minecraft:player_wall_head', ], 'minecraft:skeleton_skull': [ 'minecraft:skeleton_skull', 'minecraft:skeleton_wall_skull', ], 'minecraft:wither_skeleton_skull': [ 'minecraft:wither_skeleton_skull', 'minecraft:wither_skeleton_wall_skull', ], // Dead coral fans. 'minecraft:dead_brain_coral_fan': [ 'minecraft:dead_brain_coral_fan', 'minecraft:dead_brain_coral_wall_fan', ], 'minecraft:dead_bubble_coral_fan': [ 'minecraft:dead_bubble_coral_fan', 'minecraft:dead_bubble_coral_wall_fan', ], 'minecraft:dead_fire_coral_fan': [ 'minecraft:dead_fire_coral_fan', 'minecraft:dead_fire_coral_wall_fan', ], 'minecraft:dead_horn_coral_fan': [ 'minecraft:dead_horn_coral_fan', 'minecraft:dead_horn_coral_wall_fan', ], 'minecraft:dead_tube_coral_fan': [ 'minecraft:dead_tube_coral_fan', 'minecraft:dead_tube_coral_wall_fan', ], // Torches. 'minecraft:torch': [ 'minecraft:torch', 'minecraft:wall_torch', ], 'minecraft:soul_torch': [ 'minecraft:soul_torch', 'minecraft:soul_wall_torch', ], 'minecraft:redstone_torch': [ 'minecraft:redstone_torch', 'minecraft:redstone_wall_torch', ], 'minecraft:beetroot_seeds': [ 'minecraft:beetroots', ], 'minecraft:carrot': [ 'minecraft:carrots', ], 'minecraft:cocoa_beans': [ 'minecraft:cocoa', ], 'minecraft:glow_berries': [ 'minecraft:cave_vines', ], 'minecraft:melon_seeds': [ 'minecraft:melon_stem', ], 'minecraft:potato': [ 'minecraft:potatoes', ], 'minecraft:pumpkin_seeds': [ 'minecraft:pumpkin_stem', ], 'minecraft:redstone': [ 'minecraft:redstone_wire', ], 'minecraft:string': [ 'minecraft:tripwire', ], 'minecraft:sweat_berries': [ 'minecraft:sweat_berry_bush', ], 'minecraft:wheat_seeds': [ 'minecraft:wheat', ], } export function getBlocksFromItem(item: core.FullResourceLocation): core.FullResourceLocation[] | undefined { return BlockItems[item] } export function getEntityFromItem(item: core.FullResourceLocation): core.FullResourceLocation | undefined { if (item === 'minecraft:armor_stand') { return item } const result = item.match(/^minecraft:([a-z0-9_]+)_spawn_egg$/) if (result) { return `minecraft:${result[1]}` } return undefined } const SpecialStrings: { [path: string]: string } = { '::minecraft::block::banner::Banner.CustomName': 'mcfunction:argument/minecraft:component', '::minecraft::block::brewingstand::BrewingStand.CustomName': 'mcfunction:argument/minecraft:component', '::minecraft::block::commandblock::CommandBlock.Command': 'mcfunction:command', '::minecraft::block::commandblock::CommandBlock.CustomName': 'mcfunction:argument/minecraft:component', '::minecraft::block::container::ContainerBase.CustomName': 'mcfunction:argument/minecraft:component', '::minecraft::block::enchantingtable::EnchantingTable.CustomName': 'mcfunction:argument/minecraft:component', '::minecraft::block::furnace::Furnace.CustomName': 'mcfunction:argument/minecraft:component', '::minecraft::block::hopper::Hopper.CustomName': 'mcfunction:argument/minecraft:component', '::minecraft::block::sign::Sign.Text1': 'mcfunction:argument/minecraft:component', '::minecraft::block::sign::Sign.Text2': 'mcfunction:argument/minecraft:component', '::minecraft::block::sign::Sign.Text3': 'mcfunction:argument/minecraft:component', '::minecraft::block::sign::Sign.Text4': 'mcfunction:argument/minecraft:component', '::minecraft::entity::effectcloud::EffectCloud.Particle': 'mcfunction:argument/minecraft:particle', '::minecraft::entity::minecart::CommandMinecart.Command': 'mcfunction:command', '::minecraft::entity::mob::LivingEntity.Team': 'mcfunction:argument/minecraft:team', '::minecraft::entity::EntityBase.Tags[]': 'mcfunction:argument/spyglassmc:tag', '::minecraft::item::blockitem::BlockItem.CanPlaceOn[]': 'mcfunction:argument/minecraft:block_predicate', '::minecraft::item::book::WrittenBook.pages[]': 'mcfunction:argument/minecraft:component', '::minecraft::item::ItemBase.CanDestroy[]': 'mcfunction:argument/minecraft:block_predicate', } export function getSpecialStringParser(nbtdocPath: string): string | undefined { return SpecialStrings[nbtdocPath] } const ExpandableCompounds: string[] = [ '::minecraft::item::ItemBase', '::minecraft::entity::marker::Any', ] /** * @param nbtdocPath Path of the nbtdoc compound definition. */ export function isExpandableCompound(nbtdocPath: string): boolean { return ExpandableCompounds.includes(nbtdocPath) }
typescript
Kareena Kapoor on box office debacle of 'Shamshera' Actress Kareena Kapoor is super excited for the release of her upcoming film 'Laal Singh Chaddha' and these days, she is busy with promotions of the same. During one such promotional interview, Kareena was asked to share her opinion on cousin Ranbir Kapoor's recent box office failure 'Shamshera'. In response Kareena shared that it'd be inappropriate of her to comment on the film for multiple reasons. She told India Today, "I am nobody to talk about a particular film because (a) I haven’t seen the film. And (b) I think everybody operates differently. Everybody, kind of, treats and takes their film very differently. Like I said, some people are very attached and some people are not. " "So, it is a very individualistic kind of thing. Every actor operates and comes from a different area and every director does. To comment on that would be very wrong on my part,” she further added. Starring and produced by Aamir Khan, 'Laal Singh Chaddha' is set to release theatrically on 11th of August. Follow us on Google News and stay updated with the latest!
english
{"nom":"Sainte-Croix","circ":"1ère circonscription","dpt":"Aisne","inscrits":97,"abs":28,"votants":69,"blancs":1,"nuls":0,"exp":68,"res":[{"nuance":"FN","nom":"<NAME>","voix":28},{"nuance":"REM","nom":"Mme <NAME>","voix":20},{"nuance":"SOC","nom":"<NAME>","voix":7},{"nuance":"LR","nom":"M. <NAME>","voix":6},{"nuance":"DIV","nom":"M. <NAME>","voix":3},{"nuance":"EXG","nom":"<NAME>","voix":2},{"nuance":"ECO","nom":"Mme <NAME>","voix":2},{"nuance":"FI","nom":"M. <NAME>","voix":0},{"nuance":"DIV","nom":"M. <NAME>","voix":0},{"nuance":"DLF","nom":"M. <NAME>","voix":0}]}
json
Indian shooters finished the 2018 ISSF World Shooting Championships with their best ever performance. At the 52nd edition of the tournament in Changwon, South Korea, the Indian shooters managed to win a total of seven medals in the senior category. The seven medals included two golds, four silvers and one bronze medal. India finished on the ninth spot with China leading the way with a total of 21 medals, nine of which were gold. In the men’s 50m pistol event, Om Prakash Mitharwal clinched the gold medal with a score of 564. Mitharwal, along with Shahzar Rizvi and Abhishek Verma won a silver in the men’s 10m air pistol team event. The second gold came in the men’s double trap event. 2018 Commonwealth Games bronze medallist, Ankur Mittal, achieved his career-best triumph after winning the medal. He teamed up with Asab Mohd and Shardul Vihan to get a bronze in the men’s double trap team event. It was Ankur’s third medal at the World Championships. Gurpreet Singh won a silver medal in the men’s 25m standard pistol event. It was the first World Championship medal for the 30-year old. The men’s team in the standard pistol team event missed out on the bronze medal after Gurpreet, Amanpreet Singh and Vijay Kumar finished fourth with a score of 1699. After a disappointing 2018 Asian Games, Anjum Moudgil made a roaring comeback at the World Shooting Championships. She became the only Indian woman shooter to win a medal in the 10m Air Rifle event. Anjum won a silver medal behind Hana Im of Korea. Apurvi Chandela finished fourth in the event, earning India two quota places for the 2020 Tokyo Olympics. The women’s team of Anjum Moudgil, Apurvi Chandela and Mehuli Ghosh won a silver medal in the team event of 10m Air Rifle to give India another medal. While the senior team managed to bring laurels to the nation, the junior shooters of the team were not far behind. With a total of 20 medals from the junior team, Indian contingent returned home with 11 gold, nine silver and seven bronze medals. This was India’s best-ever finish at the World Shooting Championships. The juniors won nine gold, five silver and six bronze medals. The Indian junior shooters finished on the second spot after China, who won just two gold medals more than the Indians. The 2018 Asian Games gold medallist, Saurabh Chaudhary, won a gold in the 10m air pistol event. He also broke his own world record with a score of 245.5 points. India’s Arjun Singh Cheema won the bronze medal in the same category. The duo teamed with Anmol Anmol to win a silver in the team event of 10 m air pistol. Indian shooters showed their complete dominance in the men’s 25m pistol, 25m standard pistol, 50m pistol and the Double trap events. They went on to win the gold medal in each of the individual and team events. Along with that, Gaurav Rana won a bronze in the 50m pistol event and Shapath Bharadwaj got another bronze in the double trap event. The Indian skeet and trap team won silver medals in their respective events, while Gurnihal Singh Garcha won a bronze in the skeet event. Hriday Hazarika won a gold in the 10m air rifle event. In the women’s junior 10m air rifle event, Elavenil Valarivan and Shreya Agrawal clinched a silver and a bronze respectively. The trio of Valarivan, Agrawal and Manini Kaushik brought home a gold in the team event of 10m air rifle. They also broke the juniors world record on their way to the gold medal. Manisha Keer won a silver medal in the trap individual event. In the mixed team events, the pairs of Shreya Agrawal / Divyansh Singh Panwar and Abhidnya Ashok Patil / Saurabh Chaudhary won a bronze each in 10m air rifle and air pistol event respectively.
english
<filename>ERPClient/src/main/java/blstubdriver/ExaminationBLService_Stub.java package blstubdriver; import java.time.LocalDate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import blservice.examinationblservice.ExaminationBLService; import util.BillState; import util.BillType; import util.ResultMessage; import vo.AccountBillItemVO; import vo.AccountBillVO; import vo.AccountVO; import vo.BillVO; import vo.GoodsItemVO; import vo.GoodsVO; import vo.InventoryBillVO; import vo.PurchaseVO; public class ExaminationBLService_Stub implements ExaminationBLService{ ArrayList<BillVO> billList = new ArrayList<BillVO>(); ArrayList<AccountBillItemVO> billItem = new ArrayList<AccountBillItemVO>(); ArrayList<GoodsItemVO> goodsItemList=new ArrayList<GoodsItemVO>(); { AccountVO account = new AccountVO("001","工商银行账户1",2000); AccountBillItemVO Item = new AccountBillItemVO(account, 2000, "无"); billItem.add(Item); GoodsItemVO gi1=new GoodsItemVO("01", "霓虹灯",null ,20, 35.0, "耐用"); GoodsItemVO gi2=new GoodsItemVO("02", "挂灯",null, 10, 35.0, "好看"); goodsItemList.add(gi1); goodsItemList.add(gi2); } AccountBillVO accountBill = new AccountBillVO(LocalDate.now().toString(), "XSFKD-20171021-00001", BillState.SUBMITTED, BillType.PAYMENT, "ZLK", "Aster",billItem); PurchaseVO purchaseBill=new PurchaseVO(BillType.PURCHASE,BillState.SUBMITTED,"JHTHD-20171022-00002","供应商2" ,"00000002","默认仓库","阿明",goodsItemList,"好看" ,LocalDate.now().toString()); public ArrayList<BillVO> show() { // TODO Auto-generated method stub billList.add(accountBill); billList.add(purchaseBill); return billList; } public BillVO checkReceipt(String billID) { // TODO Auto-generated method stub if(billID == "XSFKD-20171021-00001"){ return accountBill; } else{ System.out.println("Check failed!"); return null; } } public ResultMessage modifyReceipt(BillVO bill) { // TODO Auto-generated method stub if(bill.ID.equals("XSFKD-20171021-00001")){ accountBill = (AccountBillVO)bill; System.out.println("Modify Bill Success!"); return ResultMessage.SUCCESS; } else{ System.out.println("Modify Bill Failed!"); return ResultMessage.NOT_EXIST; } } public ResultMessage approveReceipt(BillVO bill) { // TODO Auto-generated method stub bill.state = BillState.PASS; return ResultMessage.SUCCESS; } @Override public ResultMessage refuseReceipt(BillVO bill) { // TODO Auto-generated method stub bill.state = BillState.FAILED; return ResultMessage.SUCCESS; } }
java
Actress and model Urvashi Rautela’s recent appearance at the 75th Annual Cannes Film Festival was full of glamour and grace. The actress donned some stunning red carpet creations that became a welcoming sight on our Instagram feed. Seems that it was not just us who were in awe of Urvashi’s graceful red carpet looks, but Hollywood actor Leonardo DiCaprio also liked her looks. In a recent interview, Urvashi revealed that Leonardo complimented her at Cannes during one of her appearances. Speaking to news agency IANS, Urvashi said, “I was freaking out and falling short of words after receiving compliments from Leonardo DiCaprio. I was so emotional and could feel happy tears in my eyes. ” Urvashi added that at the same time she was blushing as well. The Hate Story 4 actress told IANS that the 47-year-old actor also appreciated her as a “very talented actress. ” She mentioned that seeing Leonardo praising her work made her pinch herself. “Did that really happen last night? Was I dreaming about the sweet moment? ” For Urvashi, this incident proved that even the younger actors want to be out there. She said that young actors want to be inspired and keep going. “That’s my memory of meeting him," she added. For her latest Cannes film festival red carpet look, Urvashi wore an all-black strapless gown. The gown was designed by Ali Younes and featured dramatic ruffles all over the bodice. The actress styled her hair in a neat bun parted in the middle and accessorized her look with a diamond choker and emerald drop earrings. At Cannes this year, she launched the poster of her Tamil debut film The Legend. Read all the Latest News , Breaking News and IPL 2022 Live Updates here.
english
import React, { PureComponent } from 'react'; import { Col, Divider, Form, Input, InputNumber, Modal, Row, Select, Spin } from 'hzero-ui'; import { Bind } from 'lodash-decorators'; import { isUndefined } from 'lodash'; import Lov from 'components/Lov'; import Switch from 'components/Switch'; import intl from 'utils/intl'; import { CODE_UPPER } from 'utils/regExp'; const { Option } = Select; const FormItem = Form.Item; const formLayout = { labelCol: { span: 6 }, wrapperCol: { span: 16 }, }; @Form.create({ fieldNameProp: null }) export default class Drawer extends PureComponent { @Bind() onOk() { const { onOk, form, executorConfigList } = this.props; form.validateFields((error, fieldsValue) => { if (!error) { const params = fieldsValue; if (executorConfigList.length > 0) { const strategyParam = { jobWeight: {} }; executorConfigList.forEach((item, index) => { Object.assign(strategyParam, { jobWeight: { ...strategyParam.jobWeight, [`${item.address}`]: fieldsValue[`${item.configId}/${index}`], }, }); delete params[`${item.configId}/${index}`]; }); if (fieldsValue.failStrategy === 'RETRY' && fieldsValue.retryNumber !== undefined) { Object.assign(strategyParam, { retryNumber: fieldsValue.retryNumber }); } Object.assign(params, { strategyParam }); } onOk(params); } }); } /** * 监听执行器策略选择 * @param {string} data - 执行器策略 */ @Bind() executorStrategyConfig(data) { const { form, initData = {}, onConfig = (e) => e } = this.props; const { executorId } = initData; const strategy = data; if (form.getFieldValue('executorId') !== undefined && strategy === 'JOB_WEIGHT') { if ( initData.executorStrategy === 'JOB_WEIGHT' && executorId === form.getFieldValue('executorId') && strategy === 'JOB_WEIGHT' ) { onConfig(initData); } else { onConfig({ executorId: form.getFieldValue('executorId') }); } } else { onConfig(); } } @Bind() executorChange(_, data) { const { form, onConfig = (e) => e } = this.props; const executorStrategy = form.getFieldValue('executorStrategy'); if (data !== undefined && executorStrategy === 'JOB_WEIGHT') { onConfig(data); } else { onConfig(); } } @Bind() renderConfigList() { const { form, configLoading = false, executorConfigList = [] } = this.props; const { getFieldDecorator } = form; return ( <Spin spinning={configLoading}> <Divider orientation="left"> {intl.get('hsdr.executable.model.executable.actuator').d('执行器配置列表')} </Divider> <Row> {executorConfigList.map((item, index) => { const { weight, address, configId } = item; return ( <Col span={24} key={configId}> <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} label={`${address}`}> {getFieldDecorator(`${configId}/${index}`, { initialValue: weight, })(<InputNumber />)} </FormItem> </Col> ); })} </Row> </Spin> ); } render() { const { tenantId, form, initData = {}, executable, title, visible, onCancel, loading, detailLoading = false, } = this.props; const { getFieldDecorator } = form; const { exeTypeList = [], executorStrategyList = [], failStrategyList = [], executorConfigList = [], } = executable; const { executorName, executableId, executorId, executableCode, exeTypeCode, jobHandler, executableName, executableDesc, failStrategy, strategyParam, executorStrategy, enabledFlag = 1, } = initData; return ( <Modal width={620} title={title} visible={visible} wrapClassName="ant-modal-sidebar-right" transitionName="move-right" onOk={this.onOk} onCancel={onCancel} confirmLoading={loading} destroyOnClose > <Spin spinning={detailLoading}> <Form> <FormItem {...formLayout} label={intl.get('hsdr.executable.model.executable.executableCode').d('可执行编码')} > {getFieldDecorator('executableCode', { initialValue: executableCode, rules: [ { required: true, message: intl.get('hzero.common.validation.notNull', { name: intl .get('hsdr.executable.model.executable.executableCode') .d('可执行编码'), }), }, { pattern: CODE_UPPER, message: intl .get('hzero.common.validation.codeUpper') .d('全大写及数字,必须以字母、数字开头,可包含“-”、“_”、“.”、“/”'), }, ], })( <Input trim typeCase="upper" inputChinese={false} disabled={!isUndefined(executableId)} /> )} </FormItem> <FormItem {...formLayout} label={intl.get('hsdr.executable.model.executable.executableName').d('可执行名称')} > {getFieldDecorator('executableName', { initialValue: executableName, rules: [ { required: true, message: intl.get('hzero.common.validation.notNull', { name: intl .get('hsdr.executable.model.executable.executableName') .d('可执行名称'), }), }, ], })(<Input />)} </FormItem> <FormItem {...formLayout} label={intl.get('hsdr.executable.model.executable.exeType').d('可执行类型')} > {getFieldDecorator('exeTypeCode', { initialValue: exeTypeCode, rules: [ { type: 'string', required: true, message: intl.get('hzero.common.validation.notNull', { name: intl.get('hsdr.executable.model.executable.exeType').d('可执行类型'), }), }, ], })( <Select style={{ width: '100%' }}> {exeTypeList.map((item) => ( <Option label={item.meaning} value={item.value} key={item.value}> {item.meaning} </Option> ))} </Select> )} </FormItem> <FormItem {...formLayout} label={intl.get('hsdr.executable.model.executable.exeHandler').d('JobHandler')} > {getFieldDecorator('jobHandler', { initialValue: jobHandler, rules: [ { required: form.getFieldValue('exeTypeCode') === 'SIMPLE', message: intl.get('hzero.common.validation.notNull', { name: intl.get('hsdr.executable.model.executable.jobHandler').d('JobHandler'), }), }, ], })(<Input />)} </FormItem> <FormItem {...formLayout} label={intl.get('hsdr.executable.model.executable.executableDesc').d('可执行描述')} > {getFieldDecorator('executableDesc', { initialValue: executableDesc, })(<Input />)} </FormItem> <FormItem {...formLayout} label={intl.get('hsdr.executable.model.executable.groupId').d('执行器')} > {getFieldDecorator('executorId', { initialValue: executorId, rules: [ { required: true, message: intl.get('hzero.common.validation.notNull', { name: intl.get('hsdr.executable.model.executable.groupId').d('执行器'), }), }, ], })( <Lov allowClear={false} code="HSDR.AVAIL_EXECUTOR" onChange={this.executorChange} textValue={executorName} queryParams={{ tenantId }} /> )} </FormItem> <FormItem {...formLayout} label={intl.get('hsdr.executable.model.executable.executorStrategy').d('执行器策略')} > {getFieldDecorator('executorStrategy', { initialValue: executorStrategy, rules: [ { type: 'string', required: true, message: intl.get('hzero.common.validation.notNull', { name: intl .get('hsdr.executable.model.executable.executorStrategy') .d('执行器策略'), }), }, ], })( <Select style={{ width: '100%' }} onChange={this.executorStrategyConfig}> {executorStrategyList.map((item) => ( <Option label={item.meaning} value={item.value} key={item.value}> {item.meaning} </Option> ))} </Select> )} </FormItem> <FormItem {...formLayout} label={intl.get('hsdr.executable.model.executable.failStrategy').d('失败处理策略')} > {getFieldDecorator('failStrategy', { initialValue: failStrategy, rules: [ { type: 'string', required: true, message: intl.get('hzero.common.validation.notNull', { name: intl .get('hsdr.executable.model.executable.failStrategy') .d('失败处理策略'), }), }, ], })( <Select style={{ width: '100%' }}> {failStrategyList.map((item) => ( <Option label={item.meaning} value={item.value} key={item.value}> {item.meaning} </Option> ))} </Select> )} </FormItem> {form.getFieldValue('failStrategy') === 'RETRY' && ( <FormItem label={intl.get('hsdr.executable.model.executable.retryNumber').d('重试次数')} {...formLayout} > {getFieldDecorator('retryNumber', { initialValue: strategyParam && JSON.parse(strategyParam).retryNumber, })(<InputNumber min={0} step={1} style={{ width: '100%' }} />)} </FormItem> )} <FormItem label={intl.get('hzero.common.status').d('状态')} {...formLayout}> {getFieldDecorator('enabledFlag', { initialValue: enabledFlag, })(<Switch />)} </FormItem> {executorConfigList.length > 0 ? this.renderConfigList() : null} </Form> </Spin> </Modal> ); } }
javascript
Bhubaneswar: The Archaeological Survey of India (ASI) Thursday started removing sand from ‘Jagamohana’ (audience hall) of 13th century Sun temple at Konark in Odisha’s Puri district for better conservation. Jagamohana, which is around 128 feet tall, is the principal surviving structure in the ruins. Nata Mandira (dance hall), and Bhoga Mandapa (dining hall) are among the other surviving structures. Senior ASI officials performed ‘Bhoomi Pujan’ before commencing work. British colonial rulers had filled river sand in the audience hall of the temple in 1903 to check further collapse of the structure, ASI said in a statement. It is estimated that the entire process will take up to three years for completion, an official said. The necessity to remove sand from the audience hall was felt for long and many experts, historians and engineers have opined in favour of it for better conservation of the Konark temple, a UNESCO World Heritage Site. “Odisha engineers and IIT Madras are rendering technical advice to the ASI for the successful execution of work,” ASI superintending archaeologist Arun Mallick said. “We have worked hard for the last two years to commence the project. After conferring with experts, including renowned archaeologists, engineers and architects through seminars, we have formulated a safe way to remove the sand,” he said. The structural condition, foundation and internal geometry were studied with the help of modern technical devices, another official said. The sanctum sanctorum of the temple, called ‘Vimana’ was 229 feet tall. It collapsed around 1837. While there is no record suggesting how and when the structures in the temple complex collapsed, certain historical evidence suggests that the damage was caused between 16th and 17th centuries.
english
#!/usr/bin/python # Written by <NAME> for funzies in 2017 # from termcolor import colored def format_targets(targets, newSurface): formattedTargets = [] i = 0 for target in targets: if target in newSurface: formattedTargets.append("%-8s%-56s" % (i, target + ' [*]')) else: formattedTargets.append("%-8s%-56s" % (i, target)) i += 1 return formattedTargets def format_responses(responses): formattedResponses = [] for (status, urlRes) in responses: formattedResponses.append("%-8s%s" % (status, urlRes)) return formattedResponses # Primary function for rendering output. # Helper functions are above. def render_output(surface, newSurface): targets = format_targets(surface.get_pending(), newSurface) responses = [] fmtRes = [] rqs = surface.get_requests() # Format the response list right for key in rqs.keys(): rqObj = rqs[key] resString = '' if key.rstrip('/') != rqObj.url.rstrip('/'): resString = key + ' -> ' + rqObj.url else: resString = key fmtRes.append((str(rqObj.status_code), resString)) responses = format_responses(fmtRes) numTargets = len(targets) numResponses = len(responses) # Padd the lists rows = max(numTargets, numResponses) while (len(targets) < rows): targets.append("%-8s%-56s" % ("", "")) while (len(responses) < rows): responses.append("%-8s%s" % ("", "")) output = [] # print "Discovered: %d" % newSurface print "%-64s | %s" % (">> SCOUTED << [%d NEW]" % len(newSurface), ">> EXPLORED <<") print "%-8s%-56s | %-8s%s" % ("ID", "URL", "STATUS", "URL") for i in range(0, rows): output.append("%s | %s" % (targets[i], responses[i])) print "%s | %s" % (targets[i], responses[i]) # targetList = ["http://abc.com", "http://abc.com/a", "http://abc.com/b"] # resList = [("200", "http://abc.com/home"), ("404", "http://abc.com/biz")] # # print_output(format_targets(targetList), format_responses(resList))
python
<filename>18/Mündliche Frage/18-71113.json { "vorgangId": "71113", "VORGANG": { "WAHLPERIODE": "18", "VORGANGSTYP": "Mündliche Frage", "TITEL": "Unterschiedliche Auslegungen der \"guten Bleibeperspektive\" bei der Bundesagentur für Arbeit und dem Bundesamt für Migration und Flüchtlinge", "AKTUELLER_STAND": "Beantwortet", "SIGNATUR": "", "GESTA_ORDNUNGSNUMMER": "", "PLENUM": { "PLPR_KLARTEXT": "Mündliche Frage/Schriftliche Antwort", "PLPR_HERAUSGEBER": "BT", "PLPR_NUMMER": "18/145", "PLPR_SEITEN": "14326A - 14326B", "PLPR_LINK": "http://dipbt.bundestag.de:80/dip21/btp/18/18145.pdf#P.14326" }, "EU_DOK_NR": "", "SCHLAGWORT": [ "Asylbewerber", { "_fundstelle": "true", "__cdata": "Aufenthaltsrecht" }, "Ausländerintegration", { "_fundstelle": "true", "__cdata": "Bundesagentur für Arbeit" }, { "_fundstelle": "true", "__cdata": "Bundesamt für Migration und Flüchtlinge" }, "Flüchtling", "Sozialgesetzbuch III" ], "ABSTRAKT": "Originaltext der Frage(n): \r\n \r\nTeilt die Bundesregierung die Darstellung des Bremer Instituts für Arbeitsmarktforschung und Jugendberufshilfe (BIAJ), dass bei der Bundesagentur für Arbeit (BA) und beim Bundesamt für Migration und Flüchtlinge (BAMF) unterschiedliche Auslegungen der \"guten Bleibeperspektive\" existieren (vgl. http://biaj.de/archiv-kurzmitteilungen/36-texte-biaj-kurzmitteilungen/715-ba-und-bamf-zwei-abweichende-auffassungen-zu-mit-guter-bleibeperspektive-421-sgb-iii.html; bitte begründen), und aus welchem Grund wird der Kreis der Personen \"mit guter Bleibeperspektive\", der bei der BA bis zum 31. Dezember 2015 über die Möglichkeit der Teilnahme an Sprachkursen nach § 421 des Dritten Buches Sozialgesetzbuch und beim BAMF über die Möglichkeit der Teilnahme an Integrationskursen entscheidet, in den einzelnen Bereichen unterschiedlich gefasst?" }, "VORGANGSABLAUF": { "VORGANGSPOSITION": [ { "ZUORDNUNG": "BT", "URHEBER": "Mündliche Frage ", "FUNDSTELLE": "11.12.2015 - BT-Drucksache 18/6996, Nr. 14", "FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/btd/18/069/1806996.pdf" }, { "ZUORDNUNG": "BT", "URHEBER": "Mündliche Frage/Schriftliche Antwort", "FUNDSTELLE": "16.12.2015 - BT-Plenarprotokoll 18/145, S. 14326A - 14326B", "FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/btp/18/18145.pdf#P.14326", "PERSOENLICHER_URHEBER": [ { "VORNAME": "Brigitte", "NACHNAME": "Pothmer", "FUNKTION": "MdB", "FRAKTION": "BÜNDNIS 90/DIE GRÜNEN", "AKTIVITAETSART": "Frage", "SEITE": "14326A" }, { "PERSON_TITEL": "Dr.", "VORNAME": "Günter", "NACHNAME": "Krings", "FUNKTION": "Parl. Staatssekr.", "RESSORT": "Bundesministerium des Innern", "AKTIVITAETSART": "Antwort", "SEITE": "14326A" } ] } ] } }
json
import Mongoose from 'mongoose'; import factory from '../../utils/factories'; import Vehicle from '../../../src/app/models/Vehicle'; import Controller from '../../../src/app/controllers/VehicleController'; const res = { status: jest.fn(() => { return res; }), json: jest.fn(response => response), }; describe('Vehicle controller', () => { beforeAll(async () => { await Mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, }); }); beforeEach(async () => { await Vehicle.deleteMany(); }); afterAll(async () => { await Mongoose.disconnect(); }); it('should be able to get a list of vehicles', async () => { const vehicles = await factory.createMany('Vehicle', 3); const response = await Controller.index({}, res); expect(response.map(v => v.toObject())).toStrictEqual( vehicles.map(v => v.toObject()) ); }); it('should be able to store a new vehicle', async () => { const { type } = await factory.attrs('Vehicle'); await Controller.store({ body: { type } }, res); expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ type })); }); it('should be able to update a vehicle', async () => { const { _id: id } = await factory.create('Vehicle'); const { type } = await factory.attrs('Vehicle'); await Controller.update({ params: { id }, body: { type } }, res); expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ type })); }); it('should not be able to update a vehicle that not exists', async () => { const vehicle = await factory.create('Vehicle'); const { type } = await factory.attrs('Vehicle'); await vehicle.delete(); await Controller.update( { params: { id: vehicle._id }, body: { type } }, res ); expect(res.status).toHaveBeenCalledWith(404); expect(res.json).toHaveBeenCalledWith({ error: { message: 'Vehicle not found', }, }); }); });
javascript
<gh_stars>0 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package business; import dao.Camioneta_cargaDAO; import dao.VeiculoDAO; import dao.VeiculologDAO; import java.util.ArrayList; import model.Camioneta_carga; import model.Veiculo; import model.Veiculolog; /** * * @author <NAME> */ public class VeiculologBusiness { private static VeiculologBusiness instance; private VeiculologDAO dao; public static VeiculologBusiness getInstance(){ if (instance == null) { instance = new VeiculologBusiness(); } return instance; } private VeiculologBusiness(){ dao = VeiculologDAO.getInstance(); } public Veiculolog getById(int id){ return dao.getById(id); } public ArrayList<Veiculolog> getAll(){ return dao.getAll(); } }
java
// Day 15: Beverage Bandits import { parseFile } from '../helpers'; import { displayMap, getCardinalNeighbours, getRemainingHP, hasBattleEnded, sortEnemiesByProximityAndHP, sortUnits, Coords, Graph, Map, MapSquare, PositionWithAdjacentsMoves, Unit, } from './utils'; const part1 = (content: string[], points = undefined) => { const map: Map = []; let units: Unit[] = []; content.forEach((line: string, y: number) => { line.split('').forEach((char, x: number) => { map[x] = map[x] ? map[x] : []; if (['E', 'G'].includes(char)) { units.push({ team: char, x, y, HP: 200 }); map[x][y] = '.'; } else { map[x][y] = char; } }); }); let round = 0; while (!hasBattleEnded(units)) { let i = 0; for (i; i < units.length; i++) { let unit = units[i]; // if unit does not have a team it is dead if (unit.team) { const opponentTeam = unit.team === 'E' ? 'G' : 'E'; const enemies = getPathsToAccessibleOpponents( unit, opponentTeam, units, map ); let { closestEnemies } = enemies.reduce(sortEnemiesByProximityAndHP, { closestEnemies: [], shortestPathCount: undefined, }); let closestEnemy = closestEnemies[0]; // make a move on the map if (closestEnemy) { if (closestEnemy.path.length > 0) { const i = units.findIndex(u => u.x === unit.x && u.y === unit.y); units[i].x = closestEnemy.path[0].x; units[i].y = closestEnemy.path[0].y; const result = enemies .map(enemy => { enemy.path.shift(); return enemy; }) .reduce(sortEnemiesByProximityAndHP, { closestEnemies: [], shortestPathCount: undefined, }); [closestEnemy] = result.closestEnemies; } if (!closestEnemy.path.length) { units = attackUnit( units, closestEnemy.target, points && points[unit.team] ); } } } // round ends prematurely if the last unit that had its turn is not the last available unit if (hasBattleEnded(units) && i < units.length - 1) { break; } } // a complete round is where all alive units had its turn // if the round is terminated because the last opponent died // with remaining units waiting for its turn, the round is not considered completed if (i === units.length) { round++; units.sort(sortUnits); } } const remainingHPs = getRemainingHP(units); const output = round * remainingHPs; console.log(displayMap(map, units)); console.log(units); return output; }; const part2 = (content: string[]) => { return part1(content, { E: 26, G: 3 }); }; const attackUnit = (units: Unit[], unit: Unit, points: number = 3) => { const i = units.findIndex(u => u.x === unit.x && u.y === unit.y); if (units[i].HP >= points) { units[i].HP -= points; } else { units[i] = { team: null, x: null, y: null, HP: 0, }; } return units; }; const getPathsToAccessibleOpponents = ( attacker: Unit, opponentTeam: string, units: Unit[], map: Map ): { target: Unit; path: Coords[] }[] => { const directOpponents = getCardinalNeighbours(attacker, units, map) .filter(({ value }) => value === opponentTeam) .map((o: MapSquare) => ({ target: { x: o.x, y: o.y, team: o.value, HP: units.find(u => u.x === o.x && u.y === o.y).HP, }, path: [], })) // weakest adjacent opponent takes priority .sort( (a, b) => a.target.HP - b.target.HP || a.target.y - b.target.y || a.target.x - b.target.x ); // if there is no opponent within immediate range, calculate the path // to get to each enemy return directOpponents.length ? directOpponents : units .filter(t => t.team === opponentTeam) .map(unit => { const availables = getCardinalNeighbours(unit, units, map).filter( ({ value }) => value === '.' ); // if no available spot at direct surroudings of current attacker, // returns null path so the attacking unit knows to ignore this target const path = getShortestPath(attacker, availables, units, map); return { target: unit, path: availables.length && path ? path : null, }; }) .filter(({ path }) => path) .sort((a, b) => { const shortestPath = a.path.length - b.path.length; if (shortestPath !== 0) { return shortestPath; } for (let i = a.path.length - 1; i >= 0; i--) { const sort = sortUnits(a.path[i], b.path[i]); if (sort !== 0) { return sort; } } return 0; }); }; /** * Get shortest paths to reach an enemy. There could be multiple possible * paths with the same move cost. * */ const getShortestPath = ( attacker: Unit, targetSpots: MapSquare[], units: Unit[], map: Map ): MapSquare[] => { let start = attacker; const graph = [moveByOne([], units, map, start)]; let i = 0; let spotFound: MapSquare; [spotFound] = graph[i].nexts.filter((next: MapSquare) => targetSpots.find(target => next.x === target.x && next.y === target.y) ); if (!spotFound) { while ( i < graph.length && graph[i].nexts.filter(next => targetSpots.find(target => next.x === target.x && next.y === target.y) ).length === 0 ) { for (let pos of graph[i].nexts) { if (graph.find(node => node.x === pos.x && node.y === pos.y)) { continue; } else { graph.push(moveByOne(graph, units, map, pos)); [spotFound] = graph[ graph.length - 1 ].nexts.filter((next: MapSquare) => targetSpots.find( target => next.x === target.x && next.y === target.y ) ); if (spotFound) { break; } } } if (spotFound) { break; } else { i++; } } } if (spotFound) { const path: MapSquare[] = []; const { x, y } = spotFound; path.unshift({ x, y }); while (true) { const { x: lastX, y: lastY } = path[0]; const parent = graph.find( ({ nexts }) => !!nexts.find( (node: MapSquare) => node.x === lastX && node.y === lastY ) ); if (parent && !(parent.x === attacker.x && parent.y === attacker.y)) { path.unshift({ x: parent.x, y: parent.y }); } else { break; } } return path; } else { // there is no possible path to get to the target return null; } }; /** * Get the next possible steps from a given point. * Next steps must be available spots (aka a dot) and not already visited * */ const moveByOne = ( graph: Graph, units: Unit[], map: Map, coords: Coords ): PositionWithAdjacentsMoves => ({ x: coords.x, y: coords.y, nexts: getCardinalNeighbours(coords, units, map).filter( ({ x, y, value }) => value === '.' && !graph.find((n: PositionWithAdjacentsMoves) => n.x === x && n.y === y) ), }); (() => { const args = process.argv.slice(2); const filePath = args[0] || 'day15.txt'; const content = parseFile(filePath); console.log(`part1: ${part1(content)}`); console.log(`part2: ${part2(content)}`); })();
typescript
<reponame>jeemb/word-search body { background-image: url("/img-noise.png"); } h1 { text-align: center; } h3 { font-size: 1.2em; text-align: center; } form { text-align: center; padding-top: 50px; } p { text-align: center; padding-top: 20px; }
css
- 29:1 Hebrew the first day of the seventh month. This day in the ancient Hebrew lunar calendar occurred in September or October. This festival is celebrated today as Rosh Hashanah, the Jewish new year. New Living Translation (NLT) Holy Bible, New Living Translation, copyright © 1996, 2004, 2015 by Tyndale House Foundation. Used by permission of Tyndale House Publishers, Inc., Carol Stream, Illinois 60188. All rights reserved. NLT Compact Giant Print Bible, Filament Enabled Edition (Red Letter, LeatherLike, Navy Blue Cross)
english
<gh_stars>1-10 #[macro_export] macro_rules! as_op { () => { fn as_op(&self) -> &dyn Op { self } fn as_op_mut(&mut self) -> &mut dyn Op { self } }; } #[macro_export] macro_rules! pulsed_op_to_typed_op { () => { fn to_typed(&self) -> Box<dyn TypedOp> { $crate::dyn_clone::clone_box(self) } }; } #[macro_export] macro_rules! op_as_typed_op { () => { fn as_typed(&self) -> Option<&dyn TypedOp> { Some(self) } }; } #[macro_export] macro_rules! not_a_typed_op { () => { fn as_typed(&self) -> Option<&dyn TypedOp> { None } }; } #[macro_export] macro_rules! op_as_pulsed_op { () => { fn as_pulsed(&self) -> Option<&dyn PulsedOp> { Some(self) } }; } #[macro_export] macro_rules! not_a_pulsed_op { () => { fn as_pulsed(&self) -> Option<&dyn PulsedOp> { None } }; } #[macro_export] macro_rules! op_core { () => { fn op_families(&self) -> &'static [&'static str] { &["core"] } }; } #[macro_export] macro_rules! op_core_mir { () => { fn op_families(&self) -> &'static [&'static str] { &["core", "mir"] } }; } #[macro_export] macro_rules! op_core_lir { () => { fn op_families(&self) -> &'static [&'static str] { &["core", "lir"] } }; } #[macro_export] macro_rules! op_core_lir_mir { () => { fn op_families(&self) -> &'static [&'static str] { &["core", "lir", "mir"] } }; } #[macro_export] macro_rules! canonic { () => { fn is_canonic(&self) -> bool { true } }; } #[macro_export] macro_rules! args_1 { ($inputs:expr) => {{ if $inputs.len() != 1 { $crate::error_chain::bail!("Expected 1 arg, got {:?}", $inputs) } let result = $inputs.pop().unwrap(); ::std::mem::drop($inputs); result }}; } #[macro_export] macro_rules! args_2 { ($inputs:expr) => {{ if $inputs.len() != 2 { $crate::error_chain::bail!("Expected 2 arg, got {:?}", $inputs) } $inputs.reverse(); let result = ($inputs.pop().unwrap(), $inputs.pop().unwrap()); ::std::mem::drop($inputs); result }}; } #[allow(unused_macros)] #[macro_export] macro_rules! args_3 { ($inputs:expr) => {{ if $inputs.len() != 3 { $crate::error_chain::bail!("Expected 3 arg, got {:?}", $inputs) } $inputs.reverse(); let result = ($inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap()); ::std::mem::drop($inputs); result }}; } #[allow(unused_macros)] #[macro_export] macro_rules! args_4 { ($inputs:expr) => {{ if $inputs.len() != 4 { $crate::error_chain::bail!("Expected 4 arg, got {:?}", $inputs) } $inputs.reverse(); let result = ( $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), ); ::std::mem::drop($inputs); result }}; } #[allow(unused_macros)] #[macro_export] macro_rules! args_5 { ($inputs:expr) => {{ if $inputs.len() != 5 { $crate::error_chain::bail!("Expected 5 arg, got {:?}", $inputs) } $inputs.reverse(); let result = ( $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), ); ::std::mem::drop($inputs); result }}; } #[allow(unused_macros)] #[macro_export] macro_rules! args_6 { ($inputs:expr) => {{ if $inputs.len() != 6 { $crate::error_chain::bail!("Expected 6 arg, got {:?}", $inputs) } $inputs.reverse(); let result = ( $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), ); ::std::mem::drop($inputs); result }}; } #[allow(unused_macros)] #[macro_export] macro_rules! args_7 { ($inputs:expr) => {{ if $inputs.len() != 7 { $crate::error_chain::bail!("Expected 7 arg, got {:?}", $inputs) } $inputs.reverse(); let result = ( $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), ); ::std::mem::drop($inputs); result }}; } #[allow(unused_macros)] #[macro_export] macro_rules! args_8 { ($inputs:expr) => {{ if $inputs.len() != 8 { $crate::error_chain::bail!("Expected 8 arg, got {:?}", $inputs) } $inputs.reverse(); let result = ( $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), $inputs.pop().unwrap(), ); ::std::mem::drop($inputs); result }}; } #[macro_export] macro_rules! dispatch_datum { ($($path:ident)::* ($dt:expr) ($($args:expr),*)) => { { use $crate::datum::DatumType; match $dt { DatumType::Bool => $($path)::*::<bool>($($args),*), DatumType::U8 => $($path)::*::<u8>($($args),*), DatumType::U16 => $($path)::*::<u16>($($args),*), DatumType::U32 => $($path)::*::<u32>($($args),*), DatumType::U64 => $($path)::*::<u64>($($args),*), DatumType::I8 => $($path)::*::<i8>($($args),*), DatumType::I16 => $($path)::*::<i16>($($args),*), DatumType::I32 => $($path)::*::<i32>($($args),*), DatumType::I64 => $($path)::*::<i64>($($args),*), DatumType::F16 => $($path)::*::<f16>($($args),*), DatumType::F32 => $($path)::*::<f32>($($args),*), DatumType::F64 => $($path)::*::<f64>($($args),*), DatumType::Blob => $($path)::*::<Blob>($($args),*), DatumType::TDim => $($path)::*::<TDim>($($args),*), DatumType::String => $($path)::*::<String>($($args),*), } } } } #[macro_export] macro_rules! dispatch_datum_by_size { ($($path:ident)::* ($dt:expr) ($($args:expr),*)) => { { use $crate::datum::DatumType; match $dt { DatumType::Bool => $($path)::*::<i8>($($args),*), DatumType::U8 => $($path)::*::<i8>($($args),*), DatumType::U16 => $($path)::*::<i16>($($args),*), DatumType::U32 => $($path)::*::<i32>($($args),*), DatumType::U64 => $($path)::*::<i64>($($args),*), DatumType::I8 => $($path)::*::<i8>($($args),*), DatumType::I16 => $($path)::*::<i16>($($args),*), DatumType::I32 => $($path)::*::<i32>($($args),*), DatumType::I64 => $($path)::*::<i64>($($args),*), DatumType::F16 => $($path)::*::<i16>($($args),*), DatumType::F32 => $($path)::*::<i32>($($args),*), DatumType::F64 => $($path)::*::<i64>($($args),*), DatumType::Blob => $($path)::*::<Blob>($($args),*), DatumType::TDim => $($path)::*::<TDim>($($args),*), DatumType::String => $($path)::*::<String>($($args),*), } } } } #[macro_export] macro_rules! dispatch_copy { ($($path:ident)::* ($dt:expr) ($($args:expr),*)) => { { use $crate::datum::DatumType; match $dt { DatumType::Bool => $($path)::*::<bool>($($args),*), DatumType::U8 => $($path)::*::<u8>($($args),*), DatumType::U16 => $($path)::*::<u16>($($args),*), DatumType::U32 => $($path)::*::<u32>($($args),*), DatumType::U64 => $($path)::*::<u64>($($args),*), DatumType::I8 => $($path)::*::<i8>($($args),*), DatumType::I16 => $($path)::*::<i16>($($args),*), DatumType::I32 => $($path)::*::<i32>($($args),*), DatumType::I64 => $($path)::*::<i64>($($args),*), DatumType::F16 => $($path)::*::<f16>($($args),*), DatumType::F32 => $($path)::*::<f32>($($args),*), DatumType::F64 => $($path)::*::<f64>($($args),*), _ => bail!("{:?} is not Copy", $dt) } } } } #[macro_export] macro_rules! dispatch_copy_by_size { ($($path:ident)::* ($dt:expr) ($($args:expr),*)) => { { use $crate::datum::DatumType; match $dt { DatumType::Bool => $($path)::*::<i8>($($args),*), DatumType::U8 => $($path)::*::<i8>($($args),*), DatumType::U16 => $($path)::*::<i16>($($args),*), DatumType::U32 => $($path)::*::<i32>($($args),*), DatumType::U64 => $($path)::*::<i64>($($args),*), DatumType::I8 => $($path)::*::<i8>($($args),*), DatumType::I16 => $($path)::*::<i16>($($args),*), DatumType::I32 => $($path)::*::<i32>($($args),*), DatumType::I64 => $($path)::*::<i64>($($args),*), DatumType::F16 => $($path)::*::<i16>($($args),*), DatumType::F32 => $($path)::*::<i32>($($args),*), DatumType::F64 => $($path)::*::<i64>($($args),*), _ => panic!("{:?} is not Copy", $dt) } } } } #[macro_export] macro_rules! dispatch_numbers { ($($path:ident)::* ($dt:expr) ($($args:expr),*)) => { { use $crate::datum::DatumType; match $dt { DatumType::U8 => $($path)::*::<u8>($($args),*), DatumType::U16 => $($path)::*::<u16>($($args),*), DatumType::U32 => $($path)::*::<u32>($($args),*), DatumType::U64 => $($path)::*::<u64>($($args),*), DatumType::I8 => $($path)::*::<i8>($($args),*), DatumType::I16 => $($path)::*::<i16>($($args),*), DatumType::I32 => $($path)::*::<i32>($($args),*), DatumType::I64 => $($path)::*::<i64>($($args),*), DatumType::F16 => $($path)::*::<f16>($($args),*), DatumType::F32 => $($path)::*::<f32>($($args),*), DatumType::F64 => $($path)::*::<f64>($($args),*), _ => bail!("{:?} is not a number", $dt) } } } } #[macro_export] macro_rules! dispatch_floatlike { ($($path:ident)::* ($dt:expr) ($($args:expr),*)) => { { use $crate::datum::DatumType; match $dt { DatumType::F16 => $($path)::*::<f32>($($args),*), // FIXME !!! DatumType::F32 => $($path)::*::<f32>($($args),*), DatumType::F64 => $($path)::*::<f64>($($args),*), _ => bail!("{:?} is not float-like", $dt) } } } } #[macro_export] macro_rules! dispatch_signed { ($($path:ident)::* ($dt:expr) ($($args:expr),*)) => { { use $crate::datum::DatumType; match $dt { DatumType::F16 => $($path)::*::<f32>($($args),*), // FIXME !!! DatumType::F32 => $($path)::*::<f32>($($args),*), DatumType::F64 => $($path)::*::<f64>($($args),*), DatumType::I8 => $($path)::*::<i8>($($args),*), DatumType::I16 => $($path)::*::<i16>($($args),*), DatumType::I32 => $($path)::*::<i32>($($args),*), DatumType::I64 => $($path)::*::<i64>($($args),*), DatumType::TDim => $($path)::*::<TDim>($($args),*), _ => bail!("{:?} is not signed", $dt) } } } } #[macro_export] macro_rules! impl_op_same_as { () => { fn same_as(&self, other: &dyn Op) -> bool { if let Some(other) = other.downcast_ref::<Self>() { self == other } else { false } } }; } #[macro_export] macro_rules! assert_close { ($left:expr, $right:expr) => ({ match (&$left, &$right) { (left_val, right_val) => { if let Err(e) = left_val.close_enough(right_val, true) { panic!(r#"assertion failed: `(left ~ right)` left: `{:?}`, right: `{:?}` {:?}"#, left_val, right_val, e) } } } }); ($left:expr, $right:expr,) => ({ assert_eq!($left, $right) }); ($left:expr, $right:expr, $($arg:tt)+) => ({ match (&($left), &($right)) { (left_val, right_val) => { if let Err(e) = left_val.close_enough(right_val, true) { panic!(r#"assertion failed: `(left ~ right)` left: `{:?}`, right: `{:?}`: {} {:?}"#, left_val, right_val, format_args!($($arg)+), e) } } } }); }
rust
<reponame>TauOmicronMu/Y13Computing # -*- coding: utf-8 -*- #LoginForm FORGOTTEN_PASS_BUTTON_TEXT = u"<PASSWORD>wort <PASSWORD>" INVALID_LOGIN_TEXT = u"Benutzername / Kennwort ungültig" LOGIN_ATTEMPTS_RESET_TEXT = u"Login Versuche zurücksetzen." LOGIN_BUTTON_TEXT = u"Login" LOGIN_HELP_TEXT = u"Von hier können Sie aus in Ihre Mitarbeiter-Account einloggen. Beide Benutzernamen, Passwörter und Kleinschreibung. Um die Software zu nutzen, müssen Sie ein Konto erstellen." PASSWORD_LABEL_TEXT = u"<PASSWORD>" LF_REGISTER_BUTTON_TEXT = u"Registrieren Neuer Mitarbeiter Konto" SYSTEM_LOCKED_TEXT = u"System gesperrt" TITLE_LABEL_LEFT_TEXT = u" Mitarbeiter \nTracker " TITLE_LABEL_RIGHT_TEXT = u"\nBETA" USERNAME_LABEL_TEXT = u"Benutzername"
python
<filename>lib/src/response/responder.rs use std::fs::File; use std::io::Cursor; use std::fmt; use http::{Status, ContentType}; use response::{Response, Stream}; /// Trait implemented by types that generate responses for clients. /// /// Types that implement this trait can be used as the return type of a handler, /// as illustrated below: /// /// ```rust,ignore /// #[get("/")] /// fn index() -> T { ... } /// ``` /// /// In this example, `T` can be any type that implements `Responder`. /// /// # Return Value /// /// A `Responder` returns an `Ok(Response)` or an `Err(Status)`: /// /// * An `Ok` variant means that the `Responder` was successful in generating /// a `Response`. The `Response` will be written out to the client. /// /// * An `Err` variant means that the `Responder` could not or did not /// generate a `Response`. The contained `Status` will be used to find the /// relevant error catcher which then generates an error response. /// /// # Provided Implementations /// /// Rocket implements `Responder` for several standard library types. Their /// behavior is documented here. Note that the `Result` implementation is /// overloaded, allowing for two `Responder`s to be used at once, depending on /// the variant. /// /// * **&str** /// /// Sets the `Content-Type` to `text/plain`. The string is used as the body /// of the response, which is fixed size and not streamed. To stream a raw /// string, use `Stream::from(Cursor::new(string))`. /// /// * **String** /// /// Sets the `Content-Type`t to `text/html`. The string is used as the body /// of the response, which is fixed size and not streamed. To stream a /// string, use `Stream::from(Cursor::new(string))`. /// /// * **File** /// /// Streams the `File` to the client. This is essentially an alias to /// `Stream::from(file)`. /// /// * **()** /// /// Responds with an empty body. No Content-Type is set. /// /// * **Option&lt;T>** /// /// If the `Option` is `Some`, the wrapped responder is used to respond to /// the client. Otherwise, an `Err` with status **404 Not Found** is /// returned and a warning is printed to the console. /// /// * **Result&lt;T, E>** _where_ **E: Debug** /// /// If the `Result` is `Ok`, the wrapped responder is used to respond to the /// client. Otherwise, an `Err` with status **500 Internal Server Error** is /// returned and the error is printed to the console using the `Debug` /// implementation. /// /// * **Result&lt;T, E>** _where_ **E: Debug + Responder** /// /// If the `Result` is `Ok`, the wrapped `Ok` responder is used to respond /// to the client. If the `Result` is `Err`, the wrapped `Err` responder is /// used to respond to the client. /// /// # Implementation Tips /// /// This section describes a few best practices to take into account when /// implementing `Responder`. /// /// ## Debug /// /// A type implementing `Responder` should implement the `Debug` trait when /// possible. This is because the `Responder` implementation for `Result` /// requires its `Err` type to implement `Debug`. Therefore, a type implementing /// `Debug` can more easily be composed. /// /// ## Joining and Merging /// /// When chaining/wrapping other `Responder`s, use the /// [merge](/rocket/struct.Response.html#method.merge) or /// [join](/rocket/struct.Response.html#method.join) methods on the `Response` /// or `ResponseBuilder` struct. Ensure that you document the merging or joining /// behavior appropriately. /// /// # Example /// /// Say that you have a custom type, `Person`: /// /// ```rust /// struct Person { /// name: String, /// age: u16 /// } /// ``` /// /// You'd like to use `Person` as a `Responder` so that you can return a /// `Person` directly from a handler: /// /// ```rust,ignore /// #[get("/person/<id>")] /// fn person(id: usize) -> Option<Person> { /// Person::from_id(id) /// } /// ``` /// /// You want the `Person` responder to set two header fields: `X-Person-Name` /// and `X-Person-Age` as well as supply a custom representation of the object /// (`Content-Type: application/x-person`) in the body of the response. The /// following `Responder` implementation accomplishes this: /// /// ```rust /// # #![feature(plugin)] /// # #![plugin(rocket_codegen)] /// # extern crate rocket; /// # /// # #[derive(Debug)] /// # struct Person { name: String, age: u16 } /// # /// use std::io::Cursor; /// /// use rocket::response::{self, Response, Responder}; /// use rocket::http::ContentType; /// /// impl<'r> Responder<'r> for Person { /// fn respond(self) -> response::Result<'r> { /// Response::build() /// .sized_body(Cursor::new(format!("{}:{}", self.name, self.age))) /// .raw_header("X-Person-Name", self.name) /// .raw_header("X-Person-Age", self.age.to_string()) /// .header(ContentType::new("application", "x-person")) /// .ok() /// } /// } /// # /// # #[get("/person")] /// # fn person() -> Person { Person { name: "a".to_string(), age: 20 } } /// # fn main() { } /// ``` pub trait Responder<'r> { /// Returns `Ok` if a `Response` could be generated successfully. Otherwise, /// returns an `Err` with a failing `Status`. /// /// When using Rocket's code generation, if an `Ok(Response)` is returned, /// the response will be written out to the client. If an `Err(Status)` is /// returned, the error catcher for the given status is retrieved and called /// to generate a final error response, which is then written out to the /// client. fn respond(self) -> Result<Response<'r>, Status>; } /// Returns a response with Content-Type `text/plain` and a fixed-size body /// containing the string `self`. Always returns `Ok`. /// /// # Example /// /// ```rust /// use rocket::response::Responder; /// use rocket::http::ContentType; /// /// let mut response = "Hello".respond().unwrap(); /// /// let body_string = response.body().and_then(|b| b.into_string()); /// assert_eq!(body_string, Some("Hello".to_string())); /// /// let content_type: Vec<_> = response.header_values("Content-Type").collect(); /// assert_eq!(content_type.len(), 1); /// assert_eq!(content_type[0], ContentType::Plain.to_string()); /// ``` impl<'r> Responder<'r> for &'r str { fn respond(self) -> Result<Response<'r>, Status> { Response::build() .header(ContentType::Plain) .sized_body(Cursor::new(self)) .ok() } } /// Returns a response with Content-Type `text/html` and a fized-size body /// containing the string `self`. Always returns `Ok`. impl Responder<'static> for String { fn respond(self) -> Result<Response<'static>, Status> { Response::build() .header(ContentType::HTML) .sized_body(Cursor::new(self)) .ok() } } /// Aliases Stream<File>: `Stream::from(self)`. impl Responder<'static> for File { fn respond(self) -> Result<Response<'static>, Status> { Stream::from(self).respond() } } /// Returns an empty, default `Response`. Always returns `Ok`. impl Responder<'static> for () { fn respond(self) -> Result<Response<'static>, Status> { Ok(Response::new()) } } /// If `self` is `Some`, responds with the wrapped `Responder`. Otherwise prints /// a warning message and returns an `Err` of `Status::NotFound`. impl<'r, R: Responder<'r>> Responder<'r> for Option<R> { fn respond(self) -> Result<Response<'r>, Status> { self.map_or_else(|| { warn_!("Response was `None`."); Err(Status::NotFound) }, |r| r.respond()) } } /// If `self` is `Ok`, responds with the wrapped `Responder`. Otherwise prints /// an error message with the `Err` value returns an `Err` of /// `Status::InternalServerError`. impl<'r, R: Responder<'r>, E: fmt::Debug> Responder<'r> for Result<R, E> { default fn respond(self) -> Result<Response<'r>, Status> { self.map(|r| r.respond()).unwrap_or_else(|e| { error_!("Response was `Err`: {:?}.", e); Err(Status::InternalServerError) }) } } /// Responds with the wrapped `Responder` in `self`, whether it is `Ok` or /// `Err`. impl<'r, R: Responder<'r>, E: Responder<'r> + fmt::Debug> Responder<'r> for Result<R, E> { fn respond(self) -> Result<Response<'r>, Status> { match self { Ok(responder) => responder.respond(), Err(responder) => responder.respond(), } } }
rust
<filename>Cutting-and-Packing/2D/Datasets/MB2D/json/376.json {"Name":"MB09_076","Objects":[{"Length":432,"Height":79,"Stock":null,"Cost":34128}],"Items":[{"Length":37,"Height":37,"Demand":53,"DemandMax":null,"Value":1369},{"Length":36,"Height":36,"Demand":41,"DemandMax":null,"Value":1296},{"Length":57,"Height":22,"Demand":71,"DemandMax":null,"Value":1254},{"Length":44,"Height":25,"Demand":67,"DemandMax":null,"Value":1100},{"Length":34,"Height":30,"Demand":76,"DemandMax":null,"Value":1020},{"Length":36,"Height":28,"Demand":61,"DemandMax":null,"Value":1008},{"Length":35,"Height":27,"Demand":55,"DemandMax":null,"Value":945},{"Length":42,"Height":22,"Demand":80,"DemandMax":null,"Value":924},{"Length":47,"Height":18,"Demand":76,"DemandMax":null,"Value":846},{"Length":32,"Height":25,"Demand":45,"DemandMax":null,"Value":800},{"Length":57,"Height":14,"Demand":75,"DemandMax":null,"Value":798},{"Length":42,"Height":19,"Demand":58,"DemandMax":null,"Value":798},{"Length":30,"Height":26,"Demand":61,"DemandMax":null,"Value":780},{"Length":39,"Height":20,"Demand":59,"DemandMax":null,"Value":780},{"Length":29,"Height":26,"Demand":65,"DemandMax":null,"Value":754},{"Length":52,"Height":14,"Demand":61,"DemandMax":null,"Value":728},{"Length":31,"Height":23,"Demand":58,"DemandMax":null,"Value":713},{"Length":37,"Height":19,"Demand":60,"DemandMax":null,"Value":703},{"Length":43,"Height":16,"Demand":73,"DemandMax":null,"Value":688},{"Length":38,"Height":18,"Demand":64,"DemandMax":null,"Value":684},{"Length":28,"Height":23,"Demand":60,"DemandMax":null,"Value":644},{"Length":26,"Height":22,"Demand":63,"DemandMax":null,"Value":572},{"Length":29,"Height":15,"Demand":71,"DemandMax":null,"Value":435},{"Length":31,"Height":14,"Demand":55,"DemandMax":null,"Value":434},{"Length":26,"Height":16,"Demand":61,"DemandMax":null,"Value":416},{"Length":39,"Height":10,"Demand":56,"DemandMax":null,"Value":390},{"Length":22,"Height":17,"Demand":52,"DemandMax":null,"Value":374},{"Length":22,"Height":13,"Demand":60,"DemandMax":null,"Value":286},{"Length":16,"Height":15,"Demand":63,"DemandMax":null,"Value":240},{"Length":16,"Height":10,"Demand":71,"DemandMax":null,"Value":160}]}
json
package com.codepath.apps.restclienttemplate.models; import androidx.room.ColumnInfo; import androidx.room.Dao; import androidx.room.Entity; import androidx.room.PrimaryKey; import androidx.room.Query; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcel; @Parcel @Entity public class User { public User(){} @ColumnInfo public String name; @ColumnInfo public String screenName; @ColumnInfo public String profileImageUrl; @PrimaryKey(autoGenerate = true) public long userId; public static User fromJson(JSONObject jsonObject) throws JSONException { User user = new User(); user.userId = jsonObject.getLong("id"); user.name = jsonObject.getString("name"); user.screenName = jsonObject.getString("screen_name"); user.profileImageUrl = jsonObject.getString("profile_image_url_https"); return user; } }
java
/* Copyright 2013 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.fuzzylite.imex; import com.fuzzylite.Engine; import com.fuzzylite.Op; import com.fuzzylite.defuzzifier.Bisector; import com.fuzzylite.defuzzifier.Centroid; import com.fuzzylite.defuzzifier.Defuzzifier; import com.fuzzylite.defuzzifier.LargestOfMaximum; import com.fuzzylite.defuzzifier.MeanOfMaximum; import com.fuzzylite.defuzzifier.SmallestOfMaximum; import com.fuzzylite.defuzzifier.WeightedAverage; import com.fuzzylite.defuzzifier.WeightedSum; import com.fuzzylite.factory.FactoryManager; import com.fuzzylite.norm.SNorm; import com.fuzzylite.norm.TNorm; import com.fuzzylite.norm.s.AlgebraicSum; import com.fuzzylite.norm.s.BoundedSum; import com.fuzzylite.norm.s.DrasticSum; import com.fuzzylite.norm.s.EinsteinSum; import com.fuzzylite.norm.s.HamacherSum; import com.fuzzylite.norm.s.Maximum; import com.fuzzylite.norm.s.NormalizedSum; import com.fuzzylite.norm.t.AlgebraicProduct; import com.fuzzylite.norm.t.BoundedDifference; import com.fuzzylite.norm.t.DrasticProduct; import com.fuzzylite.norm.t.EinsteinProduct; import com.fuzzylite.norm.t.HamacherProduct; import com.fuzzylite.norm.t.Minimum; import com.fuzzylite.rule.Rule; import com.fuzzylite.rule.RuleBlock; import com.fuzzylite.term.Constant; import com.fuzzylite.term.Discrete; import com.fuzzylite.term.Function; import com.fuzzylite.term.Linear; import com.fuzzylite.term.Term; import com.fuzzylite.variable.InputVariable; import com.fuzzylite.variable.OutputVariable; import java.io.BufferedReader; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Pattern; /** * * @author jcrada */ public class FclImporter extends Importer { @Override public Engine fromString(String fcl) { Engine engine = new Engine(); Map<String, String> tags = new HashMap<>(); tags.put("VAR_INPUT", "END_VAR"); tags.put("VAR_OUTPUT", "END_VAR"); tags.put("FUZZIFY", "END_FUZZIFY"); tags.put("DEFUZZIFY", "END_DEFUZZIFY"); tags.put("RULEBLOCK", "END_RULEBLOCK"); String currentTag = "", closingTag = ""; StringBuilder block = new StringBuilder(); BufferedReader fclReader = new BufferedReader(new StringReader(fcl)); int lineNumber = 0; String line; try { while ((line = fclReader.readLine()) != null) { ++lineNumber; List<String> comments = Op.split(line, "//"); if (comments.size() > 1) { line = comments.get(0); } comments = Op.split(line, "#"); if (comments.size() > 1) { line = comments.get(0); } line = line.trim(); // (%) indicates a comment only when used at the start of line if (line.isEmpty() || line.charAt(0) == '%' || line.charAt(0) == '#' || "//".equals(line.substring(0, 2))) { continue; } line = line.replaceAll(Pattern.quote(";"), ""); StringTokenizer tokenizer = new StringTokenizer(line); String firstToken = tokenizer.nextToken(); if ("FUNCTION_BLOCK".equals(firstToken)) { if (tokenizer.hasMoreTokens()) { StringBuilder name = new StringBuilder(); name.append(tokenizer.nextToken()); while (tokenizer.hasMoreTokens()) { name.append(" ").append(tokenizer.nextToken()); } engine.setName(name.toString()); } continue; } if ("END_FUNCTION_BLOCK".equals(firstToken)) { break; } if (currentTag.isEmpty()) { if (!tags.containsKey(firstToken)) { throw new RuntimeException(String.format( "[syntax error] unknown block definition <%s> in line <%d>: %s", firstToken, lineNumber, line)); } currentTag = firstToken; closingTag = tags.get(firstToken); block.setLength(0); block.append(line).append("\n"); continue; } if (!currentTag.isEmpty()) { if (firstToken.equals(closingTag)) { processBlock(currentTag, block.toString(), engine); currentTag = ""; closingTag = ""; } else if (tags.containsKey(firstToken)) { //if opening new block without closing the previous one throw new RuntimeException(String.format( "[syntax error] expected <%s> before <%s> in line: %s", closingTag, firstToken, line)); } else { block.append(line).append("\n"); } continue; } if (!currentTag.isEmpty()) { String error = "[syntax error] "; if (block.length() > 0) { error += String.format("expected <%s> for block:\n%s", closingTag, block.toString()); } else { error += String.format("expected <%s>, but not found"); } throw new RuntimeException(error); } } } catch (Exception ex) { throw new RuntimeException(ex); } return engine; } protected void processBlock(String tag, String block, Engine engine) throws Exception { if ("VAR_INPUT".equals(tag) || "VAR_OUTPUT".equals(tag)) { processVar(tag, block, engine); } else if ("FUZZIFY".equals(tag)) { processFuzzify(block, engine); } else if ("DEFUZZIFY".equals(tag)) { processDefuzzify(block, engine); } else if ("RULEBLOCK".equals(tag)) { processRuleBlock(block, engine); } else { throw new RuntimeException(String.format( "[syntax error] unexpected tag <%s> for block:\n%s", tag, block)); } } protected void processVar(String tag, String block, Engine engine) throws Exception { BufferedReader reader = new BufferedReader(new StringReader(block)); reader.readLine();//discard first line (VAR_INPUT) String line; while ((line = reader.readLine()) != null) { List<String> token = Op.split(line, ":"); if (token.size() != 2) { throw new RuntimeException(String.format( "[syntax error] expected property of type " + "(key : value) in line: %s", line)); } String name = Op.makeValidId(token.get(0)); if ("VAR_INPUT".equals(tag)) { engine.addInputVariable(new InputVariable(name)); } else if ("VAR_OUTPUT".equals(tag)) { engine.addOutputVariable(new OutputVariable(name)); } else { throw new RuntimeException(String.format( "[syntax error] unexpected tag <%s> in line: %s", tag, line)); } } } protected void processFuzzify(String block, Engine engine) throws Exception { BufferedReader reader = new BufferedReader(new StringReader(block)); String line = reader.readLine(); String name; int index = line.indexOf(' '); if (index >= 0) { name = Op.makeValidId(line.substring(index + 1)); } else { throw new RuntimeException("[syntax error] expected name of input variable in line: " + line); } if (!engine.hasInputVariable(name)) { throw new RuntimeException(String.format( "[syntax error] engine does not contain input variable <%s> from line: %s", name, line)); } InputVariable inputVariable = engine.getInputVariable(name); while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); String firstToken = tokenizer.nextToken(); if ("RANGE".equals(firstToken)) { Op.Pair<Double, Double> range = extractRange(line); inputVariable.setRange(range.first, range.second); } else if ("ENABLED".equals(firstToken)) { inputVariable.setEnabled(extractEnabled(line)); } else if ("TERM".equals(firstToken)) { inputVariable.addTerm(prepareTerm(extractTerm(line), engine)); } else { throw new RuntimeException(String.format( "[syntax error] token <%s> not recognized", firstToken)); } } } protected void processDefuzzify(String block, Engine engine) throws Exception { BufferedReader reader = new BufferedReader(new StringReader(block)); String line = reader.readLine(); String name; int index = line.indexOf(' '); if (index >= 0) { name = Op.makeValidId(line.substring(index + 1)); } else { throw new RuntimeException("[syntax error] expected name of output variable in line: " + line); } if (!engine.hasOutputVariable(name)) { throw new RuntimeException(String.format( "[syntax error] engine does not contain output variable <%s> from line: %s", name, line)); } OutputVariable outputVariable = engine.getOutputVariable(name); while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); String firstToken = tokenizer.nextToken(); if ("TERM".equals(firstToken)) { outputVariable.addTerm(prepareTerm(extractTerm(line), engine)); } else if ("METHOD".equals(firstToken)) { outputVariable.setDefuzzifier(extractDefuzzifier(line)); } else if ("ACCU".equals(firstToken)) { outputVariable.fuzzyOutput().setAccumulation(extractSNorm(line)); } else if ("DEFAULT".equals(firstToken)) { Op.Pair<Double, Boolean> defaultAndLock = extractDefaultValue(line); outputVariable.setDefaultValue(defaultAndLock.first); outputVariable.setLockValidOutput(defaultAndLock.second || outputVariable.isLockingValidOutput()); } else if ("RANGE".equals(firstToken)) { Op.Pair<Double, Double> range = extractRange(line); outputVariable.setRange(range.first, range.second); } else if ("LOCK".equals(firstToken)) { Op.Pair<Boolean, Boolean> output_range = extractLocksOutputAndRange(line); outputVariable.setLockValidOutput(output_range.first); outputVariable.setLockOutputRange(output_range.second); } else if ("ENABLED".equals(firstToken)) { outputVariable.setEnabled(extractEnabled(line)); } else { throw new RuntimeException(String.format( "[syntax error] unexpected token <%s>", firstToken)); } } } protected void processRuleBlock(String block, Engine engine) throws Exception { BufferedReader reader = new BufferedReader(new StringReader(block)); String line = reader.readLine(); String name = ""; int index = line.indexOf(' '); if (index >= 0) { name = line.substring(index + 1); //does not need to be valid name } RuleBlock ruleBlock = new RuleBlock(name); engine.addRuleBlock(ruleBlock); while ((line = reader.readLine()) != null) { String firstToken = line.substring(0, line.indexOf(' ')); if ("AND".equals(firstToken)) { ruleBlock.setConjunction(extractTNorm(line)); } else if ("OR".equals(firstToken)) { ruleBlock.setDisjunction(extractSNorm(line)); } else if ("ACT".equals(firstToken)) { ruleBlock.setActivation(extractTNorm(line)); } else if ("ENABLED".equals(firstToken)) { ruleBlock.setEnabled(extractEnabled(line)); } else if ("RULE".equals(firstToken)) { int ruleStart = line.indexOf(':'); if (ruleStart < 0) { ruleStart = "RULE".length(); } String rule = line.substring(ruleStart + 1).trim(); ruleBlock.addRule(Rule.parse(rule, engine)); } else { throw new RuntimeException(String.format( "[syntax error] keyword <%s> not recognized in line %s", firstToken, line)); } } } protected TNorm extractTNorm(String line) { List<String> token = Op.split(line, ":"); if (token.size() != 2) { throw new RuntimeException("[syntax error] " + "expected property of type (key : value) in line: " + line); } String name = token.get(1).trim(); String className = null; if ("MIN".equals(name)) { className = Minimum.class.getSimpleName(); } else if ("PROD".equals(name)) { className = AlgebraicProduct.class.getSimpleName(); } else if ("BDIF".equals(name)) { className = BoundedDifference.class.getSimpleName(); } else if ("DPROD".equals(name)) { className = DrasticProduct.class.getSimpleName(); } else if ("EPROD".equals(name)) { className = EinsteinProduct.class.getSimpleName(); } else if ("HPROD".equals(name)) { className = HamacherProduct.class.getSimpleName(); } return FactoryManager.instance().tnorm().createInstance(className); } protected SNorm extractSNorm(String line) { List<String> token = Op.split(line, ":"); if (token.size() != 2) { throw new RuntimeException("[syntax error] " + "expected property of type (key : value) in line: " + line); } String name = token.get(1).trim(); String className = name; if ("MAX".equals(name)) { className = Maximum.class.getSimpleName(); } else if ("ASUM".equals(name)) { className = AlgebraicSum.class.getSimpleName(); } else if ("BSUM".equals(name)) { className = BoundedSum.class.getSimpleName(); } else if ("NSUM".equals(name)) { className = NormalizedSum.class.getSimpleName(); } else if ("DSUM".equals(name)) { className = DrasticSum.class.getSimpleName(); } else if ("ESUM".equals(name)) { className = EinsteinSum.class.getSimpleName(); } else if ("HSUM".equals(name)) { className = HamacherSum.class.getSimpleName(); } return FactoryManager.instance().snorm().createInstance(className); } protected Term extractTerm(String line) { String spacedLine = ""; for (char c : line.toCharArray()) { if (c == '(' || c == ')' || c == ',') { spacedLine += " " + c + " "; } else if (c == ':') { spacedLine += " :"; } else if (c == '=') { spacedLine += "= "; } else { spacedLine += c; } } final int S_KWTERM = 1, S_NAME = 2, S_ASSIGN = 3, S_TERM_CLASS = 4, S_PARAMETERS = 5; int state = S_KWTERM; StringTokenizer tokenizer = new StringTokenizer(spacedLine); String token, name = "", termClass = ""; List<String> parameters = new ArrayList<>(); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (state == S_KWTERM && "TERM".equals(token)) { state = S_NAME; continue; } if (state == S_NAME) { name = token; state = S_ASSIGN; continue; } if (state == S_ASSIGN && ":=".equals(token)) { state = S_TERM_CLASS; continue; } if (state == S_TERM_CLASS) { if (Op.isNumeric(token)) { termClass = Constant.class.getSimpleName(); parameters.add(token); } else if ("(".equals(token)) { termClass = Discrete.class.getSimpleName(); } else { termClass = token; } state = S_PARAMETERS; continue; } if (state == S_PARAMETERS) { if (!Function.class.getSimpleName().equals(termClass) && ("(".equals(token) || ")".equals(token) || ",".equals(token))) { continue; } if (";".equals(token)) { break; } parameters.add(token.trim()); } } if (state <= S_ASSIGN) { throw new RuntimeException("[syntax error] malformed term in line: " + line); } try { Term result = FactoryManager.instance().term().createInstance(termClass); result.setName(Op.makeValidId(name)); if (result instanceof Function) { result.configure(Op.join(parameters, ""));//remove spaces for formula of function } else { result.configure(Op.join(parameters, " ")); } return result; } catch (Exception ex) { throw ex; } } protected Term prepareTerm(Term term, Engine engine) { if (term instanceof Linear) { Linear linear = (Linear) term; linear.set(linear.coefficients, engine.getInputVariables()); } else if (term instanceof Function) { Function function = (Function) term; function.setEngine(engine); //builtin functions are loaded from TermFactory calling Function::create function.load(); } return term; } protected Defuzzifier extractDefuzzifier(String line) { List<String> token = Op.split(line, ":"); if (token.size() != 2) { throw new RuntimeException("[syntax error] " + "expected property of type (key : value) in line: " + line); } String name = token.get(1).trim(); String className = name; if ("COG".equals(className)) { className = Centroid.class.getSimpleName(); } else if ("COA".equals(className)) { className = Bisector.class.getSimpleName(); } else if ("LM".equals(className)) { className = SmallestOfMaximum.class.getSimpleName(); } else if ("RM".equals(className)) { className = LargestOfMaximum.class.getSimpleName(); } else if ("MM".equals(className)) { className = MeanOfMaximum.class.getSimpleName(); } else if ("COGS".equals(className)) { className = WeightedAverage.class.getSimpleName(); } else if ("COGSS".equals(className)) { className = WeightedSum.class.getSimpleName(); } return FactoryManager.instance().defuzzifier().createInstance(className); } protected Op.Pair<Double, Boolean> extractDefaultValue(String line) { List<String> token = Op.split(line, ":="); if (token.size() != 2) { throw new RuntimeException("[syntax error] " + "expected property of type (key := value) in line: " + line); } List<String> values = Op.split(token.get(1), "|"); String defaultValue = values.get(0).trim(); String nc = ""; if (values.size() == 2) { nc = values.get(1).trim(); } double value; try { value = Op.toDouble(defaultValue); } catch (Exception ex) { throw new RuntimeException(String.format( "[syntax error] expected numeric value, but found <%s> in line %s", defaultValue, line)); } boolean lockValidOutput = nc.equals("NC"); if (!(lockValidOutput || nc.isEmpty())) { throw new RuntimeException(String.format( "[syntax error] expected keyword <NC>, but found <%s> in line: %s", nc, line)); } return new Op.Pair<>(value, lockValidOutput); } protected Op.Pair<Double, Double> extractRange(String line) { List<String> token = Op.split(line, ":="); if (token.size() != 2) { throw new RuntimeException("[syntax error] " + "expected property of type (key := value) in line: " + line); } String rangeToken = token.get(1); String range = ""; for (char c : rangeToken.toCharArray()) { if (c == '(' || c == ')' || c == ' ' || c == ';') { continue; } range += c; } token = Op.split(range, ".."); if (token.size() != 2) { throw new RuntimeException(String.format("[syntax error] expected property of type" + " 'start .. end', but found <%s> in line: %s", range, line)); } double minimum, maximum; int index = -1; try { minimum = Op.toDouble(token.get(index = 0)); maximum = Op.toDouble(token.get(index = 1)); } catch (Exception ex) { throw new RuntimeException(String.format( "[syntax error] expected numeric value, but found <%s> in line %s", token.get(index), line)); } return new Op.Pair<>(minimum, maximum); } protected Op.Pair<Boolean, Boolean> extractLocksOutputAndRange(String line) { int index = line.indexOf(':'); if (index < 0) { throw new RuntimeException("[syntax error] expected property of type " + "'key : value' in line: " + line); } boolean output, range; String value = line.substring(index + 1); List<String> flags = Op.split(value, "|"); if (flags.size() == 1) { String flag = flags.get(0).trim(); output = "VALID".equals(flag); range = ("RANGE".equals(flag)); if (!(output || range)) { throw new RuntimeException(String.format( "[syntax error] expected locking flags " + "<VALID|RANGE>, but found <%s> in line: %s", flag, line)); } } else if (flags.size() == 2) { String flagA = flags.get(0).trim(); String flagB = flags.get(1).trim(); output = ("VALID".equals(flagA) || "VALID".equals(flagB)); range = ("RANGE".equals(flagA) || "RANGE".equals(flagB)); if (!(output && range)) { throw new RuntimeException(String.format( "[syntax error] expected locking flags <VALID|RANGE>, " + "but found <%s|%s> in line %s", flags.get(0), flags.get(1), line)); } } else { throw new RuntimeException(String.format( "[syntax error] expected locking flags <VALID|RANGE>, " + "but found <%s> in line: ", value, line)); } return new Op.Pair<>(output, range); } protected boolean extractEnabled(String line) { List<String> tokens = Op.split(line, ":"); if (tokens.size() != 2) { throw new RuntimeException("[syntax error] expected property of type " + "(key : value) in line: " + line); } String bool = tokens.get(1).trim(); if ("TRUE".equals(bool)) { return true; } if ("FALSE".equals(bool)) { return false; } throw new RuntimeException("[syntax error] expected boolean <TRUE|FALSE>, " + "but found <" + line + ">"); } }
java
Vijay Devarakonda's meteoric rise to stardom was achieved in a remarkably short span, and he endeared himself to fans not only through his on-screen performances but also his altruistic endeavors in real life. Frequently, Vijay Devarakonda is misconstrued for the attitudes he portrays in his on-screen characters, often labeled as arrogant and egocentric. What many may not know is that Vijay Devarakonda remains grounded and humble, never forgetting his modest beginnings. He emerged from a humble background, and his success triggered jealousy in some influential individuals who reveled in his setbacks. Yet, Vijay Devarakonda remains resolute, allowing his hard work and on-screen performances to be the ultimate expression of his character. He consistently goes the extra mile to support his fans, and through his charitable trust, he has fulfilled the dreams of many. Recently, he pledged to send select fans on a five-day holiday trip to Manali. True to his word, Vijay Devarakonda has now delighted his fans who are showering him with praise, sharing videos of their exhilarating journey. This year, he sent 100 fans on an all-expense-paid trip to Manali. He took to Instagram to share a glimpse of his enthusiastic fans, who were hooting and cheering for him on their flight. In the caption, the actor expressed his joy and wrote, 'Cutest, they sent me a video from their flight this morning. They are off on their holiday to the mountains! 100 from across the country, makes me so happy #deverasanta.' In addition to this gesture, Vijay Devarakonda has consistently demonstrated his gratitude towards his fans. He previously donated 1 crore to 100 families, providing each with a check for 1 lakh rupees, all under the initiative of #SpreadingKushi. As a way of showing appreciation for his fans, he annually takes on the role of 'DeveraSanta,' treating 100 fans to an all-expense-paid trip to Manali, further emphasizing how much he values his fans and his success. Additionally, on his birthday, he ensures his fans feel special by announcing the distribution of free ice cream through "The Deverakonda Birthday Truck,' making their day even sweeter. Follow us on Google News and stay updated with the latest!
english
<filename>detail/os/reactor/kqueue/events/kqueue_recv_from.cpp /** * MIT License * Copyright (c) 2020 <NAME> **/ #include "os/reactor/kqueue/events/kqueue_recv_from.h" #include "baba/semantics.h" #include "os/common/event_registrar.h" namespace baba::os { kqueue_recv_from::kqueue_recv_from(const lifetime &scope, const std::shared_ptr<reactor_io_descriptor> &io_desc, const enqueue_for_initiation_fn &enqueue_for_initiation, const register_to_reactor_fn &register_to_reactor, const enqueue_for_completion_fn &enqueue_for_completion, const recv_from_fn &do_recv_from) noexcept : _do_recv_from(do_recv_from), _evt(event_registrar::take()) { RUNTIME_ASSERT(scope); RUNTIME_ASSERT(io_desc); _evt->scope = scope; _evt->descriptor = io_desc; _evt->enqueue_for_initiation = enqueue_for_initiation; _evt->register_to_reactor = register_to_reactor; _evt->enqueue_for_completion = enqueue_for_completion; } kqueue_recv_from::~kqueue_recv_from() noexcept { auto final_evt = event_registrar::take(); final_evt->initiate = [final_evt, evt = _evt](io_handle) { final_evt->complete = [final_evt, evt]() { event_registrar::give(evt); event_registrar::give(final_evt); }; evt->enqueue_for_completion(final_evt); }; _evt->enqueue_for_initiation(final_evt); } void kqueue_recv_from::recv_from(const ip_endpoint &receiver_ep, uint8_t *buffer, int size, ip_endpoint &peer_ep, const receive_finish_fn &cb) noexcept { _evt->initiate = [evt = _evt, cb](io_handle kqueue_fd) { const auto ec = evt->register_to_reactor(kqueue_fd, evt, EVFILT_READ, 0, 0); if (ec != ec::OK) { evt->complete = [ec, cb]() { cb(ec, 0); }; evt->enqueue_for_completion(evt); } }; _evt->react = [evt = _evt, do_recv_from = _do_recv_from, &receiver_ep, buffer, size, &peer_ep, cb]() { int bytes = 0; const auto ec = do_recv_from(evt->descriptor->fd, receiver_ep, buffer, size, peer_ep, bytes); evt->complete = [ec, bytes, cb]() { cb(ec, bytes); }; evt->enqueue_for_completion(evt); }; _evt->enqueue_for_initiation(_evt); } void kqueue_recv_from::recv_from() noexcept { _evt->enqueue_for_initiation(_evt); } } // namespace baba::os
cpp
As the minutes ticked by, the paper-dunking sound of files hitting the digital bin became oddly satisfying. As I hunted through the dusty corners of my laptop looking for unneeded documents, duplicate photos, and, the ultimate treasure, an old video file, I got a rush seeing the storage space bar on my laptop dwindle down by megabytes and gigabytes. But perhaps the most satisfying moment of all was the crinkling sound of the bin being emptied at the end of the hour. This was not a type A personality’s fantasy, this was Miele X’s Digital Clean-Up Challenge. Unlike the first time I visited the company’s hip new workspace in Amsterdam’s Zuid district, this time there was a mission: to clear as many unneeded OneDrive files and emails from your laptop as possible within one hour. In the past, Miele X had participated in several different physical environmental clean-up initiatives, including Clean the Beat organised by Bye Bye Plastic. This time the team wanted to see how they could continue to be more environmentally conscious on a daily basis. As the heart of digital services at Miele, this group of tech-focused employees spend the entirety of their working day on their devices. The fact is that, even if we recycle religiously, navigate to work every day on a bike, and take part in regular park clean-ups, our digital carbon footprint is hard to tangibly quantify. The Digital Clean-Up Challenge aimed to do just that: drive awareness of and build a movement towards green IT internally. But does keeping inboxes and OneDrive folders clean really have that big an impact on the environment? The event was kicked off with a talk by Olivier Vergeynst, Director of the Belgian Institute for Sustainable IT. What I was shocked to discover was that, when comparing personal devices, networks, and data centres, personal devices are the highest energy users and polluters. Although we’re continuously hearing about electricity-sucking data centres, user equipment and the manufacturing of it is a bigger problem. A whopping 83% of emissions come from production. And we replace our personal devices much more regularly than networks and data centres replace their equipment. Vergeynst also shared some simple ways we can lower our digital carbon footprint on a regular basis. For example, turning off your video during a call when you don’t need it. Of course, keeping the camera on during meetings is important because of the human impact you get from seeing someone’s facial expressions, but if you’re watching a webinar for an hour then having everyone else switch off their cameras is good practice. Instead of sending an attachment, send a link when possible to lighten the weight of your emails. And, most important of all, “buy less and keep it longer.” During Vergeynst’s presentation, we found out it takes 200 kg of material to manufacture a smartphone. Opinions vary on the actual impact that sending and storing emails has on the environment. Author Mike Berners-Lee argues in How Bad Are Bananas? The Carbon Footprint of Everything, that email usage generates up to 40 kilograms of CO2 annually, the equivalent of driving 200 kilometres. Yet, an academic study by researchers in Canada argues that sending and storing fewer emails has a minimal impact compared to simply using our devices less. “The Digital Clean-Up in itself is more like an awareness exercise. The key element is about understanding that this is a part of something much bigger. We need to start taking a deeper look at how we can lower the impact of the equipment we use and the data we transmit and store. The goal is to change habits,” says Vergeynst. An example he posed is the emergence of AI. It’s such a transformative technology that can really make a difference in the workplace. Of course, it also generates more emissions. But that doesn’t mean you shouldn’t use it. “It’s about understanding and choosing, rather than just saying it’s bad,” Vergeynst explained. And of course, company-wide initiatives will have a much bigger impact than individual efforts. At the end of the hour, everyone was invited to have a drink and some snacks, while the crew behind the Digital Clean-Up crunched the numbers. I took the opportunity to chat with a few participants to see how they got along. Jouvence Monteiro, Miele X’s Country Success Manager, enthusiastically shared that she was able to reduce the number of emails in her inbox by 20% by focusing on a few quick wins: The automatic notifications you get when you book a desk are a great place to start. You receive one when you check in and check out and that’s a lot of notifications. Then all the newsletters that are nice to read but eventually you need to delete. And all the monthly reports. I just kept the ones from the last few months. It definitely made Jouvence think more about her digital footprint. One fact that was really surprising was that production of laptops and day-to-day equipment have a bigger impact than data centres! I had no idea! It’s really about being more mindful about how we use our equipment on a daily basis and focusing on buying refurbished. Stijn de Bresser, a Compliance & Risk Manager, shared: It surprised me how many automated emails you receive from user systems or cooperation boards you work with internally. It definitely made me more conscious about what I save. In an hour of digital scrubbing, the participants were able to cut 48 kg of CO2. The equivalent of the production of two smartphones or 222 km in a car. While the challenge was only attended by a couple of representatives from each team, the end results were really a sticking point. If just a small group could achieve this within an hour, what could be achieved if the next Digital Clean-Up is done on a company-wide scale? It’s time that more companies started taking a deeper look at their digital carbon footprint. For those ready to follow Miele X’s lead, here are a few tips from their team: Employees will often struggle to decide where to focus on first. Give them a helping hand by providing a scope (like emails and OneDrive folders) and sharing some important dos and don’ts to keep in mind, especially when it comes to sensitive files. Creating a benchmark and quantifying your results is an important way to motivate the team and track progress. They can then use these benchmarks in the future as they continue to keep their digital space clean. Much like exercising, nothing motivates new habits more than seeing the impact of your efforts. Knowing how much storage space you’ve freed up is a great start but understanding how this translates into real tangible results, in terms of CO2 emissions, is essential to motivate habit forming beyond a designated clean-up day. Make this even more tangible by putting it into context: X CO2 emissions are the equivalent of producing X smartphones or driving X kilometres. Finally, celebrate your achievements together as a team and be sure to give a shout-out to people who are really helping to bring this change forward throughout the company. The people who participated in Miele X’s Digital Clean-Up will now play an important role as green IT changemakers, sharing their learnings with the rest of their team. As we as a society become more aware of the impact of our digital activities, it’s internal role models rather than top-down initiatives that will help us move towards a greener digital future, and that’s what the company is counting on. Get the most important tech news in your inbox each week.
english
import memoize from 'lru-memoize' import { createValidator, required, maxLength, date, oneOf, integer, email } from 'utils/validation' const validation = createValidator({ name: [required, maxLength(100)], birthdate: [required, date], gender: [required, oneOf(['f', 'm'])], nationality_id: [required, integer], contact_email: [required, email], mobile: [required, integer] }) export default memoize(10)(validation)
javascript
It’s a long battle to overtake China in the global market. Our markets are stocked with Chinese products, It's a long battle to overtake China in the global market. Our markets are stocked with Chinese products, either as a whole or as assembled part, which have no Indian substitute at all. Even if they are removed from the markets, the customer can order it online. We need is to build better substitutes for these products. For this, we need to improve our work culture, stop brain-drain and infuse confidence among the working class by paying them well. We have the best doctors, engineers and scientists in the world. Unfortunately, they are serving other developed nations, due to lack of opportunities in India. If they could find growth here, they would definitely serve here. Our English speaking skills give us an edge over China in the global labour market. We need to prepare ourselves fully before boycotting Chinese goods. Chandan Kumar Nath,
english
We all must have heard this growing up. We are taught to turn a blind eye when we encounter doubts of a woman going through domestic violence. “Yeh unke ghar ka mamla hai”. Domestic violence has been an open secret in our country. Recently, I came across a video on social media which sent shivers down my spine. A man in Kerala held the bruised face of his wife and announced on camera that he is the one who has beaten her up and broken her mouth. The wife then said, he did that because she chose to go to work. According to NCRB data, there has been a 53% rise in domestic violence cases in India. These are just reported cases.I can't even imagine what the real numbers are. And even more shockingly, 86% of women who face domestic violence in India do not seek help. Why will they? The people around expect them to sort it out in their own homes. So they do, often at the cost of their own lives. Growing up in Punjab, where drug abuse is rampant I’ve met countless women who’ve suffered domestic abuse. None of these women were aware of the domestic abuse national helpline 181. Many of them aren’t literate, so their access to information is anyway limited. But there is one common thread that ties them all together: They regularly use Zomato & Blinkit to order food and groceries for their families. I can imagine thousands of women in India feeling empowered and having the agency to speak up if Zomato and Blinkit could display the domestic abuse national helpline number on their apps. It would be a subtle yet powerful gesture of solidarity towards the millions of Indian women who face domestic abuse. They’d appreciate the message and maybe, before having to order food for their perpetrators, they could try and call 181 and seek help. Zomato has over 32 million users in our country and Blinkit delivers over one lakh orders everyday. Imagine how many women could make use of this! I feel this step from Zomato and Blinkit could help save many lives. Sign my petition to request Zomato and Blinkit, the popular food delivery companies, to display domestic abuse national helpline 181 prominently on their app screens so that women facing domestic abuse know where to seek help in case of danger. Spreading awareness about this helpline can ensure that nobody has to live with violence at home. If you sign my petition, then Zomato and Blinkit will listen.
english
Speaking on the occasion, Shri Jawhar Sircar and Shri Jim Nickel expressed the hope that visitors from around the world during the Commonwealth Games 2010 will see a glimpse of ‘Intuit Art’ through this exhibition. Inuit Nunangat-the Inuit homeland in Canada- is a glorious expanse of taiga and tundra, polar ice and permafrost that has been inhabited by Inuit and ancestral peoples for more than 4000 years. Since the mid-twentieth century, Inuit artists have established a powerful art movement that tells a compelling story of artistic invention and cultural continuity. Featuring masterworks from the collection of the National Gallery of Canada, the exhibition Sanaugavut, meaning “our works of art” in Inuktitut, focuses on the emergence of this most recent stage of creative expression and features sculptures, prints, drawings, textile art, and video that highlight the significant themes of Inuit art- traditional social life and customs, spiritual beliefs and mythology, historical moments and personal experiences- in a richly diverse range of artistic media and styles. The exhibition will be opened to public from 28th September 2010 at the National Museum, Janpath, New Delhi.
english
<filename>server/index.js // load the configuration import config from './config'; // load the mongo database import './mongo'; // load the express application import app from './express'; // initialize the configuration first! require('./config/init')(); const logger = require('./lib/logger')(); // output the configuration logger.log('config: %o', config); // start the application app.listen(config.port, (err) => { if (err) { logger.log(err); } logger.log(`Express server listening on port ${config.port} ` + `in ${process.env.NODE_ENV} environment`); // log logo logger.log(` ======╔═╗╔═╗╦═╗╦╔╗ ╔═╗====== ======╚═╗║ ╠╦╝║╠╩╗║╣======= ======╚═╝╚═╝╩╚═╩╚═╝╚═╝====== `); });
javascript