text
stringlengths
1
1.04M
language
stringclasses
25 values
<reponame>khiem111189/incubator-openaz /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * AT&T - PROPRIETARY * THIS FILE CONTAINS PROPRIETARY INFORMATION OF * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN * ACCORDANCE WITH APPLICABLE AGREEMENTS. * * Copyright (c) 2013 AT&T Knowledge Ventures * Unpublished and Not for Publication * All Rights Reserved */ package org.apache.openaz.xacml.rest; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.file.Files; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.entity.ContentType; import org.apache.openaz.xacml.api.Request; import org.apache.openaz.xacml.api.Response; import org.apache.openaz.xacml.api.pap.PDPStatus.Status; import org.apache.openaz.xacml.api.pdp.PDPEngine; import org.apache.openaz.xacml.api.pdp.PDPException; import org.apache.openaz.xacml.std.dom.DOMRequest; import org.apache.openaz.xacml.std.dom.DOMResponse; import org.apache.openaz.xacml.std.json.JSONRequest; import org.apache.openaz.xacml.std.json.JSONResponse; import org.apache.openaz.xacml.std.pap.StdPDPStatus; import org.apache.openaz.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; /** * Servlet implementation class XacmlPdpServlet This is an implementation of the XACML 3.0 RESTful Interface * with added features to support simple PAP RESTful API for policy publishing and PIP configuration changes. * If you are running this the first time, then we recommend you look at the xacml.pdp.properties file. This * properties file has all the default parameter settings. If you are running the servlet as is, then we * recommend setting up you're container to run it on port 8080 with context "/pdp". Wherever the default * working directory is set to, a "config" directory will be created that holds the policy and pip cache. This * setting is located in the xacml.pdp.properties file. When you are ready to customize, you can create a * separate xacml.pdp.properties on you're local file system and setup the parameters as you wish. Just set * the Java VM System variable to point to that file: * -Dxacml.properties=/opt/app/xacml/etc/xacml.pdp.properties Or if you only want to change one or two * properties, simply set the Java VM System variable for that property. -Dxacml.rest.pdp.register=false */ @WebServlet(description = "Implements the XACML PDP RESTful API and client PAP API.", urlPatterns = { "/" }, loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pdp.properties", description = "The location of the PDP xacml.pdp.properties file holding configuration information.") }) public class XACMLPdpServlet extends HttpServlet implements Runnable { private static final long serialVersionUID = 1L; // // Our application debug log // private static final Log logger = LogFactory.getLog(XACMLPdpServlet.class); // // This logger is specifically only for Xacml requests and their corresponding response. // It's output ideally should be sent to a separate file from the application logger. // private static final Log requestLogger = LogFactory.getLog("xacml.request"); // // This thread may getting invoked on startup, to let the PAP know // that we are up and running. // private Thread registerThread = null; private XACMLPdpRegisterThread registerRunnable = null; // // This is our PDP engine pointer. There is a synchronized lock used // for access to the pointer. In case we are servicing PEP requests while // an update is occurring from the PAP. // private PDPEngine pdpEngine = null; private static final Object pdpEngineLock = new Object(); // // This is our PDP's status. What policies are loaded (or not) and // what PIP configurations are loaded (or not). // There is a synchronized lock used for access to the object. // private static volatile StdPDPStatus status = new StdPDPStatus(); private static final Object pdpStatusLock = new Object(); // // Queue of PUT requests // public static class PutRequest { public Properties policyProperties = null; public Properties pipConfigProperties = null; PutRequest(Properties policies, Properties pips) { this.policyProperties = policies; this.pipConfigProperties = pips; } } public static volatile BlockingQueue<PutRequest> queue = new LinkedBlockingQueue<PutRequest>(2); // // This is our configuration thread that attempts to load // a new configuration request. // private Thread configThread = null; private volatile boolean configThreadTerminate = false; /** * Default constructor. */ public XACMLPdpServlet() { } /** * @see Servlet#init(ServletConfig) */ @Override public void init(ServletConfig config) throws ServletException { // // Initialize // XACMLRest.xacmlInit(config); // // Load our engine - this will use the latest configuration // that was saved to disk and set our initial status object. // PDPEngine engine = XACMLPdpLoader.loadEngine(XACMLPdpServlet.status, null, null); if (engine != null) { synchronized (pdpEngineLock) { pdpEngine = engine; } } // // Kick off our thread to register with the PAP servlet. // if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) { this.registerRunnable = new XACMLPdpRegisterThread(); this.registerThread = new Thread(this.registerRunnable); this.registerThread.start(); } // // This is our thread that manages incoming configuration // changes. // this.configThread = new Thread(this); this.configThread.start(); } /** * @see Servlet#destroy() */ @Override public void destroy() { super.destroy(); logger.info("Destroying...."); // // Make sure the register thread is not running // if (this.registerRunnable != null) { try { this.registerRunnable.terminate(); if (this.registerThread != null) { this.registerThread.interrupt(); this.registerThread.join(); } } catch (InterruptedException e) { logger.error(e); } } // // Make sure the configure thread is not running // this.configThreadTerminate = true; try { this.configThread.interrupt(); this.configThread.join(); } catch (InterruptedException e) { logger.error(e); } logger.info("Destroyed."); } /** * PUT - The PAP engine sends configuration information using HTTP PUT request. One parameter is expected: * config=[policy|pip|all] policy - Expect a properties file that contains updated lists of the root and * referenced policies that the PDP should be using for PEP requests. Specifically should AT LEAST contain * the following properties: xacml.rootPolicies xacml.referencedPolicies In addition, any relevant * information needed by the PDP to load or retrieve the policies to store in its cache. EXAMPLE: * xacml.rootPolicies=PolicyA.1, PolicyB.1 * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1 * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1 * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1 * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1 * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1 pip - Expect a properties file that * contain PIP engine configuration properties. Specifically should AT LEAST the following property: * xacml.pip.engines In addition, any relevant information needed by the PDP to load and configure the * PIPs. EXAMPLE: xacml.pip.engines=foo,bar foo.classname=com.foo foo.sample=abc foo.example=xyz ...... * bar.classname=com.bar ...... all - Expect ALL new configuration properties for the PDP * * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // // Dump our request out // if (logger.isDebugEnabled()) { XACMLRest.dumpRequest(request); } // // What is being PUT? // String cache = request.getParameter("cache"); // // Should be a list of policy and pip configurations in Java properties format // if (cache != null && request.getContentType().equals("text/x-java-properties")) { if (request.getContentLength() > Integer.parseInt(XACMLProperties .getProperty("MAX_CONTENT_LENGTH", "32767"))) { String message = "Content-Length larger than server will accept."; logger.info(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } this.doPutConfig(cache, request, response); } else { String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'"; logger.error(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } } protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // prevent multiple configuration changes from stacking up if (XACMLPdpServlet.queue.remainingCapacity() <= 0) { logger.error("Queue capacity reached"); response.sendError(HttpServletResponse.SC_CONFLICT, "Multiple configuration changes waiting processing."); return; } // // Read the properties data into an object. // Properties newProperties = new Properties(); newProperties.load(request.getInputStream()); // should have something in the request if (newProperties.size() == 0) { logger.error("No properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); return; } // // Which set of properties are they sending us? Whatever they send gets // put on the queue (if there is room). // if (config.equals("policies")) { newProperties = XACMLProperties.getPolicyProperties(newProperties, true); if (newProperties.size() == 0) { logger.error("No policy properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=policies must contain at least one policy property"); return; } XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null)); } else if (config.equals("pips")) { newProperties = XACMLProperties.getPipProperties(newProperties); if (newProperties.size() == 0) { logger.error("No pips properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=pips must contain at least one pip property"); return; } XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties)); } else if (config.equals("all")) { Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true); if (newPolicyProperties.size() == 0) { logger.error("No policy properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one policy property"); return; } Properties newPipProperties = XACMLProperties.getPipProperties(newProperties); if (newPipProperties.size() == 0) { logger.error("No pips properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one pip property"); return; } XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties)); } else { // // Invalid value // logger.error("Invalid config value: " + config); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Config must be one of 'policies', 'pips', 'all'"); return; } } catch (Exception e) { logger.error("Failed to process new configuration.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } } /** * Parameters: type=hb|config|Status 1. HeartBeat Status HeartBeat OK - All Policies are Loaded, All PIPs * are Loaded LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration * LAST_UPDATE_FAILED - Need to track the items that failed during last update LOAD_FAILURE - ??? Need to * determine what information is sent and how 2. Configuration 3. Status return the StdPDPStatus object in * the Response content * * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { XACMLRest.dumpRequest(request); // // What are they requesting? // boolean returnHB = false; response.setHeader("Cache-Control", "no-cache"); String type = request.getParameter("type"); // type might be null, so use equals on string constants if ("config".equals(type)) { response.setContentType("text/x-java-properties"); try { String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n"; try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes()); InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); OutputStream os = response.getOutputStream()) { IOUtils.copy(listInputStream, os); IOUtils.copy(pipInputStream, os); } response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { logger.error("Failed to copy property file", e); response.sendError(400, "Failed to copy Property file"); } } else if ("hb".equals(type)) { returnHB = true; response.setStatus(HttpServletResponse.SC_NO_CONTENT); } else if ("Status".equals(type)) { // convert response object to JSON and include in the response synchronized (pdpStatusLock) { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getOutputStream(), status); } response.setStatus(HttpServletResponse.SC_OK); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'"); } if (returnHB) { synchronized (pdpStatusLock) { response .addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString()); } } } /** * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or * JSON according to the XACML 3.0 Specifications for both. * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // // no point in doing any work if we know from the get-go that we cannot do anything with the request // if (status.getLoadedRootPolicies().size() == 0) { logger.warn("Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded"); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } XACMLRest.dumpRequest(request); // // Set our no-cache header // response.setHeader("Cache-Control", "no-cache"); // // They must send a Content-Type // if (request.getContentType() == null) { logger.warn("Must specify a Content-Type"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given"); return; } // // Limit the Content-Length to something reasonable // if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) { String message = "Content-Length larger than server will accept."; logger.info(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } if (request.getContentLength() <= 0) { String message = "Content-Length is negative"; logger.info(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } ContentType contentType = null; try { contentType = ContentType.parse(request.getContentType()); } catch (Exception e) { String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage(); logger.error(message, e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } // // What exactly did they send us? // String incomingRequestString = null; Request pdpRequest = null; if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) || contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { // // Read in the string // StringBuilder buffer = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { buffer.append(line); } incomingRequestString = buffer.toString(); } logger.info(incomingRequestString); // // Parse into a request // try { if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { pdpRequest = JSONRequest.load(incomingRequestString); } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML .getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { pdpRequest = DOMRequest.load(incomingRequestString); } } catch (Exception e) { logger.error("Could not parse request", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } } else { String message = "unsupported content type" + request.getContentType(); logger.error(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } // // Did we successfully get and parse a request? // if (pdpRequest == null || pdpRequest.getRequestAttributes() == null || pdpRequest.getRequestAttributes().size() <= 0) { String message = "Zero Attributes found in the request"; logger.error(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } // // Run it // try { // // Get the pointer to the PDP Engine // PDPEngine myEngine = null; synchronized (pdpEngineLock) { myEngine = this.pdpEngine; } if (myEngine == null) { String message = "No engine loaded."; logger.error(message); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } // // Send the request and save the response // long lTimeStart, lTimeEnd; Response pdpResponse = null; // TODO - Make this unnecessary // TODO It seems that the PDP Engine is not thread-safe, so when a configuration change occurs in // the middle of processing // TODO a PEP Request, that Request fails (it throws a NullPointerException in the decide() // method). // TODO Using synchronize will slow down processing of PEP requests, possibly by a significant // amount. // TODO Since configuration changes are rare, it would be A Very Good Thing if we could eliminate // this sychronized block. // TODO // TODO This problem was found by starting one PDP then // TODO RestLoadTest switching between 2 configurations, 1 second apart // TODO both configurations contain the datarouter policy // TODO both configurations already have all policies cached in the PDPs config directory // TODO RestLoadTest started with the Datarouter test requests, 5 threads, no interval // TODO With that configuration this code (without the synchronized) throws a NullPointerException // TODO within a few seconds. // synchronized (pdpEngineLock) { myEngine = this.pdpEngine; try { lTimeStart = System.currentTimeMillis(); pdpResponse = myEngine.decide(pdpRequest); lTimeEnd = System.currentTimeMillis(); } catch (PDPException e) { String message = "Exception during decide: " + e.getMessage(); logger.error(message); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } } requestLogger.info(lTimeStart + "=" + incomingRequestString); if (logger.isDebugEnabled()) { logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms"); } // // Convert Response to appropriate Content-Type // if (pdpResponse == null) { requestLogger.info(lTimeStart + "=" + "{}"); throw new Exception("Failed to get response from PDP engine."); } // // Set our content-type // response.setContentType(contentType.getMimeType()); // // Convert the PDP response object to a String to // return to our caller as well as dump to our loggers. // String outgoingResponseString = ""; if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { // // Get it as a String. This is not very efficient but we need to log our // results for auditing. // outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled()); if (logger.isDebugEnabled()) { logger.debug(outgoingResponseString); // // Get rid of whitespace // outgoingResponseString = JSONResponse.toString(pdpResponse, false); } } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { // // Get it as a String. This is not very efficient but we need to log our // results for auditing. // outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled()); if (logger.isDebugEnabled()) { logger.debug(outgoingResponseString); // // Get rid of whitespace // outgoingResponseString = DOMResponse.toString(pdpResponse, false); } } // // lTimeStart is used as an ID within the requestLogger to match up // request's with responses. // requestLogger.info(lTimeStart + "=" + outgoingResponseString); response.getWriter().print(outgoingResponseString); } catch (Exception e) { String message = "Exception executing request: " + e; logger.error(message, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } response.setStatus(HttpServletResponse.SC_OK); } @Override public void run() { // // Keep running until we are told to terminate // try { while (!this.configThreadTerminate) { PutRequest request = XACMLPdpServlet.queue.take(); StdPDPStatus newStatus = new StdPDPStatus(); // TODO - This is related to the problem discussed in the doPost() method about the PDPEngine // not being thread-safe. // TODO See that discussion, and when the PDPEngine is made thread-safe it should be ok to // move the loadEngine out of // TODO the synchronized block. // TODO However, since configuration changes should be rare we may not care about changing // this. PDPEngine newEngine = null; synchronized (pdpStatusLock) { XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION); newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); } // PDPEngine newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, // request.pipConfigProperties); if (newEngine != null) { synchronized (XACMLPdpServlet.pdpEngineLock) { this.pdpEngine = newEngine; try { logger.info("Saving configuration."); if (request.policyProperties != null) { try (OutputStream os = Files.newOutputStream(XACMLPdpLoader .getPDPPolicyCache())) { request.policyProperties.store(os, ""); } } if (request.pipConfigProperties != null) { try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPIPConfig())) { request.pipConfigProperties.store(os, ""); } } newStatus.setStatus(Status.UP_TO_DATE); } catch (Exception e) { logger.error("Failed to store new properties."); newStatus.setStatus(Status.LOAD_ERRORS); newStatus.addLoadWarning("Unable to save configuration: " + e.getMessage()); } } } else { newStatus.setStatus(Status.LAST_UPDATE_FAILED); } synchronized (pdpStatusLock) { XACMLPdpServlet.status.set(newStatus); } } } catch (InterruptedException e) { logger.error("interrupted"); } } }
java
[{"meeting_cd":"C5102005072110001","committee":"Business & Commerce Committee","dttm":"July 21, 2005 -10:00A","session":"792","bill_name":"SB 5","bill_cd":"SB5","position":"Against","rbnt":true,"self":false,"fullWitnessName":"<NAME> (Texas Public Interest Research Group), Austin, TX\r","given_name":"Kenneth , Austin, TX","sur_name":"Hwang","organization":"Texas Public Interest Research Group","error":false}]
json
This year, as China's economy wobbled and money left the country, the PBOC took a starkly different approach, defending the currency by signalling to markets what kind of selling it would and would not tolerate. One of the much talked about interesting trends for the year is a significant reduction in the Foreign Institutional Investors (FIIs) holding in our markets. At present, of the total Indian market cap of US$~4.33trillion, FII holding is US$~656billion or ~15%. This will be one of the lowest FII holdings in our stock markets in the last 10 years plus. To put it in context, in 2012 the FII holding was ~25%. These seven stocks have given more than 15% returns during each of the 10000-point rally Sensex saw from 40000 levels, and they are Titan Company, Sun Pharmaceutical Industries, ICICI Bank, Bharti Airtel, UltraTech Cement, JSW Steel, and Nestle India. The token jumped 5.8% to scale $42,000 on Monday and was just below that level in morning Asian trading on Tuesday. In contrast, gauges of global shares and bonds are nursing losses since the start of the week. Indian large, small and midcap indices are the amongst best-performing Equities in the world in the last four months, led by our resilient macro environment. As the Fed has once again raised interest rates by 25 bps, RBI has maintained its pause showing the underlying strength in the Indian economy. India today consumes almost 50% of its oil imports from Russia at cheaper prices leading to swelling forex reserves. All this is building up a case for a stronger currency in the medium-term horizon. Global investors are also wary of the effects of China's weakening economy, which has added to worries about inflation and high interest rates in Europe and the United States. On Friday, European stocks mostly fell and the S&P 500 was flat. The U.S. benchmark index is on track to record its third consecutive weekly decline. "India had a very long period of underperformance in the 2010-2020 decade when we were far below the trend line. Instead of that 15-16% compounding that was expected, we compounded only 8% odd at a time when fixed deposit rates were 7-8%. We were far below the trend line. That is why once the revival came post Covid , I expected it to last long as the risk of a crash goes down because crashes come when the markets are far above the trend line." India’s economic and earnings growth strength, coupled with a possible recession in the US are the two key reasons behind India’s outperformance and we are hopeful that this outperformance should continue due to 3 reasons. Sanjiv Bhasin of IIFL Securities explains why IEX, which is going through a lot of regulatory headwinds and GMR Infrastructure are in his recommended list. Also, he says on a valuation basis one can put some more extra weight on Hindalco. It has a very good risk reward at this price. Bitcoin's correlation with technology stocks has weakened, as the digital asset posted a monthly slump for the first time this year, while the Nasdaq 100 added almost 8%. The 30-day correlation coefficient for Bitcoin and the tech-heavy Nasdaq 100 is at around 0.2 versus 0.8 in May 2022. Crypto investors were delighted earlier in the year when tokens surged and left equities behind. However, the split has become less favourable now, with digital-asset investors facing a bit of idiosyncratic risk as everything is no longer the same, said Peter van Dooijeweert, head of multi-asset solutions at Man Group. The clampdown of global commodity prices has improved the outlook for Indian industry, reducing operational costs and increasing profitability. The correlation between the Nifty50 index and Brent crude oil is relatively weak due to the strong influences of economic, social, and earnings data. The current market rally in India is being influenced by consistent FII inflows driven by lower Treasury yields and the weakness of the US Dollar. However, investors must evaluate if the recent decline in commodity prices is temporary or long-lasting as an extended in-equilibrium in the global economy could ultimately affect the Indian stock market. The Indian stock market has delivered positive returns in April and May after underperforming in the first quarter of 2023, but experts urge caution. Rising interest rates affected both equity and debt returns in the first quarter, but Lotusdew Wealth CEO Abhishek Banerjee suggests a relatively stable or falling interest-rate environment could boost equities. HDFC Securities' Deepak Jasani recommends investors move into debt to take advantage of the current peak in rates, but warns against shifting to equity too quickly. Meanwhile, TrustPlutus Wealth's Kaizad Hozdar calls for a systematic allocation to equities to benefit from an eventual recovery. Apart from these challenges in the past decade, 2020 turned out to be the biggest blow with the Covid-19 pandemic. All these challenges have had a significant impact on Indian equities. Thus, it can be surmised that Indian equities have undergone an intense period of cleansing, now showing sustainable results. Last month's auto sales have rebounded when compared with September 2019. Passenger car sales rose 44.5%, trucks 17% and tractors 37%. The hospitality industry has seen explosive growth with all sub-sectors gaining, from hotels to airlines to dining out. The global slump did not spare the Indian markets. The Fed scare had shaved off about 4% from Nifty in just few trading sessions with serious collateral damage to the currency and Gsec yield. Indian Rupee breached the long-held support level of 80 to move near 82 while the ten year Gsec yield surged by over 15bps. With this, the decoupling debate has been put to rest. While the Euro Zone is reeling under an unprecedented energy crisis and is on the brink of a recession, China is struggling under the twin impact of a deepening property market crisis and widespread Covid-related lockdowns. Chinese equities are seen making up lost ground as the extreme pessimism toward its economy recedes and authorities take further steps to revive stuttering growth. At the same time, the gathering enthusiasm over other developing-nation equities could peter out amid a global slowdown, causing their correlation with China to reassert itself.
english
<reponame>5aboteur/cft-task package filesorter.application; import java.nio.file.Path; import filesorter.util.content.ContentType; import filesorter.sort.SortMode; /** * Because application settings are immutable, we need this auxiliary class to * get all the parameters alternately, before we build the AppSettings instance. */ public class AppSettingsBuilder { private Path path; private String outPrefix; private ContentType contentType; private SortMode sortMode; private int numOfWorkers; public Path getPath() { return path; } public String getOutPrefix() { return outPrefix; } public ContentType getContentType() { return contentType; } public SortMode getSortMode() { return sortMode; } public int getNumOfWorkers() { return numOfWorkers; } public void setPath(Path path) { this.path = path; } public void setOutPrefix(String pfx) { this.outPrefix = pfx; } public void setContentType(ContentType ct) { this.contentType = ct; } public void setSortMode(SortMode sm) { this.sortMode = sm; } public void setNumOfWorkers(int wrk) { this.numOfWorkers = wrk; } public AppSettings build() { return new AppSettings(path, outPrefix, contentType, sortMode, numOfWorkers); } }
java
It just took 101 innings for Hashim Amla to become the fastest ever batsman to reach 5000 ODI runs. He has overtaken Sir Vivian Richards who had achieved this feat in 1987. The new entries into the top ten list are Shikhar Dhawan. India's Virat Kohli is in the third position above Joe root and Brain Lara.
english
Joachim Fritze explores using Perspector and other add-ins in PowerPoint. Joachim Fritze was born and grew up in nothern Germany. He is a chemist by profession with twenty years of experience in the sales and marketing of dentistry stuff. An avid PowerPoint user for almost a decade, Joachim churns up PowerPoint presentation all the time and loves to use Perspector, the 3D add-in for PowerPoint. Joachim lives in Liechtenstein, and is married with two children. Geetesh: How do you typically use PowerPoint, and what type of presentations do you create / present? Also, tell us more about your PowerPoint rants and raves. What do you like, and what do you dislike about the program? Joachim: I have been working in marketing & sales division of a health care industry firm since some years. Everybody here is so used to PowerPoint—it simply is the standard presentation instrument in every meeting. This can be a strength—but in the meantime, it also presents a shortfall of the program since everybody has seen the typical PowerPoint charts at least a hundred times—bars and pies, cylinders and circles, scares and rectangles. Worst case examples are the bullet lists, animated or not—after some years they become pretty uninteresting for everybody. In a competitive situation, where you have to sell an idea, a product, or a service to a group of people whom you have never met before, it is difficult to hold the attention of the audience and make a lasting impression if you have nothing new to show. It can be even worse when you work internationally. I am not a native English speaker—nor are lots of people in the audiences I have to talk to. So it is natural that part of the information I want to transfer may not reach the targeted brain if it isn't re-inforced through other parallel, communication channels. Over the years, I did my best to support my messages with the creativity that PowerPoint tools can provide. But unfortunately everybody is doing so—and it becomes more and more difficult to make a difference with the built-in options. In a nutshell: PowerPoint is the best presentation tool on the planet for me, but it is becoming more and more difficult for me to use only PowerPoint and create with it an impression that will last. I need more tools. Geetesh: How did you get started with Perspector, the 3D add-in for PowerPoint. Joachim: I looked at stock photos, and used strong images to anchor my central messages more intensively. I started with Photoshop to improve the images I used, or to create professional looking clipart, and imported it into PowerPoint. Then I went over to Xara/Xara 3D because the drawing functions are great, the import/export options fantastic, and the price/performance positioning more reasonable than the upgrade costs for Photoshop and Illustrator. I did all this to let my presentations look more unique than the ones from others, so that people will remember me and the solutions I have to offer. But even with Xara/Xara 3D, it was difficult to create what I really wanted to have—3D and perspective drawings in PowerPoint. And then I found Perspector. And the product lived up to the claim in the name: I could create perspective graphics. Very fast, very easy, without having to learn how to make them with one of the expensive professional 3D graphic tools in the market, like Lightwave or 3DSMax. Geetesh: Tell us more about Perspector, their support, your experiences, etc. Joachim: Perspector easily generates a perspective 3D-version of simply every 2D-shape which is available in PowerPoint, plus it includes also a number of prefabricated shape-arrangements/cliparts, which you can pick from a wizard-like library. In most cases, you can choose from several variations of a shape. For instance the bullet point list or the pyramid-chart. You work in a preview window, and when you are satisfied with the result, you click the OK button—and after a rendering-time of 5 to 10 seconds, you get a beautiful output. For the more experienced user, Perspector offers amazing options to spread a shade range equally over shapes you picked from a starting shade to an end shade. You can decide what degree of shine your shapes should have, and where you would like to set light sources. You have different views to control the correct position of your construction in the 3D-room, and you can group pieces together, rotate and resize them—and ungroup them again when appropriate. Of course, this way you can also create real perspective text, and you can twist text and pictures around every shape you decide. You can also fill the surfaces of a cube—or you can cover a sphere with a map of the earth, rotate it the way you want so that you have exactly any continent in front, that you are going to talk about—and of course, you can also animate the earth or any other shape in 3D. Such earth maps take just 3 clicks, and your earth rotates around a given axis during your presentation. You don't need Perspector to view the results. So every PowerPoint user can integrate slides generated by Perspector in their presentations, although they cannot modify them without having the add-in installed. And there is more. The professional version contains a big number of slide layouts, so you can put different slides of your PowerPoint presentation together, arranged as required in the 3D-room, and compare or relate the content elements in a very elegant way. There is a library of perspective 3D-charts built in where you can pick your preferred example from, but can also modify every single detail you might want to change. For beginners, there are a number of sample presentations available at the web site, so that they can play with them to understand how they have been made. But there's more. With the libraries you open, you can load a "how to do" video, so that you can explore the possibilities. By the way, the whole command architecture is very similar to PowerPoint—so without learning a single new command, you should be able to generate your first graphic in minutes. Exact positioning in 3D is not that easy, so in case that you have to put elements in exact positions to each other, you can write the exact values in the coordination sections of the feature window you may open for every shape or group you work with by right-clicking the object. If you have to modify an existing Perspector file, you simply double-click it to edit it to your needs. Perspector also works together nicely with other PowerPoint add-ins. For instance, pptXTREME SoftShadows or AutoShape Magic. I have worked with Perspector now more than a year and I never had a problem. Also, animated Perspector charts are handled like normal PowerPoint objects. A rotating earth can in addition to its rotation created by Perspector, also be moved across the screen and animated with the normal PowerPoint animation controls. Geetesh: Do you also use any other PowerPoint add-ins?. Joachim: I also tried other add-ins. I bought all the CrystalGraphics add-ins, but some of them modified my screen resolution and others did not install completely. I couldn't use most of the features as I expected it. I had to remove them. Perspector did what I expected from it. It is the best add-in I ever worked with, in terms of stability, product quality, price performance ratio, and customer support. With the new 3D chart library, the opportunities to use the program are incredible. I can highly recommend Perspector and do not want to work without it again. Geetesh: Would you like to share some trivia about a non-conventional usage of PowerPoint, or just something you want to share with Indezine readers? Joachim: In the early years with PowerPoint, it was fun to see the surprise in the eyes of my audience whenever I used a never-seen-animation, or a clever combination of PowerPoint's 3D and transparency options. Give it a try. I am sure you will love the program and it will pay off in very short time. P.S. To see the eyes of the audience members, I try to use light backgrounds in the presentations all the time. This way I have light in the room and I can take up energy from those who concentrate on me. Is a picture is worth a thousand words? You probably have heard this adage so often that we decided not to repeat this phrase throughout this book! Now here’s some more info: the human brain uses a larger part of its area to store visual information rather than textual content. And that’s possibly because a picture describes so much more than text. Go and get a copy of our Pictures in Presentations ebook. Microsoft and the Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries.
english
Akkineni Nagarjuna who is basking in the success of Bangarraju has visited Tirumala and got the blessings of Lord Venkateswara. He along with his wife Amala Akkineni arrived Tirumala. Later, Nagarjuna expressed his jubilation of getting the blessings of Lord Venkateswara after two long years. He said he prayed for all the well-being of Telugu people. King Nagarjuna and Naga Chaitanya’ Bangarraju emerged as the Pongal winner. This film is going great guns at the box office despite Covid restrictions. As per the trade analysts, this film will be emerged as a huge hit in the lead actors’ respective careers. Akkineni Nagarjuna who is basking in the success of Bangarraju has visited Tirumala and got the blessings of Lord Venkateswara. He along with his wife Amala Akkineni arrived Tirumala.
english
Plants and trees are part of nature and Hinduism is very closely associated with nature. Many of these trees and plants are believed to be the abode of different deities and their auspiciousness can be gauged by the fact that having them in your house brings in abundance of blessings in different forms into your life. Trees and plants are part of mother nature and Hinduism is closely associated with nature. Many plants and trees are deeply worshipped according to the scriptures. It is also said that several deities reside in these plants and trees. For example, according to Hindu scriptures, some trees and plants have the abode of gods and goddesses, such as Sri Hari Vishnu in the banana tree, Lord Shiva in the Bael tree. Planting these trees and plants in one’s house, attracts positive energy and happiness and prosperity. Many plants are planted in the house for happiness, peace and positive energy. There is one such tree which has special importance in the religious rituals and functions in Hinduism. This tree is also known as Palash or Parsa tree. These are of two types, one orange and the other white. Palash tree is considered very auspicious in Vastu Shastra. It is believed that Tridev resides in the Palash tree. It is believed that by having the Palash tree in your house, brings the special blessings of Goddess Lakshmi and one will never ever face any shortage of money and grains in the house. Along with Palash tree, some remedies of its flower are also considered very miraculous. Palash flowers are used for many special remedies in astrology. Apart from religious remedies, Palash flowers are also used in Ayurveda. Palash means sacred leaves and this tree has an important place in Hinduism. Palash leaves, wood and flowers are used in religious rituals in Hinduism. According to Hindu belief, the Palash tree originated from a fallen feather of an eagle immersed in Somras. There is a legend about the Palash tree in which Goddess Parvati cursed Brahma Dev to become a Palash tree. The religious significance of this tree begins with the triangular formation of its leaves, with the center of the leaf representing Lord Vishnu, the left and Brahma, and the right representing Mahadev. In the scriptures, the Palash tree has been called the treasurer of the gods. Also, it is considered the symbol of the moon. Because a beautiful view of the moon is visible in the center of its flower. According to astrology, keeping Palash flower in the vault is considered very auspicious and fruitful. If you want that your vault should never be empty, then wrap a Palash flower in a red cloth and keep it in your vault. The only thing you need to keep in mind is that you should change this cloth from time to time. On the other hand, according to Vastu Shastra, keeping Palash flower in your house also removes the Vastu defects from your house and you start attracting positive energy into your house. If Mars is giving inauspicious effects to a person, then one should collect some Palash leaves and spread some rice all around on Wednesday and put them in water. Now install it in your home. If you want that there should be happiness and peace in your house, then one should offer white Palash flower to Maa Lakshmi on Friday. Doing this will fill your life and house with abundance of happiness. If someone is ill for a long time, then on Sunday, one should wrap the root of Palash tree with the help of cotton thread and tie it on one’s right hand. It is said that by doing this the illness will leave the person and that person will heal completely. Manipur Unrest: CM N Biren Singh Hints At Involvement Of 'External Forces' In Ethnic Violence, Calls It 'Pre-Planned'
english
<reponame>wesgraham/plasma-mvp-sidechain package store import ( "github.com/FourthState/plasma-mvp-sidechain/plasma" "github.com/FourthState/plasma-mvp-sidechain/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rlp" "github.com/stretchr/testify/require" "math/big" "reflect" "testing" ) // Test that an wallet can be serialized and deserialized func TestWalletSerialization(t *testing.T) { // Construct Wallet acc := Wallet{ Balance: big.NewInt(234578), Unspent: []plasma.Position{getPosition("(8745.1239.1.0)"), getPosition("(23409.12456.0.0)"), getPosition("(894301.1.1.0)"), getPosition("(0.0.0.540124)")}, Spent: []plasma.Position{getPosition("(0.0.0.3)"), getPosition("(7.734.1.3)")}, } bytes, err := rlp.EncodeToBytes(&acc) require.NoError(t, err) recoveredAcc := Wallet{} err = rlp.DecodeBytes(bytes, &recoveredAcc) require.NoError(t, err) require.True(t, reflect.DeepEqual(acc, recoveredAcc), "mismatch in serialized and deserialized wallet") } // Test that the Deposit can be serialized and deserialized without loss of information func TestDepositSerialization(t *testing.T) { // Construct deposit plasmaDeposit := plasma.Deposit{ Owner: common.BytesToAddress([]byte("an ethereum address")), Amount: big.NewInt(12312310), EthBlockNum: big.NewInt(100123123), } deposit := Deposit{ Deposit: plasmaDeposit, Spent: true, SpenderTx: []byte{}, } bytes, err := rlp.EncodeToBytes(&deposit) require.NoError(t, err) recoveredDeposit := Deposit{} err = rlp.DecodeBytes(bytes, &recoveredDeposit) require.NoError(t, err) require.True(t, reflect.DeepEqual(deposit, recoveredDeposit), "mismatch in serialized and deserialized deposit") } // Test that Transaction can be serialized and deserialized without loss of information func TestTxSerialization(t *testing.T) { hashes := []byte("fourthstate") var sigs [65]byte // Construct Transaction transaction := plasma.Transaction{ Inputs: []plasma.Input{plasma.NewInput(getPosition("(1.15.1.0)"), sigs, [][65]byte{}), plasma.NewInput(getPosition("(0.0.0.1)"), sigs, [][65]byte{})}, Outputs: []plasma.Output{plasma.NewOutput(common.HexToAddress("1"), utils.Big1), plasma.NewOutput(common.HexToAddress("2"), utils.Big2)}, Fee: utils.Big1, } pos := getPosition("(0.1.1.1)") tx := Transaction{ Transaction: transaction, Spent: []bool{false, false}, SpenderTxs: [][]byte{}, ConfirmationHash: hashes, Position: pos, } bytes, err := rlp.EncodeToBytes(&tx) require.NoError(t, err) recoveredTx := Transaction{} err = rlp.DecodeBytes(bytes, &recoveredTx) require.NoError(t, err) require.True(t, reflect.DeepEqual(tx, recoveredTx), "mismatch in serialized and deserialized transactions") }
go
Rabada to Stokes, out Lbw!! Stokes has walked off. Even before Pistol could raise his finger. Stokes giving himself out. And look at the celebration from Rabada. Firstly Elgar puts his hand to close Rabada's mouth and then the latter covers his mouth with one finger. Vertically raised across his lips. This pitched on a good length and scuttled through to ping Stokes in front. No chance for Stokes as it missed the inside edge and struck him low on the pad. Plumbest of plumb. Stokes walks off with a wry smile on his face. Stokes lbw b Rabada 1(4)
english
#!/usr/bin/env python # coding: utf-8 # `Firefly/ntbks/multiple_datasets_tutorial.ipynb` # In[1]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') from IPython.display import YouTubeVideo # A recording of this jupyter notebook in action is available at: # In[2]: YouTubeVideo("TMq3IvnxGY8") # In[3]: import numpy as np import os import sys sys.path.insert(0,'/Users/agurvich/research/repos/Firefly/src') from Firefly.data_reader import ArrayReader # # Tutorial notebook: Managing multiple datasets with Firefly # There are two ways to manage multiple datasets with Firefly # 1. listing multiple entries in startup.json # 2. creating a "standalone" iteration of Firefly # # 1 and 2 can be combined so that visitors to different "standalone" iterations of Firefly can select between different sets of multiple datasets using a dropdown see <a href="https://agurvich.github.io/firefly_versions">this example</a>. # ## Editing the entries of `startup.json` # When the Firefly webapp starts up it looks for a `Firefly/static/data/startup.json` file to tell it which dataset to display. If only a single entry is present then it will automatically begin loading that dataset. If multiple entries are listed then it will present the user with a dropdown box to select which dataset to load. See the <a href="https://ageller.github.io/Firefly/docs/build/html/data_reader/multiple_datasets.html">documentation for managing multiple datasets</a> for how to format the `startup.json` file to list multiple entries manually. We provide a method of easily adding datasets to the `startup.json` file using the `write_startup` keyword argument of the `Firefly.data_reader.Reader` (sub-)class(es). # In[4]: ## let's create some sample data, a grid of points in a 3d cube my_coords = np.linspace(-10,10,20) xs,ys,zs = np.meshgrid(my_coords,my_coords,my_coords) xs,ys,zs = xs.flatten(),ys.flatten(),zs.flatten() coords = np.array([xs,ys,zs]).T ## we'll pick some random field values to demonstrate filtering/colormapping fields = np.random.random(size=xs.size) # We'll overwrite whatever file is existing with a new `startup.json` with only 1 entry in it. Then we'll append a second entry. Then we'll create a reader and specify that it should not be added to the `startup.json` file. # In[5]: ## initialize an ArrayReader reader = ArrayReader( coordinates=[coords[:-1],coords], ## pass in two particle groups as a demonstration (just copies of our sample data) fields=[[],[fields,fields]], ## field data for each particle group, 0 fields for 1 and 2 repeated fields for the other. write_startup=True) ## overwrite the existing startup.json file ## initialize a second ArrayReader fake_reader = ArrayReader( coordinates=[coords[:-1],coords], ## pass in two particle groups as a demonstration (just copies of our sample data) fields=[[],[fields,fields]],## field data for each particle group, 0 fields for 1 and 2 repeated fields for the other. JSONdir="FakeData", write_startup='append') ## append this entry to the startup.json file if it doesn't already exists ## initialize a THIRD ArrayReader null_reader = ArrayReader( coordinates=[coords[:-1],coords], ## pass in two particle groups as a demonstration (just copies of our sample data) fields=[[],[fields,fields]],## field data for each particle group, 0 fields for 1 and 2 repeated fields for the other. JSONdir="NullData", write_startup=False) ## do not add this reader to the startup.json file # Let's read the content of the `startup.json` file: # In[6]: get_ipython().system('cat /Users/agurvich/research/repos/Firefly/src/Firefly/static/data/startup.json') # Notice that the "NullData" `JSONdir` is not listed because we set `write_startup=False`. # ## Creating a standalone iteration of Firefly # You can copy the necessary Firefly source files by creating a `Reader` object containing your data and using the `copyFireflySourceToTarget`. # We've also included a script that will automatically create a new Github repository and enable GitHub pages so that your data can be visited by users over the internet via URL. # For instructions on how to configure this feature and details for copying the Firefly source see the <a href="https://ageller.github.io/Firefly/docs/build/html/data_reader/multiple_datasets.html">documentation for managing multiple datasets</a>. # In[7]: reader.copyFireflySourceToTarget(init_gh_pages=False) # Let's read the contents of the new `my_Firefly` directory: # In[8]: get_ipython().system('ls /Users/agurvich/my_Firefly/') # In[9]: get_ipython().system('ls /Users/agurvich/my_Firefly/static/data/')
python
Lita did not believe her Women’s Championship victory over Stephanie McMahon was going to happen when WWE’s higher-ups originally informed her about the idea. The Hall of Famer won the first of her four Women’s Championships on the August 21, 2000 episode of RAW. In a dramatic finish, she pinned McMahon for the title after receiving help from special guest referee The Rock. Speaking on Steve Austin’s Broken Skull Sessions show, Lita said former WWE trainer Dr. Tom Prichard told her about her title victory before the event. WWE has a history of changing booking decisions at short notice, which left the legendary superstar wondering if the plan was going to change: “Dr. Tom said the plan is to put the title on you, but I’m like, ‘Prepare for the worst and hope for the best.’ So I’m like, ‘Cool, probably won’t happen.’ Even until you walk out the curtain, it’s really not until that moment that you’re like, ‘Oh, they are... I got the title,’” said Lita. Lita is widely regarded as one of the greatest female superstars in WWE history. She was inducted into the Hall of Fame by her close friend and former in-ring rival Trish Stratus in 2014. The finish to the Women’s Championship match saw The Rock attack Kurt Angle and Triple H. He then hit a spinebuster on Stephanie McMahon, which allowed Lita to land her trademark moonsault to pick up the victory. The 46-year-old added that she immediately left the ring because she did not want to take the male superstars’ spotlight: Lita recently returned to in-ring competition as a participant in the 2022 Women’s Royal Rumble match. Three weeks later, she unsuccessfully challenged Becky Lynch for the RAW Women’s Championship at Elimination Chamber. Please credit Broken Skull Sessions and give a H/T to Sportskeeda Wrestling for the transcription if you use quotes from this article. Poll : Who would you rather see back on WWE TV?
english
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.junit.Test; import java.io.IOException; import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class TestClass { @Test public void testHttpCall() throws IOException { // Build request HttpDelete request = new HttpDelete("{{SERVER}}/api/v1/accounts/{{ACCOUNT_ID}}/tokens/{{TOKEN_ID}}"); request.add("Authorization", "Basic {{API_CREDENTIALS}}"); // Send request HttpResponse response = HttpClientBuilder.create().build().execute(request); // Extract response HttpEntity entity = response.getEntity(); String jsonString = EntityUtils.toString(entity); assertThat(jsonString, hasJsonPath("$.status", is("OK"))); } }
java
Around 90 minutes into the 95th Academy Awards, Deepika Padukone appeared on stage to introduce RRR’s ‘Naatu Naatu’, nominated for Best Original Song, before its live performance. Calling it a “total banger” and “the first song ever from an Indian production to be nominated for an Oscar”, the actor spoke for one-and-a-half minutes, amid roaring applause interrupting her several times. After singers Rahul Sipligunj and Kaala Bhairava recreated the number, with more than a dozen dancers, a surprise awaited them: the attendees in the Dolby Theatre gave them a standing ovation. Around 90 minutes later, music director M. M. Keeravani and lyricist Chandrabose won the Academy Award, upstaging such heavyweights as Lady Gaga and Rihanna. Two more Indians won the Oscars this year, director Kartiki Gonsalves and producer Guneet Monga, for The Elephant Whisperers in the Best Documentary Short Subject category. (Shaunak Sen’s All That Breathes, nominated for Best Documentary Feature, lost to Navalny, pivoted on the Russian opposition leader Alexei Navalny and the investigation into his poisoning. ) Now what about the rest of the ceremony? Over the last few years, the Academy Awards have battled several crisis: plummeting viewership (from over 30 million six years ago to 16. 6 million last year), strange changes (in 2022, eight categories were awarded off air), fading relevance (best exemplified by HBO airing the finale of its popular drama, The Last of Us, at the same time as this year’s awards), and more. The Academy, in response, made a few crucial changes this year – reinstating all the awards during the ceremony, posting the acceptance speeches on TikTok and Facebook almost simultaneously, and QR codes appearing before commercial breaks to help audiences learn more about technical categories – hoping to win back its lost pride. Nominated for 11 Oscars and winning seven (including Best Picture and Best Director), Everything Everywhere All At Once dominated the awards night. It secured three out of the four awards in the acting categories, too. Jamie Lee Curtis won the Best Supporting Actor (her first Oscar), while Michelle Yeoh became the first Asian woman to win the Best Actress award (and the second woman of colour after Halle Barry). Ke Huy Quan, winning the Best Supporting Actor award, became only the second man of Asian descent to clinch the honour. Brendan Fraser won the Best Actor for The Whale. Quan and Fraser’s wins have been stories of comebacks, sharing remarkable similarities. If Quan returned to acting after two decades – as roles dried up due to his ethnicity – then Fraser’s acting career slowed during the late aughts to mid-2010s because of various personal problems (including being a victim of an alleged sexual assault). The anti-war German epic All Quiet on the Western Front, nominated for nine Oscars, ended up winning four, including Best International Feature, Cinematography, Production Design and Original Score. This year’s Oscars may not have deepened The Academy’s crisis, but they’ve not resolved it, either. At 210 minutes, the ceremony still felt long. Neither Kimmel nor the other presenters could elevate the show to a compelling watch that warranted a live viewing. The whole event – including and especially the banter – had a predictable air to it. You could have simply read the list of the winners online, and it wouldn’t have made much of a difference. In fact, one of the few things breaking the tedium was the performance of ‘Naatu Naatu’. The Oscars have unveiled a similar show for so long that it doesn’t even feel surprising. What is surprising, though, is India’s two wins this year – something that, one hopes, becomes a regular fixture in the future.
english
Think spring and all that comes to mind is freshness, flowers and sunshine. Everything is bright and refreshing, so why should your makeup not be in sync with the mood of the season? And what better than keeping it simple with the natural or ‘no-makeup’ makeup look. You can let your imperfections show and keep your skin looking glowing and fresh with minimal products. Here are the steps to achieve this makeup look for days you want to keep it simple and effortless. The key to acing the ‘no-makeup’ makeup look is that your skincare routine needs to be top-notch. But by that we don’t mean you burn a hole in your pocket. Play smart and invest time and patience. The effects won’t show up overnight; it’s like maintaining a relationship with your skin, even the best needs enough attention. The best part about this makeup look is that you don’t have to hide the blemishes. The rule here is less is more, which is why you don’t have to apply foundation to your entire face. Just apply some in areas where you may have hyperpigmentation or uneven skin tone. However, if you have oily skin or have creases, we suggest you take a fluffy brush and dab on some loose powder and set your face instead. Contouring is for days you are heading out to a party or for a fancy brunch. It should be avoided when you want to keep things minimal and natural. You can instead apply some bronzer to add colour to your face. Ditch your bright blush and simply use your cream lipstick as a blush on the apple of your cheeks for a more luminous and natural look. You are almost done with your base, and now it is time to give your face a little dimension. Do this by not filling your eyebrows too much and giving it a filled-in natural brow look. Create thin strokes with an eyebrow pencil, almost micro-bladed and brush it with a spoolie to get a slightly bushy effect. This hack with just a soap will help you get fluffy eyebrows, check it out here. It is time to add a little colour by opting for your favourite brown or pink nude shade. Pro tip: For a more natural look, apply your lipstick using your fingers, this helps to melt the products without looking too overdone. Are you going to try this makeup look?
english
A recent Stanford Business School Study delved into a seemingly non-intuitive case study — “Humor at scale” — at McKinsey & Company. During the pandemic, just as companies across the world were trying to find different ways to motivate employees, so did the consulting firm. One of their employees created a comedy set based on the lived experiences of the people working in the company. Is this the experience of a single company or can there be larger lessons for senior leaders and for their teams? Be it Dilbert, the evergreen cartoon series on office culture, or the sitcom ‘Office’ or memes on social media or the viral skits by talented comedians such as Aiyyo Shraddha, the workplace lends itself to many hilarious moments. The emerging world of digital technology — with new tools that many pretend to understand but in reality may not always know everything about — can be fodder for humour. Beyond individuals, there have always been companies that have adopted humour as a brand tone — from Amul to Fevicol. We recognise the moments. We understand the characters. We see ourselves in the characters. And we laugh. But, at the same time, fun is not considered synonymous with senior leadership styles. Or can it be? Leadership, and especially executive leadership, is a hard job. We have to navigate multiple decisions, convince stakeholders and motivate teams. All in a day’s work. Of course, there are funny moments within these. If a leader can bring out some of these funny moments, it can help in various ways. Here are a few examples: A senior leader who was having to hire a lot of people for his team and spending a humongous amount of his workday doing so, while dealing with last-minute candidate rejections and more, made a smart word play and called it his “higher” (hire) purpose in life. Leaders in a data science company who wanted to demystify seemingly difficult terms on data science created a data love poem during Valentine's Day bringing out multiple statistical terms in a funny and unexpected way. Humour helps build a more relatable persona of the leader. A leader who can laugh at herself/himself can also help bring more open communication within the team. In some cases, it can become the unique personal brand for the leader, extending far beyond the role. It also helps people bond better when they share laughter, and that makes for more engaged teams. But, it’s not always that easy. Humour can also hurt, especially if it becomes derogatory and non-inclusive. Leaders need to keep a watch out for that. Self-deprecating humour or humour with word play or based on light-hearted office situations are safer bets. Some of the spaces to share these could be at offsites, training sessions, team huddles and such events. But, when there are really difficult moments, humour may not always help. So humour has to be contextual, relevant and real for it to connect. It should not come across as flippant or inauthentic. On that note, let’s hope we find more leaders nurturing their funny bones as part of their leadership skills.
english
After completing the dubbing work for Puli, Vijay is planning to go for a holiday in the US along with his family. The actor is likely to begin the photo-shoot for Vijay 59 as soon as he comes back to Chennai after the US trip. Devi Sri Prasad is also planning to record a song in Vijay and Shruti Haasan's voice for the album which will be unveiled in the month of July. The team is currently gearing up to release the first look teaser of the film on Vijay's birthday on June 22nd. Vijay's next film with Atlee will commence from the month of July and the first schedule is planned in Chennai before the team moves on to China for their next leg of shoot. Tags :
english
<gh_stars>1-10 export class LoginRequest { public language: number; public loginId: string; public password: string; constructor(username: string, password: string) { this.language = 0; this.loginId = username; this.password = password; } }
typescript
<filename>output/schemes/base24-borland.json "workbench.colorCustomizations": { "terminal.foreground": "#d1d1d1", "terminal.background": "#0000a4", "terminal.ansiBlack": "#4e4e4e", "terminal.ansiBlue": "#96cafd", "terminal.ansiBrightBlack": "#7c7c7c", "terminal.ansiBrightBlue": "#b5dcfe", "terminal.ansiBrightCyan": "#dfdffe", "terminal.ansiBrightGreen": "#ceffab", "terminal.ansiBrightPurple": "#ff9cfe", "terminal.ansiBrightRed": "#ffb6b0", "terminal.ansiBrightWhite": "#ffffff", "terminal.ansiBrightYellow": "#ffffcb", "terminal.ansiCyan": "#c6c4fd", "terminal.ansiGreen": "#a7ff60", "terminal.ansiPurple": "#ff73fd", "terminal.ansiRed": "#ff6b60", "terminal.ansiWhite": "#eeeeee", "terminal.ansiYellow": "#ffffb6" },
json
The Delhi High Court Bar Association (DHCBA) Thursday expressed concern over the Supreme Court collegium's recommendation to shift Delhi High Court judge Justice Gaurang Kanth to the Calcutta High Court, saying such transfer will adversely affect the dispensation of justice on account of a reduction in the existing strength of judges. The bar body has asked its members to abstain from work on July 17 as a token of protest, saying the transfer is a "rarest of rare case”. “It is a matter of regret that while no attention is being paid by all concerned regarding the process of filling up the existing vacancies in the Delhi High Court, yet the transfer of sitting judges is being made thereby further reducing the existing strength of judges in the Delhi High Court,” a resolution moved by its president Mohit Mathur and adopted by the bar body said. The resolution requested the Supreme Court collegium to revisit its recommendation of transferring Justice Kanth. The DHCBA said a copy of the resolution was also being sent to the central government requesting it to not act on the recommendation and instead call upon the collegium to reconsider the decision. “DHCBA unanimously resolves to request its members to abstain from work on Monday, that is, July 17, 2023, as a token of protest as the transfer is a rarest of rare case,” the resolution said. On Wednesday, the Supreme Court collegium resolved to recommend the transfer of three judges of different high courts ignoring their representations for choice posting. The collegium, headed by Chief Justice of India DY Chandrachud, and also comprising Justices SK Kaul, Sanjiv Khanna, BR Gavai, and Surya Kant, recommended the transfer of Delhi High Court judge Justice Gaurang Kanth to the Calcutta High Court. Justice Kanth made a representation on July 7, 2023, requesting a transfer to the Madhya Pradesh or Rajasthan High Court, or a court in any of the neighbouring states. (This story has not been edited by News18 staff and is published from a syndicated news agency feed - PTI)
english
— Our thanks to Animal Blawg, where this post was originally published on July 13, 2015. The Alliance to End Chickens as Kaporos along with 20 additional plaintiffs filed a lawsuit in the New York Supreme Court New York to issue an injunction against Hasidic rabbis and synagogues in Brooklyn from participating in “Kaporos,” a highly controversial religious custom which involves the confinement, torture and barbaric slaughter of more than 50,000 chickens on public streets every year during the week preceding the Jewish holiday Yom Kippur. The case also names the NYPD, NYC Department of Health and the City of New York for failing to enforce city health laws and animal cruelty laws, among others. The Alliance to End Chickens as Kaporos was formed in New York City in 2010 as a project of, and under the umbrella of, United Poultry Concerns, founded by Karen Davis, Ph.D. Kaporos using live chickens is also practiced in other cities throughout the U.S. and Canada, including Los Angeles. See 2014 Brooklyn Kaporos video here: http://bit.ly/1gsvAmw. The 21 plaintiffs are a group of individuals and residents of the subject locations who have endured the inconvenience, nuisance, filth, stench, public health risk and emotional trauma involved in Kaporos for years. Each plaintiff is gravely concerned about the health risks in their community, the contaminants on the streets and sidewalks and the emotional trauma caused by the bloody animal violence they are forced to witness. What is Kaporos? Kaporos is allegedly a ritual of atonement practiced by Hasidic Jews as part of the Jewish holiday of Yom Kippur. The ritual involves practitioners grasping live chickens by their wings and swinging them above the practitioners’ heads. The purpose of this act, followed by the slaughter, is allegedly to transfer the practitioners’ sins and punishment to the birds, allegedly absolving the participants of their sins. In order to conduct the slaughter of the birds, Kaporos involves the erection of make-shift slaughterhouses on the public streets and sidewalks of the City of New York. Dead chickens, half dead chickens, chicken blood, chicken feathers, chicken urine, chicken feces, other toxins and garbage such as used latex gloves and filthy tarps consume the public streets. There is no oversight and no remedy for cleanup. Plaintiffs maintain that operating such illegal public slaughterhouses causes and creates a public nuisance, a public health risk, a public health hazard and a dangerous condition. All of the plaintiffs witnessed chickens being tortured, unjustifiably injured and maimed, and deprived of food and water. Chickens are usually grabbed by their wings, sometimes three birds at a time. According to veterinarian John Hynes, DVM, this causes ligaments to rip and wings to break, causing extreme agony for the birds. Meanwhile the birds are packed tightly into transport crates and stacked up to 10 crates high, with no protection from the elements, no food or water, and excrement constantly falling on them from the birds above. The birds often die of heat prostration, dehydration and starvation before they are ever used. Plaintiffs have witnessed garbage bags on the city streets moving only to find dying and live birds inside slowly suffocating to death. Co-counsel Jessica Astrof, a practicing Jew herself (along with eight of the plaintiffs, two of whom are ultra-Orthodox) says that, “It is one thing for these communities to be violating the Jewish teachings in the Torah relating to tza’ar ba’alei chayim, which prohibits animal cruelty, but to violate New York State and City laws regarding public health and safety raises the severity of this infraction to a whole new level. The NYPD told our plaintiffs that they could not enforce health laws or animal cruelty laws because ‘their hands were tied.’ Ultimately judicial intervention became their only recourse.” According to Orthodox Rabbi Shmuly Yanklowitz, Kaporos can still take place while at the same time abiding by, and not violating, existing laws. There is an easy solution for this; the practitioners can use coins. According to Yanklowitz, the Jewish religion permits the use of coins for Kaporos. Hasidic rabbis, including Rabbi YonassanGershom, have made public pleas for fellow Hasids to use coins instead of torturing birds. A hearing is anticipated in August to determine whether a preliminary injunction will be granted this year, foreclosing the use of live chickens in September 2015 and requiring the Hasidic communities to join most other Jews around the world and perform the custom using coins. Exhibits 5 – 71 are photos. Email [email protected] for clean copies of images. www.upc-online.org, Facebook and twitter @upcnews and @kindkaporos. Press contact:
english
{ "schema_version": "1.2.0", "id": "GHSA-cvwp-gwp2-6xqh", "modified": "2022-05-02T03:12:57Z", "published": "2022-05-02T03:12:57Z", "aliases": [ "CVE-2009-0129" ], "details": "libcrypt-openssl-dsa-perl does not properly check the return value from the OpenSSL DSA_verify and DSA_do_verify functions, which might allow remote attackers to bypass validation of the certificate chain via a malformed SSL/TLS signature, a similar vulnerability to CVE-2008-5077.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2009-0129" }, { "type": "WEB", "url": "http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=511519" }, { "type": "WEB", "url": "http://openwall.com/lists/oss-security/2009/01/12/4" } ], "database_specific": { "cwe_ids": [ "CWE-287" ], "severity": "MODERATE", "github_reviewed": false } }
json
Sohil Sehran was part of Hindustan Times’ nationwide network of correspondents that brings news, analysis and information to its readers. He no longer works with the Hindustan Times. Five vehicles on their way to Agra and eight vehicles going to Delhi collided on the expressway. Officials said that of the total number of people to be fined, 1,060 were found riding two-wheelers without helmets. The drive is being conducted across Gautam Budh Nagar and will continue till November 30. Officials said that the left turns were blocked at Labour Chowk, Mamura and sectors 18, 37 and 63, among others. Officials said that the authority is aiming to streamline vehicular movement across the city and reduce congestion on roads. The month-long programme is aimed at sensitising people about rules and the maximum number of violators will be punished. The trio and an associate, identified as Robin, were intercepted by a police team for checking around 7pm near Gautam Budh Nagar University on Tuesday, following which the suspects allegedly opened fire and fled. Police said Kuldeep received a phone call from the call centre regarding a technical snag after which all the four men, who were already together, drove towards the centre in Maruti Swift Dzire car. The six idols of octal metal were stolen from the temple situated in Sector Beta-2, opposite the Kasna police station, on the intervening night of October 18 and 19. The police said the suspects, who are not linked to one another and are residents of different villages, have been absconding for the last two to three years. Kumar, who was injured, was rushed to Yatharth Hospital by passersby but was declared brought dead, the police said. The speed cameras, equipped with automatic number plate recognition (ANPR), were installed two weeks ago on the corridor, near ISKCON temple. Due to the snarls, commuters had a harrowing time reaching their destinations. Vehicles were moving at a snail’s pace for over three hours. The chock-a-block traffic led to congestion on Delhi-Noida-Direct (DND) Flyway as well. Police said the accused had murdered a 30-year-old woman, identified as Sushma Devi, on the night of October 14 at her rented accommodation. He then fled to his home town in Aligarh. Traffic lights at major intersections remained out of order and there were a few police personnel on the roads to streamline vehicular movement. Most attributed the dip to the Goods and Services Taxes (GST), demonetisation and change in banking norms.
english
<filename>g2-ts-lambda-to-lambda-with-iam/package.json { "name": "ts-lambda-to-lambda-with-iam", "scripts": { "all": "npm run init && npm run build && npm run deploy && npm run demo && npm run destroy && npm run clean", "build": "rm -rf dist && mkdir dist && cd src && tsc && cd .. && cp src/package.json dist/package.json && cp src/package-lock.json dist/package-lock.json && cd dist && npm install --only=prod && cd ..", "clean": "git clean -xdf", "demo": "cd client && python3 demo.py -stack 1 && python3 demo.py -stack 2 && cd ..", "deploy": "npm run deploy2 && npm run deploy1", "deploy1": "cd cdk1 && npx cdk deploy --outputs-file stack-data.json && cd ..", "deploy2": "cd cdk2 && npx cdk deploy --outputs-file stack-data.json && cd ..", "destroy": "cd cdk2 && npx cdk destroy && cd .. && cd cdk1 && npx cdk destroy && cd ..", "init": "cd src && npm install && cd .. && cd cdk1 && npm install && cd .. && cd cdk2 && npm install && cd .." } }
json
<reponame>Garinmckayl/researchhub-web<filename>components/GAnalytics/EventTracker.js import ReactGA from "react-ga"; /** * Event - Add custom tracking event. * @param {string} category * @param {string} action * @param {string} label */ export const Event = (category, action, label) => { ReactGA.event({ category: category, action: action, label: label, }); };
javascript
<reponame>alvin97231/Dev_Wr_MongoDB<gh_stars>0 (function(){ 'use strict'; angular.module('mdDataTable', ['mdtTemplates', 'ngMaterial', 'ngMdIcons']); }()); (function(){ 'use strict'; function mdtAlternateHeadersDirective(){ return { restrict: 'E', templateUrl: '/main/templates/mdtAlternateHeaders.html', transclude: true, replace: true, scope: true, require: ['^mdtTable'], link: function($scope){ $scope.deleteSelectedRows = deleteSelectedRows; function deleteSelectedRows(){ var deletedRows = $scope.tableDataStorageService.deleteSelectedRows(); $scope.deleteRowCallback({rows: deletedRows}); } } }; } angular .module('mdDataTable') .directive('mdtAlternateHeaders', mdtAlternateHeadersDirective); }()); (function(){ 'use strict'; /** * @ngdoc directive * @name mdtTable * @restrict E * * @description * The base HTML tag for the component. * * @param {object=} tableCard when set table will be embedded within a card, with data manipulation tools available * at the top and bottom. * * Properties: * * - `{boolean=}` `visible` - enable/disable table card explicitly * - `{string}` `title` - the title of the card * - `{array=}` `actionIcons` - (not implemented yet) * * @param {boolean=} selectableRows when set each row will have a checkbox * @param {String=} alternateHeaders some table cards may require headers with actions instead of titles. * Two possible approaches to this are to display persistent actions, or a contextual header that activates * when items are selected * * Assignable values are: * * - 'contextual' - when set table will have kind of dynamic header. E.g.: When selecting rows, the header will * change and it'll show the number of selected rows and a delete icon on the right. * - 'persistentActions' - (not implemented yet) * * @param {boolean=} sortableColumns sort data and display a sorted state in the header. Clicking on a column which * is already sorted will reverse the sort order and rotate the sort icon. * (not implemented yet: Use `sortable-rows-default` attribute directive on a column which intended to be the * default sortable column) * * @param {function(rows)=} deleteRowCallback callback function when deleting rows. * At default an array of the deleted row's data will be passed as the argument. * When `table-row-id` set for the deleted row then that value will be passed. * * @param {boolean=} animateSortIcon sort icon will be animated on change * @param {boolean=} rippleEffect ripple effect will be applied on the columns when clicked (not implemented yet) * @param {boolean=} paginatedRows if set then basic pagination will applied to the bottom of the table. * * Properties: * * - `{boolean=}` `isEnabled` - enables pagination * - `{array}` `rowsPerPageValues` - set page sizes. Example: [5,10,20] * * @param {object=} mdtRow passing rows data through this attribute will initialize the table with data. Additional * benefit instead of using `mdt-row` element directive is that it makes possible to listen on data changes. * * Properties: * * - `{array}` `data` - the input data for rows * - `{integer|string=}` `table-row-id-key` - the uniq identifier for a row * - `{array}` `column-keys` - specifying property names for the passed data array. Makes it possible to * configure which property assigned to which column in the table. The list should provided at the same order * as it was specified inside `mdt-header-row` element directive. * * @param {function(page, pageSize)=} mdtRowPaginator providing the data for the table by a function. Should set a * function which returns a promise when it's called. When the function is called, these parameters will be * passed: `page` and `pageSize` which can help implementing an ajax-based paging. * * @param {string=} mdtRowPaginatorErrorMessage overrides default error message when promise gets rejected by the * paginator function. * * * @example * <h2>`mdt-row` attribute:</h2> * * When column names are: `Product name`, `Creator`, `Last Update` * The passed data row's structure: `id`, `item_name`, `update_date`, `created_by` * * Then the following setup will parese the data to the right columns: * <pre> * <mdt-table * mdt-row="{ * 'data': controller.data, * 'table-row-id-key': 'id', * 'column-keys': ['item_name', 'update_date', 'created_by'] * }"> * * <mdt-header-row> * <mdt-column>Product name</mdt-column> * <mdt-column>Creator</mdt-column> * <mdt-column>Last Update</mdt-column> * </mdt-header-row> * </mdt-table> * </pre> */ mdtTableDirective.$inject = ['TableDataStorageFactory', 'mdtPaginationHelperFactory', 'mdtAjaxPaginationHelperFactory']; function mdtTableDirective(TableDataStorageFactory, mdtPaginationHelperFactory, mdtAjaxPaginationHelperFactory){ return { restrict: 'E', templateUrl: '/main/templates/mdtTable.html', transclude: true, scope: { tableCard: '=', selectableRows: '=', alternateHeaders: '=', sortableColumns: '=', deleteRowCallback: '&', animateSortIcon: '=', rippleEffect: '=', paginatedRows: '=', mdtRow: '=', mdtRowPaginator: '&?', mdtRowPaginatorErrorMessage:"@" }, controller: ['$scope', function($scope){ var vm = this; vm.addHeaderCell = addHeaderCell; initTableStorageServiceAndBindMethods(); function initTableStorageServiceAndBindMethods(){ $scope.tableDataStorageService = TableDataStorageFactory.getInstance(); if(!$scope.mdtRowPaginator){ $scope.mdtPaginationHelper = mdtPaginationHelperFactory .getInstance($scope.tableDataStorageService, $scope.paginatedRows, $scope.mdtRow); }else{ $scope.mdtPaginationHelper = mdtAjaxPaginationHelperFactory.getInstance({ tableDataStorageService: $scope.tableDataStorageService, paginationSetting: $scope.paginatedRows, mdtRowOptions: $scope.mdtRow, mdtRowPaginatorFunction: $scope.mdtRowPaginator, mdtRowPaginatorErrorMessage: $scope.mdtRowPaginatorErrorMessage }); } vm.addRowData = _.bind($scope.tableDataStorageService.addRowData, $scope.tableDataStorageService); } function addHeaderCell(ops){ $scope.tableDataStorageService.addHeaderCellData(ops); } }], link: function($scope, element, attrs, ctrl, transclude){ injectContentIntoTemplate(); $scope.isAnyRowSelected = _.bind($scope.tableDataStorageService.isAnyRowSelected, $scope.tableDataStorageService); $scope.isPaginationEnabled = isPaginationEnabled; if(!_.isEmpty($scope.mdtRow)) { //local search/filter if (angular.isUndefined(attrs.mdtRowPaginator)) { $scope.$watch('mdtRow', function (mdtRow) { $scope.tableDataStorageService.storage = []; addRawDataToStorage(mdtRow['data']); }, true); }else{ //if it's used for 'Ajax pagination' } } function addRawDataToStorage(data){ var rowId; var columnValues = []; _.each(data, function(row){ rowId = _.get(row, $scope.mdtRow['table-row-id-key']); columnValues = []; _.each($scope.mdtRow['column-keys'], function(columnKey){ columnValues.push(_.get(row, columnKey)); }); $scope.tableDataStorageService.addRowData(rowId, columnValues); }); } function isPaginationEnabled(){ if($scope.paginatedRows === true || ($scope.paginatedRows && $scope.paginatedRows.hasOwnProperty('isEnabled') && $scope.paginatedRows.isEnabled === true)){ return true; } return false; } function injectContentIntoTemplate(){ transclude(function (clone) { var headings = []; var body = []; _.each(clone, function (child) { var $child = angular.element(child); if ($child.hasClass('theadTrRow')) { headings.push($child); } else { body.push($child); } }); element.find('#reader').append(headings).append(body); }); } } }; } angular .module('mdDataTable') .directive('mdtTable', mdtTableDirective); }()); (function(){ 'use strict'; TableDataStorageFactory.$inject = ['$log']; function TableDataStorageFactory($log){ function TableDataStorageService(){ this.storage = []; this.header = []; this.sortByColumnLastIndex = null; this.orderByAscending = true; } TableDataStorageService.prototype.addHeaderCellData = function(ops){ this.header.push(ops); }; TableDataStorageService.prototype.addRowData = function(explicitRowId, rowArray){ if(!(rowArray instanceof Array)){ $log.error('`rowArray` parameter should be array'); return; } this.storage.push({ rowId: explicitRowId, optionList: { selected: false, deleted: false, visible: true }, data: rowArray }); }; TableDataStorageService.prototype.getRowData = function(index){ if(!this.storage[index]){ $log.error('row is not exists at index: '+index); return; } return this.storage[index].data; }; TableDataStorageService.prototype.getRowOptions = function(index){ if(!this.storage[index]){ $log.error('row is not exists at index: '+index); return; } return this.storage[index].optionList; }; TableDataStorageService.prototype.setAllRowsSelected = function(isSelected, isPaginationEnabled){ if(typeof isSelected === 'undefined'){ $log.error('`isSelected` parameter is required'); return; } _.each(this.storage, function(rowData){ if(isPaginationEnabled) { if (rowData.optionList.visible) { rowData.optionList.selected = isSelected ? true : false; } }else{ rowData.optionList.selected = isSelected ? true : false; } }); }; TableDataStorageService.prototype.reverseRows = function(){ this.storage.reverse(); }; TableDataStorageService.prototype.sortByColumn = function(columnIndex, iteratee){ if(this.sortByColumnLastIndex === columnIndex){ this.reverseRows(); this.orderByAscending = !this.orderByAscending; }else{ this.sortByColumnIndex(columnIndex, iteratee); this.sortByColumnLastIndex = columnIndex; this.orderByAscending = true; } return this.orderByAscending ? -1 : 1; }; TableDataStorageService.prototype.sortByColumnIndex = function(index, iteratee){ var sortFunction; if (typeof iteratee === 'function') { sortFunction = function(rowData) { return iteratee(rowData.data[index], rowData, index); }; } else { sortFunction = function (rowData) { return rowData.data[index]; }; } var res = _.sortBy(this.storage, sortFunction); this.storage = res; }; TableDataStorageService.prototype.isAnyRowSelected = function(){ return _.some(this.storage, function(rowData){ return rowData.optionList.selected === true && rowData.optionList.deleted === false; }); }; TableDataStorageService.prototype.getNumberOfSelectedRows = function(){ var res = _.countBy(this.storage, function(rowData){ return rowData.optionList.selected === true && rowData.optionList.deleted === false ? 'selected' : 'unselected'; }); return res.selected ? res.selected : 0; }; TableDataStorageService.prototype.deleteSelectedRows = function(){ var deletedRows = []; _.each(this.storage, function(rowData){ if(rowData.optionList.selected && rowData.optionList.deleted === false){ if(rowData.rowId){ deletedRows.push(rowData.rowId); //Fallback when no id was specified } else{ deletedRows.push(rowData.data); } rowData.optionList.deleted = true; } }); return deletedRows; }; return { getInstance: function(){ return new TableDataStorageService(); } }; } angular .module('mdDataTable') .factory('TableDataStorageFactory', TableDataStorageFactory); }()); (function(){ 'use strict'; function mdtAjaxPaginationHelperFactory(){ function mdtAjaxPaginationHelper(params){ this.tableDataStorageService = params.tableDataStorageService; this.rowOptions = params.mdtRowOptions; this.paginatorFunction = params.mdtRowPaginatorFunction; this.mdtRowPaginatorErrorMessage = params.mdtRowPaginatorErrorMessage || 'Ajax error during loading contents.'; if(params.paginationSetting && params.paginationSetting.hasOwnProperty('rowsPerPageValues') && params.paginationSetting.rowsPerPageValues.length > 0){ this.rowsPerPageValues = params.paginationSetting.rowsPerPageValues; }else{ this.rowsPerPageValues = [10,20,30,50,100]; } this.rowsPerPage = this.rowsPerPageValues[0]; this.page = 1; this.totalResultCount = 0; this.totalPages = 0; this.isLoading = false; //fetching the 1st page this.fetchPage(this.page); } mdtAjaxPaginationHelper.prototype.getStartRowIndex = function(){ return (this.page-1) * this.rowsPerPage; }; mdtAjaxPaginationHelper.prototype.getEndRowIndex = function(){ return this.getStartRowIndex() + this.rowsPerPage-1; }; mdtAjaxPaginationHelper.prototype.getTotalRowsCount = function(){ return this.totalPages; }; mdtAjaxPaginationHelper.prototype.getRows = function(){ return this.tableDataStorageService.storage; }; mdtAjaxPaginationHelper.prototype.previousPage = function(){ var that = this; if(this.page > 1){ this.fetchPage(this.page-1).then(function(){ that.page--; }); } }; mdtAjaxPaginationHelper.prototype.nextPage = function(){ var that = this; if(this.page < this.totalPages){ this.fetchPage(this.page+1).then(function(){ that.page++; }); } }; mdtAjaxPaginationHelper.prototype.fetchPage = function(page){ this.isLoading = true; var that = this; return this.paginatorFunction({page: page, pageSize: this.rowsPerPage}) .then(function(data){ that.tableDataStorageService.storage = []; that.setRawDataToStorage(that, data.results, that.rowOptions['table-row-id-key'], that.rowOptions['column-keys']); that.totalResultCount = data.totalResultCount; that.totalPages = Math.ceil(data.totalResultCount / that.rowsPerPage); that.isLoadError = false; that.isLoading = false; }, function(){ that.tableDataStorageService.storage = []; that.isLoadError = true; that.isLoading = false; }); }; mdtAjaxPaginationHelper.prototype.setRawDataToStorage = function(that, data, tableRowIdKey, columnKeys){ var rowId; var columnValues = []; _.each(data, function(row){ rowId = _.get(row, tableRowIdKey); columnValues = []; _.each(columnKeys, function(columnKey){ columnValues.push(_.get(row, columnKey)); }); that.tableDataStorageService.addRowData(rowId, columnValues); }); }; mdtAjaxPaginationHelper.prototype.setRowsPerPage = function(rowsPerPage){ this.rowsPerPage = rowsPerPage; this.page = 1; this.fetchPage(this.page); }; return { getInstance: function(tableDataStorageService, isEnabled, paginatorFunction, rowOptions){ return new mdtAjaxPaginationHelper(tableDataStorageService, isEnabled, paginatorFunction, rowOptions); } }; } angular .module('mdDataTable') .service('mdtAjaxPaginationHelperFactory', mdtAjaxPaginationHelperFactory); }()); (function(){ 'use strict'; function mdtPaginationHelperFactory(){ function mdtPaginationHelper(tableDataStorageService, paginationSetting){ this.tableDataStorageService = tableDataStorageService; if(paginationSetting && paginationSetting.hasOwnProperty('rowsPerPageValues') && paginationSetting.rowsPerPageValues.length > 0){ this.rowsPerPageValues = paginationSetting.rowsPerPageValues; }else{ this.rowsPerPageValues = [10,20,30,50,100]; } this.rowsPerPage = this.rowsPerPageValues[0]; this.page = 1; } mdtPaginationHelper.prototype.calculateVisibleRows = function (){ var that = this; _.each(this.tableDataStorageService.storage, function (rowData, index) { if(index >= that.getStartRowIndex() && index <= that.getEndRowIndex()) { rowData.optionList.visible = true; } else { rowData.optionList.visible = false; } }); }; mdtPaginationHelper.prototype.getStartRowIndex = function(){ return (this.page-1) * this.rowsPerPage; }; mdtPaginationHelper.prototype.getEndRowIndex = function(){ return this.getStartRowIndex() + this.rowsPerPage-1; }; mdtPaginationHelper.prototype.getTotalRowsCount = function(){ return this.tableDataStorageService.storage.length; }; mdtPaginationHelper.prototype.getRows = function(){ this.calculateVisibleRows(); return this.tableDataStorageService.storage; }; mdtPaginationHelper.prototype.previousPage = function(){ if(this.page > 1){ this.page--; } }; mdtPaginationHelper.prototype.nextPage = function(){ var totalPages = Math.ceil(this.getTotalRowsCount() / this.rowsPerPage); if(this.page < totalPages){ this.page++; } }; mdtPaginationHelper.prototype.setRowsPerPage = function(rowsPerPage){ this.rowsPerPage = rowsPerPage; this.page = 1; }; return { getInstance: function(tableDataStorageService, isEnabled){ return new mdtPaginationHelper(tableDataStorageService, isEnabled); } }; } angular .module('mdDataTable') .service('mdtPaginationHelperFactory', mdtPaginationHelperFactory); }()); (function(){ 'use strict'; ColumnAlignmentHelper.$inject = ['ColumnOptionProvider']; function ColumnAlignmentHelper(ColumnOptionProvider){ var service = this; service.getColumnAlignClass = getColumnAlignClass; function getColumnAlignClass(alignRule) { if (alignRule === ColumnOptionProvider.ALIGN_RULE.ALIGN_RIGHT) { return 'rightAlignedColumn'; } else { return 'leftAlignedColumn'; } } } angular .module('mdDataTable') .service('ColumnAlignmentHelper', ColumnAlignmentHelper); }()); (function(){ 'use strict'; var ColumnOptionProvider = { ALIGN_RULE : { ALIGN_LEFT: 'left', ALIGN_RIGHT: 'right' } }; angular.module('mdDataTable') .value('ColumnOptionProvider', ColumnOptionProvider); })(); (function(){ 'use strict'; /** * @ngdoc directive * @name mdtCell * @restrict E * @requires mdtTable * @requires mdtRow * * @description * Representing a cell which should be placed inside `mdt-row` element directive. * * @param {boolean=} htmlContent if set to true, then html content can be placed into the content of the directive. * * @example * <pre> * <mdt-table> * <mdt-header-row> * <mdt-column>Product name</mdt-column> * <mdt-column>Price</mdt-column> * <mdt-column>Details</mdt-column> * </mdt-header-row> * * <mdt-row ng-repeat="product in ctrl.products"> * <mdt-cell>{{product.name}}</mdt-cell> * <mdt-cell>{{product.price}}</mdt-cell> * <mdt-cell html-content="true"> * <a href="productdetails/{{product.id}}">more details</a> * </mdt-cell> * </mdt-row> * </mdt-table> * </pre> */ mdtCellDirective.$inject = ['$parse']; function mdtCellDirective($parse){ return { restrict: 'E', replace: true, transclude: true, require: '^mdtRow', link: function($scope, element, attr, mdtRowCtrl, transclude){ transclude(function (clone) { //TODO: rework, figure out something for including html content if(attr.htmlContent){ mdtRowCtrl.addToRowDataStorage(clone, 'htmlContent'); }else{ //TODO: better idea? var cellValue = $parse(clone.html().replace('{{', '').replace('}}', ''))($scope.$parent); mdtRowCtrl.addToRowDataStorage(cellValue); } }); } }; } angular .module('mdDataTable') .directive('mdtCell', mdtCellDirective); }()); (function(){ 'use strict'; /** * @ngdoc directive * @name mdtRow * @restrict E * @requires mdtTable * * @description * Representing a row which should be placed inside `mdt-table` element directive. * * <i>Please note the following: This element has limited functionality. It cannot listen on data changes that happens outside of the * component. E.g.: if you provide an ng-repeat to generate your data rows for the table, using this directive, * it won't work well if this data will change. Since the way how transclusions work, it's (with my best * knowledge) an impossible task to solve at the moment. If you intend to use dynamic data rows, it's still * possible with using mdtRow attribute of mdtTable.</i> * * @param {string|integer=} tableRowId when set table will have a uniqe id. In case of deleting a row will give * back this id. * * @example * <pre> * <mdt-table> * <mdt-header-row> * <mdt-column>Product name</mdt-column> * <mdt-column>Price</mdt-column> * </mdt-header-row> * * <mdt-row * ng-repeat="product in products" * table-row-id="{{product.id}}"> * <mdt-cell>{{product.name}}</mdt-cell> * <mdt-cell>{{product.price}}</mdt-cell> * </mdt-row> * </mdt-table> * </pre> */ function mdtRowDirective(){ return { restrict: 'E', transclude: true, require: '^mdtTable', scope: { tableRowId: '=' }, controller: ['$scope', function($scope){ var vm = this; vm.addToRowDataStorage = addToRowDataStorage; $scope.rowDataStorage = []; function addToRowDataStorage(value, contentType){ if(contentType === 'htmlContent'){ $scope.rowDataStorage.push({value: value, type: 'html'}); }else{ $scope.rowDataStorage.push(value); } } }], link: function($scope, element, attrs, ctrl, transclude){ appendColumns(); ctrl.addRowData($scope.tableRowId, $scope.rowDataStorage); function appendColumns(){ transclude(function (clone) { element.append(clone); }); } } }; } angular .module('mdDataTable') .directive('mdtRow', mdtRowDirective); }()); (function(){ 'use strict'; mdtAddAlignClass.$inject = ['ColumnAlignmentHelper']; function mdtAddAlignClass(ColumnAlignmentHelper){ return { restrict: 'A', scope: { mdtAddAlignClass: '=' }, link: function($scope, element){ var classToAdd = ColumnAlignmentHelper.getColumnAlignClass($scope.mdtAddAlignClass); element.addClass(classToAdd); } }; } angular .module('mdDataTable') .directive('mdtAddAlignClass', mdtAddAlignClass); }()); (function(){ 'use strict'; function mdtAddHtmlContentToCellDirective(){ return { restrict: 'A', link: function($scope, element, attr){ $scope.$watch('htmlContent', function(){ element.empty(); element.append($scope.$eval(attr.mdtAddHtmlContentToCell)); }); } }; } angular .module('mdDataTable') .directive('mdtAddHtmlContentToCell', mdtAddHtmlContentToCellDirective); }()); (function(){ 'use strict'; function mdtAnimateSortIconHandlerDirective(){ return { restrict: 'A', scope: false, link: function($scope, element){ if($scope.animateSortIcon){ element.addClass('animate-sort-icon'); } } }; } angular .module('mdDataTable') .directive('mdtAnimateSortIconHandler', mdtAnimateSortIconHandlerDirective); }()); (function(){ 'use strict'; function mdtSelectAllRowsHandlerDirective(){ return { restrict: 'A', scope: false, link: function($scope){ $scope.selectAllRows = false; $scope.$watch('selectAllRows', function(val){ $scope.tableDataStorageService.setAllRowsSelected(val, $scope.isPaginationEnabled()); }); } }; } angular .module('mdDataTable') .directive('mdtSelectAllRowsHandler', mdtSelectAllRowsHandlerDirective); }()); (function(){ 'use strict'; function mdtSortHandlerDirective(){ return { restrict: 'A', scope: false, link: function($scope, element){ var columnIndex = $scope.$index; $scope.isSorted = isSorted; $scope.direction = 1; element.on('click', sortHandler); function sortHandler(){ if($scope.sortableColumns){ $scope.$apply(function(){ $scope.direction = $scope.tableDataStorageService.sortByColumn(columnIndex, $scope.headerRowData.sortBy); }); } } function isSorted(){ return $scope.tableDataStorageService.sortByColumnLastIndex === columnIndex; } $scope.$on('$destroy', function(){ element.off('click', sortHandler); }); } }; } angular .module('mdDataTable') .directive('mdtSortHandler', mdtSortHandlerDirective); }()); (function(){ 'use strict'; /** * @ngdoc directive * @name mdtColumn * @restrict E * @requires mdtTable * * @description * Representing a header column cell which should be placed inside `mdt-header-row` element directive. * * @param {string=} alignRule align cell content. This settings will have affect on each data cells in the same * column (e.g. every x.th cell in every row). * * Assignable values: * - 'left' * - 'right' * * @param {function()=} sortBy compareFunction callback for sorting the column data's. As every compare function, * should get two parameters and return with the comapred result (-1,1,0) * * @param {string=} columnDefinition displays a tooltip on hover. * * @example * <pre> * <mdt-table> * <mdt-header-row> * <mdt-column align-rule="left">Product name</mdt-column> * <mdt-column * align-rule="right" * column-definition="The price of the product in gross.">Price</mdt-column> * </mdt-header-row> * * <mdt-row ng-repeat="product in ctrl.products"> * <mdt-cell>{{product.name}}</mdt-cell> * <mdt-cell>{{product.price}}</mdt-cell> * </mdt-row> * </mdt-table> * </pre> */ mdtColumnDirective.$inject = ['$parse']; function mdtColumnDirective($parse){ return { restrict: 'E', transclude: true, replace: true, scope: { alignRule: '@', sortBy: '=', columnDefinition: '@' }, require: ['^mdtTable'], link: function ($scope, element, attrs, ctrl, transclude) { var mdtTableCtrl = ctrl[0]; transclude(function (clone) { var cellValue; if(clone.html().indexOf('{{') !== -1){ cellValue = $parse(clone.html().replace('{{', '').replace('}}', ''))($scope.$parent); }else{ cellValue = clone.html(); } mdtTableCtrl.addHeaderCell({ alignRule: $scope.alignRule, sortBy: $scope.sortBy, columnDefinition: $scope.columnDefinition, columnName: cellValue }); }); } }; } angular .module('mdDataTable') .directive('mdtColumn', mdtColumnDirective); }()); (function(){ 'use strict'; function mdtGeneratedHeaderCellContentDirective(){ return { restrict: 'E', templateUrl: '/main/templates/mdtGeneratedHeaderCellContent.html', replace: true, scope: false, link: function(){ } }; } angular .module('mdDataTable') .directive('mdtGeneratedHeaderCellContent', mdtGeneratedHeaderCellContentDirective); }()); (function(){ 'use strict'; /** * @ngdoc directive * @name mdtHeaderRow * @restrict E * @requires mdtTable * * @description * Representing a header row which should be placed inside `mdt-table` element directive. * The main responsibility of this directive is to execute all the transcluded `mdt-column` element directives. * */ function mdtHeaderRowDirective(){ return { restrict: 'E', replace: true, transclude: true, require: '^mdtTable', scope: true, link: function($scope, element, attrs, mdtCtrl, transclude){ appendColumns(); function appendColumns(){ transclude(function (clone) { element.append(clone); }); } } }; } angular .module('mdDataTable') .directive('mdtHeaderRow', mdtHeaderRowDirective); }()); (function(){ 'use strict'; mdtCardFooterDirective.$inject = ['$timeout']; function mdtCardFooterDirective($timeout){ return { restrict: 'E', templateUrl: '/main/templates/mdtCardFooter.html', transclude: true, replace: true, scope: true, require: ['^mdtTable'], link: function($scope){ $scope.rowsPerPage = $scope.mdtPaginationHelper.rowsPerPage; $scope.$watch('rowsPerPage', function(newVal, oldVal){ $scope.mdtPaginationHelper.setRowsPerPage(newVal); }); } }; } angular .module('mdDataTable') .directive('mdtCardFooter', mdtCardFooterDirective); }()); (function(){ 'use strict'; function mdtCardHeaderDirective(){ return { restrict: 'E', templateUrl: '/main/templates/mdtCardHeader.html', transclude: true, replace: true, scope: true, require: ['^mdtTable'], link: function($scope){ $scope.isTableCardEnabled = false; if($scope.tableCard && $scope.tableCard.visible !== false){ $scope.isTableCardEnabled = true; } } }; } angular .module('mdDataTable') .directive('mdtCardHeader', mdtCardHeaderDirective); }());
javascript
package eventcenter.leveldb; import eventcenter.api.*; import eventcenter.api.async.QueueEventContainer; import eventcenter.api.support.DefaultEventCenter; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class TestLevelDBEventContainerFactory { DefaultEventCenter eventCenter; @Ignore @Test public void test() throws Exception { eventCenter = new DefaultEventCenter(); eventCenter.startup(); EventCenterConfig config = new EventCenterConfig(); List<EventListener> listeners = new ArrayList<EventListener>(); listeners.add(new TestListener()); CommonEventListenerConfig listenerConfig = new CommonEventListenerConfig(); listenerConfig.getListeners().put("test", listeners ); config.loadCommonEventListenerConfig(listenerConfig); LevelDBContainerFactory factory = new LevelDBContainerFactory(); factory.setCorePoolSize(1); factory.setMaximumPoolSize(1); QueueEventContainer container = factory.createContainer(config); container.startup(); Assert.assertEquals(true, container.isIdle()); container.send(new CommonEventSource(this, UUID.randomUUID().toString(), "test", null, null, null)); Thread.sleep(200); Assert.assertEquals(false, container.isIdle()); container.send(new CommonEventSource(this, UUID.randomUUID().toString(), "test", null, null, null)); Thread.sleep(500); Assert.assertEquals(false, container.isIdle()); Thread.sleep(1500); Assert.assertEquals(true, container.isIdle()); container.shutdown(); eventCenter.shutdown(); } class TestListener implements EventListener { @Override public void onObserved(CommonEventSource source) { try { System.out.println("begin consuming:" + source.getEventId()); Thread.sleep(1000); System.out.println("consumed:" + source.getEventId()); } catch (InterruptedException e) { e.printStackTrace(); } } } }
java
{ "name": "hexo-filter-responsive-images", "version": "1.5.0", "description": "Generate multiple version of images for responsive Hexo blogs", "main": "index.js", "directories": { "lib": "lib" }, "scripts": { "test": "ava" }, "repository": { "type": "git", "url": "git+https://github.com/hexojs/hexo-filter-responsive-images.git" }, "author": "ertrzyiks <<EMAIL>>", "license": "MIT", "bugs": { "url": "https://github.com/hexojs/hexo-filter-responsive-images/issues" }, "homepage": "https://github.com/hexojs/hexo-filter-responsive-images#readme", "peerDependencies": { "hexo": "3.x || 4.x" }, "dependencies": { "bluebird": "^3.7.0", "micromatch": "^4.0.2", "sharp": "^0.25.1", "stream-to-array": "^2.3.0", "stream-to-promise": "^2.2.0" }, "devDependencies": { "@ava/babel": "^1.0.0", "ava": "^3.0", "hexo": "^4.0.0", "hexo-test-utils": "^0.4.1" }, "ava": { "files": [ "specs/*_spec.js" ], "babel": true, "snapshotDir": "specs/snapshots" } }
json
<filename>projects/survey-component-lib/src/lib/survey/survey-question/survey-question.module.ts import {NgModule} from '@angular/core'; import { SurveyQuestionComponent } from './survey-question.component'; import {QuestionVariantsModule} from './question-variants/question-variants.module'; import {QuestionFreetextModule} from './question-freetext/question-freetext.module'; import {SharedModule} from '../../shared/shared.module'; @NgModule({ imports: [SharedModule, QuestionVariantsModule, QuestionFreetextModule], declarations: [SurveyQuestionComponent], exports: [SurveyQuestionComponent] }) export class SurveyQuestionModule { }
typescript
Rishabh Pant was not included in India's ODI squad for the upcoming three-match series against Australia starting January 12. By India Today Web Desk: Chairman selectors for the Board of Control for Cricket in India (BCCI), MSK Prasad on Monday confirmed that Rishabh Pant is on their radar for selection in the Indian one-day team ahead of the 2019 World Cup. Pant was ignored for the upcoming three-match ODI series against Australia but his performance in the just-concluded Test series, and his ability with the bat in white-ball cricket, makes him a hot property in limited-overs cricket. Pant finished as India's second highest run-scorer in the four-match Test series which India won 2-1 earlier on Monday after the Sydney Test ended in a draw, owing to poor weather conditions and constant rain on the fifth and final day. Pant amassed 350 runs in the series at an average of over 58 which included his unbeaten 159 that he scored at the Sydney Cricket Ground on Saturday. Looking at his form in the Test series and improved wicketkeeping performance in the Tests, it came as a surprise after he was not included in the ODI team, especially with the World Cup in England just a few months away. Pant also scored his maiden Test hundred in England last year at The Oval and has improved a lot with the bat and gloves since then. But Prasad has clarified that Pant remains in their plans for the World Cup with MS Dhoni being the primary keeper-batsman along with Dinesh Karthik. "There is absolutely no doubt that he is among one of those wicketkeepers [for World Cup]. All the three shortlisted keepers are doing well. He is definitely part of pour World Cup plans. It's a part of the workload management we are following," Prasad told India Today's Boria Majumdar in an exclusive interview. Prasad also went on to reveal that Pant is carrying a few niggles in his body after playing four high-intensity Tests against Australia which is why they are looking to manage his workload at the moment. "You have seen how many players we are resting these days. This kid has played the T20s and the four high-intensity Tests. Body also takes a wear and tear. He is having a few niggles, he needs to recover. I am sure he will come back much stronger. "He is the only wicketkeeper to score hundred in England and Australia. We have given him some targets. We have set him he has to finish the matches and come. This Sydney Test match will be a turning point in his career," Prasad added. His exploits with the bat Down Under even prompted former India captain Sunil Gavaskar to say that it's only a matter of time before Pant becomes a permanent member of the Indian limited-overs sides. "It will happen sooner than later (play all three formats for India). But let's not forget this was Test-match innings that he played. "I think India need to first look at tour Test team, then we can think about getting him back into the ODI team. That day is also not too far away. We all know MSD (MS Dhoni) is not going to play after the ICC World Cup in June-July. Rishabh will get his opportunity in the next season, if not at the World Cup next year," Gavaskar told India Today.
english
<filename>ReactNativeFrontend/ios/Pods/boost/boost/phoenix/support/preprocessed/vector_20.hpp /*============================================================================== Copyright (c) 2005-2010 <NAME> Copyright (c) 2010 <NAME> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ namespace boost { namespace phoenix { template <typename Dummy = void> struct vector0 { typedef mpl::int_<0> size_type; static const int size_value = 0; }; template <int> struct vector_chooser; template <> struct vector_chooser<0> { template <typename Dummy = void> struct apply { typedef vector0<> type; }; }; }} namespace boost { namespace phoenix { template <typename A0> struct vector1 { typedef A0 member_type0; A0 a0; typedef mpl::int_<1> size_type; static const int size_value = 1; typedef vector0<> args_type; args_type args() const { args_type r = {}; return r; } }; template <> struct vector_chooser<1> { template <typename A0> struct apply { typedef vector1<A0> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) , ( boost::phoenix::vector1 ) (A0) , (A0, a0) ) namespace boost { namespace phoenix { template <typename A0 , typename A1> struct vector2 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef mpl::int_<2> size_type; static const int size_value = 2; typedef vector1<A1> args_type; args_type args() const { args_type r = {a1}; return r; } }; template <> struct vector_chooser<2> { template <typename A0 , typename A1> struct apply { typedef vector2<A0 , A1> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) , ( boost::phoenix::vector2 ) (A0) (A1) , (A0, a0) (A1, a1) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2> struct vector3 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef mpl::int_<3> size_type; static const int size_value = 3; typedef vector2<A1 , A2> args_type; args_type args() const { args_type r = {a1 , a2}; return r; } }; template <> struct vector_chooser<3> { template <typename A0 , typename A1 , typename A2> struct apply { typedef vector3<A0 , A1 , A2> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) , ( boost::phoenix::vector3 ) (A0) (A1) (A2) , (A0, a0) (A1, a1) (A2, a2) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3> struct vector4 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef mpl::int_<4> size_type; static const int size_value = 4; typedef vector3<A1 , A2 , A3> args_type; args_type args() const { args_type r = {a1 , a2 , a3}; return r; } }; template <> struct vector_chooser<4> { template <typename A0 , typename A1 , typename A2 , typename A3> struct apply { typedef vector4<A0 , A1 , A2 , A3> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) , ( boost::phoenix::vector4 ) (A0) (A1) (A2) (A3) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4> struct vector5 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef mpl::int_<5> size_type; static const int size_value = 5; typedef vector4<A1 , A2 , A3 , A4> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4}; return r; } }; template <> struct vector_chooser<5> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4> struct apply { typedef vector5<A0 , A1 , A2 , A3 , A4> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) , ( boost::phoenix::vector5 ) (A0) (A1) (A2) (A3) (A4) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5> struct vector6 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef mpl::int_<6> size_type; static const int size_value = 6; typedef vector5<A1 , A2 , A3 , A4 , A5> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5}; return r; } }; template <> struct vector_chooser<6> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5> struct apply { typedef vector6<A0 , A1 , A2 , A3 , A4 , A5> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) , ( boost::phoenix::vector6 ) (A0) (A1) (A2) (A3) (A4) (A5) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6> struct vector7 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef mpl::int_<7> size_type; static const int size_value = 7; typedef vector6<A1 , A2 , A3 , A4 , A5 , A6> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6}; return r; } }; template <> struct vector_chooser<7> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6> struct apply { typedef vector7<A0 , A1 , A2 , A3 , A4 , A5 , A6> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) , ( boost::phoenix::vector7 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7> struct vector8 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef mpl::int_<8> size_type; static const int size_value = 8; typedef vector7<A1 , A2 , A3 , A4 , A5 , A6 , A7> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7}; return r; } }; template <> struct vector_chooser<8> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7> struct apply { typedef vector8<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) , ( boost::phoenix::vector8 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8> struct vector9 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef mpl::int_<9> size_type; static const int size_value = 9; typedef vector8<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8}; return r; } }; template <> struct vector_chooser<9> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8> struct apply { typedef vector9<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) , ( boost::phoenix::vector9 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9> struct vector10 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef mpl::int_<10> size_type; static const int size_value = 10; typedef vector9<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9}; return r; } }; template <> struct vector_chooser<10> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9> struct apply { typedef vector10<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) , ( boost::phoenix::vector10 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10> struct vector11 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef mpl::int_<11> size_type; static const int size_value = 11; typedef vector10<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10}; return r; } }; template <> struct vector_chooser<11> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10> struct apply { typedef vector11<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) , ( boost::phoenix::vector11 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11> struct vector12 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef mpl::int_<12> size_type; static const int size_value = 12; typedef vector11<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11}; return r; } }; template <> struct vector_chooser<12> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11> struct apply { typedef vector12<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) , ( boost::phoenix::vector12 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12> struct vector13 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef mpl::int_<13> size_type; static const int size_value = 13; typedef vector12<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12}; return r; } }; template <> struct vector_chooser<13> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12> struct apply { typedef vector13<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) , ( boost::phoenix::vector13 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13> struct vector14 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef A13 member_type13; A13 a13; typedef mpl::int_<14> size_type; static const int size_value = 14; typedef vector13<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12 , a13}; return r; } }; template <> struct vector_chooser<14> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13> struct apply { typedef vector14<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) , ( boost::phoenix::vector14 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) (A13, a13) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14> struct vector15 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef A13 member_type13; A13 a13; typedef A14 member_type14; A14 a14; typedef mpl::int_<15> size_type; static const int size_value = 15; typedef vector14<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12 , a13 , a14}; return r; } }; template <> struct vector_chooser<15> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14> struct apply { typedef vector15<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) , ( boost::phoenix::vector15 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) (A13, a13) (A14, a14) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15> struct vector16 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef A13 member_type13; A13 a13; typedef A14 member_type14; A14 a14; typedef A15 member_type15; A15 a15; typedef mpl::int_<16> size_type; static const int size_value = 16; typedef vector15<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12 , a13 , a14 , a15}; return r; } }; template <> struct vector_chooser<16> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15> struct apply { typedef vector16<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) , ( boost::phoenix::vector16 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) (A13, a13) (A14, a14) (A15, a15) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16> struct vector17 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef A13 member_type13; A13 a13; typedef A14 member_type14; A14 a14; typedef A15 member_type15; A15 a15; typedef A16 member_type16; A16 a16; typedef mpl::int_<17> size_type; static const int size_value = 17; typedef vector16<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12 , a13 , a14 , a15 , a16}; return r; } }; template <> struct vector_chooser<17> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16> struct apply { typedef vector17<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) , ( boost::phoenix::vector17 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) (A13, a13) (A14, a14) (A15, a15) (A16, a16) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16 , typename A17> struct vector18 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef A13 member_type13; A13 a13; typedef A14 member_type14; A14 a14; typedef A15 member_type15; A15 a15; typedef A16 member_type16; A16 a16; typedef A17 member_type17; A17 a17; typedef mpl::int_<18> size_type; static const int size_value = 18; typedef vector17<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12 , a13 , a14 , a15 , a16 , a17}; return r; } }; template <> struct vector_chooser<18> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16 , typename A17> struct apply { typedef vector18<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) (A17) , ( boost::phoenix::vector18 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) (A17) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) (A13, a13) (A14, a14) (A15, a15) (A16, a16) (A17, a17) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16 , typename A17 , typename A18> struct vector19 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef A13 member_type13; A13 a13; typedef A14 member_type14; A14 a14; typedef A15 member_type15; A15 a15; typedef A16 member_type16; A16 a16; typedef A17 member_type17; A17 a17; typedef A18 member_type18; A18 a18; typedef mpl::int_<19> size_type; static const int size_value = 19; typedef vector18<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12 , a13 , a14 , a15 , a16 , a17 , a18}; return r; } }; template <> struct vector_chooser<19> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16 , typename A17 , typename A18> struct apply { typedef vector19<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) (A17) (A18) , ( boost::phoenix::vector19 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) (A17) (A18) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) (A13, a13) (A14, a14) (A15, a15) (A16, a16) (A17, a17) (A18, a18) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16 , typename A17 , typename A18 , typename A19> struct vector20 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef A13 member_type13; A13 a13; typedef A14 member_type14; A14 a14; typedef A15 member_type15; A15 a15; typedef A16 member_type16; A16 a16; typedef A17 member_type17; A17 a17; typedef A18 member_type18; A18 a18; typedef A19 member_type19; A19 a19; typedef mpl::int_<20> size_type; static const int size_value = 20; typedef vector19<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12 , a13 , a14 , a15 , a16 , a17 , a18 , a19}; return r; } }; template <> struct vector_chooser<20> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16 , typename A17 , typename A18 , typename A19> struct apply { typedef vector20<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) (A17) (A18) (A19) , ( boost::phoenix::vector20 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) (A17) (A18) (A19) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) (A13, a13) (A14, a14) (A15, a15) (A16, a16) (A17, a17) (A18, a18) (A19, a19) ) namespace boost { namespace phoenix { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16 , typename A17 , typename A18 , typename A19 , typename A20> struct vector21 { typedef A0 member_type0; A0 a0; typedef A1 member_type1; A1 a1; typedef A2 member_type2; A2 a2; typedef A3 member_type3; A3 a3; typedef A4 member_type4; A4 a4; typedef A5 member_type5; A5 a5; typedef A6 member_type6; A6 a6; typedef A7 member_type7; A7 a7; typedef A8 member_type8; A8 a8; typedef A9 member_type9; A9 a9; typedef A10 member_type10; A10 a10; typedef A11 member_type11; A11 a11; typedef A12 member_type12; A12 a12; typedef A13 member_type13; A13 a13; typedef A14 member_type14; A14 a14; typedef A15 member_type15; A15 a15; typedef A16 member_type16; A16 a16; typedef A17 member_type17; A17 a17; typedef A18 member_type18; A18 a18; typedef A19 member_type19; A19 a19; typedef A20 member_type20; A20 a20; typedef mpl::int_<21> size_type; static const int size_value = 21; typedef vector20<A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20> args_type; args_type args() const { args_type r = {a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 , a10 , a11 , a12 , a13 , a14 , a15 , a16 , a17 , a18 , a19 , a20}; return r; } }; template <> struct vector_chooser<21> { template <typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 , typename A12 , typename A13 , typename A14 , typename A15 , typename A16 , typename A17 , typename A18 , typename A19 , typename A20> struct apply { typedef vector21<A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20> type; }; }; }} BOOST_FUSION_ADAPT_TPL_STRUCT_NO_PARTIAL( (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) (A17) (A18) (A19) (A20) , ( boost::phoenix::vector21 ) (A0) (A1) (A2) (A3) (A4) (A5) (A6) (A7) (A8) (A9) (A10) (A11) (A12) (A13) (A14) (A15) (A16) (A17) (A18) (A19) (A20) , (A0, a0) (A1, a1) (A2, a2) (A3, a3) (A4, a4) (A5, a5) (A6, a6) (A7, a7) (A8, a8) (A9, a9) (A10, a10) (A11, a11) (A12, a12) (A13, a13) (A14, a14) (A15, a15) (A16, a16) (A17, a17) (A18, a18) (A19, a19) (A20, a20) )
cpp
/* Soot - a J*va Optimization Framework * Copyright (C) 2002 <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.jimple.spark.sets; import soot.jimple.spark.pag.Node; import soot.jimple.spark.pag.PAG; import java.util.*; import soot.Type; /** HashSet implementation of points-to set. * @author <NAME> */ public final class HashPointsToSet extends PointsToSetInternal { public HashPointsToSet( Type type, PAG pag ) { super( type ); this.pag = pag; } /** Returns true if this set contains no run-time objects. */ public final boolean isEmpty() { return s.isEmpty(); } /** Adds contents of other into this set, returns true if this set * changed. */ public final boolean addAll( final PointsToSetInternal other, final PointsToSetInternal exclude ) { if( other instanceof HashPointsToSet && exclude == null && ( pag.getTypeManager().getFastHierarchy() == null || type == null || type.equals( other.type ) ) ) { return s.addAll( ((HashPointsToSet) other).s ); } else { return super.addAll( other, exclude ); } } /** Calls v's visit method on all nodes in this set. */ public final boolean forall( P2SetVisitor v ) { for( Iterator<Node> it = new ArrayList<Node>(s).iterator(); it.hasNext(); ) { v.visit( it.next() ); } return v.getReturnValue(); } /** Adds n to this set, returns true if n was not already in this set. */ public final boolean add( Node n ) { if( pag.getTypeManager().castNeverFails( n.getType(), type ) ) { return s.add( n ); } return false; } /** Returns true iff the set contains n. */ public final boolean contains( Node n ) { return s.contains( n ); } public static P2SetFactory getFactory() { return new P2SetFactory() { public PointsToSetInternal newSet( Type type, PAG pag ) { return new HashPointsToSet( type, pag ); } }; } /* End of public methods. */ /* End of package methods. */ private final HashSet<Node> s = new HashSet<Node>(4); private PAG pag = null; }
java
# pylivecoding Pylivecoding is a live coding environment implementation inspired by Smalltalk Essentially this library reloads modules and updates all live instances of classes defined in those modules to the latest code of the class definition without losing any of the data/state. This way you can change code in your favorite code editor and IDE and immediately see the results without any delays. # How to use Pylivecoding is an extremely small library and its functionality is super simple. First of course you import the single module pylovecoding.py to your project. ```python import livecoding ``` In order for your modules to be reloaded and the live instances to be updated you have to issue the update command ```python livecoding.update_env() ``` This should be coded in a module that won't be used for live coding. Also the update and general live coding makes sense for code that repeats so its better put this update inside a loop of some sort. Your modules can be any kind of Python modules as long as all live classes are subclasses of livecoding.LiveObject. ```python import livecoding class MyClass(livecoding.LiveObject): ``` Thats all you have to do and you can code as you awlays code following whatever style you want. # Debugging live coding Traditional debugging compared to live code debugging is like fire compared to nucleal power. Because not only you see the problems in your source code you can change the live code while still the debugger is stepping through your code. This allows coding Smalltalk style. In Smalltalk some coders code entirely inside the debugger, they make intential mistakes under the safety that they can correct their errors with no delays at all because there is no need to restard the debugger and each new error triggers the debugger again.When the error is fixed via live coding, the breakpoint can be removed and the debugger instructed to continue execution like nothing happened. Fortunately python does provide such functionality through the use of post mortem debugging. Essentially it means that in the case of error the debugger triggers using the line that triggered the error as a temporary breakpoint. The code is the following ```python try: live_env.update() execute_my_code() except Exception as inst: type, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb) ``` As you can see we have here a usual exception handling code, inside the try we first live update our code to make sure it updated to the latest source code and execute our code , if an error occur or anyting else, it is stored and printed and then the debugger is triggered , hitting c inside pdb will continue execution first statement being updating to live code. The assumption here is that all this runs inside a loop of some sort so you can actually see the results of the updated code. Obviously if it is not and this is the last line of code , the application will just end end execution after the debugger was instructed to continue with the "c" command ;) # The actual benefits of live coding Technically speaking you can even use your source code editor as a debugger the reason being because of live coding you can print real time whatever value you want, inspect and even modify existing objects and generally do all the things you want even create your own breakpoints using if condition that will stop the execution if specific criteria are not met. Also you wont have the bigest disadvantage of a debugger , its inability to change the source code. Obviously this works great with Test Driven Development because the ability to lively manipulate tests making writting tests far easier. Live coding empowers the users with the ease needed to constantly experiment with code and it makes the whole experience far more enjoyable and productive. live coding make repls also uneccessary for the same reason. # Future plans The library is far from finished. The Smalltalk enviroment comes with a wealth of conveniences and automations and a very powerful IDE. Generally Python is powerful enough to do those things and there are good enough IDEs out there but I will be replicating some of the ideas to make my life easier. So to do list is the following - Make the library smart enough to detect changes inside modules and automatically update the live code/state
markdown
import sys import gtk from datetime import datetime import gobject from threading import Thread class uiSignalHelpers(object): def __init__(self, *args, **kwargs): super(uiSignalHelpers, self).__init__(*args, **kwargs) #print 'signal helpers __init__' def callback(self, *args, **kwargs): super(uiSignalHelpers, self).callback(*args, **kwargs) #print 'signal helpers callback' def gtk_widget_show(self, w, e = None): w.show() return True def gtk_widget_hide(self, w, e = None): w.hide() return True def information_message(self, widget, message, cb = None): self.attention = "INFO: %s" % message messagedialog = gtk.MessageDialog(widget, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message) messagedialog.connect("delete-event", lambda w, e: w.hide() or True) if cb: messagedialog.connect("response", cb) messagedialog.set_default_response(gtk.RESPONSE_OK) messagedialog.show() messagedialog.present() return messagedialog def error_message(self, widget, message): self.attention = "ERROR: %s" % message messagedialog = gtk.MessageDialog(widget, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CANCEL, message) messagedialog.run() messagedialog.destroy() def warning_message(self, widget, message): self.attention = "WARNING: %s" % message messagedialog = gtk.MessageDialog(widget, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK_CANCEL, message) messagedialog.show() messagedialog.present() messagedialog.run() messagedialog.destroy() def question_message(self, widget, message, cb = None): self.attention = "QUESTION: %s" % message messagedialog = gtk.MessageDialog(widget, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, message) messagedialog.connect("delete-event", lambda w, e: w.hide() or True) if cb: messagedialog.connect("response", cb) messagedialog.set_default_response(gtk.RESPONSE_YES) messagedialog.show() messagedialog.present() return messagedialog def interval_dialog(self, message): if not self.interval_dialog_showing: if not self.timetracker_window.is_active(): self.timetracker_window.show() self.timetracker_window.present() self.interval_dialog_showing = True return self.question_message(self.timetracker_window, message, self.on_interval_dialog) return None def stop_interval_dialog(self, message): if not self.stop_interval_dialog_showing: if not self.timetracker_window.is_active(): self.timetracker_window.show() self.timetracker_window.present() self.stop_interval_dialog_showing = True return self.information_message(self.timetracker_window, message, self.on_stopped) return None def set_custom_label(self, widget, text): #set custom label on stock button Label = widget.get_children()[0] Label = Label.get_children()[0].get_children()[1] Label = Label.set_label(text) def window_state(self, widget, state): self.timetracker_window_state = state.new_window_state class uiSignals(uiSignalHelpers): def __init__(self, *args, **kwargs): super(uiSignals, self).__init__(*args, **kwargs) #these are components defined inside the ui file #print 'signals __init__' self.preferences_window.connect('delete-event', lambda w, e: w.hide() or True) self.timetracker_window.connect('delete-event', lambda w, e: w.hide() or True) self.timetracker_window.connect('destroy', lambda w, e: w.hide() or True) self.timetracker_window.connect("window-state-event", self.window_state) self.about_dialog.connect("delete-event", lambda w, e: w.hide() or True) self.about_dialog.connect("response", lambda w, e: w.hide() or True) self.notes_textview.connect('key_press_event', self.on_textview_ctrl_enter) def callback(self, *args, **kwargs): #stub super(uiSignals, self).callback(*args, **kwargs) #executed after init, hopefully this will let me inject interrupts #print 'signals callback' self.icon.connect('activate', self.left_click) self.icon.connect("popup-menu", self.right_click) if sys.platform == "win32": from gtkwin32 import GTKWin32Ext self.timetracker_window.realize() self.win32ext = GTKWin32Ext(self.timetracker_window) self.win32ext.add_notify_icon() def before_init(self): #stub for later #print 'signals before init' pass def after_init(self): #init any other callback we can't setup in the actual init phase #print 'signals after init' self.project_combobox_handler = self.project_combobox.connect('changed', self.on_project_combobox_changed) self.task_combobox_handler = self.task_combobox.connect('changed', self.on_task_combobox_changed) def on_show_about_dialog(self, widget): self.about_dialog.show() def on_interval_dialog(self, dialog, a): #interval_dialog callback if a == gtk.RESPONSE_NO: self.refresh_and_show() else: #keep the timer running self.running = True self.current_selected_project_id = self.last_project_id self.current_selected_task_id = self.last_task_id self.current_notes = self.get_notes(self.last_notes) self.current_hours = "%0.02f" % round(float(self.last_hours) + float(self.interval), 2) self.current_text = self.last_text self.current_entry_id = self.last_entry_id entry = self.harvest.update(self.current_entry_id, {#append to existing timer 'notes': self.current_notes, 'hours': self.current_hours, 'project_id': self.current_project_id, 'task_id': self.current_task_id }) self.refresh_and_show() self.timetracker_window.hide() #hide timetracker and continue task dialog.destroy() self.attention = None self.interval_dialog_showing = False def on_textview_ctrl_enter(self, widget, event): ''' submit clicked event on ctrl+enter in notes textview ''' if event.state == gtk.gdk.CONTROL_MASK and \ gtk.gdk.keyval_name(event.keyval) == "Return": self.submit_button.emit('clicked') def on_stopped(self, dialog): if not self.timetracker_window.is_active(): self.timetracker_window.show() self.timetracker_window.present() dialog.destroy() self.attention = None self.stop_interval_dialog_showing = False def on_save_preferences_button_clicked(self, widget): if self.running: #if running it will turn off, lets empty the comboboxes #stop the timer #self.toggle_current_timer(self.current_entry_id) #maybe add pref option to kill timer on pref change? if self.interval_dialog_instance: self.interval_dialog_instance.hide() #hide the dialog self.stop_and_refactor_time() self.get_prefs() if self.connect_to_harvest(): self.preferences_window.hide() self.timetracker_window.show() self.timetracker_window.present() def on_task_combobox_changed(self, widget): new_idx = widget.get_active() if new_idx != -1: if new_idx != self.current_selected_task_idx: #-1 is sent from pygtk loop or something self.current_selected_task_id = self.get_combobox_selection(widget) self.current_selected_task_idx = new_idx self.refresh_comboboxes() def on_project_combobox_changed(self, widget): self.current_selected_project_id = self.get_combobox_selection(widget) new_idx = widget.get_active() if new_idx != -1: #reset task when new project is selected self.current_selected_project_idx = new_idx self.current_selected_task_id = None self.current_selected_task_idx = 0 self.refresh_comboboxes() def on_show_preferences(self, widget): self.preferences_window.show() self.preferences_window.present() def on_away_from_desk(self, widget): #toggle away state if self.running: self.away_from_desk = True if not self.away_from_desk else False def on_check_for_updates(self, widget): pass def on_top(self, widget): self.always_on_top = False if self.always_on_top else True self.timetracker_window.set_keep_above(self.always_on_top) def on_submit_button_clicked(self, widget): self.away_from_desk = False self.attention = None self.append_add_entry() self.set_textview_text(self.notes_textview, "") self.notes_textview.grab_focus() def on_stop_timer(self, widget): self.stop_and_refactor_time() def on_quit(self, widget): if self.running and self.harvest: self.harvest.toggle_timer(self.current_entry_id) gtk.main_quit() def refresh_and_show(self): self.set_entries() self.timetracker_window.show() self.timetracker_window.present() self.notes_textview.grab_focus() def on_refresh(self, widget): self.refresh_and_show() def left_click(self, widget): self.refresh_and_show() def right_click(self, widget, button, time): #create popup menu menu = gtk.Menu() refresh = gtk.ImageMenuItem(gtk.STOCK_REFRESH) refresh.connect("activate", self.on_refresh) menu.append(refresh) if self.running: stop_timer = gtk.MenuItem("Stop Timer") stop_timer.connect("activate", self.on_stop_timer) menu.append(stop_timer) if not self.away_from_desk: away = gtk.ImageMenuItem(gtk.STOCK_NO) away.set_label("Away from desk") else: away = gtk.ImageMenuItem(gtk.STOCK_YES) away.set_label("Back at desk") away.connect("activate", self.on_away_from_desk) menu.append(away) top = gtk.MenuItem("Always on top") prefs = gtk.MenuItem("Preferences") about = gtk.MenuItem("About") quit = gtk.MenuItem("Quit") top.connect("activate", self.on_top) prefs.connect("activate", self.on_show_preferences) about.connect("activate", self.on_show_about_dialog) quit.connect("activate", self.on_quit) menu.append(prefs) menu.append(top) menu.append(about) menu.append(quit) menu.show_all() menu.popup(None, None, gtk.status_icon_position_menu, button, time, self.icon)
python
Pawan Kalyan attended the puja ceremony of Arjun Sarja’s next directorial venture. Pictures and videos from the puja ceremony have surfaced online. Here, Pawan Kalyan is seen with the clap board. The film stars Vishwak Sen in the lead role. It will also mark the debut of Arjun Sarja’s daughter Aishwarya Arjun. After a four-year-long break, Kollywood actor Arjun Sarja will return to the director’s chair. And, for the first time in his career, Arjun Sarja is directing a Telugu film. The project wil be bankrolled by Sriram Films International. Jagapathi Babu is also part of the movie. KGF fame Ravi Basroor is composing the music. The costume department is headed by Neeraja Kona. Chandra Bose is the person behind the lyrics. The cinematography is taken care of by Balamurugan. Vishwak was last seen in Ashoka Vanamulo Arjuna Kalyanam. He played the titular role, Ginger Arjun Prasad, in the film. The movie was released on May 6. Vishwak’s performance was loved by the audience and critics alike. It was directed by Vidya Sagar. The Arjun Sarja directorial will be Vishwak Sen’s eleventh film. Read all the Latest News , Breaking News , watch Top Videos and Live TV here.
english
Mad-hatter artist Graziano Cecchini has struck again. The public-art prankster who filled the Trevi Fountain in Rome with blood-red dye last October released 500,000 brightly colored plastic balls Wednesday from the top of the Spanish Steps in Rome. The balls, similar to the ones you can jump into at a Chuck E. Cheese pizza parlor, "represented a lie told by a politician," Cecchini told the Italian press. The stunt cost Cecchini close to $30,000. Excited tourists grabbed the balls as artistic mementos, while Italian police proceeded to arrest Cecchini. Look for overpriced plastic balls on eBay soon. See also:
english
Malaika Arora and Arbaaz Khan’s son Arhaan seems to be soaking in all the Vitamin D, during his time in the United States. Returning to his Instagram account after hiatus of three months, the star kid, on Monday, dropped a series of photos of himself chilling with his friends. Keeping his “Sunny side up,” Arhaan dropped sun-kissed pictures of him sitting with his buddies, presumably in some café. The first happy picture shows Arhaan smiling his heart out, as he relishes his cup of coffee. Next, appears to be a candid click of Arhaan, while his friend Jon Lahav, sitting beside him, can be seen posing for the camera. Lastly, Arhaan shared a picture of his friends Aryan Sher and James Roumeliotis enjoying their beverages. Decked in a brown baggy check shirt, Arhaan wore it in a buttoned-down style, with sleeves folded to quarter length. He can also be seen accessorising his look with a silver chain bracelet and gold neckpiece. As soon as Arhaan shared the pictures, they started making rounds on the internet, with several users flooding the comments section. Many industry friends of Arhaan’s parents and a few family members also acknowledged his post. Earlier, Arbaaz, in one of his interviews, spilled beans about his son’s Bollywood career. Back in November last year, the Dabangg star revealed that Arhaan will be working as an assistant director for Karan Johar on the sets of Rocky Aur Rani Ki Prem Kahani. Not only this, but Arbaaz also revealed that his son will also be joining him on the sets of Patna Shukla.
english
{"code": "ABF006", "lang": "de", "description": null, "name": "Abf\u00e4lle zur Beseitigung", "type": "Merkmal"}
json
{"name":"<NAME>","classjob_category":"GLA PLD","icon":"https://secure.xivdb.com/img/game/000000/000160.png","id":25,"level":30,"recast_time":15,"help":"Delivers an attack with a potency of 100.\nCan only be executed immediately after blocking an attack.\nAdditional Effect: Pacification\nDuration: 6s\nAdditional Effect: Increased enmity","action_category":4}
json
<reponame>helightdev/Odysseus package dev.helight.odysseus.inventory.routes; import dev.helight.odysseus.inventory.Gui; import dev.helight.odysseus.inventory.InteractivePoint; import dev.helight.odysseus.item.Item; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; //TODO Implement public class PagedBarRoute extends BarRoute { private final Gui gui; private final InteractivePoint previous; private final InteractivePoint next; private final InteractivePoint pages; private final ItemStack right = Item.builder(Material.LIME_STAINED_GLASS_PANE).name("§a->").delegate(); private final ItemStack left = Item.builder(Material.RED_STAINED_GLASS_PANE).name("§c<-").delegate(); public PagedBarRoute(int rows, Gui gui) { super(rows); this.gui = gui; this.pages = InteractivePoint.builder() .item( Item.builder(new ItemStack(Material.BOOK)) .name(" ") .amount(gui.currentPage() + 1) .delegate() ) .event(event -> {}) .parent(gui) .build(); this.previous = InteractivePoint.builder() .parent(gui) .item(null) .event(inventoryClickEvent -> { if (gui.currentPage() == 0) return; gui.changeOffset(-1); }) .build(); this.next = InteractivePoint.builder() .parent(gui) .item(null) .event(inventoryClickEvent -> { if (gui.currentPage() == pages() - 1) return; gui.changeOffset(1); }) .build(); addBar(4, previous); addBar(5, pages); addBar(6, next); } @Override public void build() { pages.setItem( Item.builder(pages.getItem()) .amount(gui.currentPage() + 1) .delegate() ); previous.setItem( gui.currentPage() == 0 ? null : left ); next.setItem( gui.currentPage() >= pages() - 1 ? null : right ); } @Override public InteractivePoint get(int absolute, int relative, int page) { return super.get(absolute, relative, page); } }
java
154/7 (20. 0 ov) 157/8 (19. 5 ov) 172/7 (20. 0 ov) 157 (20. 0 ov) Bangladesh will want bowl England out early into the first session on Day 2, and look to bat much better than the visitors against their spinning trio of Moeen Ali, Adil Rashid and Gareth Batty. England’s left-handed batsman Moeen Ali had all the luck on his side as he survived not one, but as many as three Decision Review System (DRS) appeals. Bangladesh's debutant Mehedi Hasan picked up 5-wickets as England are stranded on 258 for 7 at Stumps on Day 1. Bangladesh were powered by Mehedi Hasan and Shakib Al Hasan's wickets as England were only helped by Moeen Ali's half-century at Tea. Bangladesh powered by their spinners managed to restrict England batsmen to for at lunch on Day 1 of 1st Test at Chittagong. Bangladesh had the start they wanted in the opening Test as England lose their top-order soon after the start of Day One's play. The live cricket streaming of the Bangladesh vs India, 1st Test, is available in India on Hotstar, while the streaming in Bangladesh is available on gazitv. com. Hello and Welcome to CricketCountry's live coverage of Day 1 of the 1st of the two-Test series between hosts Bangladesh and visitors England, at Chittagong. Bangladesh are all set to face England in the longest format of the game as the teams head to a two-match Test series starting Thursday.
english
import { AuthenticationService } from './authentication.service'; import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http'; import { BASEURL_PROXY } from '../../shared/constants/app.constants'; import { Observable, forkJoin, of, isObservable } from 'rxjs'; import { map, tap, mergeMap, catchError } from 'rxjs/operators'; import { Injector } from '@angular/core'; import { ListResource, Resource } from 'src/app/shared/models/resource.model'; declare function stringToInt(initials: string): any; export function RestService(options: { serviceURL: string, resource: string }) { return function (constructor: Function) { constructor.prototype.serviceURL = options.serviceURL; constructor.prototype.resource = options.resource; constructor.prototype.urlEndPoint = BASEURL_PROXY + options.serviceURL + "/" + options.resource; } } export type FetchFunction<T> = (data: any | any[]) => ListResource<T> | T; export type ResponseHandler<T> = (data: any | any[], res: ListResource<T> | T) => void; export interface FetchPropertyOptions { name: string; /** * If true, indicates that the property will be fetched for all data by making a single request. Otherwise a request per record will be done */ singleRequest?: boolean; /** * Function that must return an observable of the data to fetch for this property * @argument data If singleRequest is true, data is an array of records, otherwise is a single record * @argument res It's the fetchFunction response data */ fetchFunction?: FetchFunction<any>; /** Function to handle response. If is a singleRequest, this property is required. * @argument data If singleRequest is true, data is an array of records, otherwise is a single record * @argument res It's the fetchFunction response data */ responseHandler?: ResponseHandler<any>; target?: string; } export interface IRequest { request: Observable<any>, error: string | Function } export function isAnIRequest(object: any): object is IRequest { return object.hasOwnProperty('request') && object.hasOwnProperty('error'); } export abstract class BaseService<I, R extends Resource>{ public urlEndPoint: string; public resource: string; protected serviceURL: string; // protected client = createClient(this.urlEndPoint); protected http: HttpClient; protected authenticationService: AuthenticationService; constructor(injector: Injector) { this.http = injector.get(HttpClient); this.authenticationService = injector.get(AuthenticationService); } getAny<T>(uri: string, requestParameters?: any): Observable<T> { return this.http.get<T>(uri, requestParameters).pipe(map(res => res as any)); } getById(uuid: string, requestParameters?: any, fetchProperties?: FetchPropertyOptions[]): Observable<R> { let uri = this.urlEndPoint + '/' + uuid; return this.getOne(uri, requestParameters, fetchProperties); } getAll(requestParameters?: any, fetchProperties?: FetchPropertyOptions[]): Observable<ListResource<R>> { return this.fetchData(requestParameters, fetchProperties); } getOne(url: string, requestParameters?: any, fetchProperties?: FetchPropertyOptions[]): Observable<R> { return this.http.get<R>(url, requestParameters) .pipe(map(res => this.convertOne(res as any)), mergeMap(res => { if (res && fetchProperties && fetchProperties.length > 0) { let tmpListResource: any = { data: [res] }; return this.fetchRecordsPropertiesV2<R>(tmpListResource, fetchProperties).pipe(map(res => res.data[0])); } else { return of(res); } })); } fetchData(requestParameters?: any, fetchProperties?: FetchPropertyOptions[]): Observable<ListResource<R>> { return this.http.get<ListResource<R>>(this.urlEndPoint, requestParameters) .pipe(map(res => this.convertDataArray<R>(res, this.resource)), mergeMap(res => this.fetchRecordsPropertiesV2<R>(res, fetchProperties))); } fetchRecordsPropertiesV2<T extends Resource>(listResource: ListResource<T>, properties: FetchPropertyOptions[]): Observable<ListResource<T>> { if (listResource.data && listResource.data.length > 0 && properties && properties.length > 0) { return new Observable<ListResource<T>>(observer => { let requests: { prop: FetchPropertyOptions, request: Observable<any> handler: Function, record?: T }[] = []; properties.forEach(prop => { if (prop.singleRequest) { if (!prop.responseHandler) { observer.error("response handler should be defined for singleRequest properties"); observer.complete(); } requests.push({ prop: prop, request: prop.fetchFunction(listResource.data), handler: prop.responseHandler }); } else { listResource.data.forEach(record => { if (prop.responseHandler) { requests.push({ prop: prop, request: prop.fetchFunction(record), handler: prop.responseHandler }); } else { requests.push({ prop: prop, request: prop.fetchFunction(record), record: record, handler: (record, res) => record[prop.name] = (res && !res.error) ? res : record[prop.name] }); } }) } }); this.safeMultiRequest(requests.map(req => req.request)).subscribe(responses => { responses.forEach((res, index) => { try { let responseHandler = requests[index].handler; if (requests[index].prop.singleRequest) { responseHandler(listResource.data, res); } else { responseHandler(requests[index].record, res); } } catch (error) { console.error(error) } }); observer.next(listResource); observer.complete(); }); }); } else { return of<ListResource<T>>(listResource); } } convertDataArray<T>(res: any, dataPath: string): ListResource<T> { res.data = (res._embedded && res._embedded[dataPath]) ? res._embedded[dataPath] : []; res.data = res.data.map(record => this.convertOne(record)); return res as ListResource<T> } convertOne(record: R): R { return record; } getIdFromLink(uri): string { let recordId = this.cleanUri(uri), lastPath = recordId.lastIndexOf("/") if (lastPath) { recordId = recordId.substring(lastPath + 1, recordId.length); } return recordId; } remove(uri: string) { //this.setHeaders(); //const resource = await this.client.delete(uri); //uri = this.urlEndPoint+'/ff8081816c045d96016c0462fd1a0001'; return this.http.delete(this.cleanUri(uri), { observe: 'response' }); } deleteMultiple(uriArray: string[]): Observable<any[]> { let deleteObservable = [] uriArray.forEach(uri => { deleteObservable.push(this.remove(uri)); }); return this.safeMultiRequest(deleteObservable); } getAssociation<T>(parentUri: string, association: string): Observable<ListResource<T>> { let associationUri = this.cleanUri(parentUri) + "/" + association; return this.getAny<T>(associationUri).pipe(map(res => this.convertDataArray(res, association))); } removeAssociation(parentUri: string, childUri: string, association: string): Observable<any> { let associationUri = this.cleanUri(parentUri) + "/" + association + "/" + this.getIdFromLink(this.cleanUri(childUri)); return this.remove(associationUri); } removeAssociationMultiple(parentUri: string, childUris: any[], association: string): Observable<any[]> { let deleteRequestArray = childUris.map(childUri => this.removeAssociation(parentUri, childUri, association)); return forkJoin(deleteRequestArray); } updateAssociation(recordURI: string, associationURIs: string[], association: string): Observable<any> { let data = associationURIs ? associationURIs.map(uri => this.cleanUri(uri)).join('\n') : ''; const options = { headers: { 'Content-Type': 'text/uri-list' }, 'observe': "response" as 'response', // to display the full response & as 'body' for type cast }; return this.http.put(this.cleanUri(recordURI) + '/' + association, data, options); } update(uri: string, data: I) { //this.setHeaders(); //const resource = await this.client.update(uri, data); return this.http.put(this.cleanUri(uri), data, { observe: 'response' }); } create(data: I): Observable<HttpResponse<R>> { //this.setHeaders(); //const resource = await this.client.create(this.urlEndPoint, data); return this.http.post<R>(this.urlEndPoint, data, { observe: 'response' }); } export(format: string) { return this.http.get(this.urlEndPoint + "/export?fileType=" + format, { responseType: "blob" }); } // private setHeaders() { // let currentUser: any = this.authenticationService.currentUserValue; // this.client.addHeader('Authorization', `Bearer ${currentUser.access_token}`); // } /** * when the object has projections o excerpts the uri contains parameters like {?projection}. To avuid to call uri with this text we clean it * @param uri */ public cleanUri(uri): string { return uri.replace(/{\?\w*}/g, ""); } updateImage(imageURI: string, file: File) { let body = new FormData(); body.append("file", file); return this.http.patch(this.cleanUri(imageURI), body, { observe: 'response' }); } downloadImage(url: string): Observable<string | ArrayBuffer> { return this.http.get(url, { responseType: 'blob' }).pipe(mergeMap(res => this.createImageFromBlob(res))); } /** * Render the client logo * @param image */ createImageFromBlob(image: Blob): Observable<string | ArrayBuffer> { const imageObservable = new Observable<string | ArrayBuffer>(observer => { if (image) { let reader = new FileReader(); reader.addEventListener("load", () => { observer.next(reader.result); observer.complete(); }, false); reader.readAsDataURL(image); } else { console.log(image); observer.next(null) observer.complete(); } }); return imageObservable; } /** * Preview the logo * @param file */ createImageFromFile(file: any): Observable<string | ArrayBuffer> { return new Observable<string | ArrayBuffer>(observer => { if (!file) { observer.next(null); observer.complete() } else { var mimeType = file.type; if (mimeType.match(/image\/*/) == null) { alert("Only images are supported."); return; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = (_event) => { observer.next(reader.result); observer.complete() } } }) } /** * Send multiple requests handling errors for each one so that all responses can be handled at once. * @param requests */ safeMultiRequest(requestArray: Observable<any>[] | IRequest[]): Observable<any[]> { let requests = []; let self = this; requestArray.forEach((request: Observable<any> | IRequest) => { if (isAnIRequest(request)) { requests.push(request.request.pipe(catchError( error => { let cause; if (error && error.error && error.error.message && error.error.message !== "No message available") { cause = error.error.message; } let errorMsg = (typeof request.error === "function") ? request.error(error) : request.error; errorMsg = errorMsg ? errorMsg : "Unkown error"; errorMsg += cause ? ": " + cause : ''; return of({ error: errorMsg, cause: error }); } ))) } else { requests.push(request.pipe(catchError(error => of({ error: error, cause: error })))) } }); return forkJoin(requests); } getUTCDate(date: any) { if (date) { let dateData = new Date(date); let dateUTC = new Date(Date.UTC( dateData.getFullYear(), dateData.getMonth(), dateData.getDate(), dateData.getHours(), dateData.getMinutes(), dateData.getSeconds() )); return dateUTC; } return null; } }
typescript
<gh_stars>100-1000 { "class": "org.batfish.minesweeper.question.searchroutepolicies.SearchRoutePoliciesQuestion", "differential": false, "nodes": "${nodes}", "policies": "${policies}", "inputConstraints": "${inputConstraints}", "action": "${action}", "outputConstraints": "${outputConstraints}", "instance": { "description": "Finds route announcements for which a route policy has a particular behavior.", "instanceName": "searchRoutePolicies", "longDescription": "This question finds route announcements for which a route policy has a particular behavior. The behaviors can be: that the policy permits the route (`permit`) or that it denies the route (`deny`). Constraints can be imposed on the input route announcements of interest and, in the case of a `permit` action, also on the output route announcements of interest. Route policies are selected using node and policy specifiers, which might match multiple policies. In this case, a (possibly different) answer will be found for each policy. This question currently supports common forms of matching on prefixes, communities, and AS-paths, as well as common forms of setting communities, the local preference, and the metric. It does not support other routing policy constructs. The question throws an exception if a route policy uses an unsupported construct.", "orderedVariableNames": [ "nodes", "policies", "inputConstraints", "action", "outputConstraints" ], "tags": [ "routing" ], "variables": { "nodes": { "description": "Only examine policies on nodes matching this specifier", "type": "nodeSpec", "optional": true, "displayName": "Nodes" }, "policies": { "description": "Only consider policies that match this specifier", "type": "routingPolicySpec", "optional": true, "displayName": "Policies" }, "inputConstraints": { "description": "Constraints on the set of input BGP route announcements to consider", "type": "bgpRouteConstraints", "optional": true, "displayName": "Input Constraints" }, "action": { "description": "The behavior to be evaluated. Specify exactly one of `permit` or `deny`.", "type": "string", "optional": true, "displayName": "Action" }, "outputConstraints": { "description": "Constraints on the set of output BGP route announcements to consider", "type": "bgpRouteConstraints", "optional": true, "displayName": "Output Constraints" } } } }
json
<filename>tests/security_test.py # -*- coding: utf-8 -*- import pytest from six import iteritems def test_security_definition_property_extraction(security_dict, security_spec): security_definitions = security_dict['securityDefinitions'] for security_name, security_spec_dict in iteritems(security_definitions): security_object = security_spec.security_definitions[security_name] for key, value in iteritems(security_spec_dict): assert getattr(security_object, key if key != 'in' else 'location') == value @pytest.mark.parametrize( 'resource, operation, expected_scopes', [ ('example1', 'get_example1', [{'apiKey1': []}, {'apiKey2': []}]), ('example2', 'get_example2', [{'apiKey3': []}]), ('example3', 'get_example3', [{'apiKey1': [], 'apiKey2': []}, {'apiKey2': []}]), ('example4', 'get_example4', [{'oauth2': ['write:resource']}]), ('example5', 'get_example5', []), ] ) def test_security_scopes(security_spec, resource, operation, expected_scopes): def _get_operation(): return security_spec.resources[resource].operations[operation] assert [ security_requirement.security_scopes for security_requirement in _get_operation().security_requirements ] == expected_scopes
python
package com.qatix.base.lock; public class ZkLockTest { private static int n = 200; private static void secsDown() { System.out.println(--n); } public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " start"); ZkLock lock = null; try { lock = new ZkLock("localhost:2181", "zklock"); lock.lock(); secsDown(); System.out.println(Thread.currentThread().getName() + " is running"); System.out.println(Thread.currentThread().getName() + " do its work"); Thread.sleep(8000); } catch (InterruptedException e) { e.printStackTrace(); } finally { if (lock != null) { lock.unlock(); } } } }; for (int i = 0; i < 5; i++) { Thread t = new Thread(runnable); t.start(); } } }
java
<gh_stars>0 --- breadcrumb: "true" tags: - "null" published: false --- #You could be next – Reproducibility Initiative shows most landmark experiments cannot be reproduced ###By <NAME> The issue of experimental reproducibility is of growing concern to the research community. Crowd-funded or grant-funded projects like the Reproducibility Initiative are re-examining some of the key experiments in different scientific fields. Why should you care? Well, at least for three reasons: 1) Funded with 1.3Mio $ the [Reproducibility Initiative](http://validation.scienceexchange.com/#/reproducibility-initiative) will probe the “50 most impactful cancer biology studies published between 2010-2012”. This is relevant to your research! 2) This kind of initiative is only one of many; some are even conducted by pharmaceutical companies. And results are worrisome as many key findings proved to be irreproducible. Again, this should matter to you. 3) Many of these reproducibility projects are being conducted through [Science Exchange](https://www.scienceexchange.com/). This commercial online portal connects researchers to hundreds of labs (both commercial and academic). Let’s say you need to sequence a sample, get a biological experiment done or perform any of the over 1,800 analytical and experimental techniques offered on Science Exchange. You can have qualified staff do it for you – often for a reasonable price - and safe precious time. If you have a couple of minutes left today, check out their website. It may safe you a lot of time during your career! ####Links: - [Reproducibility Project ](http://validation.scienceexchange.com/#/reproducibility-initiative) - [Want to read more?](http://www.nature.com/nature/journal/v483/n7391/full/483531a.html#affil-auth) - [Don't forget to check out science exchange](https://www.scienceexchange.com/)
markdown
<gh_stars>10-100 { "vorgangId": "245449", "VORGANG": { "WAHLPERIODE": "19", "VORGANGSTYP": "Bericht, Gutachten, Programm", "TITEL": "Fortschreibung und Weiterentwicklung der Afrikapolitischen Leitlinien der Bundesregierung", "INITIATIVE": "Bundesregierung", "AKTUELLER_STAND": "", "SIGNATUR": "", "GESTA_ORDNUNGSNUMMER": "", "WICHTIGE_DRUCKSACHE": { "DRS_HERAUSGEBER": "BT", "DRS_NUMMER": "19/8765", "DRS_TYP": "Unterrichtung", "DRS_LINK": "http://dipbt.bundestag.de:80/dip21/btd/19/087/1908765.pdf" }, "EU_DOK_NR": "", "SACHGEBIET": "Außenpolitik und internationale Beziehungen", "SCHLAGWORT": [ { "_fundstelle": "true", "__cdata": "Afrika" }, "Außenpolitik", "Entwicklungszusammenarbeit", "Flüchtlingspolitik", "Friedenssicherung", "Internationale Beziehungen", "Internationale Wirtschaftsbeziehungen", "Internationale Zusammenarbeit", "Nachhaltige Entwicklung", "Wachstumspolitik", "Wirtschaftswachstum", "Zivilgesellschaft" ], "ABSTRAKT": "Ziele für die Zusammenarbeit mit Afrika: Förderung von Frieden und Stabilität, Schaffung von nachhaltigem Wirtschaftswachstum durch Zugang von jungen Menschen und Frauen zu Bildung und Beschäftigung, Migrationspolitik, Stärkung der regelbasierten Weltordnung, Vertiefung zivilgesellschaftlicher Partnerschaften" }, "VORGANGSABLAUF": { "VORGANGSPOSITION": { "ZUORDNUNG": "BT", "URHEBER": "Unterrichtung, Urheber : Bundesregierung, Auswärtiges Amt (federführend)", "FUNDSTELLE": "29.03.2019 - BT-Drucksache 19/8765", "FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/btd/19/087/1908765.pdf" } } }
json
import React, { Component } from 'react' import CoffeeBeanForm from '../components/CoffeeBeanForm' import CoffeeBeanList from '../components/CoffeeBeansList' import CoffeeBean from '../components/CoffeeBean' import { connect } from 'react-redux' import { deleteCoffeeBeanAction, sendCoffeeBeanDataAction } from '../actions/CoffeeBeanActions' import { Route, Switch} from 'react-router-dom' class CoffeeBeansContainer extends Component { constructor() { super() this.state = { coffeeBeans: [], } } render() { return ( <div className='coffee-bean-container'> <Switch> <Route exact path='/coffee-beans'> <CoffeeBeanList coffeeBeans={this.props.coffeeBeans} deleteCoffeeBean={this.props.deleteCoffeeBean} /> </Route> <Route exact path='/coffee-beans/new' component={(routeInfo) => { return ( <CoffeeBeanForm addCoffeeBean={this.props.addCoffeeBean} roastersList={this.props.roastersList} errors={this.props.errors} return={() => routeInfo.history.push('/coffee-beans')} /> ) }}/> <Route exact path='/coffee-beans/:id' component={(routeInfo) => { const id = parseInt(routeInfo.match.params.id) const foundCoffeeBean = this.props.coffeeBeans.find((bean) => bean.id === id) const coffeeBeanInfo = <CoffeeBean coffeeBean={foundCoffeeBean}/> return (this.props.coffeeBeans.length > 0 ? coffeeBeanInfo : <h1>Loading Coffee Bean...</h1>) }} /> </Switch> </div> ) } } const mapStateToProps = (state) => { return { errors: state.errors.coffeeBeanErrors, coffeeBeans: state.coffeeBeans.coffeeBeans, roastersList: state.roasters.roasters } } const mapDispatchToProps = (dispatch) => { return { addCoffeeBean: (formData) => dispatch(sendCoffeeBeanDataAction(formData)), deleteCoffeeBean: (id) => dispatch(deleteCoffeeBeanAction(id)) } } export default connect(mapStateToProps, mapDispatchToProps)(CoffeeBeansContainer)
javascript
The upcoming Barbie fragrance, slated for a release in August 2023, seizes the essence of the iconic Barbie doll, thanks to the merger of DefineMe Creative Studio with Mattel. Welcoming the 'Barbiecore' trend and the fondness for all things 'pink', the DefineMe studio x Barbie fragrance is crafted with meticulous detailing, reflecting Barbie's empowering self. The DefineMe studio x Barbie fragrance aspires to encapsulate the sparkling and delightful character that the Margot Robbie-starrer character is famous for, incorporating her enchanting traits that exude confidence and charm. Concerning the same, Jennifer Newton, founder of DefineMe, told WWD: With the brewing excitement among the Barbie fanciers and aroma connoisseurs, the release date tip-toes. For those keen on securing their very own Barbie Eau de Parfum, DefineMe is proposing preorder facilities on its authorised website. Retailing for $65 for a 100-ml bottle and shipping planned for August 2023, fans will not have to shelve their enthusiasm for long to welcome the DefineMe studio x Barbie fragrance. True to Barbie's iconic aesthetic, the DefineMe studio x Barbie fragrance is sealed in a gorgeous pink box. The square pink-hued glass bottle with a pink round-shaped lid and glossy box emits a neon hot pink glimmer, which is attention-grabbing. This eye-catching packaging captures the spirit of Barbie's energetic world. The Barbie logo squirted across the glass bottle and box in yellow is a lively reminder of the doll that has long been a part of pop culture. Jennifer Newton first associated with Mattel at Beautycon in 2019, soon after signing a contract with Disney to assemble a line of perfumes inspired by princesses. Once COVID-19 hit, talks with the toy manufacturer reportedly stopped. Nevertheless, the emergence of #PerfumeTok and the rising rage of the 'Barbiecore' aesthetic pushed Newton to continue the expansion by launching the fragrance. Newton, who is presently working on the Ken fragrance with DefineMe Creative Studio (launch date yet to be announced), commented: “I intend to continue this line and to grow it into, you know, Ken and Malibu Barbie — I see this continuing. Barbie Eau de Parfum is a vibrant mix of flowery, fruity, and gourmand notes, skillfully blending to delight a scent lover's senses and bring all the joy while moving. The fragrance is a comforting mix of varied notes about Barbie's disposition. The top notes comprise the invigorating aromas of Pomelo, Strawberry Nectar, Red Cherry, and Dragon Fruit. These fruity and vibrant harmonies set the backdrop for a stimulating olfactory adventure. Toting on to the fragrance's heart, one can experience the flowery bouquet that counts on to womanhood and classiness. Dahlia Rose, Gardenia, Peony, and Pink Magnolia merge to produce a balanced combination that catches Barbie's classiness and magnificence. Ultimately, the base notes of Sandalwood, Whipped Cream, and Soft Musk deliver a friendly and enjoyable foundation for the aroma. These notes add refinement and hedonism, making Barbie Eau de Parfum a universal and tantalising fragrance. Simple steps to apply Barbie Eau de Parfum: - Spray this Barbie fragrance gently to the pulse points, inner wrists, behind the earlobes, and the nape of the neck. - Give a slight rub to spread the aroma evenly. - Let the enticing smell charm everyone! The association between DefineMe Creative Studio and Mattel has rendered a noteworthy hum, which is not startling regarding the growing rate of the 'Barbiecore' sensation. The medley of the popular doll's unchanging pizzazz and DefineMe's expertise in producing exquisite scents will strike a perfect alliance in the aromatic world. This Barbie fragrance, priced at $65 for a 100-ml bottle, is an accolade for her empowering spirit and lasting influence. It features an exquisite scent profile and arrives in lovely pink packaging. Perfume buffs can book their bottle by preordering on DefineMe's authorised website. The expected shipping date for these preorders is scheduled for August 2023.
english
Our editors will review what you’ve submitted and determine whether to revise the article. Lady Lever Art Gallery, art museum in Port Sunlight, Merseyside, England, part of the National Museums Liverpool. It is known for its unrivaled collection of Wedgwood ware and paintings by members of the Pre-Raphaelite Brotherhood and their followers. The museum was a gift to the public from Lever Brothers cofounder William Hesketh Lever, the 1st Viscount Leverhulme, as a memorial to his wife, who died in 1913. The building was begun in 1914 and opened in December 1922. (Read Sister Wendy’s Britannica essay on art appreciation.) The museum is located in a model village founded for Lever Brothers workers in Bebington, Cheshire (now in Merseyside). The collection was formed by Lord Leverhulme and reflects his personal taste, which was strongly biased in favour of British works, especially of the Victorian period. In addition to Wedgwood ware, the gallery has a superb collection of English furniture; many of the pieces are decorated with classical scenes using inlaid woods of different colours. The museum’s Pre-Raphaelite collection comprises works by such artists as John Everett Millais, William Holman Hunt, Frederic Leighton, and Ford Madox Brown. There is an important series of 18th-century portraits, including examples by Joshua Reynolds, George Romney, and John Hoppner. The gallery also has a very fine collection of Chinese ceramics and a collection of Napoleonic relics, namely a bronze death mask of Napoleon. (Read Glenn Lowry’s Britannica essay on "Art Museums & Their Digital Future.")
english
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Literary Mutilator</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.css" integrity="sha384-2QMA5oZ3MEXJddkHyZE/e/C1bd30ZUPdzqHrsaHMP3aGDbPA9yh77XDHXC9Imxw+" crossorigin="anonymous"> <!-- <link href="css/bootstrap.min.css" rel="stylesheet"> --> <link href="css/style.css" rel="stylesheet"> </head> <body> <p id="first">Suspendisse laoreet eleifend justo nec elementum. Quisque ac malesuada turpis, et suscipit neque. Maecenas bibendum velit risus, nec tempus lacus sodales id. Praesent lacinia tristique ipsum id maximus. Nulla ultricies sodales hendrerit. Sed id eros cursus, ornare urna quis, tristique orci. Nunc ex dui, hendrerit a aliquam eu, iaculis in leo. Suspendisse nec ante elementum, suscipit nunc eget, mattis lectus. Donec non quam odio. Maecenas gravida ante et turpis ullamcorper, in malesuada nibh hendrerit. Morbi tincidunt lobortis nisl. Vestibulum accumsan ornare lacus. Fusce velit erat, commodo a tempor sed, mattis eget mi. Nunc tortor lectus, venenatis quis turpis vel, tempus cursus felis. Nulla at scelerisque dui. Suspendisse finibus euismod tellus, vitae semper diam.</p> <p id="second">In condimentum id ipsum in malesuada. Etiam ultrices aliquet erat. Maecenas sit amet leo tincidunt, aliquam ipsum vel, eleifend nisi. Donec vel tortor in quam suscipit scelerisque. Donec vitae lacus risus. Morbi scelerisque, erat quis aliquam cursus, sem nisi placerat quam, a faucibus massa ipsum nec lectus. Suspendisse diam nisl, auctor at egestas eu, congue a mi. Ut nec sagittis nisi. Curabitur gravida odio at est dictum feugiat. Pellentesque elementum feugiat ligula ac finibus. Praesent justo mauris, lobortis at hendrerit vel, vehicula id dolor. Cras eu vehicula nulla.</p> <p id="third">Quisque tristique tellus a nisi convallis, at gravida justo finibus. Praesent at dolor tellus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In aliquet pulvinar mi non pretium. Proin ultricies fringilla urna, sit amet tincidunt purus consectetur hendrerit. Pellentesque rhoncus lectus facilisis auctor scelerisque. Nam vehicula, purus ut rutrum malesuada, purus justo volutpat nunc, consequat hendrerit neque sem semper mauris. Phasellus quis est a sem fermentum iaculis. Integer ornare est dui, mattis faucibus mauris bibendum vitae. Fusce interdum congue mauris, ac bibendum lectus imperdiet vel. Phasellus rhoncus ligula at interdum auctor.</p> <div class="container-fluid"> <div class="row"> <div class="col-md-4"> <h2 class="text-center">Find / Replace</h2> <form id="form-replace"> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="find">Find</label> <input type="text" class="form-control" id="find" aria-describedby="findHelp" placeholder="Replace this pattern"> <small id="findHelp" class="form-text text-muted">Enter the pattern to replace.</small> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="replace">Replace</label> <input type="text" class="form-control" id="replace" aria-describedby="replaceHelp" placeholder="with this pattern"> <small id="replaceHelp" class="form-text text-muted">Enter the pattern to replace with.</small> </div> </div> </div><!--row--> <div class="row"> <button type="button" class="btn btn-primary" onclick="replaceFirst()">Replace First</button> <button type="button" class="btn btn-primary" onclick="replaceAll()">Replace All</button> <button type="button" class="btn btn-warning" onclick="resetAll()">Reset</button> </div> </div><!--container--> </form> </div> <div class="col-md-5"> <h2 class="text-center">Change Color</h2> <form id="change-color"> <div class="container"> <div class="row"> <section>Click the button to change font of the document paragraphs to the corresponding color.</section> </div><!--row--> <div class="row"> <button type="button" class="btn btn-danger" onclick="changeToRed()">Red</button> <button type="button" class="btn btn-primary" onclick="changeToBlue()">Blue</button> <button type="button" class="btn btn-success" onclick="changeToGreen()">Green</button> <button type="button" class="btn btn-warning" onclick="changeToDefault()">Reset</button> </div><!--row--> </div><!--container--> </form> </div> <div class="col-md-3"> <h2 class="text-left">Highlight Word</h2> <form id="form-highlight"> <div class="container"> <div class="row"> <div class="form-group"> <label for="highlight">Highlight</label> <input type="text" class="form-control" id="highlight" aria-describedby="highlightHelp" placeholder="Enter word"> <small id="highlightHelp" class="form-text text-muted">Enter a word to highlight in the document.</small> </div> </div><!--row--> <div class="row"> <button type="button" class="btn btn-primary" onclick="highlight()">Highlight First</button> <button type="button" class="btn btn-primary">Highlight All</button> </div> </div><!--container--> </form> </div><!--row--> </div><!--container-fluid--> <!-- jQuery Form, Additional Methods, Validate --> <!--<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js"></script>--> <!--<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>--> <!--<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>--> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Your JavaScript Form Validator --> <script type="application/javascript" src="scripts/literary-mutilator.js"></script> </body> </html>
html
{"generated_at": "2017-01-27T09:37:26.883305", "required_by": ["hitchpostgres", "hitchdjango", "hitchvagrant", "hitchnode", "hitchcelery", "hitchelasticsearch", "hitchmemcache", "hitchhttp", "hitchmysql", "hitchrabbit", "hitchsmtp", "hitchredis", "hitchselenium", "hitchs3", "hitchcron", "hitchpython"], "requires": ["humanize", "colorama", "psutil", "pyuv", "tblib", "faketime", "commandlib"], "package": "hitchserve"}
json
{ "title": "XOOPIC", "content": " Berkeley 에서 개발된 PIC 시뮬레이션 코드인 XOOPIC을 설치했습니다.<br> 코드를 기간이나 라이센스 제한없이 무료로 사용할 수 있도록 하기 위해서 부득이하게 LINUX 서버에 프로그램을 설치하였습니다.<br><br> 이용하시고자 하신분들은 아래 1. 직접 서버 머신을 이용하시던지,<br> X-manager를 통해서 본인의 PC에서 2. 원격으로 접속하셔서 사용하실 수 있습니다.<br><br> LINUX 서버 머신은 제 자리 옆에 있는 빈책상에 올려져 있습니다.<br> 현재는 모니터를 포함한 마우스, 키보드 등의 콘솔이 연결되어 있지만,<br> 조만간 콘솔을 없애고 실험실 서버 옆으로 자리를 옮길 것으로 계획하고 있기 때문에<br> 그 이후에는 X-manager를 통한 원격접속을 통한 사용이 편리할 것 같습니다.<br><br>  1-1. 서버 머신을 통한 직접 접속<br>   - 서버에 'nuplex' 아이디로 접속을 합니다. <br>     ( 패스워드는 개별적으로 확인하시기 바랍니다. )<br>   - 바탕화면에 오른쪽 클릭을 하면 나오는 메뉴바에서 \"새 터미널\"을 선택합니다.<br><br>  1-2. X-manager를 통한 원격 접속<br>   - PC에 X-manager를 설치합니다. <br>      ( X-manager는 정호화 포털의 캠퍼스라이센스 소프트웨어에서 다운받으시거나, 영무형 컴퓨터에 \"\\\\Nompangs\\Sources\\Communication\"라는 디렉터리에서 다운받으실 수 있습니다. )<br>   - 설치된 프로그램중 \"Xshell\" 을 실행합니다.<br>   - Xshell창과 함께 세션창이 뜰텐데 제일 왼쪽에 있는 '새로 만들기' 아이콘을 클릭해서 새로운 세션을 추가합니다.<br>   - 새 세션 등록정보에 '이름'항목에는 이 세션에 대한 임의의 이름을 입력하고, '호스트' 항목에 서버 IP인 '192.168.127.12'를 입력합니다. '사용자 이름'에는 아이디인 'nuplex'를 입력하고, '비밀번호'란에도 정보를 입력합니다. 그후 '확인'버튼을 클릭합니다.<br>   - 새로 만든 세션이 등록된것을 확인하시고 그것을 선택하신후 오른쪽 아래에 있는 '연결' 버튼을 클릭하시면 서버에 접속하게 됩니다.<br><br>  2. XOOPIC 사용법<br>   위의 1-1. 1-2. 방법을 통해 접속을 하면 LINUX 환경의 터미널이 생성됩니다.<br>   그곳에서 아래와 같이 명령을 실행하시면 XOOPIC을 사용하실 수 보실 수 있습니다.<br>   [nuplex@linuplex nuplex]# xoopic -i 입력파일<br>   입력파일을 만드는 방법은 따로 경재형이 가지고 계신 메뉴얼을 통해 익히시기 바랍니다. 윤재형과 경재형이 사용경험이 있으시니 자문을 구하는 방법도 좋을 것 같습니다.<br>   더불어 샘플로 제공되는 입력파일을 참고하실 수도 있습니다.<br>   sample1, sample2 라는 디렉터리에 샘플파일들이 있으니 참고하시기 바랍니다.<br>   [nuplex@linuplex nuplex]# xoopic -i $XPIN1/dring.inp<br><br>  이 밖에 궁금하신 점이 있으시면 이곳에 글을 남겨 주시던지, 영무형이나 저에게 말씀해 주십시오." }
json
{ "id": "d818-10", "text": "-9-\nZolotow, M., ”2,000,000 Words of Lowell Thomas.” Coronet, XXVI (June 191*9).\npp. 167-72.\nh. Religious Programs\nAnonymous, “Baptists Ask for Better Sunday Evening Radio.” Christian Century,\nLXVI (January 19, 19l*9), p. 70.\n-, ”For Many Reasons, One Great Hour.” Christian Century, LXVI\nMarch 16, 19l*9), p. 323. --\n-,\"Religious Radio Awards.” Christian Century, LXVI (Seotember ll*.\n19h9), p. 1081*. --\n<NAME>., “Radio in a Youth Fellowship.” International Journal of\nReligious Education, XXV (March 19l*9)> p. 17.\n<NAME>., and <NAME>., \"California*s New-Fashioned Religion,* Station\nKFOX.” Colliers, CXXIII (January 15, 19l*9), pp. Il*-l5 /.\nAdvertising\nAnonymous, \"Analysis of 19l*9 Radio-TV Advertising.” Broadcasting, (January\n1950), pp. 11-12 /. --*\n-9 “Banks Plan Greater Use of Both Radio, Television Programs.\"\nAdvertising Age, XX (April 18, 191*9), p. 7l*.\n—-, \"For Unwilling Ears.” Publishers Weekly, CLVIII (January 7, 1950).\n-9 “Goa’s Gift to India; Radio Commercials.” Business Week,\n(December 31, 191*9), p. 63.\n-9 “Leading Advertisers in 191*8 Listed for 1* Media.” Printers Ink,\nCCXXVII (April 1, 19l*9), p. 38. -\n-9 “Newspaper Use of Radio Found to Vary Greatly.” Advertising Age,\nXX (April 18, 191*9), p. 28. ---\n-^Survey of Advertiser and Agency Buying Practices and Patterns for\nSoot Radio. Chicago: Standard Rate and Data Service. 191*9.\n-,“TV*s Gain is Radio’s Loss.\" Business Week, (April 15, 1950), p. 90.\n--> \"200,000-Circ. Daily Tops All in Radio Promotion.” Editor and\nPublisher, LXXXII (April 16, 191*9), p. 16. -\<NAME>., Advertising Text and Cases. Chicago: <NAME>. 1950.\nP. 1037. --\nBridge, <NAME>., Practical Advertising. New York: Rinehart & Co., 191*9.\nP. xxii / 81*2.\n<NAME>., and <NAME>., \"Radio as an Advertising Medium.”\nHarvard Business Review, XXVII (January 19l*9), pp. 62-78.\nHepner, <NAME>., Effective Advertising. New York: McGraw Hill Book Co., 19h9.\n<NAME>j \"Radio and the Drycleaner; what to Ask the Salesman of Radio\nppWfri! (0ctober A (November" }
json
Congress general secretary Priyanka Gandhi on Tuesday attacked Prime Minister Narendra Modi saying no one was happy with his government. Gandhi said, "Be it farmers, youth or anybody, no one is satisfied with the government. Together they will change the government this year. " The 47-year-old, who had embarked on a three-day boat journey on Ganga to reach out to the electorate residing on the river banks, offered prayers at the Sitamarhi temple before starting for her next stop en route to Mirzapur. But, the big question is will Priyanka Gandhi's temple run help Congress defeat PM Modi? Watch the debate to know what panelists think.
english
import os import os.path import tempfile import unittest import xen.xend.XendOptions xen.xend.XendOptions.XendOptions.config_default = '/dev/null' import xen.xm.create from xen.util import auxbin class test_create(unittest.TestCase): def assertEqualModuloNulls_(self, a, b): for k, v in a.iteritems(): if v: self.failUnless(k in b, '%s not in b' % k) self.assertEqual(v, b[k]) else: self.assert_(k not in b or not b[k], '%s in b' % k) def assertEqualModuloNulls(self, a, b): self.assertEqualModuloNulls_(a, b) self.assertEqualModuloNulls_(b, a) def t(self, args, expected): self.assertEqualModuloNulls( xen.xm.create.parseCommandLine(args.split(' '))[0].vals.__dict__, expected) def testCommandLine(self): (fd, fname) = tempfile.mkstemp() os.close(fd) self.t('-f %s kernel=/mykernel display=fakedisplay ' 'macaddr=ab:cd:ef:ed' % fname, { 'name' : os.path.basename(fname), 'xm_file' : fname, 'defconfig' : fname, 'kernel' : '/mykernel', 'display' : 'fakedisplay', 'macaddr' : 'ab:cd:ef:ed', 'memory' : 128, 'vcpus' : 1, 'boot' : 'c', 'dhcp' : 'off', 'interface' : 'eth0', 'path' : '.:' + auxbin.xen_configdir(), 'builder' : 'linux', 'nics' : -1, 'vncunused' : 1, 'xauthority': xen.xm.create.get_xauthority(), }) def testConfigFile(self): (fd, fname) = tempfile.mkstemp() try: os.write(fd, ''' kernel = "/boot/vmlinuz-xenU-smp" memory = 768 name = "dom1" vcpus = 4 disk = ['phy:/dev/virt-blkdev-backend/dom1,sda1,w', 'phy:/dev/virt-blkdev-backend/usr,sda2,r'] root = "/dev/sda1 ro" extra = " profile=1 GATEWAY=192.0.2.254 NETMASK=255.255.255.0 IPADDR=192.0.2.1 HOSTNAME=dom1" on_poweroff = 'destroy' on_reboot = 'destroy' on_crash = 'destroy' ''') finally: os.close(fd) self.t('-f %s display=fakedisplay' % fname, { 'kernel' : '/boot/vmlinuz-xenU-smp', 'memory' : 768, 'name' : 'dom1', 'vcpus' : 4, 'nics' : -1, 'root' : '/dev/sda1 ro', 'extra' : ' profile=1 GATEWAY=192.0.2.254 NETMASK=255.255.255.0 IPADDR=192.0.2.1 HOSTNAME=dom1', 'on_poweroff' : 'destroy', 'on_reboot' : 'destroy', 'on_crash' : 'destroy', 'disk' : [['phy:/dev/virt-blkdev-backend/dom1', 'sda1', 'w', None], ['phy:/dev/virt-blkdev-backend/usr', 'sda2', 'r', None]], 'xm_file' : fname, 'defconfig' : fname, 'display' : 'fakedisplay', 'boot' : 'c', 'dhcp' : 'off', 'interface' : 'eth0', 'path' : '.:' + auxbin.xen_configdir(), 'builder' : 'linux', 'vncunused' : 1, 'xauthority' : xen.xm.create.get_xauthority(), }) def testConfigFileAndCommandLine(self): (fd, fname) = tempfile.mkstemp() try: os.write(fd, ''' name = "testname" memory = 256 kernel = "/mykernel" maxmem = 1024 cpu = 2 cpu_weight = 0.75 ''') finally: os.close(fd) self.t('-f %s display=fakedisplay macaddr=ab:cd:ef:ed' % fname, { 'name' : 'testname', 'xm_file' : fname, 'defconfig' : fname, 'kernel' : '/mykernel', 'display' : 'fakedisplay', 'macaddr' : 'ab:cd:ef:ed', 'memory' : 256, 'maxmem' : 1024, 'cpu' : 2, 'cpu_weight' : 0.75, 'vcpus' : 1, 'boot' : 'c', 'dhcp' : 'off', 'interface' : 'eth0', 'path' : '.:' + auxbin.xen_configdir(), 'builder' : 'linux', 'nics' : -1, 'vncunused' : 1, 'xauthority' : xen.xm.create.get_xauthority(), }) def testHVMConfigFile(self): (fd, fname) = tempfile.mkstemp() try: os.write(fd, ''' kernel = "hvmloader" builder='hvm' memory = 128 name = "ExampleHVMDomain" vcpus=1 vif = [ 'type=ioemu, bridge=xenbr0' ] disk = [ 'file:/var/images/min-el3-i386.img,ioemu:hda,w' ] device_model = 'qemu-dm' sdl=0 vnc=1 vncviewer=1 ne2000=0 ''') finally: os.close(fd) self.t('-f %s display=fakedisplay' % fname, { 'kernel' : 'hvmloader', 'builder' : 'hvm', 'memory' : 128, 'name' : 'ExampleHVMDomain', 'vcpus' : 1, 'nics' : -1, 'vif' : ['type=ioemu, bridge=xenbr0'], 'disk' : [['file:/var/images/min-el3-i386.img', 'ioemu:hda', 'w', None]], 'device_model': 'qemu-dm', 'extra' : ('VNC_VIEWER=%s:%d ' % (xen.xm.create.get_host_addr(), xen.xm.create.VNC_BASE_PORT + xen.xm.create.choose_vnc_display())), 'vnc' : 1, 'vncunused' : 1, 'vncviewer' : 1, 'xm_file' : fname, 'defconfig' : fname, 'display' : 'fakedisplay', 'boot' : 'c', 'dhcp' : 'off', 'interface' : 'eth0', 'path' : '.:' + auxbin.xen_configdir(), 'xauthority' : xen.xm.create.get_xauthority(), }) def test_suite(): return unittest.makeSuite(test_create)
python
How are Jats distributed in Haryana? Jats constitute about 28 per cent of the state’s population (25 per cent of the electorate) and are distributed all over the state. Only SCs at a combined 21 per cent come close. Barring northern Haryana, the Jats have strongholds everywhere. Their strength is particularly high in central Haryana, which includes Rohtak. They also have a significant presence in Hisar, Bhiwani, Jind, Sirsa and Sonepat. How dominant are they? They are considered a forward caste, particularly in rural areas, though then chief minister Bhupinder Singh Hooda had included Jats among OBCs amid demands that they had been historically oppressed. Members of the community are among the state’s wealthiest people, though their individual land holdings have been slashed over the years. They carry on with their social dominance because of their headcount. Is the Jat vote as crucial as politicians make it out to be? Jats are usually seen as electing or overthrowing Jat leaders. Former chief minister O P Chautala was voted out by Jats. Hooda’s fall is now being attributed to Jat votes outside of Rohtak and Jhajjar. What gives Jats their ability to swing an election? They have a social structure that sees them voting en bloc. They run educational institutes, carry out social initiatives and have khaps that make many decisions binding. Is 25 per cent enough? Not always. The fact that non-Jats outnumber Jats is something politicians have often played on; many parties are identified as Jat or non-Jat. The BJP has come to power on the basis of its identity as a non-Jat partym, and it has indeed selected a non-Jat CM. The BJP did field 25 Jat candidates, a record for the party. Did the Jat vote dictate in the recent election verdict? According to a post-poll survey by Lokniti-CSDS and published in this newspaper, areas with a high Jat population went against the BJP, yet it came to power. Of 37 seats where Jats number over 25 per cent, the BJP won only nine while the Congress bagged 12 and the INLD 11. The inference is that the BJP successfully consolidated the non-Jat vote, winning 38 of the 53 seats where Jats number 25 per cent or lower. How do khaps work? Jats follow an organised caste system that divides the community into gotras. Their social system prevents marriages within the same gotra. Khaps decide on such social issues and pass binding diktats. They are also known to run a parallel justice system whose controversial decisions have often made news. Crucially, khaps also take a political stand during elections. Who have represented the Jat leadership? Jats consider Sir Chhotu Ram, a minister in undivided Punjab, to be their leader. All important leaders claim his legacy. Veteran Congress leader Birender Singh, who joined the BJP before the assembly elections, is a grandson of Chhotu Ram. But the Jat leadership has split over the years. Which parties have later leaders represented? Former deputy prime minister Devi Lal became a powerful Jat leader among non-Congress parties, while former chief minister Bansi Lal was accepted as a Jat leader of the Congress. Their areas of influence were Sirsa and Bhiwani respectively. Before Hooda emerged as the Jat leader from Rohtak, the votes in the Jat heartland use to split between Devi Lal and Bansi Lal. Devi Lal’s legacy went to INLD chief Om Prakash Chautala, and Bansi Lal’s to his daughter-in-law Kiran Choudhary.
english
WASHINGTON -- The health industry wants the Bush administration to rewrite medical privacy rules issued by the previous White House, arguing the regulations would delay help to patients. The regulations are designed to prevent doctors and insurers from sharing confidential information about patients and to punish them if they do. Now health groups will ask Health and Human Services Secretary Tommy Thompson to delay the rules beyond the April 14 effective date and consider eliminating key provisions they say hamstring their ability to serve patients. Particularly, the groups want the administration to reconsider rules requiring patient consent for using or disclosing oral or written communications as well as electronic records. They say the new rules go beyond the intent of the original law, drawn up in the budding computer age. A pharmacist who gives a patient simple advice could be subjected to legal penalties under the privacy law, the groups contend, unless the patient had gone through the extra step of filing written consent with the pharmacy. "Pharmacies are literally expecting chaos at the counters when people try to pick up their own or their families' prescription drugs without having the proper consent forms on file," said Mary Grealy, president of the Healthcare Leadership Council, which represents the groups. They represent a range of interests from drug stores to teaching hospitals to doctors. At issue are major rules written during President Clinton's final days in office. Tardy paperwork in the Clinton White House delayed implementation of the rules and gave the Bush administration a chance to review them. Even if ultimately approved, the rules won't take effect for two years. Under the rules, patients could sign one-time consent forms on their first visit to a doctor that would allow disclosures for routine matters like billing and treatment. But they would have to explicitly authorize most other uses of their records. Thompson told the House Ways and Means Committee on Wednesday that he has not decided what course to take on the rules and that he would consider public comments.
english
--- title: createRecord (Client-API-Referenz) in modellgestützten Apps| MicrosoftDocs ms.date: 10/31/2018 ms.service: crm-online ms.topic: reference applies_to: Dynamics 365 (online) ms.assetid: 848c277b-bd44-4388-852a-0f59a3a15538 author: KumarVivek ms.author: kvivek manager: amyla search.audienceType: - developer search.app: - PowerApps - D365CE --- # <a name="createrecord-client-api-reference"></a>createRecord (Client-API-Referenz) [!INCLUDE[./includes/createRecord-description.md](./includes/createRecord-description.md)] ## <a name="syntax"></a>Syntax `Xrm.WebApi.createRecord(entityLogicalName, data).then(successCallback, errorCallback);` ## <a name="parameters"></a>Parameter <table style="width:100%"> <tr> <th>Name</th> <th>Typ</th> <th>Erforderlich</th> <th>Beschreibung</th> </tr> <tr> <td>entityLogicalName</td> <td>String</td> <td>Ja</td> <td>Der logische Name der zu erstellenden Entität Zum Beispiel: "Konto".</td> </tr> <tr> <td>-Daten</td> <td>Objekt</td> <td>Ja</td> <td><p>Ein JSON-Objekt, das die Attribute und die Werte für den neuen Entitätsdatensatz definiert.</p> <p>Siehe Beispiele weiter unten in diesem Thema, um zu sehen, wie Sie das <code>data</code>-Objekt für verschiedene Erstellungsszenarios definieren können.</td> </tr> <tr> <td>successCallback</td> <td>Funktion</td> <td>No</td> <td><p>Eine Funktion zum Aufrufen, wenn ein Datensatz erstellt wird. Ein Objekt mit den folgenden Eigenschaften wird übergeben, um den neuen Datensatz zu ermitteln:</p> <ul> <li><b>entityType</b>: Zeichenfolge. Der logische Name des neuen Datensatzes.</li> <li><b>id</b>: Zeichenfolge. GUID des neuen Datensatzes.</li> </ul></td> </tr> <tr> <td>errorCallback</td> <td>Funktion</td> <td>No</td> <td>Eine Funktion zum Aufrufen, wenn der Vorgang fehlschlug. Es wird ein Objekt mit den folgenden Eigenschaften übergeben: <ul> <li><b>ErrorCode</b>: Zahl. Der Fehlercode.</li> <li><b>Nachricht</b>: Zeichenfolge. Eine Fehlermeldung, die das Problem beschreibt.</li> </ul></td> </tr> </table> ## <a name="return-value"></a>Rückgabewert Bei Erfolg wird ein Versprechenobjekt mit den Attributen zurückgegeben, die zuvor in der Beschreibung des **successCallback**-Parameters angegeben wurden. ## <a name="examples"></a>Beispiele Die Beispiele verwenden dieselben Anforderungsobjekte wie veranschaulicht in [Erstellen einer Entität mit der Web-API](../../../../common-data-service/webapi/create-entity-web-api.md), um das Datenobjekt zum Erstellen eines Entitätsdatensatzes zu definieren. ### <a name="basic-create"></a>Grundlegende Erstellung Einen Firmendatensatz erstellen. ```JavaScript // define the data to create new account var data = { "name": "<NAME>", "creditonhold": false, "address1_latitude": 47.639583, "description": "This is the description of the sample account", "revenue": 5000000, "accountcategorycode": 1 } // create account record Xrm.WebApi.createRecord("account", data).then( function success(result) { console.log("Account created with ID: " + result.id); // perform operations on record creation }, function (error) { console.log(error.message); // handle error conditions } ); ``` ### <a name="create-related-entity-records-along-with-the-primary-record"></a>Erstellen Sie verknüpfte Entitätsdatensätze zusammen mit dem primären Datensatz Sie können die Entitäten, die miteinander verknüpft werden, indem Sie sie als Navigationseigenschaftenwerte definieren. Dies ist bekannt als *tiefe Einfügung*. In diesem Beispiel wird ein Beispielfirmendatensatz erstellt zusammen mit dem Datensatz des primären Kontakts und einem zugeordneten Verkaufschancendatensatz. ```JavaScript // define data to create primary and related entity records var data = { "name": "<NAME>", "primarycontactid": { "firstname": "John", "lastname": "Smith" }, "opportunity_customer_accounts": [ { "name": "Opportunity associated to Sample Account", "Opportunity_Tasks": [ { "subject": "Task associated to opportunity" } ] } ] } // create account record Xrm.WebApi.createRecord("account", data).then( function success(result) { console.log("Account created with ID: " + result.id); // perform operations on record creation }, function (error) { console.log(error.message); // handle error conditions } ); ``` ### <a name="associate-entities-on-creating-new-records"></a>Zuordnen von Entitäten beim Erstellen neuer Datensätze Um neue Entitätsdatensätze vorhandenen Entitätsdatensätzen zuzuordnen, müssen Sie den Wert für Einzelwert-Navigationseigenschaften über die `@odata.bind`-Notation festlegen. Für mobile Clients im Offlinemodus können Sie die `@odata.bind`Notiz nicht verwenden und müssen stattdessen das Objekt **Suche** (**logicalname** und **ID**) zum entsprechenden Zieldatensatz übermitteln. Im Anschluss finden Sie Codebeispiele für beide Szenarien: **Für Online-Szenario (Verbindung mit Server)** Im folgenden Beispiel wird ein Firmendatensatz erstellt und in einen vorhandenen Kontaktdatensatz eingeordnet, um den letzteren als primären Kontakt für den neuen Firmendatensatz festzulegen: ```JavaScript var data = { "name": "<NAME>", "<EMAIL>": "/contacts(465b158c-541c-e511-80d3-3863bb347ba8)" } // create account record Xrm.WebApi.createRecord("account", data).then( function success(result) { console.log("Account created with ID: " + result.id); // perform operations on record creation }, function (error) { console.log(error.message); // handle error conditions } ); ``` **Für mobiles offine Szenario** Hier der aktualisierte Beispielcode, um einen Firmendatensatzes zu aktualisieren, der mit einem weiteren Kontaktdatensatz als primären Kontakt für die Firma in der mobilen Clients verknüpft ist, während Sie im Offlinemodus arbeiten: ```JavaScript var data = { "name": "<NAME>", "primarycontactid": { "logicalname": "contact", "id": "465b158c-541c-e511-80d3-3863bb347ba8" } } // create account record Xrm.WebApi.offline.createRecord("account", data).then( function success(result) { console.log("Account created with ID: " + result.id); // perform operations on record creation }, function (error) { console.log(error.message); // handle error conditions } ); ``` ### <a name="related-topics"></a>Verwandte Themen [Erstellen einer Entität mithilfe des Web-API](../../../../common-data-service/webapi/create-entity-web-api.md) [Xrm.WebApi](../xrm-webapi.md)
markdown
{ "name": "company-email-validator", "version": "1.0.6", "author": "<NAME> <<EMAIL>>", "description": "Provides a fast company / work email validator by checking whether the email domain is in the free email provider list.", "main": "index", "scripts": { "test": "mocha test.js" }, "typings": "index.d.ts", "engines": { "node": ">4.0" }, "license": "Unlicense", "keywords": [ "email", "validation", "validator", "syntax", "company", "work" ], "homepage": "http://github.com/bnurbekov/company-email-validator", "licenses": [ { "type": "Unlicense", "url": "http://github.com/bnurbekov/company-email-validator/raw/master/LICENSE" } ], "contributors": [ { "name": "<NAME>", "email": "<EMAIL>", "url": "https://utterly.app" }, { "name": "<NAME>", "email": "<EMAIL>", "url": "https://utterly.app" } ], "repository": { "type": "git", "url": "http://github.com/bnurbekov/company-email-validator.git" }, "devDependencies": { "chai": "4.1.2", "mocha": "5.0.5" }, "dependencies": { "email-validator": "^2.0.4" } }
json
<reponame>Ivy286/cluster_basedfps<filename>third_party_package/RDKit_2015_03_1/rdkit/ML/Descriptors/UnitTestParser.py # # Copyright (C) 2001 <NAME> # """ unit testing code for compound descriptors """ from __future__ import print_function import unittest import Parser from rdkit.six.moves import xrange class TestCase(unittest.TestCase): def setUp(self): print('\n%s: '%self.shortDescription(),end='') self.piece1 = [['d1','d2'],['d1','d2']] self.aDict = {'Fe':{'d1':1,'d2':2},'Pt':{'d1':10,'d2':20}} self.pDict = {'d1':100.,'d2':200.} self.compos = [('Fe',1),('Pt',1)] self.cExprs = ["SUM($1)","SUM($1)+SUM($2)","MEAN($1)","DEV($2)","MAX($1)","MIN($2)","SUM($1)/$a"] self.results = [11.,33.,5.5,9.,10.,2.,0.11] self.tol = 0.0001 def testSingleCalcs(self): " testing calculation of a single descriptor " for i in xrange(len(self.cExprs)): cExpr= self.cExprs[i] argVect = self.piece1 + [cExpr] res = Parser.CalcSingleCompoundDescriptor(self.compos,argVect,self.aDict,self.pDict) self.assertAlmostEqual(res,self.results[i],2) def testMultipleCalcs(self): " testing calculation of multiple descriptors " for i in xrange(len(self.cExprs)): cExpr= self.cExprs[i] argVect = self.piece1 + [cExpr] res = Parser.CalcMultipleCompoundsDescriptor([self.compos,self.compos],argVect, self.aDict,[self.pDict,self.pDict]) self.assertAlmostEqual(res[0],self.results[i],2) self.assertAlmostEqual(res[1],self.results[i],2) #self.assertTrue(abs(res[0]-self.results[i])<self.tol,'Expression %s failed'%(cExpr)) #self.assertTrue((res[1]-self.results[i])<self.tol,'Expression %s failed'%(cExpr)) def TestSuite(): suite = unittest.TestSuite() suite.addTest(TestCase('testSingleCalcs')) suite.addTest(TestCase('testMultipleCalcs')) return suite if __name__ == '__main__': suite = TestSuite() unittest.TextTestRunner().run(suite)
python
package all_problems; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class P1743_RestoreTheArrayFromAdjacentPairs { public int[] restoreArray(int[][] adjacentPairs) { int n = adjacentPairs.length + 1; int[] ans = new int[n]; Map<Integer, Set<Integer>> adj = new HashMap<>(); for (int[] pair : adjacentPairs) { // Loop through the input and build the corresponding graph. adj.computeIfAbsent(pair[0], s -> new HashSet<>()).add(pair[1]); adj.computeIfAbsent(pair[1], s -> new HashSet<>()).add(pair[0]); } int prev = 1 << 31, cur = -1, k = 0; // prev and cur are initialized as dummy values. for (Map.Entry<Integer, Set<Integer>> e : adj.entrySet()) { if (e.getValue().size() == 1) { // locate an end. cur = e.getKey(); break; } } ans[k++] = cur; // start from the end. while (k < n) { for (int next : adj.remove(cur)) { // locate the corresponding pair. if (k < n && next != prev) { ans[k++] = next; prev = cur; // move to next element. cur = next; // move to next element. break; } } } return ans; } }
java
<filename>src/com/elektrimasinad/aho/client/AdministratorLogin.java package com.elektrimasinad.aho.client; import java.awt.Dialog; import java.awt.TextField; import java.util.Date; import com.elektrimasinad.aho.shared.Device; import com.elektrimasinad.aho.shared.Device; import com.elektrimasinad.aho.shared.MaintenanceItem; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.datepicker.client.DateBox; import com.google.gwt.user.datepicker.client.DatePicker; import com.google.gwt.core.client.GWT; import com.google.gwt.dev.resource.Resource; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitEvent; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.PasswordTextBox; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextArea; public class AdministratorLogin extends VerticalPanel { public AdministratorLogin() { super(); } public void createNewAdministratorLogin() { super.clear(); DeviceTreeServiceAsync deviceTreeService = DeviceCard.getDevicetreeservice(); VerticalPanel LoginPanel = new VerticalPanel(); HorizontalPanel UserPanel = new HorizontalPanel(); Label User = new Label("Username"); TextBox tb = new TextBox(); HorizontalPanel PassPanel = new HorizontalPanel(); Label Pass = new Label("Password"); PasswordTextBox ptb = new PasswordTextBox(); tb.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { if (!Character.isDigit(event.getCharCode())) { ((TextBox) event.getSource()).cancelKey(); } } }); VerticalPanel LoginButtonPanel = new VerticalPanel(); Button login = new Button("Log in!", new ClickHandler() { public void onClick(ClickEvent event) { Window.alert("Login successful!"); Window.Location.assign("/Index.html"); } }); LoginPanel.add(UserPanel); UserPanel.add(User); UserPanel.add(tb); LoginPanel.add(PassPanel); PassPanel.add(Pass); PassPanel.add(ptb); LoginPanel.add(LoginButtonPanel); LoginButtonPanel.add(login); add(LoginPanel); } }
java
Former Pakistan skipper Inzamam-ul-Haq said that Pakistan pace bowler Shaheen Afridi’s latest injury is a huge setback for the national team. The Pakistan Cricket Board (PCB) issued a statement on Saturday (August 20) where they mentioned that Afridi needs rest for four-six weeks to recover from a knee injury. The latest scans and reports are not a good sign for the Pakistan men’s team as their bowling spearhead is set to miss Asia Cup 2022 followed by the seven-match T20I series against England at home. Afridi picked up the right ligament knee injury while fielding during the first Test against Sri Lanka last month and hasn’t played any match for the national team since then. He recently missed the three-match ODI series against the Netherlands in Rotterdam, though he was available with the squad. Shaheen starred during Pakistan’s emphatic 10-wicket win against India in 2021 T20 World Cup. The lanky left-arm pacer claimed the wickets of Rohit Sharma, KL Rahul and Virat Kohli to restrict India to a below-par score. “It’s a massive setback for Pakistan that Shaheen Afridi is out of the Asia Cup. If you look at the last match against India, he created pressure right from the very first over in the previous edition of the T20 World Cup,” Inzamam said on his YouTube channel. “It’s a tough decision for Pakistan as Shaheen has been ruled out of the tournament, but injuries are part of the game,” he added. Inzamam, who faced India in 10 Tests and 67 ODIs in a storied international career, expects nothing less than a thrilling encounter when the two teams clash in the upcoming Asia Cup 2022. “It will be a thrilling match since India versus Pakistan matches are always entertaining. We can witness exciting cricket action since both teams are good in T20Is,” Inzamam said. India and Pakistan will play against each other on August 28 at the Dubai International Cricket Stadium.
english
Pokhara, March 16: India’s Exterl Affairs Minister Sushma Swaraj arrived here in this lake resort town in Nepal on Wednesday to attend the Saarc ministerial meeting. She will participate in the ministerial meeting in Pokhara on Thursday and meet her counterparts from the region. Nepal Prime Minister K. P. Sharma Oli will iugurate the ministerial meeting. Sushma Swaraj is expected to hold talks with Oli and other regiol counterparts including Sartaj Aziz, foreign affairs adviser to the Pakistan prime minister, on the sidelines of the meeting, diplomatic sources said. However, both India and Pakistan were not forthcoming about the exact time of the meeting. Sushma Swaraj will attend a reception hosted by her Nepali counterpart Kamal Thapa on Wednesday, where she is also expected to meet Aziz, said sources. (IANS)
english
# Простое управление сложными интерфейсами на React/Redux kate-form - простой способ управления данными форм и их поведением с разделением логики и отображения для React/Redux. - [Описание](#Описание) - [Работа с библиотекой](#Работа-с-библиотекой) - [Детали устройства библиотеки](#Детали-устройства-библиотеки) - [Лицензия](#Лицензия) Полный пример использования библиотеки можно найти в репозитории [kate-form-demo](https://github.com/romannep/kate-form-demo) ## Ограничения Библиотека использует объект Proxy. Для браузеров без Proxy используется полифилл, который ограничивает использование `this.content` теми элементами и их свойствами, которые были определены при создании (`kateFormInit` или `setData('', ...)` ). Браузеры, поддерживающие Proxy можно глянуть тут [https://caniuse.com/#search=proxy](https://caniuse.com/#search=proxy) ## Описание ### Область использования При создании сложных интерфейсов на React для: - админ. панелей, - систем управления задачами/проектами, - CRM систем, и аналогичных, необходимо разрабатывать множество форм. Каждая форма в подобном интерфесе состоит из данных, элементов которые отображают и изменяют эти данные (input, select, checkbox и прочих), а также логики поведения самих элементов - изменении их атрибутов (видимость, доступность, визуальные характеристики и прочих) в зависимости от данных или действий пользователя. Например: - по клику на кнопку "Отправить уведомление" появляется поле ввода "e-mail" - в зависимости от прав пользователя становится доступной кнопка "Редактировать" - при отличии значения поля "Пароль" от значения поля "Повторите пароль" выводится надпись "Пароли не совпадают" Для управления данными формы и их вводом есть, например, популярное решение - [redux-form](https://redux-form.com), которое хранит лишь данные формы. При его использовании, все характеристики и логика поведения элементов формы описывается либо в самих элементах либо внутри render. При таком подходе и отображение и логика идут вперемешку. В больших формах со сложной логикой это может приводить к неудобствам как разработки, так и поддержки. Данная бибилиотека создана для удобства описания поведения форм, с помощью разделения логики и отображения: - помимо данных (значения) элемента формы, в `redux` `store` хранится и набор параметров, описывающих его визуальные характеристики, - за отображение элемента формы отвечает отдельный компонент, - предоставляется простой способ манипулирования как данными, так и характеристиками элементов. ### Пример использования Рассмотрим два примера, предложенных выше: - по клику на кнопку "Отправить уведомление" появляется поле ввода "e-mail" или скрывается, если оно уже отображено - при отличии значения поля "Пароль" от значения поля "Повторите пароль" выводится надпись "Пароли не совпадают" Элементы формы определеяются простым массивом, где мы указыаем их тип и связываем с нужными обработчиками событий: ```` const elements = [ { type: Elements.BUTTON, title: 'Send notification', onClick: this.showEMail, }, { id: 'email', type: Elements.INPUT, placeholder: 'e-mail', hidden: true, }, { id: 'password', type: Elements.INPUT, placeholder: 'Password', inputType: 'password', onChange: this.checkPasswords, }, { id: 'password2', type: Elements.INPUT, placeholder: 'Retype password', inputType: 'password', onChange: this.checkPasswords, }, { id: 'passwordsMatchText', type: Elements.LABEL, title: 'Passwords match', }, ]; ```` А обработчики определяем как методы компонента и используем в них поле `content` для доступа к свойствам элементов формы, используя заданные в списке `id` элементов как имена полей. ```` showEMail = () => { this.content.email.hidden = !this.content.email.hidden; } checkPasswords = () => { if (this.content.password.value !== this.content.password2.value) { this.content.passwordsMatchText.title = 'Passwords do not match'; } else { this.content.passwordsMatchText.title = 'Passwords match'; } } ```` Просто, быстро, удобно и читаемо! При таком подходе возникает вопрос о расположении различных элементов на странице. В примере выше - они описаны простым массивом, а значит будут выводится единообразно, друг за другом, что, в некоторых случаях недостаточно. Для решения этого вопроса можно сделать вспомогательные элементы, которые будут регулировать расположение других элементов на станице. Код обработчиков остается таким-же, т.к. `content` рекурсивно находит нужные элементы по `id`. ```` const elements = [ { type: Elements.GROUP, layout: 'horizontal', elements: [ { type: Elements.BUTTON, title: 'Send notification', onClick: this.showEMail, }, { id: 'email', type: Elements.INPUT, placeholder: 'e-mail', hidden: true, }, ], }, { type: Elements.GROUP, elements: [ { id: 'password2_1', type: Elements.INPUT, placeholder: 'Password', inputType: 'password', onChange: this.checkPasswords, }, { id: 'password2_2', type: Elements.INPUT, placeholder: 'Retype password', inputType: 'password', onChange: this.checkPasswords, }, { id: 'passwordsMatchText', type: Elements.LABEL, title: 'Passwords match', }, ], }, ]; ```` ### Концепция Принцип работы `kate-form` очень простой: - есть набор `компонентов` - компонентов элементов, которые используются в формах, с уникальным именами для каждого - в самой форме определяется набор элементов, с указанием имени нужного компонента в поле type - Компонент `KateForm` выполняет рендер элементов, подставляя нужный компонент в соответствии с типом, передавая значение остальных полей как `props`. Таким образом достигается разделение отображения и логики: - за отображение отвечают `компоненты`, - за логику формы отвечают набор элементов и их взаимодействие в классе компонента формы. ## Работа с библиотекой Полный пример использования библиотеки можно найти в репозитории https://github.com/romannep/kate-form-demo ### Установка ```` npm install kate-form --save ```` ### Подключение приложения Для работы `kate-form` требуется `redux`. Для хранения состояния необходимо подключить `reducer` из `kate-form` в корневом `reducer`-e: ```` import { reducer } from 'kate-form'; const rootReducer = combineReducers({ ... 'kate-form': reducer, ... }); ```` Набор `компонентов` передается через `KateFormProvider` в корневом для использующих их форм компоненте. ```` import { KateFormProvider } from 'kate-form'; ... <KateFormProvider components={components} t={t} [logRerender]> <App /> </KateFormProvider> ... ```` Без передачи `компонентов` `kate-form` будет использовать свой минимальный набор встроенных. Помимо компонентов в `KateFormProvider` передается функция перевода `t` которая будет доступна внутри каждого `компонента`. Без указания функции будет использована функция по умолчанию, просто возвращающая полученный параметр. ```` const t = param => param; ```` Для отладки производительности можно указать опциональный параметр `logRerender`. При этом в `console` будут выводится сообщения о рендере каждого элемента. ### Подключение компонента формы Компонент формы необходимо подключить к `kate-form`, используя `HOC` функцию `withKateForm(FormComponent, formPath, subElementsPath= 'elements', kateFormPath = 'kate-form')`, где - `FormComponent` - подключаемый компонент - `formPath` - путь к данным формы в `redux` `store` относительно всех данных `kate-form` - `subElementsPath` - имя поля вложенных элементов в групповых компонентах. Необязательный параметр, по умолчанию `'elements'`. - `kateFormPath` - путь к данным `kate-form` в `redux` `store`. Необязательный параметр, по умолчанию `'kate-form'` ```` import { withKateForm } from 'kate-form'; const kateFormPath = 'formLayout'; class FormLayout extends Component { ... } export default withKateForm(FormLayout, kateFormPath); ```` Фукнция `withKateForm` передает в `props` следующие параметры: - `kateFormInit(formElements)` - метод первоначальной установки элементов формы - `kateFormContent` - объект `content` для работы с элементами формы - `setData(path, value)` - метод прямого изменения данных формы, где `path` - строка - путь к данным - индексы массива, имена полей объектов через `.` - `data` - данные формы - `setValues(obj)`- метод, для каждого `{ key: data }` в переданом в параметре объекта ищет элемент с `id` == `key` и устанавливает поле `value` равному `data` - `getValues()` - метод, который переберает все элементы формы имеющие поле `value` и возвращает объект где ключами будут `id` элементов, а значениями - значения полей `value` - `kateFormPath` - полученный в параметре путь к форме При первоначальном определении данных формы их необходимо установить в `redux store`. Для этого используется метод `kateFormInit`. Для удобства работы с данными формы объект `kateFormContent` можно сохранить в свойство класса Для вывода формы в `render` необходимо использовать компонент `KateForm` с параметром `path` - пути к данным формы относительно всех данных `kate-form` ``` import { ..., KateForm } from 'kate-form'; class FormLayout extends Component { constructor(props) { super(props); const { kateFormInit, kateFormContent } = this.props; const elements = [ { type: 'button', title: 'Show/hide email', onClick: this.showEMail, }, { id: 'email', type: 'input', placeholder: 'e-mail', hidden: true, }, ... ]; kateFormInit(elements); this.content = kateFormContent; } showEMail = () => { this.content.email.hidden = !this.content.email.hidden; } ... render() { const { kateFormPath } = this.props; return ( <KateForm path={kateFormPath} /> ); } } ``` ### Жизненный цикл Работать с объектом `content` для доступа к элементам формы прямо в конструкторе не получится: метод `kateFormInit` устанавливает элементы формы условно в следующем цикле событий javascript (см детали реализации `redux`). Отследить момент инициализации данных, а следовательно момент начала возможной работы с `content` можно с помощью метода `react` компонента `componentDidUpdate`. В общем случае (при изменении `state` родительских компонентов) этот метод может быть вызван не один раз, поэтому логично дополнить компонент функцией `shouldComponentUpdate`. ```` shouldComponentUpdate(nextProps) { return this.props.data !== nextProps.data; } componentDidUpdate() { // do some after init stuff } ```` При обновлении данных корневого элемента будет естественно перерисована и этот компонент - т.е. метод `componentDidUpdate` будет вызан повторно. При неохоимости выолнить некоторые действия только разово, можно прибегнуть к `setTimeout`: ```` constructor() { ... ... setTimeout(() => { // do somethng with content }, 0); } ```` ### Компоненты Компоненты это набор React компонентов, которые представляют собой элементы формы, которые используются для рендера. ```` const label = ({ title, ...props }) => ( <span {...props}>{title}</span> ); const components = { ... 'label': label, } ```` В форме мы можем использовать данный копмонент следующим образом: ```` constructor(props) { ... const elements = [ ... { type: 'label', title: 'Some label', style: { color: '#FF0000'} } ]; ... } ```` `kate-form` выполняет рендер компонента по его имени, указанном в поле `type`, передавая остальные поля как `props`. Данный пример будет эквивалентен ```` <span style={{ color: '#FF0000' }} >Some label</span> ```` В `props` компонента, помимо данных элемента передаются еще следующие параметры: - `setData(subPath, value)` - метод изменения данных, где `subPath` - путь к данным относительно самого элемента и `value` - значение, которое нужно установить. - `path` - полный путь к самому элементу. - `t` - функция для переводов Компонент для поля ввода в минимальном ввиде может выглядеть так: ```` const input = ({ setData, value, ...props }) => { const change = (e) => { setData('value', e.target.value); }; return ( <input onChange={change} value={value || ''} {...props} /> ); }; ```` Компонент для вывода группы элементов, где элементы группы находятся в поле `elements` ```` const elements = [ ... { type: 'group', elements: [ { type: 'button', title: 'Send notification', onClick: this.showEMail, }, { id: 'email', type: 'input', placeholder: 'e-mail', hidden: true, }, ] } ... ] ```` в минимальном ввиде может выглядеть так ```` const group = ({ path, elements, ...props }) => { return ( <div> { elements.map((item, index) => ( <div key={index}> <KateForm path={`${path}.elements.${index}`} /> </div> )) } </div> ); }; ```` Для исключения использования строк в качестве идентификаторов компонентов, а также для исключения кофликтов имен при использовании разных наборов компонентов логично использовать набор констант: Компоненты: ```` const label = ({ title, setData, t, ...props }) => ( <span {...props}>{t(title)}</span> ); const Elements = { LABEL: Symbol('label'), ... }; const components = { [Elements.LABEL]: label, ... }; ```` Форма ```` import { ..., Elements } from 'kate-form'; ... constructor(props) { ... const elements = [ ... { type: Elements.LABEL, title: 'Some label', style: { color: '#FF0000'} } ]; ... } ```` ## Детали устройства библиотеки ### Компонент формы Данные каждой формы подключаются в `redux` по определенному пути относительно всех данных `kate-form`, чтобы можно было использовать несколько различных форм. Для доступа к данным формы и методу их изменения компонент формы подключается к `redux` следующим образом ```` import { getSetData, ... } from 'kate-form'; const kateFormPath = 'formLayout'; class FormLayout extends Component { ... } const mapStateToProps = (state) => { return { ... data: state['kate-form'][kateFormPath], }; }; export default connect(mapStateToProps, { ... setData: getSetData(kateFormPath), })(FormLayout); ```` При таком подключении в `props` в поле `data` у нас актуальное состояние данных формы, а в поле `setData` - метод изменения данных. В чистом виде, метод для изменения данных принимает путь к данным и значние для установки. Путь - `path` - строка, с именами полей объекта или индексами массива через `.`. Для примера в описании, установка в объекте с id == `email` поля hidden равным `false` вызов этого метода будет иметь вид: ```` setData('0.elements.1.hidden', false) ```` Структура элементов может быть сложной, со множеством уровней вложенности, поэтому для удобства `kate-form` предоставляет объект `content`, где можно удобно обратитья к нужному элементу по его `id`: ```` content.email.hidden = false ```` ### Данные формы и логика При первоначальном определении данных формы их необходимо установить в `redux store`, т.к. `kate-form` для рендера берет данные от туда. Для этого используется метод `setData`; Если компонент предоставляет собой только форму, это можно сделать в методах `constructor` или `componentWillMount`. ```` constructor(props) { super(props); const { setData } = this.props; const elements = [ ... ]; setData('',elements); } ```` Для получения объекта `content` для удобной работы с элементами формы используется функция `getContent`. Фнукция создает `Proxy` объекты для доступа к данным, поэтому ей необходимо передать два метода - получения и установки данных. ```` import { ..., createContent } from 'kate-form'; ... class FormLayout extends Component { constructor(props) { super(props); const { setData } = this.props; ... this.content = createContent(this.getData, setData); } getData = () => this.props.data; ... } ```` Функция `getContent` подразумевает, что в элементах - группах их вложенные элементы хранятся в массиве в поле `elements`. Если вложенные элементы хранятся в поле с другим названием, его необходимо передать третьим параметром. ```` this.content = createContent(this.getData, setData, 'subElements'); ```` Для обработки значений формы можно использовать объект-массив `data`, а также функцию `getValues`, которая переберет все элементы формы имеющие поле `value` и вернет объект где ключем будет `id` элемента, а значением - значение его поля `value` ```` import { ..., getValues } from 'kate-form'; ... class FormLayout extends Component { ... logValues = () => { console.log(getValues(this.props.data)); } } ```` Функция `getValues` подразумевает, что в элементах - группах их вложенные элементы хранятся в массиве в поле `elements`. Если вложенные элементы хранятся в поле с другим названием, его необходимо передать вторым параметром. ```` getValues(this.props.data, 'subElements') ```` ### Рендер формы Для рендера формы используется компонент `KateForm`, которому в качестве параметра передается путь к `redux store` относительно данных `kate-form` по которому находятся данные формы. ```` import { ..., KateForm } from 'kate-form'; const kateFormPath = 'formLayout'; ... class FormLayout extends Component { ... render() { return ( <KateForm path={kateFormPath} /> ); } } ```` Компонент `KateForm` работает следующим образом: - если по переданному `path` находится массив, вызывается рендер `KateForm` для каждого элемента массива с добавлением в `path` его индекса - если по переданному `path` находится объект, вызывается рендер компонента согласно значению поля `type`. ## Лицензия [MIT](https://github.com/romannep/kate-form/blob/master/license.md)
markdown
Former NFL linebacker Jay Richardson reacts to Kevin Durant’s statement about his titles with the Warriors. It has been 4 years since Kevin Durant joined the Warriors, but people still don’t stop talking about it. In his recent appearance on JJ Redick’s podcast, KD said that he earned the trophies with the Warriors. This statement did not sit right with a lot of people, including former NFL player Jay Richardson. The former linebacker showed his amusement at the statement in a very loud manner. KD did not take the harsh response from Jay Richardson kindly. He replied to Jay’s tweet with a strong tweet of his own, taking a dig at the linebacker’s success in the NFL. Jay responded to the same with two different replies: In the first one, he tries to explain his point of view: While in the second one, Jay once again took a dig at Durant and made a reference to all the burner account jokes on KD. To this, Kevin paraphrased Drake and said he wanted to put Jay on live TV since he loves so much attention. Once again, Jay took a dig at Kevin and asked him to leave the ‘quoting Drake’ for the school girls. Clearly, that did not sit well with Kevin Durant, who is a close friend of Drake, and was also seen on Drake’s music video “Laugh now Cry later”. Jay Richardson explains why he said what he said initially, and tries to end this online battle of words. It has been 4 years since KD brought his talents to the Bay and he has been gone for over a year. However, people all over still make it a point to malign Kevin Durant’s decision of taking the easy way out. Will Kevin Durant let this go or will he respond to Jay again?
english
<gh_stars>0 { "name": "delay-req", "version": "1.0.1", "description": "Delay each http request in expressjs, as a part of security implementation", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/AkashBabu/delay-req.git" }, "keywords": [ "delay", "express", "expressjs", "rate", "limiter", "request" ], "author": "<NAME> <<EMAIL>>", "license": "MIT", "bugs": { "url": "https://github.com/AkashBabu/delay-req/issues" }, "homepage": "https://github.com/AkashBabu/delay-req#readme", "dependencies": { "on-finished": "^2.3.0" } }
json
Actress-turned-Politician Divya Spandana (Ramya) who is also the youngest MP of 15th Lok Sabha hints at quitting films completely to devote full time to politics. The Congress leader was elected as MP from Mandya constituency in Karnataka in the by-polls held last year. Speaking to media persons, Divya told: "I haven't signed any new films recently. I am just focusing on completing the shooting of films signed by me in the past. Managing both films and political responsibilities is difficult. In all possibility, My last film would be 'Aryan'. " The actress, however, made it clear she isn't quitting films permanently. She didn't rule out the chances of playing sister roles in films after few years. She also appealed to fans to offer her the same kind of support and assistance they have given her during her stint as an actress.
english
package oio.trans; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * @author k.jiang * 2020/4/21 下午10:14 * Description Bio 网络编程 */ public class OioServer { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(9000); for (;;) { Socket socket = serverSocket.accept(); System.out.println("Accept New connect: " + socket); new Thread(new Runnable() { @Override public void run() { OutputStream outputStream; try { outputStream = socket.getOutputStream(); outputStream.write("I am server".getBytes()); outputStream.flush(); socket.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { //do nothing } } } }).start(); } } catch (IOException e) { e.printStackTrace(); } } }
java
<reponame>Aleks0509111/Server { "Name": "Sliderkey Flash drive", "ShortName": "Flash drive", "Description": "Sliderkey Secure Flash drive Such USB sticks are frequently used by TerraGroup brass. They can definitely contain sensitive data." }
json
<gh_stars>0 package io.jenkins.plugins.analysis.warnings; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.WebElement; import edu.umd.cs.findbugs.annotations.CheckForNull; /** * Representation of a table row displaying the blames details for an issue. * * @author <NAME> */ public class BlamesTableRow extends BaseIssuesTableRow { private static final String AUTHOR = "Author"; private static final String EMAIL = "Email"; private static final String COMMIT = "Commit"; private static final String ADDED = "Added"; private final String author; private final String email; private final String commit; private final String added; BlamesTableRow(final WebElement rowElement, final BlamesTable table) { super(rowElement, table); if (isDetailsRow()) { author = StringUtils.EMPTY; email = StringUtils.EMPTY; commit = StringUtils.EMPTY; added = StringUtils.EMPTY; } else { author = getCellContent(AUTHOR); email = getCellContent(EMAIL); commit = getCellContent(COMMIT); added = getCellContent(ADDED); } } public String getAuthor() { return author; } public String getEmail() { return email; } public String getCommit() { return commit; } public String getAdded() { return added; } @Override public boolean equals(@CheckForNull final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } BlamesTableRow that = (BlamesTableRow) o; if (!author.equals(that.author)) { return false; } if (!email.equals(that.email)) { return false; } if (!commit.equals(that.commit)) { return false; } return added.equals(that.added); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + author.hashCode(); result = 31 * result + email.hashCode(); result = 31 * result + commit.hashCode(); result = 31 * result + added.hashCode(); return result; } }
java
import React from 'react' import { StaticQuery, graphql } from 'gatsby' import styled from '@emotion/styled' import TestimonialItem from '../components/TestimonialItem' import SectionContainer from '../components/SectionContainer' import { Row, Column } from '../components/Global' import Button from '../components/Button' const TestimonialCustomRow = styled(Row)` .testimonial-section .col[data-items-count="8"]:nth-child(4) { grid-column: 3 / span 4; } .testimonial-section .col[data-items-count="7"]:nth-child(7) { grid-column: 5 / span 4; } .testimonial-section .col[data-items-count="5"]:nth-child(4) { grid-column: 3 / span 4; } ` const TestimonialsSection = ({ title, greyBg, cta, testimonials, }) => ( <SectionContainer title={title || 'Cosa dicono di noi'} greyBg={greyBg} titleCenter className="testimonial-section" > <TestimonialCustomRow scrolling> {testimonials.map((testimonial, i) => ( <Column key={i} size="4" slide className="col" data-items-count={testimonials.length}> <TestimonialItem name={testimonial.name} body={testimonial.body} image={testimonial.image} company={testimonial.company} /> </Column> ))} </TestimonialCustomRow> {cta && ( <Row> <Column style={{ textAlign: 'center', marginTop: '5px' }} size="12"> <Button href={cta.url || cta.link} primary> {cta.text} </Button> </Column> </Row> )} </SectionContainer> ) // const TestimonialsSection = ({ title, greyBg, cta }) => ( // <SectionContainer // title={title || 'Cosa dicono di noi'} // greyBg={greyBg} // titleCenter // > // <Row scrolling> // <StaticQuery // query={graphql` // query TestimonialQuery { // markdownRemark( // frontmatter: { templateKey: { eq: "testimonials" } } // ) { // id // frontmatter { // testimonials { // body // company // image // name // } // } // } // } // `} // render={(data) => { // if (data.markdownRemark.frontmatter.testimonials) { // return data.markdownRemark.frontmatter.testimonials.map( // (testimonial, i) => ( // <Column key={i} size="4" slide> // <TestimonialItem // name={testimonial.name} // body={testimonial.body} // image={testimonial.image} // company={testimonial.company} // /> // </Column> // ), // ) // } // return null // }} // /> // </Row> // {cta && ( // <Row> // <Column size="12"> // <Button href={cta.url || cta.link} primary> // {cta.text} // </Button> // </Column> // </Row> // )} // </SectionContainer> // ) export default TestimonialsSection
javascript
The AATS (All Assam Tribal Sangha) has urged the State government not to mix Mission Bhumiputra and Mission Busandhara since these two are different entities. GUWAHATI: The AATS (All Assam Tribal Sangha) has urged the State government not to mix Mission Bhumiputra and Mission Busandhara since these two are different entities. Talking to The Sentinel, AATS secretary general Aditya Khakhlari said, "The government has sought the certificates issued under the Mission Bhumiputra for the Mission Basundhara scheme. The government does not accept the age-old caste certificates in the Mission Basundhara. It is nothing but harassment. " He said that under the Mission Bhumiputra online service, the government issues caste certificates to ST students reading from Class IX-XII. "However, issuing such caste certificates to adult people has not yet started. How justified is the government seeking caste certificates issued under Mission Bhumiputra for Mission Basundhara Scheme? How can adult ST people get caste certificates issued under Mission Basundhara when the process has not started? We request the government to accept the ST certificates that AATS issues and the deputy commissioners countersign them," Khakhlari said, and added: "Mission Basundhara has sought caste certificates of parents, Xerox copies of the voter list and affidavit from the court. It is harassment. The government should stop. Many tribal-populated places in the state are still non-cadastral. The government should survey such lands immediately and give land rights to the tribal people for the land under their possession for generations. It should also provide land rights to devottor and xatra lands. " Khakhlari said, "The wetlands of Dhemaji and Majuli districts have become arable and homestead lands. The government should also issue myadi patta for such lands. It should also convert the 'gram sabha myadi' to myadi patta. " He said that AATS took all these decisions at its joint executive meeting with the All Assam Tribal Youth League held recently. The meeting decided to take out a bicycle rally from December 15-21 to make the tribal people aware of Mission Basundhar 2. 0 in the state. The rally would also cover the BTR, where non-tribal people rampantly encroach upon tribal lands. The other demands for BTR are providing land rights to forest dwellers as per the Forest Land Rights Act and land rights to the landless. The meeting also demanded the government to extend the last date for application for Mission Bhumiputra up to March 30, 2023. Also Watch:
english
<filename>dagger/pipeline/tasks/redshift_load_task.py from dagger import conf from dagger.pipeline.task import Task from dagger.utilities.config_validator import Attribute class RedshiftLoadTask(Task): ref_name = "redshift_load" default_pool = "redshift" @staticmethod def _get_default_load_params(): return {"statupdate": "on"} @classmethod def init_attributes(cls, orig_cls): cls.add_config_attributes( [ Attribute( attribute_name="iam_role", required=False, parent_fields=["task_parameters"], ), Attribute( attribute_name="columns", required=False, parent_fields=["task_parameters"], ), Attribute( attribute_name="incremental", required=True, parent_fields=["task_parameters"], validator=bool, format_help="on/off/yes/no/true/false", auto_value="true", ), Attribute( attribute_name="delete_condition", required=True, nullable=True, parent_fields=["task_parameters"], format_help="SQL where statement", comment="Recommended when doing incremental load", ), Attribute( attribute_name="max_errors", required=False, parent_fields=["task_parameters"], comment="Default is 0", ), Attribute( attribute_name="postgres_conn_id", required=False, parent_fields=["task_parameters"], ), Attribute( attribute_name="extra_load_parameters", required=True, nullable=True, parent_fields=["task_parameters"], format_help="dictionary", comment="Any additional parameter will be added like <key value> \ Check https://docs.aws.amazon.com/redshift/latest/dg/r_COPY.html", ), Attribute( attribute_name="tmp_table_prefix", required=False, parent_fields=["task_parameters"], format_help="string", comment="Only valid if job is truncated. If set table will be loaded into a tmp table prefixed " "<tmp_table_prefix> and than it will be moved to it's final destination", ), Attribute( attribute_name="create_table_ddl", required=False, parent_fields=["task_parameters"], format_help="string", comment="Path to the file which contains the create table ddl", ), Attribute( attribute_name="copy_ddl_from", required=False, parent_fields=["task_parameters"], format_help="string {schema}.{table}", comment="If you have the schema of the table e.g.: in spectrum you can copy the ddl from there", ), ] ) def __init__(self, name, pipeline_name, pipeline, job_config): super().__init__(name, pipeline_name, pipeline, job_config) self._incremental = self.parse_attribute("incremental") self._delete_condition = self.parse_attribute("delete_condition") self._iam_role = self.parse_attribute("iam_role") or conf.REDSHIFT_IAM_ROLE self._columns = self.parse_attribute("columns") self._max_errors = self.parse_attribute("max_errors") self._postgres_conn_id = ( self.parse_attribute("postgres_conn_id") or conf.REDSHIFT_CONN_ID ) self._tmp_table_prefix = self.parse_attribute("tmp_table_prefix") self._create_table_ddl = self.parse_attribute("create_table_ddl") self._copy_ddl_from = self.parse_attribute("copy_ddl_from") load_parameters = self._get_default_load_params() if self._max_errors: load_parameters["maxerrors"] = self._max_errors load_parameters.update(self.parse_attribute("extra_load_parameters") or {}) self._extra_parameters = load_parameters @property def iam_role(self): return self._iam_role @property def columns(self): return self._columns @property def incremental(self): return self._incremental @property def delete_condition(self): return self._delete_condition @property def max_errors(self): return self._max_errors @property def postgres_conn_id(self): return self._postgres_conn_id @property def extra_parameters(self): return self._extra_parameters @property def tmp_table_prefix(self): return self._tmp_table_prefix @property def create_table_ddl(self): return self._create_table_ddl @property def copy_ddl_from(self): return self._copy_ddl_from
python
The Pakistan Cricket Board (PCB) has named Afridi as the national T20 captain till the ICC World Twenty20 early next year. “We know the World T20 is coming close and it is important for the captain to start contributing to the team. But I think the pitches have not suited Afridi in Zimbabwe and I am sure he will strike form soon,” the former Test captain said. The Pakistan Cricket Board (PCB) has named Afridi as the national T20 captain till the ICC World Twenty20 early next year after which the flamboyant all-rounder has indicated that he plans to bid adieu to international cricket. “I am sure Afridi himself realises the importance of striking form with bat and ball. I am sure he wants to end with a bang. So I am not worried he will regain his best soon. He is a player for the big occasion,” Waqar said. Waqar noted that Afridi had led the side well in recent T20 matches. Pakistan has won its last six T20 matches taking the team to the number two spot in the ICC T20 rankings. Waqar also said that he was satisfied with the series win over Zimbabwe but said obviously would have liked the batsmen to get more runs in the low scoring series. “The good thing is that we have defended low totals and the bowlers have done their jobs. The batsmen we have are capable of big scores. But in this format of the game I don’t think you need to get big scores, small contributions give you a fighting total and our bowling so far has been very good while the fielding has also improved a lot,” he said.
english
[ { "id": "list-project-cards", "name": "List project cards", "url": "https://developer.github.com/v3/projects/cards/#list-project-cards" }, { "id": "get-a-project-card", "name": "Get a project card", "url": "https://developer.github.com/v3/projects/cards/#get-a-project-card" }, { "id": "create-a-project-card", "name": "Create a project card", "url": "https://developer.github.com/v3/projects/cards/#create-a-project-card" }, { "id": "update-a-project-card", "name": "Update a project card", "url": "https://developer.github.com/v3/projects/cards/#update-a-project-card" }, { "id": "delete-a-project-card", "name": "Delete a project card", "url": "https://developer.github.com/v3/projects/cards/#delete-a-project-card" }, { "id": "move-a-project-card", "name": "Move a project card", "url": "https://developer.github.com/v3/projects/cards/#move-a-project-card" } ]
json
--- title: "Hacker News: Why aren’t we all more serious?" date: "2020-09-27T10:18:38+10:00" abstract: "Feedback from the post in HN, including talk about the site mascot." year: "2020" category: Internet tag: - comments - feedback - hacker-news location: Sydney --- Another post of mine [appeared on Hacker News](https://news.ycombinator.com/item?id=24537147) last week, this time thanks to [luu](https://news.ycombinator.com/user?id=luu). It was one I wrote back in July responding to the charge that my [blog isn't serious enough](https://rubenerd.com/why-arent-you-more-serious/), a touchy-feely topic I didn't expect given HN tends to appeal to hard computer science and engineering types. I was also surprised at the number of positive comments. The biggest takeaway I took were an affirmation that not everything needs to be a hussle, or justified in the context of money. tayo42 had my favourite comment: > I really wish we didn't put so much pressure to be professional and serious all the time. Working takes up 1/3 of my life currently and I can't actually be my self. Another third is sleeping. So for only 1/3 of my time I can actually act like my self. I hate that there is a pressure to talk a certain, act a certain way, express my self a certain way. I think we really need more of a emphasis on being human, less "circle back" and "work streams", more jokes, more smiling and experimenting. KaiserPro also raised a point I hadn't considered: being too serious could also *limit* the reach of your work in unexpected ways: > They couldn't seem to grasp that if I'd have written [his sweary post in] a dry, clean style, not only would they have not read it, but they wouldn't have understood my point. [..] Humour, irreverence and swearing are all tools to convey a meaning, point or story. Used well (I am fully willing to admit that I have not been masterful in my use) they can create a mental image far stronger than any other metaphor. There's also the angle that simply fewer people are writing online these days, or are confining themselves to social networks. There are so many reasons why this is sad, not least because they're surrendering control, propping up invasive business models, and relegating their important ideas to ephemeral social posts. But just as important is the lack of personality: I miss seeing people's personal sites in the 1990s, and how people presented their blogs in the 2000s. Curiously, the few negative comments had to do with my [site mascot Rubi](https://rubenerd.com/about/#mascot), which I'll admit didn't surprise me. Once people on mobile found her&mdash;she only appears in the desktop theme&mdash;a few proceeded to discuss her appropriateness. One specifically called out her "hiked-up skirt" (since deleted) which amused Clara who drew her, and who often cosplays in similar getup. It was a good thing they didn't see Rubi in her summer swimsuit and shorts for that brief month a few years ago! I've always had a small anime badge somewhere on my sites since at least 2006, back when it was SOS-Dan to demonstrate my allegiance to Haruhi. Before then it was Star Trek insignia. I love stumbling on another personal site and seeing a different aspect of someone's personality shine through. That's what makes the web fun. If I lose a few readers from doing that, they probably weren't the kind of people I wanted to spend mental energy on in the first place.
markdown
BERLIN, Germany, Mar 28 – President William Ruto has said impunity will not be part of the country’s political discourse. He said all Kenyans must submit to the rule of law. “That is what makes us equal. Nobody should trample on the rights of others,” he said. The President was speaking on Tuesday in Berlin when he met Kenyans living in Germany. He said he will ensure everyone’s life, property and business is protected. He said it is incumbent of the Inspector General of Police to decide on how to secure Kenya. Dr Ruto said the Government will leverage on its diverse, rich and skilled human capital to ensure Kenya shines globally.
english
{"psl.js":"sha256-NkoiVNf8cc79Y9qft1a4VM5lsueg6q8mEmrhwPSBhD8=","psl.min.js":"sha256-t9j6XZnxBIpcAR/vz/V6ePXy0eRP6abiJJ/Hj5wFg/w="}
json
Mumbai: The BSE Sensex extended gains for the second straight day by rising about 139 points in opening trade on sustained buying by domestic institutional investors amid a firm trend at other Asian bourses. The 30-share barometer, which had gained 318. 48 points in the previous session, was trading higher by 138. 52 points, or 0. 41 per cent, at 33,490. 09. Sectoral indices led by Metal, IT, Teck, Consumer Durables and FMCG led the gains, rising by up to 0. 64 per cent. On similar lines, the NSE Nifty was up by 35. 35 points, or 0. 34 per cent, at 10,278 points. Traders said sentiment remained upbeat on increased buying by domestic institutional investors and a firm trend at other Asian markets, extending gains on Wall Street following signs from the White House that US President Donald Trump's tariffs may be softer than initially feared. Major gainers that supported the upmove were Bajaj Auto, Bharti Airtel, Asian Paints, Tata Steel, Adani Ports, Hero MotoCorp, HDFC, ITC and Dr Reddy's, rising by up to 1. 03 per cent. However, Gitanjali Gems remained under selling pressure and traded 4. 82 per cent lower at Rs 15. 80. Domestic institutional investors bought shares worth a net Rs 675. 26 crore, while foreign portfolio investors sold shares worth a net Rs 364. 80 crore yesterday, provisional data showed.
english
Greenville, South Carolina played host to the latest edition of Monday Night Raw with just six days away from the annual TLC pay-per-view. Apart from the chaotic preparations that were going on for the Sunday Night show, Raw also was the stage for this year’s Slammy awards. There were some eyebrow raising winners and matches throughout the night, and apart from a few segments here and there, the weekly flagship show of WWE fell flat on the ground and failed miserably in selling TLC. However, despite the disappointing outing as a whole, there were some perks here and there that the fans enjoyed. And here is a rundown on those perks with this week’s top Monday Night Raw moments. This wasn’t a great moment to be frank but it was something that we’ve been waiting for a long time. Fans who follow NXT would know what Ric Flair’s daughter Charlotte is all about and when WWE decided to let her make a debut on Raw, it was probably a big shock. Things were picture perfect till then but once the match ended, everything turned upside down. Natalya and Charlotte, who had a match of the year contender a few months ago were given just two minutes. In the end, Natalya got the win making all those efforts put into Charlotte go in vain. The booking of the match wasn’t a great thing, but the debut surely had a shock value making it one of the top moments of this week. Brock Lesnar ended the two decade long WrestleMania streak of Undertaker; he dismantled John Cena at SummerSlam to become the WWE Champion. Seth Rollins was the catalyst for Shield’s break up and also won the Money in the bank. Daniel Bryan headlined WrestleMania and became the champion in a historic battle. These three were the clear front runners for winning this year’s Superstar of the year Slammy Award but instead, the award went to Roman Reigns. It was a great moment in the short career of his and if there were no rigging done by the company, this shows that the fans are firmly behind him. Reigns will have a great amount of momentum when he returns as well. A lot of faces were frowned when WWE rebooted the feud between Jack Swagger and Rusev. The fans thought that it was a back step for the Bulgarian Brute considering the opponents he was having before but the duo stole the show this week. WWE did a great job of putting Swagger over as a real threat to Rusev and incorporating Zeb Colter’s injury into the mix made it look better. The Real American isn’t the best talker in the business, but this time around, there were a lot of intensity oozing out of him which covered up for the shortcomings. These two men will face once again on Sunday and the odds will be equal instead of Rusev having the upper hand. There were only a handful of segments from Raw that actually sold the TLC pay-per-view, the main event was one of them. Big Show vs. John Cena as a match had nothing good to offer but what happened afterwards really changed the game. It was an all-out brawl between the heels and babyface that headlined Survivor Series and once all the smoke cleared it was the bad guys that stood tall. One name in particular that deserves a mention here is Seth Rollins. He crashed Cena through the announce table and made it clear that it won’t be a walk in the park at TLC. it would be huge if Rollins can get a win at TLC and that’s the best decision WWE could make. If there is any feud that deserves to headline TLC on Sunday, it is the one between Bray Wyatt and Dean Ambrose. Both men have been tearing down the roof right from the moment this storyline started and the further heights were scaled on Raw. Bray delivered a classic promo which showed a lot of vulnerability in him while Ambrose showed up in a typical lunatic fashion. The Eater of the Worlds revealing that the chair belonged to Sister Abigail added more personal heat between the two. This being the first ever singles TLC match where there is no championship on the line makes sure that both Ambrose and Bray would be out there on Sunday to inflict punishment.
english
Usually, when they talk about the features of the program, they understand the language in which it was compiled. Or the system requirements required to run. But there are a number of other less well-known definitions. One of them is thin clients. What is it and why are they being developed? What is a thin client? Thin clients are understood by computers or programs that work as part of a network with a terminal or client-server architecture. But they do not just function there. All or at least most of the information processing tasks are transferred to the servers to which thin clients are connected. What is it in the implementation? An example is the browser, which is used to process network applications, thanks to which you can now read these lines. For the system to work, you need a server for thin clients, otherwise it becomes impossible for such an idea. Why are they needed? To put it more simply, a thin client is an inferior computer that loads a light operating system and connects to a terminal server. It is used solely to save on hardware and software (although in rare cases, there may be other considerations). A typical thin client is a system unit that does not have a hard disk, and there is only a minimum of hardware that is required to run the operating system. The power supply, mouse, keyboard, monitor and network cable are connected. There may be other devices, but their use is possible only if they are identified and transmitted to the terminal server. Also, the required level of spending on software is reduced. There is no need to buy a license for each computer - it is only needed for one server. At the same time, costs for maintenance personnel are reduced , because only one terminal is needed to administer. As practice shows, it is rather problematic to damage a thin client (provided that no purposeful efforts are made). But at the same time, the requirements for service personnel are increasing. Especially it concerns the transfer of cases from one administrator to another. Then it is necessary that the intercessor is well versed in everything, because potentially any failure can lead to the collapse of the entire system, and then thin clients will lose their value. What is it that you know, and how do they differ from fat ones? What is taken into account when a thick and thin client is distinguished? Differences between them are: under the first one understand the usual kind of programs that can work autonomously on a separate terminal. They do not need a remote server for high-quality execution of their work. What the second is, you already know. And this is the main and at the same time the only difference that a thick and thin client has. Differences can still be cited in the features of implementation, but they all fit into a previously formulated proposition. How does it work and what types of downloads are there? How does the technology work? In general, all information can be accommodated in three points: - On the computer, through one of the possible sources is loaded thin client. The main options are: LAN, CD, HDD. - In the process of downloading a thin client (or when working with a local network to it), the network card of the computer gets its own IP address. - When the pumping of all necessary software ends, the connection to the terminal session with the server specified in the settings is created through the desktop. Access can already be given or you need a password and login. The thin client connection due to the enterprise LAN must be enabled in the server settings. How the system works, in general you already have an idea. But one of the most important is the download phase, which all thin clients have. What is it, where it can be taken, if there are no hard disks on which data is normally stored? There are two possibilities: - Download using the network. The TFTP and DHCP servers must work on the local network. In the computer itself, there must be a network card that has the BootROM property, or special drivers that emulate it. It checks the presence of all pointers, receives settings and loads the operating system. - Download the pre-installed system from DVD \ CD \ Flash \ IDE. Technology "thin client" is much more popular than it may seem at first glance. Want an example that indicates that you are using it right now? Well, we assume that a special role should be given to the most common at the moment thin clients - browsers. They are excellent examples of work on such principles. By itself, the browser has little to do with it. But the opportunities that he opens up to a computer that has a connection to the global network are huge! The machine can have a very meager software resource, but, getting the necessary data from remote servers, you can count on creating a high-quality and multi-purpose facility. All that is necessary for the user of the computer is to formulate his request, after which the necessary information will be obtained from external sources. In addition to the cases described above, it is worth highlighting one more hardware feature of a possible thin client - a special device that is structurally different from a personal computer. Such a mechanism is not equipped with a hard disk and uses a special local operating system (whose tasks include organizing a session with a terminal server so that the user can work). Also, such a device does not have special moving parts, it is produced in special cases and has completely passive cooling. Let's look at an example of a real program, where a thin client is implemented? What it is? 1C is the program that will be considered. So, in it everything is based on the work of two parts: one is the platform proper, which is necessary for work. The second is an extension that fulfills separate goals. But it can not work without a platform. It is possible to identify the 9 most popular types of protocols that are used in the development of this software. Their list is as follows: - X11 - found application in Unix-systems. - Telnet is a multiplatform protocol. It is a bi-directional eight-bit byte-oriented communication medium. - SSH is a multiplatform analog of Telnet. The main difference is the security of the transmitted data. - NX NoMachine is an improved X11 protocol. The main advantage is data compression. - Virtual Network Computing is a platform independent system. Uses a simple client-server application-layer protocol to access the necessary computers that are connected to this program. - Independent Computing Architecture is a rather imperfect way of transmitting data. This protocol is significantly displayed on the performance and requirements for the systems on which it operates. - Remote Desktop Protocol - Serves remote desktop access. Can transfer a wide range of data, and also opens up wide opportunities for using remote machines. - SPICE is a protocol for data transmission, which can be used with comfort not only in the local network, but also via the Internet. Its feature is "software ease", which allows you to quickly exchange data. This is possible due to the simplicity of the data transfer processes (which are performed not at the expense of performance). It can also work on a wide range of machine architectures. - Various closed protocols, which were developed by programmers of various firms and enterprises. They are used only, as a rule, on the territory of the enterprise for which they were made. They have a number of unique parameters, including: implementation, system requirements, architecture. The thin client in this case is fully developed for individual enterprises and protocols operating on their territory. As an example of the implementation of a thin client, you can develop such developments as: - Terminal access. - Diskless station. - LTSP. - Thinstation. The use of thin clients allows in such cases to accelerate the update of all necessary software for work.
english
<gh_stars>10-100 // Package database provides a wrapper between the database and stucts package database import ( "crypto/rand" "crypto/sha512" "encoding/base64" "errors" "strings" "golang.org/x/crypto/bcrypt" ) const sessionDictionary = "<KEY>" const accessKeyDictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_?!+=%$&/()" const sessionLength = 256 const accessKeyLength = 64 // User stores a user account including the password using bcrypt. type User struct { ID int64 Email string FirstName string LastName string Password string Admin bool Session string AccessKey string } // ListUsers returns a list of all users. func ListUsers() []*User { var u []*User db.Find(&u) return u } // GetUser returns the user for a given email address. func GetUser(email string) (*User, error) { u := &User{} db.Where("email = ?", email).First(u) if u.ID == 0 { return nil, errors.New("Could not find user.") } return u, nil } // GetUserBySession returns the user for a given session key. func GetUserBySession(key string) (*User, error) { u := &User{} db.Where("session = ?", key).First(u) if u.ID == 0 { return nil, errors.New("Could not find user.") } return u, nil } // GetUserByAccessKey returns the user for a given access key. func GetUserByAccessKey(key string) (*User, error) { u := &User{} db.Where("access_key = ?", key).First(u) if u.ID == 0 { return nil, errors.New("Could not find user.") } return u, nil } // GetUserByID returns the user for a given ID. func GetUserByID(id int64) (*User, error) { u := &User{} db.Where("ID = ?", id).First(u) if u.ID == 0 { return nil, errors.New("Could not find user.") } return u, nil } // CreateUser creates a new user. func CreateUser(email, firstName, lastName, password string, admin bool) (*User, error) { u, err := GetUser(email) if err == nil { return nil, errors.New("User with this email address already exists.") } hash, err := hashPassword(password) if err != nil { return nil, err } u = &User{ Email: email, FirstName: firstName, LastName: lastName, Password: hash, Admin: admin, } db.Create(u) return u, nil } // Update updates an existing user. func (u *User) Update(email, firstName, lastName, password string, admin bool) (*User, error) { u.FirstName = firstName u.LastName = lastName u.Email = email u.Admin = admin if password != "" { hash, err := hashPassword(password) if err != nil { return nil, err } u.Password = hash } db.Save(u) return u, nil } // Delete this user. func (u *User) Delete() error { db.Delete(u) return nil } // NewSession generates a session key and stores it. func (u *User) NewSession() string { for { key := generateSessionID(u.Email, sessionDictionary, sessionLength) _, err := GetUserBySession(key) if err != nil { u.Session = key db.Save(u) return u.Session } } } // NewAccessKey generates a access key and stores it. func (u *User) NewAccessKey() string { for { key := generateAccessKey(accessKeyDictionary, accessKeyLength) _, err := GetUserByAccessKey(key) if err != nil { u.AccessKey = key db.Save(u) return u.AccessKey } } } // generateSessionID generates a new session ID for a user combining the // email address and a random string. func generateSessionID(email, dictionary string, length int) string { var random = make([]byte, length) rand.Read(random) for k, v := range random { random[k] = dictionary[v%byte(len(dictionary))] } joined := strings.Join([]string{email, string(random)}, "") hash := sha512.New() hash.Write([]byte(joined)) return base64.StdEncoding.EncodeToString(hash.Sum(nil)) } // generateAccessKey generates a new access key for a user. func generateAccessKey(dictionary string, length int) string { var random = make([]byte, length) rand.Read(random) for k, v := range random { random[k] = dictionary[v%byte(len(dictionary))] } return string(random) } // HashPassword generates a hash using bcrypt. func hashPassword(password string) (string, error) { hash, err := bcrypt.GenerateFromPassword([]byte(password), 10) return string(hash), err } // ComparePassword returns true if the password matches the hash. func ComparePassword(password, hash string) bool { err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) if err != nil { return false } return true }
go
<!DOCTYPE html> <html> <head> <title>Dante's Website</title> <link rel="stylesheet" href="pageStyle.css"> </head> <body style="background-color: lightgray;"> <header><u>Welcome to Dante's Website</u></header> <section> <nav> <div style="font-size: 30px; text-align: center;"> <span> <a href="imagesPage.html">Images</a> <a href="videoPage.html">Video</a> <a href="linksPage.html">Links</a> <a href="squareJump.html">Square Jump</a> </span> </div> </nav> <article> <p style="font-size: 25px; padding-left: 400px; padding-right: 400px">Hi im <NAME>. I am currently a senior at UTSA studying computer science with a concentration in software engineering. This past year I worked on three personal software projects. I created a 2d platform game in Python, a personal project tracker in Java, and a searching algorithim visualizer in HTML, JavaScript, and CSS. All three of these projects were a joy to work on and strengthened my software engineering skills. </p> </article> </section> </body> </html>
html
In 2018, sharp observers of self-driving vehicles may have noticed that a few of the things have arrived. While most are still testing, only allowing employees inside—including Uber, Ford, Argo, Aurora, and Cruise—this year also saw the 25,000th passenger trip provided by a collaboration between Aptiv and Lyft, which uses a handful of autonomous vehicles to ferry riders around Las Vegas. Also this year: Autonomous shuttle companies May Mobility, Optimus Ride, and Navya beckoned members of the public aboard in Columbus, Ohio; the suburbs of Boston; and Vegas. Just this month, Waymo launched a driverless service in the Phoenix area, if a limited one. This body of evidence should help you understand the nuanced answer to an increasingly common question. That’s the not-so-whispered secret of self-driving. Most developers believe it will take decades to build a car that can drive anywhere it pleases, likes humans do today—if it ever happens at all. “I think it’s possible, but there’s no way to predict when that’s going to be,” says Ryan Chin, the CEO and cofounder of the cheekily-named Boston-based AV company Optimus Ride. In recent months, developers have made it clearer than ever that building an automated vehicle requires driving over a veritable mountain of problems. The technical challenges are numerous, and keep cropping up. How will the robots’ expensive, sometimes-sensitive sensors handle snow, rain, sand, and hail? What about construction zones and unrelenting sun glare? Can the vehicles be trained to prepare for hard-to-imagine road situations—a truck that suddenly unloads its cargo, or a roadster that makes an unusual (or irrational) maneuver on the road? How will they communicate with humans, who have their own, subtle road culture? Self-driving developers have responded by limiting where their cars go, and when, restricting them to well-mapped, carefully selected terrain. It explains why even though some folks test in tricky areas like San Francisco and Pittsburgh, most of the public-facing services stick to simple routes or calm areas with reliably good weather. May Mobility CEO Ed Olson once called this kind of geofencing a "scalpel for carving away the tricky areas." Other places like California and New York have passed more restrictive rules, requiring companies to pay larger fees to test or submit data on their operations. So fewer companies are thinking about offering their first services there. (California may be the exception, because the engineering workforce lives in the state.) Others restrict themselves to small parts of larger cities. May Mobility’s robo-shuttles only drive on fixed routes in specific cities—Detroit, Columbus, Ohio, Providence, Rhode Island. Waymo’s deployment in Phoenix is limited to an 80-square-mile area. Uber, which just returned its self-driving Volvo SUVs to the road after one of its vehicles struck and killed a woman in March, is limiting testing to a small portion of Pittsburgh. To pay off years of expensive R&D, self-driving car companies want to get their products in as many places they can, available everywhere people have places to go. The robots are here now. Where they go next is the real question. 1Story updated, 1/2/19, 5:35 PM EST: This story has been updated to clarify where Optimus Ride currently deploys autonomous shuttles. - Sci-fi promised us home robots. So where are they?
english
In this day and age, information is one of the most valuable assets. People want their questions answered, problems solved, and entertainment needs satisfied through fast and reliable Internet content that delivers. Google’s rise and consolidation can no doubt be explained by (or explain) this high demand for information. What is geolocation? A great user experience (UX) is one of the factors that influence an Internet user's decision to stay and engage with a website or leave and return to the results page. A way to improve user experience (UX) is by providing localized web content through Geolocation browser-based tools. Localized content refers to content that has been adapted to particular countries, regions, areas, etc. Internet geolocation is the process by which the geographical location of a device connected to the Internet, such as a computer or mobile phone, is detected through different processes. One of the most common ways your browser knows your location is with the HTML5 Geolocation Api (Application Programming Interface), a software interface that works with browsers such as Chrome, Safari, Firefox, and Edge to track the location of devices. The HTML5 Geolocation API gets location information from different sources like GPS, IP addresses, and Wi-Fi and Bluetooth data. How can I use geolocation to target website content? Using geolocation to redirect users to relevant localized website content is an excellent way of providing a personalized user experience that may lead to higher engagement with your website, increased conversion rates, and, ultimately, ranking higher on Google results pages. Some of the ways you can use geolocation and localized browser-based content include: - Display holiday or seasonal offers adapted to specific countries or regions on e-commerce sites. - Manage regional or language-specific website versions. These help create a feeling of familiarity and trust in users. - Adjust time zones, currency, or payment methods according to the visitor’s location. Doing this helps streamline the user or buyer’s journey through websites to get to the product, service, or piece of information they need seamlessly. - Display or conceal products or services on websites based on user location to comply with country or regional restrictions. - Provide faster page loading time by only showing geographically relevant content to visitors. To learn more about geolocation and how to implement it on your website, you can contact an experienced web designer who will walk you through the options. Happy localizing! The post Improve user experience (UX) using geolocation and website content localization appeared first on Web Design Services in Syracuse NY Blog.
english
The dream of truly wireless charging has been around for some time now. Companies such as Energous release fresh concepts and information every now and then, while Xiaomi touted its Mi Air Charge tech earlier this year. Turns out, however, the first consumer product to support the tech may come from ... Motorola? The company has announced that it is partnering with GuRu, one of the companies working on truly wireless charging, to bring the tech to future Motorola smartphones. The joint press release, unfortunately, doesn’t note when the tech might become available — so it could still be a matter of years before it’s consumer-ready. Of course, it’s important to not overreact to announcements like this. As mentioned, companies have been working on this kind of tech for years, but it still has yet to really become part of the consumer tech landscape. GuRu says that its RF Lensing tech is able to power devices from up to 30 feet away, using a propriety millimeter wave technology. This can be used to charge devices with batteries, like a smartphone, but eventually it could also be used to power devices that don’t have or need batteries — like, for example, a TV. It will likely be years before the tech can work like that, though, given the greater power demands of a TV compared to a battery-powered device that really only uses a lot of energy when it’s on. To actually use the tech, you’ll need to install small base stations in the rooms that you want to wirelessly charge in. In GuRu’s concept, these base stations will be built into things like light fixtures, meaning they’ll blend into their environment. It remains to be seen how that will impact upgradeability — it’s a lot easier to replace a wireless charging pad today that it would be to replace a light fixture.
english
<reponame>OpenLocalizationTestOrg/azure-docs-pr15_pt-BR <properties pageTitle="Implementação de contrato Mobile Azure para aplicativo de jogos" description="Cenário de aplicativo de jogos para implementar o contrato de celular do Azure" services="mobile-engagement" documentationCenter="mobile" authors="piyushjo" manager="dwrede" editor=""/> <tags ms.service="mobile-engagement" ms.devlang="na" ms.topic="article" ms.tgt_pltfrm="mobile-multiple" ms.workload="mobile" ms.date="08/19/2016" ms.author="piyushjo"/> #<a name="implement-mobile-engagement-with-gaming-app"></a>Implementar o contrato móvel com o aplicativo de jogos ## <a name="overview"></a>Visão geral Uma inicialização de jogos tenha iniciado um novo aplicativo jogo de role-play/estratégia de fichim com base. O jogo foi configurar e utilizar para 6 meses. Este jogo é um enorme sucesso e ela tem milhões de downloads e a retenção é muito alta em comparação com outros aplicativos de jogo de inicialização. A reunião de revisão trimestral, os participantes concordam que precisam para aumentar a receita média por usuário (ARPU). Pacotes de jogo Premium estão disponíveis como ofertas especiais. Esses pacotes de jogos permitem aos usuários atualizar a aparência e o desempenho de suas linhas de fichim e iscas ou soluciona no jogo. No entanto, as vendas de pacote são muito baixo. Assim que eles decidirem primeiro analisar a experiência do cliente com uma ferramenta de análise e, em seguida, para desenvolver um contrato de programa para aumentar a usando vendas avançadas segmentação. Com base no [Azure Mobile contrato - guia de Introdução com as práticas recomendadas](mobile-engagement-getting-started-best-practices.md) que eles criam uma estratégia de contrato. ##<a name="objectives-and-kpis"></a>Objetivos e KPIs Atender às principais responsáveis para o jogo. Todos concordar sobre um objetivo principal - aumentar as vendas de pacote premium por 15%. Criam Business indicadores chave de desempenho (KPIs) medida e unidade este objetivo * Em que nível do jogo esses pacotes adquiridos? * Qual é a receita por usuário, por sessão, por semana e mês? * Quais são os tipos de compra favoritas? Parte 1 do [Guia de Introdução](mobile-engagement-getting-started-best-practices.md) explica como definir os objetivos e KPIs. Com os KPIs de negócios agora definidos, o gerente de produto Mobile cria KPIs de contrato para determinar retenção e novas tendências de usuário. * Monitorar retenção e usar entre intervalos a seguir: diariamente, cada 2 dias, semanal, mensal e cada 3 meses * Contagens de usuário ativo * A classificação de aplicativo no repositório Os seguintes KPIs técnicos com base nas recomendações da equipe de TI, foram adicionados ao responder às seguintes perguntas: * O que é o meu caminho de usuário (qual página é visitada, quanto tempo os usuários gastam nele) * Número de falhas ou bugs encontrados por sessão * Quais versões do sistema operacional estão executando meus usuários? * O que é o tamanho médio da tela para meus usuários? * Que tipo de conectividade com a internet que tenho que meus usuários? Para cada KPI o gerente de produto do celular especifica os dados que ela precisa e onde ele está localizado no seu manual. ## <a name="engagement-program-and-integration"></a>Programa de contrato e integração Antes de criar um programa de contrato avançado, o Diretor de projeto Mobile responsável pelo projeto deve ter uma profunda compreensão de como e quando produtos são consumidos pelos usuários. Após 3 meses, o Diretor de projeto Mobile tenha coletado dados suficientes para aprimorar suas vendas de notificação de envio do aplicativo. Ele aprende que: * A primeira compra geralmente acontece no nível de 14. Para 90% dos casos, a compra é novo armas lendária para $3. * 80% dos casos, os usuários que tem feito uma compra, continue com o produto e fazer mais compras. * Os usuários que passaram o nível de 20, comece a gastar mais de US $10/ semana. * Os usuários tendem a comprar pacotes de premium no nível 16, 24 e 32. Graças a essa análise o Director de projeto Mobile decide criar push específico sequências de notificação para aumentar em vendas de aplicativo. Ele cria três sequências de envio que ele chama: Bem-vindo do programa, o programa de vendas e programa inativa. Para obter mais informações, consulte a [Guias estratégicos](https://github.com/Azure/azure-mobile-engagement-samples/tree/master/Playbooks) ![][1] <!--Image references--> [1]: ./media/mobile-engagement-game-scenario/notification-scenario.png <!--Link references-->
markdown
MANGALDAI: In a positive development, Darrang district has been selected for 'Prime Minister's Award for Excellence in Public Administration, 2019', in implementation of the Pradhan Mantri Sahaj Bijli Har Ghar Yojana SAUBHAGYA in the Northeast. Darrang Deputy Commissioner Pranab Kumar Sarmah, while informing about the award, said that Darrang had performed exceptionally in implementation of SAUBHAGYA scheme as all targeted households in the district have been provided power connections under the scheme within the stipulated time frame. He congratulated the implementing agencies for this achievement and he expressed optimism that this would inspire all government departments in the district to deliver quality public service. "The award will inspire us to perform better in public service delivery," said the Deputy Commissioner of Darrang while talking to The Sentinel on Tuesday evening. The 'Prime Minister's Award for Excellence in Public Administration, 2019' consists of a trophy, a scroll and an incentive of Rs 10 lakh to the awardee district. The award will be presented at Civil Services Day 2022 to be held on April 20 and 21, 2022, at Vigyan Bhavan, New Delhi. Also Watch:
english
import styled from 'styles/styled-components'; const Wrapper = styled.li` width: 100%; height: 3em; display: flex; align-items: center; position: relative; border-top: 1px solid #eee; &:first-child { border-top: none; } `; export default Wrapper;
typescript
{ "kind": "Property", "name": "HTMLMediaElement.disableRemotePlayback", "href": "https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/disableRemotePlayback", "description": "The HTMLMediaElement.disableRemotePlayback property determines whether the media element is allowed to have a remote playback UI.", "refs": [ { "name": "Remote Playback API", "href": "https://w3c.github.io/remote-playback/#the-disableremoteplayback-attribute", "description": "disableRemotePlayback - Remote Playback API" } ] }
json
Humans have only discovered around 20% of the species on Earth. This means that as much as 80% of life has still to be found & protected for future generations. A new product in farm animal feed will help to reduce the amount of CO2 in the atmosphere. Nine-in-10 people around the world live somewhere that has air quality below levels recommended by the World Health Organization. China is pushing for steel output to drop from a record of more than 1 billion tons. But moves to squeeze steelmakers have fired up prices & policymakers are worried about inflation. Otters have helped protect patches of kelp forests, an example of how important ecosystems are in the natural world. When the same thing happened 252 million years ago, 90% of all marine species died. To be effective against high pollution levels, purifiers need to run almost constantly and their filters need replacing every few months. Those components often wind up in a landfill. US climate envoy John Kerry is on a 3-day visit to India ahead of President Joe Biden’s virtual 'Leaders Summit on Climate' to be held with 40 world leaders, including PM Modi. In curbing emissions, India has advantages. Most of the factories, vehicles & power plants its economy will need have yet to be built, so it can avoid locking in polluting tech. Governments and businesses are increasingly realising that recycling is not enough to address plastic pollution. More action is needed at the upstream level. Launched in 2017 as Xi’s pet urban project, Xiong’an has faced delays and limited progress despite the talk of turning the area into the next Shenzhen or Shanghai. The government had in February estimated GDP growth for 2022-23 to be 7%. The higher-than-expected actual performance is largely due to a strong cross-sector showing in Q4. Transfer of Technology (ToT) for jet engines was the main thrust of National Security Advisor Ajit Doval's talks with his American counterpart Jack Sullivan in February. Copyright © 2023 Printline Media Pvt. Ltd. All rights reserved.
english
/* Copyright (c) 2016, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "jit-module.h" #include <jit/jit-dynamic.h> typedef struct { PyObject_HEAD jit_dynlib_handle_t obj; } PyJit_dynlib_handle; extern PyTypeObject PyJit_dynlib_handle_Type; static PyObject * PyJit_dynamic_set_debug(PyObject * UNUSED(dummy), PyObject *args, PyObject *kwargs) { PyObject *py_flag; const char *keywords[] = {"flag", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "O:set_debug", (char **) keywords, &py_flag)) { return NULL; } jit_dynlib_set_debug(PyObject_IsTrue(py_flag)); Py_RETURN_NONE; } static PyObject * PyJit_dynamic_get_suffix() { return Py_BuildValue((char *) "s", jit_dynlib_get_suffix()); } static PyMethodDef jit_dynamic_functions[] = { {(char *) "set_debug", (PyCFunction) PyJit_dynamic_set_debug, METH_KEYWORDS|METH_VARARGS, NULL }, {(char *) "get_suffix", (PyCFunction) PyJit_dynamic_get_suffix, METH_NOARGS, NULL }, {NULL, NULL, 0, NULL} }; static PyObject * PyJit__dynamic_get_symbol(PyJit_dynlib_handle *self, PyObject *args, PyObject *kwargs) { char const *name; const char *keywords[] = {"name", NULL}; void *symbol; if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "s:get_symbol", (char **) keywords, &name)) { return NULL; } if ((symbol = jit_dynlib_get_symbol(self->obj, name)) == NULL) { PyErr_Format(PyExc_ValueError, "symbol '%s' not found", name); return NULL; } return PyLong_FromVoidPtr(symbol); } static PyMethodDef PyJit_dynlib_handle_methods[] = { {(char *) "get_symbol", (PyCFunction) PyJit__dynamic_get_symbol, METH_KEYWORDS|METH_VARARGS, NULL }, {NULL, NULL, 0, NULL} }; static int PyJit_dynlib_handle__tp_init(PyJit_dynlib_handle *self, PyObject *args, PyObject *kwargs) { char const *name; const char *keywords[] = {"name", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "s", (char **) keywords, &name)) { return -1; } self->obj = jit_dynlib_open(name); if (self->obj == NULL) { PyErr_Format(PyExc_ValueError, "unable to open library '%s'", name); return -1; } return 0; } static void PyJit_dynlib_handle__tp_dealloc(PyJit_dynlib_handle *self) { jit_dynlib_handle_t tmp = self->obj; self->obj = NULL; if (tmp) { jit_dynlib_close(tmp); } Py_TYPE(self)->tp_free((PyObject*)self); } PyTypeObject PyJit_dynlib_handle_Type = { PyVarObject_HEAD_INIT(NULL, 0) (char *) "jit.dynamic.Library", /* tp_name */ sizeof(PyJit_dynlib_handle), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)PyJit_dynlib_handle__tp_dealloc, /* tp_dealloc */ (printfunc)0, /* tp_print */ (getattrfunc)NULL, /* tp_getattr */ (setattrfunc)NULL, /* tp_setattr */ (cmpfunc)NULL, /* tp_compare */ (reprfunc)NULL, /* tp_repr */ (PyNumberMethods*)NULL, /* tp_as_number */ (PySequenceMethods*)NULL, /* tp_as_sequence */ (PyMappingMethods*)NULL, /* tp_as_mapping */ (hashfunc)NULL, /* tp_hash */ (ternaryfunc)NULL, /* tp_call */ (reprfunc)NULL, /* tp_str */ (getattrofunc)NULL, /* tp_getattro */ (setattrofunc)NULL, /* tp_setattro */ (PyBufferProcs*)NULL, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ NULL, /* Documentation string */ (traverseproc)NULL, /* tp_traverse */ (inquiry)NULL, /* tp_clear */ (richcmpfunc)NULL, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)NULL, /* tp_iter */ (iternextfunc)NULL, /* tp_iternext */ (struct PyMethodDef*)PyJit_dynlib_handle_methods, /* tp_methods */ (struct PyMemberDef*)0, /* tp_members */ 0, /* tp_getset */ NULL, /* tp_base */ NULL, /* tp_dict */ (descrgetfunc)NULL, /* tp_descr_get */ (descrsetfunc)NULL, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)PyJit_dynlib_handle__tp_init, /* tp_init */ (allocfunc)PyType_GenericAlloc, /* tp_alloc */ (newfunc)PyType_GenericNew, /* tp_new */ (freefunc)0, /* tp_free */ (inquiry)NULL, /* tp_is_gc */ NULL, /* tp_bases */ NULL, /* tp_mro */ NULL, /* tp_cache */ NULL, /* tp_subclasses */ NULL, /* tp_weaklist */ (destructor) NULL /* tp_del */ }; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef jit_dynamic_moduledef = { PyModuleDef_HEAD_INIT, "jit.dynamic", NULL, -1, jit_dynamic_functions, }; #endif PyObject * initjit_dynamic(void) { PyObject *m; #if PY_VERSION_HEX >= 0x03000000 m = PyModule_Create(&jit_dynamic_moduledef); #else m = Py_InitModule3((char *) "jit.dynamic", jit_dynamic_functions, NULL); #endif if (m == NULL) { return NULL; } /* Register the 'jit_dynlib_handle_t' class */ if (PyType_Ready(&PyJit_dynlib_handle_Type)) { return NULL; } PyModule_AddObject(m, (char *) "Library", (PyObject *) &PyJit_dynlib_handle_Type); return m; }
cpp
New Delhi: Around 300 candidates appeared in the Common Entrance Test for Agniveer candidates. The entrance exam was held at Sainik School, Badami Bagh Cantonment Area, Srinagar. The written exam was conducted for the posts of General Duty, Technical, Clerk or Store Keeper Technical and Tradesman in the districts of Srinagar, Anantnag, Baramulla, Pulwama, Badgam, Kupwara, Shopian, Ganderbal, Bandipora, Kulgam, Ladakh and Kargil Leh. Defence PRO, Srinagar informed that the exam result will be declared on the official website www. joinindianarmy. nic. in and no separate letter will be sent to the candidates. Candidates have also been asked to check and report the result at the Army Recruiting Office, Srinagar on the third day of the result declaration. Then the eligibility documents of eligible candidates will be collected. Selected candidates should report for training by December 31. The entrance exam was conducted for those who qualified in the physical and medical test held from September 17 to 30.
english
Galle (Sri Lanka), April 18 (IANS) Left-arm spinner Prabath Jayasuriya picked up his second ten-wicket haul in a Test match as Sri Lanka defeated Ireland by an innings and 280 runs in the first Test here on Tuesday. Unbeaten hundreds from Dinesh Chandimal (102*) and Sadeera Samarawickrama (104*) after Dimuth Karunaratne (179) and Kusal Mendis' (140) massive knocks had given Sri Lanka a big total of 591/6 declared on Day Two. Prabath Jayasuriya then went on to dominate the Ireland batters, taking a five-wicket haul on day two and ending with a seven-fer (7-52) in the innings. Bowled out for 143, Ireland couldn't do much better following on, finishing on 168 with Harry Tector, Curtis Campher and George Dockrell getting starts. In the second innings on Tuesday, Jayasuriya claimed 3-56 in 24. 1 overs. Ramesh Mendis was the wrecker-in-chief in the second innings, claiming 4-76 in 20 overs while Vishwa Fernando claimed 2-3 in four overs. For Ireland, Harry Tector top scored with 42 off 95 balls while George Dockrell scored 32 off 54 and Curtis Campher contributed 30 off 76 deliveries. The innings and 280-run victory give Sri Lanka a 1-0 lead in the two-match Test series. Prabath Jayasuriya took the honours in the bowing department. In six Tests thus far, Jayasuriya has five five-wicket hauls in an innings and two match hauls of 10 wickets or more. The left-arm spinner, who won the Player of the Match award, finished with figures of 10/108. He has already raced to 43 Test wickets, 39 of those coming in Galle alone, where he has now played four Tests and taken five five-wicket hauls. His tally of 43 wickets after six Tests is the joint-third-best in Test cricket history. Only Charles Turner (50) and Vernon Philander (45) have more after the first six Tests. The second and final Test begins in Galle on April 24. Brief scores: Disclaimer: This story has not been edited by the Sakshi Post team and is auto-generated from syndicated feed.
english
<filename>reseq/AdapterStats.cpp #include "AdapterStats.h" using reseq::AdapterStats; #include <algorithm> using std::max; using std::max_element; using std::min; using std::sort; #include <array> using std::array; #include <cmath> using std::ceil; #include <fstream> using std::ifstream; using std::ofstream; #include <iterator> using std::distance; #include <list> using std::list; //include <string> using std::string; //include <vector> using std::vector; #include <utility> using std::pair; #include "reportingUtils.hpp" //include <seqan/bam_io.h> using seqan::BamAlignmentRecord; using seqan::CharString; using seqan::Dna; using seqan::Dna5; using seqan::DnaString; using seqan::Exception; using seqan::reverseComplement; using seqan::StringSet; #include <seqan/seq_io.h> using seqan::readRecords; using seqan::SeqFileIn; #include "skewer/src/matrix.h" //include "utilities.hpp" using reseq::utilities::at; using reseq::utilities::SetToMax; inline reseq::uintSeqLen AdapterStats::GetStartPosOnReference(const BamAlignmentRecord &record){ uintSeqLen start_pos = record.beginPos; if('S' == at(record.cigar, 0).operation){ if(at(record.cigar, 0).count < start_pos){ start_pos -= at(record.cigar, 0).count; } else{ start_pos = 0; } } else if('H' == at(record.cigar, 0).operation){ if( 2 <= length(record.cigar) && 'S' == at(record.cigar, 1).operation){ if(at(record.cigar, 1).count < start_pos){ start_pos -= at(record.cigar, 1).count; } else{ start_pos = 0; } } } return start_pos; } reseq::uintReadLen AdapterStats::CountErrors(uintReadLen &last_error_pos, const BamAlignmentRecord &record, const Reference &reference){ uintReadLen num_errors(0), read_pos(0); auto ref_pos = GetStartPosOnReference(record); auto &ref_seq = reference.ReferenceSequence(record.rID); for( const auto &cigar_element : record.cigar ){ switch( cigar_element.operation ){ case 'M': case '=': case 'X': case 'S': // Treat soft-clipping as match, so that bwa and bowtie2 behave the same for(auto i=cigar_element.count; i--; ){ if( ref_pos >= length(ref_seq) || at(ref_seq, ref_pos++) != at(record.seq, read_pos++) ){ if( !hasFlagRC(record) || !num_errors ){ // In case of a normal read always overwrite errors to get the last; in case of a reversed read stop after the first last_error_pos = read_pos - 1; } ++num_errors; } } break; case 'N': case 'D': // Deletions can be attributed to the base before or after the deletion, choose the one resulting in the lowest last_error_pos in the end (so shortest adapter required length) if( hasFlagRC(record) ){ if( !num_errors ){ last_error_pos = read_pos; } } else{ last_error_pos = read_pos-1; } num_errors += cigar_element.count; ref_pos += cigar_element.count; break; case 'I': // Insertions can be attributed to the first or last base of the insertion, choose the one resulting in the lowest last_error_pos in the end (so shortest adapter required length) if( hasFlagRC(record) ){ if( !num_errors ){ last_error_pos = read_pos; } } else{ last_error_pos = read_pos+cigar_element.count-1; } num_errors += cigar_element.count; read_pos += cigar_element.count; break; default: printErr << "Unknown cigar operation: " << cigar_element.operation << std::endl; } } // Reverse position for normal reads to get them counted from the end of the read if( !hasFlagRC(record) ){ last_error_pos = length(record.seq) - 1 - last_error_pos; } return num_errors; } bool AdapterStats::VerifyInsert(const CharString &read1, const CharString &read2, intSeqShift pos1, intSeqShift pos2){ if( 1 > pos1 || 1 > pos2){ return true; } if( pos1 == pos2 ){ uintReadLen matches(0), i2(0); for(uintReadLen i1=pos1; i1--; ){ switch(at(read1, i1)){ case 'A': if( 'T' == at(read2, i2) ){ ++matches; } break; case 'C': if( 'G' == at(read2, i2) ){ ++matches; } break; case 'G': if( 'C' == at(read2, i2) ){ ++matches; } break; case 'T': if( 'A' == at(read2, i2) ){ ++matches; } break; } ++i2; } if(matches > pos1*95/100){ return true; } } return false; } bool AdapterStats::AdaptersAmbigous(const seqan::DnaString &adaper1, const seqan::DnaString &adaper2, uintReadLen max_length){ auto compare_until = max( static_cast<uintReadLen>(max(length(adaper1), length(adaper2))), max_length ); uintReadLen num_diff = 0; for( auto pos=compare_until; pos--; ){ if(at(adaper1, pos) != at(adaper2, pos)){ ++num_diff; } } return num_diff < 2+compare_until/10; } AdapterStats::AdapterStats(){ // Clear adapter_overrun_bases_ for( auto i = tmp_overrun_bases_.size(); i--; ){ tmp_overrun_bases_.at(i) = 0; } } bool AdapterStats::LoadAdapters(const char *adapter_file, const char *adapter_matrix){ StringSet<CharString> ids; StringSet<DnaString> seqs; printInfo << "Loading adapters from: " << adapter_file << std::endl; printInfo << "Loading adapter combination matrix from: " << adapter_matrix << std::endl; try{ SeqFileIn seq_file_in(adapter_file); readRecords(ids, seqs, seq_file_in); } catch(const Exception &e){ printErr << "Could not load adapter sequences: " << e.what() << std::endl; return false; } vector<string> matrix; matrix.resize(length(seqs)); ifstream matrix_file; matrix_file.open(adapter_matrix); uintAdapterId nline=0; while( length(seqs) > nline && matrix_file.good() ){ getline(matrix_file, matrix.at(nline++)); } matrix_file.close(); // Check if matrix fits to adapter file bool error = false; if(length(seqs) != nline ){ printErr << "Matrix has less rows than adapters loaded from file." << std::endl; error = true; } matrix_file.get(); // Test if file is at the end if( !matrix_file.eof() ){ printErr << "Matrix has more rows than adapters loaded from file." << std::endl; error = true; } for( ; nline--; ){ if( length(seqs) > matrix.at(nline).size() ){ printErr << "Matrix row " << nline << " has less columns than adapters loaded from file." << std::endl; error = true; } else if( length(seqs) < matrix.at(nline).size() ){ printErr << "Matrix row " << nline << " has more columns than adapters loaded from file." << std::endl; error = true; } for(auto nchar = matrix.at(nline).size(); nchar--; ){ if( '0' != matrix.at(nline).at(nchar) && '1' != matrix.at(nline).at(nchar)){ printErr << "Not allowed character '" << matrix.at(nline).at(nchar) << "' in matrix at line " << nline << ", position " << nchar << std::endl; error = true; } } } if(error){ return false; } // Get adapters that are allowed for first or second array<vector<pair<DnaString, uintAdapterId>>, 2> adapter_list; for(uintTempSeq seg=2; seg--; ){ adapter_list.at(seg).reserve(length(seqs)); } for( nline = length(seqs); nline--; ){ for(auto nchar = length(seqs); nchar--; ){ if( '1' == matrix.at(nline).at(nchar) ){ // If one adapter pair has this adaptor as first, add it to first and continue with the next adapter adapter_list.at(0).push_back({at(seqs, nline),nline}); break; } } } for(auto nchar = length(seqs); nchar--; ){ for( nline = length(seqs); nline--; ){ if( '1' == matrix.at(nline).at(nchar) ){ adapter_list.at(1).push_back({at(seqs, nchar),nchar}); break; } } } for(uintTempSeq seg=2; seg--; ){ // Also add reverse complement of adapters (as the direction is different depending on the sequencing machine Hiseq2000 vs. 4000) adapter_list.at(seg).reserve(adapter_list.at(seg).size()*2); for( uintAdapterId i=adapter_list.at(seg).size(); i--;){ adapter_list.at(seg).push_back(adapter_list.at(seg).at(i)); reverseComplement(adapter_list.at(seg).back().first); adapter_list.at(seg).back().second += length(ids); } // Sort adapters by sequence (necessary for SolveAmbiguities function later) and fill the class variables sort(adapter_list.at(seg)); seqs_.at(seg).reserve(adapter_list.at(seg).size()); names_.at(seg).reserve(adapter_list.at(seg).size()); for( auto &adapter : adapter_list.at(seg) ){ seqs_.at(seg).push_back(adapter.first); if(adapter.second < length(ids)){ names_.at(seg).push_back((string(toCString(at(ids, adapter.second)))+"_f").c_str()); } else{ names_.at(seg).push_back((string(toCString(at(ids, adapter.second-length(ids))))+"_r").c_str()); } } } // Fill adapter_combinations_ with the valid combinations of both adapters combinations_.clear(); combinations_.resize(adapter_list.at(0).size(), vector<bool>(adapter_list.at(1).size(), true) ); // Set all combinations by default to valid for( auto adapter1 = adapter_list.at(0).size(); adapter1--; ){ for( auto adapter2 = adapter_list.at(1).size(); adapter2--; ){ if('0' == matrix.at( adapter_list.at(0).at(adapter1).second%length(ids) ).at( adapter_list.at(1).at(adapter2).second%length(ids) )){ // Combination not valid combinations_.at(adapter1).at(adapter2) = false; } } } return true; } void AdapterStats::PrepareAdapterPrediction(){ if(0 == combinations_.size()){ for(uintTempSeq template_segment=2; template_segment--; ){ adapter_kmers_.at(template_segment).Prepare(); adapter_start_kmers_.at(template_segment).resize(adapter_kmers_.at(template_segment).counts_.size(), 0); } } } void AdapterStats::ExtractAdapterPart(const seqan::BamAlignmentRecord &record){ if(0 == combinations_.size()){ if( hasFlagUnmapped(record) || hasFlagNextUnmapped(record) ){ auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceForward(record.seq, 0); if( adapter_start >= 0 ){ ++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start); } } else if( hasFlagRC(record) ){ if(record.beginPos <= record.pNext && record.beginPos+length(record.seq) > record.pNext){ uintReadLen clipped(0); if('S' == at(record.cigar, 0).operation){ clipped = at(record.cigar, 0).count; } else if('H' == at(record.cigar, 0).operation){ clipped = at(record.cigar, 0).count; if('S' == at(record.cigar, 1).operation){ clipped += at(record.cigar, 1).count; } } auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceReverse(record.seq, clipped + record.pNext-record.beginPos); if( adapter_start >= 0 ){ ++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start); } } } else{ if(record.beginPos >= record.pNext && record.beginPos < record.pNext+length(record.seq)){ uintReadLen clipped(0); if('S' == at(record.cigar, length(record.cigar)-1).operation){ clipped = at(record.cigar, length(record.cigar)-1).count; } else if('H' == at(record.cigar, length(record.cigar)-1).operation){ clipped = at(record.cigar, length(record.cigar)-1).count; if('S' == at(record.cigar, length(record.cigar)-2).operation){ clipped += at(record.cigar, length(record.cigar)-2).count; } } auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceForward(record.seq, length(record.seq) - max(clipped, static_cast<uintReadLen>(record.beginPos - record.pNext))); if( adapter_start >= 0 ){ ++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start); } } } } } bool AdapterStats::PredictAdapters(){ if(0 == combinations_.size()){ std::vector<bool> use_kmer; uintBaseCall max_extension, second_highest; auto base = adapter_kmers_.at(0).counts_.size() >> 2; uintReadLen adapter_ext_pos(0); ofstream myfile; if(kAdapterSearchInfoFile){ myfile.open(kAdapterSearchInfoFile); myfile << "template_segment, tries_left, position, kmer, counts" << std::endl; } for(uintTempSeq template_segment=2; template_segment--; ){ // Find start of adapter use_kmer.clear(); use_kmer.resize(adapter_kmers_.at(template_segment).counts_.size(), true); use_kmer.at(0) = false; // Ignore all A's as possible adapter Kmer<kKmerLength>::intType excluded_kmer; for(uintBaseCall nuc=3; --nuc; ){ excluded_kmer = nuc; for(auto i=kKmerLength-1; i--; ){ excluded_kmer <<= 2; excluded_kmer += nuc; } use_kmer.at(excluded_kmer) = false; // Ignore all C's/G's as possible adapter } use_kmer.at( adapter_kmers_.at(template_segment).counts_.size()-1 ) = false; // Ignore all T's as possible adapter DnaString adapter; reserve(adapter, 50); bool found_adapter = false; uintNumFits tries = 100; while(!found_adapter && tries--){ Kmer<kKmerLength>::intType max_kmer = 1; while(!use_kmer.at(max_kmer)){ ++max_kmer; } for(Kmer<kKmerLength>::intType kmer = max_kmer+1; kmer < adapter_start_kmers_.at(template_segment).size(); ++kmer ){ if( use_kmer.at(kmer) && adapter_start_kmers_.at(template_segment).at(kmer) > adapter_start_kmers_.at(template_segment).at(max_kmer) ){ max_kmer = kmer; } } use_kmer.at(max_kmer) = false; // Prevent endless circle auto kmer = max_kmer; resize(adapter, kKmerLength); for(uintReadLen pos=kKmerLength; pos--; ){ at(adapter, pos) = kmer%4; kmer >>= 2; } if(kAdapterSearchInfoFile){ // Sort kmers to get top 100 std::vector<std::pair<uintNucCount, Kmer<kKmerLength>::intType>> sorted_kmers; sorted_kmers.reserve(adapter_start_kmers_.size()); for(Kmer<kKmerLength>::intType kmer = 0; kmer < adapter_start_kmers_.at(template_segment).size(); ++kmer ){ sorted_kmers.emplace_back(adapter_start_kmers_.at(template_segment).at(kmer), kmer); } sort(sorted_kmers.begin(),sorted_kmers.end()); string kmer_nucs; kmer_nucs.resize(kKmerLength); for(auto sk = sorted_kmers.size(); sk-- > sorted_kmers.size()-100; ){ myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Start, "; kmer = sorted_kmers.at(sk).second; for(uintReadLen pos=kKmerLength; pos--; ){ kmer_nucs.at(pos) = static_cast<Dna>(kmer%4); kmer >>= 2; } myfile << kmer_nucs << ", " << sorted_kmers.at(sk).first << std::endl; } } // Restore start cut kmer = max_kmer; if(kAdapterSearchInfoFile){ adapter_ext_pos = 0; } while(true){ kmer >>= 2; if(kAdapterSearchInfoFile){ myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << ++adapter_ext_pos << ", A"; for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){ myfile << at(adapter, pos); } myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", C"; for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){ myfile << at(adapter, pos); } myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+base) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", G"; for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){ myfile << at(adapter, pos); } myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+2*base) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", T"; for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){ myfile << at(adapter, pos); } myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+3*base) << std::endl; } if( adapter_kmers_.at(template_segment).counts_.at(kmer+3*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+2*base) ){ max_extension = 3; second_highest = 2; } else{ max_extension = 2; second_highest = 3; } for(uintBaseCall ext=2; ext--; ){ if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+max_extension*base) ){ second_highest = max_extension; max_extension = ext; } else if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+second_highest*base) ){ second_highest = ext; } } kmer += base*max_extension; if( use_kmer.at(kmer) && adapter_kmers_.at(template_segment).counts_.at(kmer) > 100 && adapter_kmers_.at(template_segment).counts_.at(kmer) > 5*adapter_kmers_.at(template_segment).counts_.at(kmer-max_extension*base+second_highest*base) ){ insertValue(adapter, 0, static_cast<Dna>(max_extension) ); use_kmer.at(kmer) = false; // Prevent endless circle } else{ break; } } // Extend adapter kmer = max_kmer; if(kAdapterSearchInfoFile){ adapter_ext_pos = 0; } while(true){ kmer <<= 2; kmer %= adapter_kmers_.at(template_segment).counts_.size(); if(kAdapterSearchInfoFile){ myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << ++adapter_ext_pos << ", "; for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){ myfile << at(adapter, pos); } myfile << "A, " << adapter_kmers_.at(template_segment).counts_.at(kmer) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", "; for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){ myfile << at(adapter, pos); } myfile << "C, " << adapter_kmers_.at(template_segment).counts_.at(kmer+1) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", "; for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){ myfile << at(adapter, pos); } myfile << "G, " << adapter_kmers_.at(template_segment).counts_.at(kmer+2) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", "; for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){ myfile << at(adapter, pos); } myfile << "T, " << adapter_kmers_.at(template_segment).counts_.at(kmer+3) << std::endl; } if( adapter_kmers_.at(template_segment).counts_.at(kmer+3) > adapter_kmers_.at(template_segment).counts_.at(kmer+2) ){ max_extension = 3; second_highest = 2; } else{ max_extension = 2; second_highest = 3; } for(uintBaseCall ext=2; ext--; ){ if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext) > adapter_kmers_.at(template_segment).counts_.at(kmer+max_extension) ){ second_highest = max_extension; max_extension = ext; } else if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext) > adapter_kmers_.at(template_segment).counts_.at(kmer+second_highest) ){ second_highest = ext; } } kmer += max_extension; if( use_kmer.at(kmer) && adapter_kmers_.at(template_segment).counts_.at(kmer) > 100 && adapter_kmers_.at(template_segment).counts_.at(kmer) > 5*adapter_kmers_.at(template_segment).counts_.at(kmer-max_extension+second_highest) ){ adapter += static_cast<Dna>(max_extension); use_kmer.at(kmer) = false; // Prevent endless circle } else{ break; } } // Remove A's at end while(length(adapter) && 0 == back(adapter)){ eraseBack(adapter); } if( 30 > length(adapter) ){ printInfo << "Detected non-extendible sequence '" << adapter << "' as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << std::endl; } else if( 120 < length(adapter) ){ printErr << "Detected very long sequence '" << adapter << "' as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << ", which is likely part of the genome." << std::endl; if(kAdapterSearchInfoFile){ myfile.close(); } return false; } else{ printInfo << "Detected adapter " << static_cast<uintTempSeqPrint>(template_segment+1) << ": " << adapter << std::endl; found_adapter = true; } } if(!found_adapter){ printErr << "Only non-extendible sequences were found as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << std::endl; if(kAdapterSearchInfoFile){ myfile.close(); } return false; } seqs_.at(template_segment).push_back(adapter); names_.at(template_segment).emplace_back(toCString(CharString(adapter))); // Free memory adapter_kmers_.at(template_segment).Clear(); adapter_start_kmers_.at(template_segment).clear(); adapter_start_kmers_.at(template_segment).shrink_to_fit(); } if(kAdapterSearchInfoFile){ myfile.close(); } combinations_.resize( 1, vector<bool>(1, true) ); // Set the single combinations to valid } return true; } void AdapterStats::PrepareAdapters(uintReadLen size_read_length, uintQual phred_quality_offset){ // Resize adapter vectors tmp_counts_.resize(seqs_.at(0).size()); for( auto &dim1 : tmp_counts_ ){ dim1.resize(seqs_.at(1).size()); for( auto &dim2 : dim1 ){ dim2.resize(size_read_length); for( auto &dim3 : dim2 ){ dim3.resize(size_read_length); } } } for(uintTempSeq seg=2; seg--; ){ tmp_start_cut_.at(seg).resize(seqs_.at(seg).size()); for( auto &dim1 : tmp_start_cut_.at(seg) ){ dim1.resize(size_read_length); } } tmp_polya_tail_length_.resize(size_read_length); // Prepare skewer matrix for adapter identification skewer::cMatrix::InitParameters(skewer::TRIM_PE, 0.1, 0.03, phred_quality_offset, false); // 0.1 and 0.03 are the default values from the skewer software for( auto &adapter : seqs_.at(0) ){ skewer::cMatrix::AddAdapter(skewer::cMatrix::firstAdapters, toCString(static_cast<CharString>(adapter)), length(adapter), skewer::TRIM_TAIL); } for( auto &adapter : seqs_.at(1) ){ skewer::cMatrix::AddAdapter(skewer::cMatrix::secondAdapters, toCString(static_cast<CharString>(adapter)), length(adapter), skewer::TRIM_TAIL); } skewer::cMatrix::CalculateIndices(combinations_, seqs_.at(0).size(), seqs_.at(1).size()); } bool AdapterStats::Detect(uintReadLen &adapter_position_first, uintReadLen &adapter_position_second, const BamAlignmentRecord &record_first, const BamAlignmentRecord &record_second, const Reference &reference, bool properly_mapped){ bool search_adapters(true); // Determine minimum adapter length int i_min_overlap(0); if( hasFlagUnmapped(record_first) || hasFlagUnmapped(record_second) ){ uintReadLen last_error_pos(kMinimumAdapterLengthUnmapped-1); // Case of both reads unmapped if( (hasFlagUnmapped(record_first) || CountErrors(last_error_pos, record_first, reference)) && (hasFlagUnmapped(record_second) || CountErrors(last_error_pos, record_second, reference)) ){ i_min_overlap = last_error_pos+1; // +1 because it is a position starting at 0 and we need a length } else{ // In case one of the reads is a perfect match don't look for adapters search_adapters = false; } } else{ uintReadLen last_error_pos1, last_error_pos2; if( CountErrors(last_error_pos1, record_first, reference) && CountErrors(last_error_pos2, record_second, reference) ){ i_min_overlap = max(last_error_pos1, last_error_pos2)+1; // A perfect matching piece cannot be an adapter, so adapter must be at least reach last error in both reads } else{ search_adapters = false; } } if(search_adapters){ // Fill read1, read2 with first/second measured in sequencer(by fastq file) not by position in bam file and convert to measurement/fastq direction (not reference/bam direction) const CharString *qual1, *qual2; CharString read1, read2, reversed_qual; if( hasFlagLast(record_second) ){ read1 = record_first.seq; if( hasFlagRC(record_first) ){ reverseComplement(read1); // Reverses in place, so don't let it act on the record sequence itself reversed_qual = record_first.qual; reverse(reversed_qual); qual1 = &reversed_qual; } else{ qual1 = &record_first.qual; } read2 = record_second.seq; if( hasFlagRC(record_second) ){ reverseComplement(read2); // Reverses in place, so don't let it act on the record sequence itself reversed_qual = record_second.qual; reverse(reversed_qual); qual2 = &reversed_qual; } else{ qual2 = &record_second.qual; } } else{ read1 = record_second.seq; if( hasFlagRC(record_second) ){ reverseComplement(read1); // Reverses in place, so don't let it act on the record sequence itself reversed_qual = record_second.qual; reverse(reversed_qual); qual1 = &reversed_qual; } else{ qual1 = &record_second.qual; } read2 = record_first.seq; if( hasFlagRC(record_first) ){ reverseComplement(read2); // Reverses in place, so don't let it act on the record sequence itself reversed_qual = record_first.qual; reverse(reversed_qual); qual2 = &reversed_qual; } else{ qual2 = &record_first.qual; } } auto index1 = skewer::cMatrix::findAdapter(toCString(read1), length(read1), reinterpret_cast<unsigned char *>(toCString(*qual1)), length(*qual1), i_min_overlap); if( index1.bc-- ){ // Adapter has been detected for first read (bc is now index of adapter) auto index2 = skewer::cMatrix::findAdapter2(toCString(read2), length(read2), reinterpret_cast<unsigned char *>(toCString(*qual2)), length(*qual2), i_min_overlap); if( index2.bc-- && combinations_.at(index1.bc).at(index2.bc)){ // Adapter has been detected also for second read and it is a valid pair with the first if( 2 > max(index1.pos,index2.pos) - min(index1.pos,index2.pos) ){ // Allow a single one-base indel in the insert between the adapters if( properly_mapped || VerifyInsert(read1, read2, index1.pos, index2.pos) ){ // Stats that need to be aware of cut length bool poly_a_tail = true; uintReadLen poly_a_tail_length = 0; for(uintReadLen pos=index1.pos + length(seqs_.at(0).at(index1.bc)); pos < length(read1); ++pos){ if(poly_a_tail){ if('A' == at(read1, pos)){ ++poly_a_tail_length; } else{ poly_a_tail=false; ++tmp_polya_tail_length_.at(poly_a_tail_length); } } if(!poly_a_tail){ ++tmp_overrun_bases_.at(Dna5(at(read1, pos))); } } poly_a_tail = true; poly_a_tail_length = 0; for(uintReadLen pos=index2.pos + length(seqs_.at(1).at(index2.bc)); pos < length(read2); ++pos){ if(poly_a_tail){ if('A' == at(read2, pos)){ ++poly_a_tail_length; } else{ poly_a_tail=false; ++tmp_polya_tail_length_.at(poly_a_tail_length); } } if(!poly_a_tail){ ++tmp_overrun_bases_.at(Dna5(at(read2, pos))); } } // If the read starts with an adapter note down if and how much it has been cut of at the beginning (position below 0) and set position to 0 for the further stats if(1>index1.pos){ ++tmp_start_cut_.at(0).at(index1.bc).at(-index1.pos); index1.pos = 0; } if(1>index2.pos){ ++tmp_start_cut_.at(1).at(index2.bc).at(-index2.pos); index2.pos = 0; } // Set return values if( hasFlagLast(record_first) ){ adapter_position_first = index2.pos; adapter_position_second = index1.pos; } else{ adapter_position_first = index1.pos; adapter_position_second = index2.pos; } // Fill in stats ++tmp_counts_.at(index1.bc).at(index2.bc).at(length(read1)-index1.pos).at(length(read2)-index2.pos); return true; } } } } } // If no adapter where found fill in read length adapter_position_first = length(record_first.seq); adapter_position_second = length(record_second.seq); return false; } void AdapterStats::Finalize(){ // Copy to final vectors counts_.resize(tmp_counts_.size()); for( auto i = tmp_counts_.size(); i--; ){ counts_.at(i).resize(tmp_counts_.at(i).size()); for( auto j = tmp_counts_.at(i).size(); j--; ){ counts_.at(i).at(j).Acquire(tmp_counts_.at(i).at(j)); } } for(uintTempSeq seg=2; seg--; ){ start_cut_.at(seg).resize(tmp_start_cut_.at(seg).size()); for( auto i = tmp_start_cut_.at(seg).size(); i--; ){ start_cut_.at(seg).at(i).Acquire(tmp_start_cut_.at(seg).at(i)); } } polya_tail_length_.Acquire(tmp_polya_tail_length_); for( auto i = tmp_overrun_bases_.size(); i--; ){ overrun_bases_.at(i) = tmp_overrun_bases_.at(i); } } void AdapterStats::SumCounts(){ for(uintTempSeq seg=2; seg--; ){ count_sum_.at(seg).clear(); count_sum_.at(seg).resize(start_cut_.at(seg).size(), 0); } // Sum adapters starting from length where adapters are unambiguous (sorted by content: so simply first position that differs from adapter before and after) uintFragCount sum; uintReadLen first_diff_before_a1(0), first_diff_after_a1, first_diff_before_a2, first_diff_after_a2; for( auto a1=counts_.size(); a1--; ){ first_diff_after_a1 = 0; if(a1){ // Not last in loop while(first_diff_after_a1 < min(length(seqs_.at(0).at(a1)), length(seqs_.at(0).at(a1-1))) && at(seqs_.at(0).at(a1), first_diff_after_a1) == at(seqs_.at(0).at(a1-1), first_diff_after_a1) ){ ++first_diff_after_a1; } } first_diff_before_a2 = 0; for( auto a2=counts_.at(0).size(); a2--; ){ // All vectors i are the same length so we can simply take the length of 0 first_diff_after_a2 = 0; if(a2){ // Not last in loop while(first_diff_after_a2 < min(length(seqs_.at(1).at(a2)), length(seqs_.at(1).at(a2-1))) && at(seqs_.at(1).at(a2), first_diff_after_a2) == at(seqs_.at(1).at(a2-1), first_diff_after_a2) ){ ++first_diff_after_a2; } } sum = 0; for( auto pos1 = max(max(first_diff_before_a1,first_diff_after_a1), static_cast<uintReadLen>(counts_.at(a1).at(a2).from())); pos1 < counts_.at(a1).at(a2).to(); ++pos1){ for( auto pos2 = max(max(first_diff_before_a2,first_diff_after_a2), static_cast<uintReadLen>(counts_.at(a1).at(a2).at(pos1).from())); pos2 < counts_.at(a1).at(a2).at(pos1).to(); ++pos2){ sum += counts_.at(a1).at(a2).at(pos1).at(pos2); } } count_sum_.at(0).at(a1) += sum; count_sum_.at(1).at(a2) += sum; first_diff_before_a2 = first_diff_after_a2; } first_diff_before_a1 = first_diff_after_a1; } } void AdapterStats::Shrink(){ for( auto &dim1 : counts_){ for( auto &adapter_pair : dim1){ ShrinkVect(adapter_pair); } } } void AdapterStats::PrepareSimulation(){ for(uintTempSeq seg=2; seg--; ){ significant_count_.at(seg).clear(); significant_count_.at(seg).resize(count_sum_.at(seg).size(), 0); uintFragCount threshold = ceil(*max_element(count_sum_.at(seg).begin(), count_sum_.at(seg).end()) * kMinFractionOfMaximumForSimulation); for(auto i=significant_count_.at(seg).size(); i--; ){ if(count_sum_.at(seg).at(i) < threshold){ significant_count_.at(seg).at(i) = 0; } else{ significant_count_.at(seg).at(i) = count_sum_.at(seg).at(i); } } } }
cpp
<reponame>dubbsong/dubbsong.github.io --- layout: post title: "squareSum.js (8kyu 28)" categories: dev tags: algorithm --- ###### [Codewars](https://www.codewars.com) 알고리즘 풀이 <br> #### Problem - Complete the square sum method so that it squares each number passed into it and then sums the results together. - 각 숫자를 제곱한 다음, 각 값을 합산한다. <br> #### Solution 01 ```js function squareSum(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i] * arr[i]; } return sum; } squareSum([1, 2, 3, 4]); // 30 (1 + 4 + 9 + 16) squareSum([2, 2, 2, 2]); // 16 (4 + 4 + 4 + 4) ``` <br> #### Solution 02 ```js function squareSum(arr) { return arr.map(i => i * i).reduce((sum, i) => sum + i, 0); } squareSum([1, 2, 3, 4]); // 30 (1 + 4 + 9 + 16) squareSum([2, 2, 2, 2]); // 16 (4 + 4 + 4 + 4) ``` > `map()` 메소드 > > 배열 내 모든 element에 대해, 호출한 함수의 결과를 모아 새 배열로 반환한다. > `reduce()` 메소드 > > 배열을 하나의 값으로 줄이고, 그 값을 반환한다. <br> #### Solution 03 ```js function squareSum(arr) { return arr.reduce((sum, i) => sum + i * i, 0); } squareSum([1, 2, 3, 4]); // 30 (1 + 4 + 9 + 16) squareSum([2, 2, 2, 2]); // 16 (4 + 4 + 4 + 4) ``` <br> #### Solution 04 ```js function squareSum(arr) { let sum = 0; arr.forEach(i => { sum += i * i; }); return sum; } squareSum([1, 2, 3, 4]); // 30 (1 + 4 + 9 + 16) squareSum([2, 2, 2, 2]); // 16 (4 + 4 + 4 + 4) ``` > `forEach()` 메소드 > > 배열의 각 element에 대해, 제공된 함수를 차례로 한 번씩 호출한다. <br> <br>
markdown
{ "smart-spaces": { "short_name": "Smart Spaces", "name": "Smart Spaces", "title": "Smart Spaces", "accelerator_type": "Solution Accelerator", "classification": "Sustainability", "solution_area": "Data & AI,BizApps,Apps & Infrastructure", "status": "Work In Progress", "industries": "Manufacturing,FSI,HLS,SLG,EDU,Automotive,Energy,High Tech,Media and Entertainment,Professional Services,Retail,Horizontal", "technology_stack": "", "github_url": "https://github.com/MSUSSolutionAccelerators/Smart-Spaces-Sustainability-Solution-Accelerator", "demo_url": null, "customer_overview_url": null, "customer_deck_url": null, "short_text": "Builds smart buildings that can prove to be a gold standard in reducing environment impact and cost by driving energy efficiency, green purchasing, waste diversion, and water efficiency", "hero_image": "assets/images/Smart_Spaces_Hero2.webp", "tags": "\"Solution Accelerator\",\"Sustainability\",\"Manufacturing\",\"FSI\",\"HLS\",\"SLG\",\"EDU\",\"Automotive\",\"Energy\",\"High Tech\",\"Media and Entertainment\",\"Professional Services\",\"Retail\",\"Horizontal\",\"Data & AI\",\"BizApps\",\"Apps & Infrastructure\"", "last_updated": "April 27, 2022 03:43:50 PM", "related": "Carbon-Tracing-Basic-Flare.html,Carbon-Tracing-Wastewater.html,ADX-IoT-Analytics.html,AIoT---Predictive-Maintenance.html,AIoT---Inventory-Lifecycle-Management.html", "order": 2, "preview": "## About this Solution Accelerator\n\nFacilities managers are under more pressure than ever to respond quickly and with greater precision to fluctuating demands on their HVAC systems. Energy costs are continuing to rise, flexible and hybrid work models are changing the way space is used, and new technologies like Internet of Things sensors are creating more opportunities to track and optimize energy use in real time.\n\nThe Smart Spaces Solution Accelerator helps facilities managers optimize HVAC systems quickly and proactively for efficient and cost-effective energy use. It integrates your building management system (BMS) with external weather data and uses predictive modeling to deliver real-time reports and actionable insights to a visual dashboard in desktop and mobile applications.\n\n### Challenges\n\n* **Operational inefficiencies** can be challenging to pinpoint, leading to excess energy use.\n* **Rising energy costs** increase pressure to conserve.\n* **Siloed data** from internal and external sources does not integrate easily.\n* **Lack of fast and accurate predictive modeling** makes it difficult to effectively forecast energy needs.\n* **A mobile application is needed** so facilities managers can work from anywhere.\n\n> Excess energy use could cost US building owners $5.2 billion each year if buildings return to pre-COVID occupancy levels.\n\n### Benefits\n\n* **Integrate with your existing BMS** and draw from external data to generate rich, predictive analytics.\n* **Generate real-time predictive modeling** to optimize lead times for temperature setpoints.\n* **Provide a holistic, mobile dashboard** so facilities managers can track and adjust systems on the go.\n* **Easily launch a solution simulation**using pre-configured Microsoft IP.", "basename": "smart-spaces" } }
json
Three-time national champion Sourabh Verma remains the last Indian standing at the Vietnam Open, a Super 100 tournament currently going on in Ho Chi Minh City. Being the second seed, Verma has lived up to the expectations and is now seeking a berth in the final of this tournament. Sourabh hasn't lost a game en route to the last-four stage. Having received a bye in the first round, the World No. 38 has put up some gritty performances in the three matches he has played so far, showing his hunger and determination in ample amounts. He first outlasted Japan's Kodai Naraoka 22-20, 22-20 in a tight second-round clash. Naraoka's compatriot, Yu Igarashi then posed a stern test which Verma passed with flying colours. A grueling 25-23, 24-22 win sealed the deal for Sourabh and put him in the quarter-finals. The match against local hope Tien Minh Nguyen turned out to be the easiest for him this week as he cruised to a 21-13, 21-18 victory. In the semi-finals, the Indian will square off against Japan's World No. 112 Minoru Koga, who upset the sixth seed Tanongsak Saensomboonsuk in the quarters in a three-game duel. Sourabh is definitely the fresher of the two and has way more experience than the 22-year-old Japanese. Besides, Sourabh has won a couple of titles this year on the BWF circuit. Having suffered a second-round exit from the Chinese Taipei Open last week, he will be eager to bounce back and finish this week with a title. Here is all you need to know about the Vietnam Open 2019: Where to watch the matches in India? There is no live telecast information for the Vietnam Open 2019 as of now. Live Stream Details and Info for the matches: Live Stream information is also not available now.
english