text
stringlengths
94
2.23M
meta
stringlengths
23
1.52k
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <style> .button { background-color: #FA58F4; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .button1 {background-color: #D315BC ;} .button2 {background-color: #EA4ED7 ;} .button3 {background-color: #D315BC ; color: black;} .button4 {background-color: #EA4ED7 ;} .button5{background-color: #D315BC ; color: black;} .button6{background-color: #EA4ED7 ;} .button7{background-color: #D315BC ;} .button8{background-color: #EA4ED7 ;} .button9{background-color: #D315BC ;} </style> <title>Класификација</title> </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/mk_MK/sdk.js#xfbml=1&version=v2.9"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fenster"> <a href="./klasifikacija.html"><img src="klasss Kopie.jpg" height="500" width="100%" style="float:left"></a> </div> <button class="button button1"><a href="./pochetna.html"><font color="black">Почетна</font></a></button> <button class="button button2"><a href="./zakancerot.html"><font color="black">За канцерот</font></a></button> <button class="button button3"><a href="./stadiumi.html"><font color="black">Хемотерапија</font></a></button> <button class="button button4"><a href="./recepti.html"><font color="black">Рецепти</font></a></button> <button class="button button5"><a href="./dieti.html"><font color="black">Исхрана</font></a></button> <button class="button button6"><a href="./soveti.html"><font color="black">Совети</font></a></button> <button class="button button7"><a href="./bolnici.html"><font color="black"</font>Болници</a></button> <button class="button button8"><a href="./Donacii.html"><font color="black">Донации</font></a></button> <button class="button button9"><a href="./lekovi.html"><font color="black">Лекови</font></a></button> <p><i><font size="4" color="black"><b>Видовите на рак се класифицираат според видот на клетки кои наликуваат на тумор, и според тоа, на ткивото за кое се претпоставува дека е зачеток на туморот. Подолу е хистологијата и местоположбата на видовите рак. Примери за неколку општи категории се: Карцином: Малигни тумори кои потекнуваат од епителни клетки. Во оваа група припаѓаат најчестите видови на рак, вклучувајќи ги ракот на дојката, простатата, белите дробови и дебелото црево. Сарком: Малигни тумори кои потекнуваат од сврзните ткива, или мезенхималните клетки. Лимфом и леукемија: Малигноми кои потекнуваат од хематопоетските (крвотворните) клетки Бактериски рак: Тумори кои потекнуваат од тотипотентните клетки. Кај возрасните најчесто може да се најде во тестисите и јајчниците, додека кај фетусите, бебињата и малите деца најчесто се наоѓаат во средишниот дел на телото, на врвот на опашната коска, а кај коњите во основата на черепот. Бластен тумор или бластом: Тумор (обично малигнен) кој наликува на незрело или ембрионско ткиво. Овие тумори се најчести кај децата. тумори (видови рак) обично се именуваат користејќи –карцином, -сарком или –бластом како суфикс, и латинскиот или грчкиот збор за органот од кој потекнуваат како корен на името. На пример, ракот на црниот дроб се нарекува хепатокарцином, ракот на масните клетки- липосарком итн. Бенигните тумори (кои не се рак) се именуваат користејќи –ом како суфикс, и името на органот како корен. На пример, бенигнен тумор на мазната мускулатура на матката се нарекува леиомиом (почест израз за овој вид тумор е фиброид). За жал, и некои видови рак го користат суфиксот –ом, како што е случајот со меланом и семином </font></i></p></b> <iframe width="70%" height="500" src="https://www.youtube.com/embed/72-2Bumwyh0" frameborder="0" allowfullscreen></iframe> <div class="fb-comments" data-href="http://127.0.0.1:8020/borbaprotivkancerot/klasifikacija.html" data-numposts="5"></div> </body> </html>
{'content_hash': '5fe8f5d153cd27a362025ba442a3f87d', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 140, 'avg_line_length': 45.84782608695652, 'alnum_prop': 0.7159791370317686, 'repo_name': 'majaradichevich/majaradichevich.github.io', 'id': '7ed025a1c9e8db3faad7a92693291f6f197a9621', 'size': '5642', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'klasifikacija.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6042'}, {'name': 'HTML', 'bytes': '185244'}, {'name': 'JavaScript', 'bytes': '11231'}]}
<h2>Installing XFramework Generator</h2> <p>You don't need to download the source code from the repo, create all the necessary files for the web app, writing two thousands line of code just to create a <code>Hello world!</code> app. XFramework Generator can make everything for you.</p> <p>XF Generator has a number of dependencies such as:</p> <ul> <li><a href="http://nodejs.org">node.js</a></li> <li><a href="https://npmjs.org">NPM</a></li> <li><a href="http://yeoman.io">Yeoman</a></li> </ul> <p>To install first two of them on Mac OS X or Windows computers you just need to download a package from <a href="http://nodejs.org/download/">nodejs.org/download/</a>. For other platforms see the <a href="https://npmjs.org/doc/README.html">readme</a>.</p> <p>After installing node.js and npm go to terminal and install Yeoman writing <code>npm install -g yo</code> (with <code>sudo</code> if necessary).</p> <p>Almost there! After these steps you need to install XF Generator with <code>npm install -g generator-xf</code>.</p>
{'content_hash': '7ec5a698f2b1bcd09b1e097b90fbd031', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 257, 'avg_line_length': 60.705882352941174, 'alnum_prop': 0.7199612403100775, 'repo_name': 'epam/xframework', 'id': '4127893e601400216714eb907402287b68e38251', 'size': '1032', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/data/installing_xframework_generator.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '275950'}, {'name': 'JavaScript', 'bytes': '730289'}]}
namespace Azure.ResourceManager.EdgeOrder.Models { /// <summary> Represents subscription registered features. </summary> public partial class CustomerSubscriptionRegisteredFeatures { /// <summary> Initializes a new instance of CustomerSubscriptionRegisteredFeatures. </summary> public CustomerSubscriptionRegisteredFeatures() { } /// <summary> Name of subscription registered feature. </summary> public string Name { get; set; } /// <summary> State of subscription registered feature. </summary> public string State { get; set; } } }
{'content_hash': 'ac471d3f33987dd6c7e35e349847293a', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 102, 'avg_line_length': 38.4375, 'alnum_prop': 0.6813008130081301, 'repo_name': 'Azure/azure-sdk-for-net', 'id': '1888fb1a8203597c021c5a97aa4c2106984a672a', 'size': '753', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'sdk/edgeorder/Azure.ResourceManager.EdgeOrder/src/Generated/Models/CustomerSubscriptionRegisteredFeatures.cs', 'mode': '33188', 'license': 'mit', 'language': []}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Sat Mar 16 04:11:58 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface org.wildfly.swarm.config.messaging.activemq.server.BindingsDirectoryPathConsumer (BOM: * : All 2.3.1.Final-SNAPSHOT API)</title> <meta name="date" content="2019-03-16"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.wildfly.swarm.config.messaging.activemq.server.BindingsDirectoryPathConsumer (BOM: * : All 2.3.1.Final-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.3.1.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/class-use/BindingsDirectoryPathConsumer.html" target="_top">Frames</a></li> <li><a href="BindingsDirectoryPathConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.wildfly.swarm.config.messaging.activemq.server.BindingsDirectoryPathConsumer" class="title">Uses of Interface<br>org.wildfly.swarm.config.messaging.activemq.server.BindingsDirectoryPathConsumer</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.messaging.activemq">org.wildfly.swarm.config.messaging.activemq</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.messaging.activemq.server">org.wildfly.swarm.config.messaging.activemq.server</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.messaging.activemq"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a> in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html" title="type parameter in Server">T</a></code></td> <td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html#bindingsDirectoryPath-org.wildfly.swarm.config.messaging.activemq.server.BindingsDirectoryPathConsumer-">bindingsDirectoryPath</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a>&nbsp;consumer)</code> <div class="block">A filesystem path pointing to one of the locations where ActiveMQ stores persistent data.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.wildfly.swarm.config.messaging.activemq.server"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a> in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>default <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="type parameter in BindingsDirectoryPathConsumer">T</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">BindingsDirectoryPathConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html#andThen-org.wildfly.swarm.config.messaging.activemq.server.BindingsDirectoryPathConsumer-">andThen</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="type parameter in BindingsDirectoryPathConsumer">T</a>&gt;&nbsp;after)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>default <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="type parameter in BindingsDirectoryPathConsumer">T</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">BindingsDirectoryPathConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html#andThen-org.wildfly.swarm.config.messaging.activemq.server.BindingsDirectoryPathConsumer-">andThen</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BindingsDirectoryPathConsumer</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="type parameter in BindingsDirectoryPathConsumer">T</a>&gt;&nbsp;after)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BindingsDirectoryPathConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.3.1.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/class-use/BindingsDirectoryPathConsumer.html" target="_top">Frames</a></li> <li><a href="BindingsDirectoryPathConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{'content_hash': '9d4a959a17bfed5d67d358e525d7f8e4', 'timestamp': '', 'source': 'github', 'line_count': 206, 'max_line_length': 793, 'avg_line_length': 64.10194174757281, 'alnum_prop': 0.6843619840969329, 'repo_name': 'wildfly-swarm/wildfly-swarm-javadocs', 'id': '1e14ac35a7c49488433c20a72a70ed6f7111d9be', 'size': '13205', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': '2.3.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/messaging/activemq/server/class-use/BindingsDirectoryPathConsumer.html', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
import ReactSharedInternals from 'shared/ReactSharedInternals'; import type {Transition} from './ReactFiberTracingMarkerComponent.new'; const {ReactCurrentBatchConfig} = ReactSharedInternals; export const NoTransition = null; export function requestCurrentTransition(): Transition | null { return ReactCurrentBatchConfig.transition; }
{'content_hash': 'dace65b4e7262d44f7cf8c5ddcea517a', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 71, 'avg_line_length': 28.5, 'alnum_prop': 0.8216374269005848, 'repo_name': 'camsong/react', 'id': 'd63b99a1862ef22435389d30a9298476688a7c25', 'size': '542', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'packages/react-reconciler/src/ReactFiberTransition.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '5225'}, {'name': 'C++', 'bytes': '44278'}, {'name': 'CSS', 'bytes': '64729'}, {'name': 'CoffeeScript', 'bytes': '16826'}, {'name': 'HTML', 'bytes': '119964'}, {'name': 'JavaScript', 'bytes': '6161428'}, {'name': 'Makefile', 'bytes': '189'}, {'name': 'Python', 'bytes': '259'}, {'name': 'Shell', 'bytes': '2306'}, {'name': 'TypeScript', 'bytes': '20868'}]}
/*! * Copyright (c) 2019 by Contributors * \file moments-inl.h * \brief Moments operator * \author Hao Jin */ #ifndef MXNET_OPERATOR_NN_MOMENTS_INL_H_ #define MXNET_OPERATOR_NN_MOMENTS_INL_H_ #include <vector> #include "../tensor/broadcast_reduce_op.h" namespace mxnet { namespace op { struct MomentsParam : public dmlc::Parameter<MomentsParam> { dmlc::optional<mxnet::TShape> axes; bool keepdims; DMLC_DECLARE_PARAMETER(MomentsParam) { DMLC_DECLARE_FIELD(axes).set_default(dmlc::optional<mxnet::TShape>()) .describe("Array of ints. Axes along which to compute mean and variance."); DMLC_DECLARE_FIELD(keepdims).set_default(false) .describe("produce moments with the same dimensionality as the input."); } }; inline bool MomentsShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { const MomentsParam& param = nnvm::get<MomentsParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 2U); mxnet::TShape out_shape = ReduceAxesShapeImpl((*in_attrs)[0], param.axes, param.keepdims, false); if (!param.axes.has_value() || param.axes.value().ndim() == 0) { LOG(FATAL) << "Empty axes is not supported, if you would like to do global moments, " << "please pass all axes to axes argument"; } SHAPE_ASSIGN_CHECK(*out_attrs, 0, out_shape); SHAPE_ASSIGN_CHECK(*out_attrs, 1, out_shape); return true; } inline bool MomentsType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 2U); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0)); TYPE_ASSIGN_CHECK(*out_attrs, 1, in_attrs->at(0)); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0)); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(1)); return out_attrs->at(0) != -1 && out_attrs->at(1) != -1; } struct VarBroadcastKernel { template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *data, const DType *mean, mshadow::Shape<6> data_shape, mshadow::Shape<6> mean_shape) { size_t data_idx = i; size_t mean_idx = i; size_t data_stride = 1; size_t mean_stride = 1; for (int axis = 5; axis >= 0; --axis) { size_t axis_idx = data_idx % data_shape[axis]; mean_idx -= axis_idx * data_stride; if (mean_shape[axis] != 1) { mean_idx += axis_idx * mean_stride; } data_idx /= data_shape[axis]; data_stride *= data_shape[axis]; mean_stride *= mean_shape[axis]; } DType res = (data[i] - mean[mean_idx]); out[i] = res * res; } }; template<typename xpu> inline void MomentsForwardImpl(const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const dmlc::optional<mxnet::TShape>& axes, const bool keepdims) { using namespace mshadow; using namespace mshadow_op; using namespace mxnet_op; Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob& data = inputs[0]; const TBlob& mean = outputs[0]; const TBlob& var = outputs[1]; mxnet::TShape small; if (keepdims) { small = outputs[0].shape_; } else { small = ReduceAxesShapeImpl(inputs[0].shape_, axes, true, false); } ReduceAxesComputeImpl<xpu, mshadow_op::sum, true, true>(ctx, {data}, {req[0]}, {mean}, small); MSHADOW_TYPE_SWITCH(data.type_flag_, DType, { Shape<6> data_shape, mean_shape; for (int i = 0; i < 6; ++i) { data_shape[i] = (i < data.shape_.ndim()) ? data.shape_[i] : 1; mean_shape[i] = (i < small.ndim()) ? small[i] : 1; } Tensor<xpu, 1, DType> temp_data = ctx.requested[0].get_space_typed<xpu, 1, DType>(Shape1(data.shape_.Size()), s);; Kernel<VarBroadcastKernel, xpu>::Launch(s, data.shape_.Size(), temp_data.dptr_, data.dptr<DType>(), mean.dptr<DType>(), data_shape, mean_shape); ReduceAxesComputeImpl<xpu, mshadow_op::sum, true, true>( ctx, {TBlob(temp_data).reshape(data.shape_)}, {kWriteTo}, {var}, small); }); } template<typename xpu> inline void MomentsForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; using namespace mshadow_op; using namespace mxnet_op; CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 2U); const MomentsParam& param = nnvm::get<MomentsParam>(attrs.parsed); MomentsForwardImpl<xpu>(ctx, inputs, req, outputs, param.axes, param.keepdims); } template<int req> struct VarBackwardKernel { template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *igrad, const DType *ograd, const DType *data, const DType *mean, mshadow::Shape<6> data_shape, mshadow::Shape<6> mean_shape, const float N, const float ddof = 0.0f) { size_t data_idx = i; size_t mean_idx = i; size_t data_stride = 1; size_t mean_stride = 1; for (int axis = 5; axis >= 0; --axis) { size_t axis_idx = data_idx % data_shape[axis]; mean_idx -= axis_idx * data_stride; if (mean_shape[axis] != 1) { mean_idx += axis_idx * mean_stride; } data_idx /= data_shape[axis]; data_stride *= data_shape[axis]; mean_stride *= mean_shape[axis]; } KERNEL_ASSIGN(igrad[i], req, ograd[mean_idx] * (data[i] - mean[mean_idx]) * 2 / (N - ddof)); } }; template<typename xpu> inline void MomentsBackwardImpl(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const dmlc::optional<mxnet::TShape>& axes) { using namespace mshadow; using namespace mshadow::expr; using namespace mshadow_op; using namespace mxnet_op; Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob& mean_grad = inputs[0]; const TBlob& var_grad = inputs[1]; const TBlob& data = inputs[2]; const TBlob& mean = inputs[3]; const TBlob& var = inputs[4]; const TBlob& data_grad = outputs[0]; mxnet::TShape small = ReduceAxesShapeImpl(data.shape_, axes, true, false); BroadcastComputeImpl<xpu>(attrs, ctx, {mean_grad}, req, outputs, small); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { Tensor<xpu, 1, DType> igrad = outputs[0].FlatTo1D<xpu, DType>(s); igrad /= scalar<DType>(outputs[0].Size()/inputs[0].Size()); }); Shape<6> data_shape, var_shape; float N = data_grad.Size() / var.Size(); for (int i = 0; i < 6; ++i) { data_shape[i] = (i < data.shape_.ndim()) ? data.shape_[i] : 1; var_shape[i] = (i < small.ndim()) ? small[i] : 1; } MSHADOW_TYPE_SWITCH(data_grad.type_flag_, DType, { Kernel<VarBackwardKernel<kAddTo>, xpu>::Launch( s, data_grad.shape_.Size(), data_grad.dptr<DType>(), var_grad.dptr<DType>(), data.dptr<DType>(), mean.dptr<DType>(), data_shape, var_shape, N); }); } template<typename xpu> inline void MomentsBackward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; using namespace mshadow_op; using namespace mxnet_op; CHECK_EQ(inputs.size(), 5U); CHECK_EQ(outputs.size(), 1U); const MomentsParam& param = nnvm::get<MomentsParam>(attrs.parsed); MomentsBackwardImpl<xpu>(attrs, ctx, inputs, req, outputs, param.axes); } } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NN_MOMENTS_INL_H_
{'content_hash': '1379c25c73b10bf4cbf94d1e3e5177af', 'timestamp': '', 'source': 'github', 'line_count': 237, 'max_line_length': 96, 'avg_line_length': 36.08438818565401, 'alnum_prop': 0.5748362956033677, 'repo_name': 'reminisce/mxnet', 'id': '6a9bdc54b9059e922e80bdd01e6bde06bf84326b', 'size': '9359', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/operator/nn/moments-inl.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '1731'}, {'name': 'Batchfile', 'bytes': '13130'}, {'name': 'C', 'bytes': '215572'}, {'name': 'C++', 'bytes': '7680259'}, {'name': 'CMake', 'bytes': '99958'}, {'name': 'Clojure', 'bytes': '622688'}, {'name': 'Cuda', 'bytes': '970884'}, {'name': 'Dockerfile', 'bytes': '85151'}, {'name': 'Groovy', 'bytes': '122800'}, {'name': 'HTML', 'bytes': '40277'}, {'name': 'Java', 'bytes': '205196'}, {'name': 'Julia', 'bytes': '436326'}, {'name': 'Jupyter Notebook', 'bytes': '3660387'}, {'name': 'MATLAB', 'bytes': '34903'}, {'name': 'Makefile', 'bytes': '201597'}, {'name': 'Perl', 'bytes': '1550163'}, {'name': 'Perl 6', 'bytes': '7280'}, {'name': 'PowerShell', 'bytes': '13786'}, {'name': 'Python', 'bytes': '7842403'}, {'name': 'R', 'bytes': '357807'}, {'name': 'Scala', 'bytes': '1305036'}, {'name': 'Shell', 'bytes': '427407'}, {'name': 'Smalltalk', 'bytes': '3497'}]}
class DeviceSettingListener < AsakusaSatellite::Hook::Listener render_on :account_setting_item, :partial => "device_setting" end
{'content_hash': '46ad3aa3b2c9fc525d06733f4de789d0', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 63, 'avg_line_length': 33.0, 'alnum_prop': 0.7803030303030303, 'repo_name': 'mallowlabs/AsakusaSatellite', 'id': 'fc863576a1861c4131cf2c1c604d62a735622fb0', 'size': '132', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'plugins/as_device_setting/lib/device_setting_listener.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4295'}, {'name': 'JavaScript', 'bytes': '70132'}, {'name': 'Ruby', 'bytes': '176805'}, {'name': 'Shell', 'bytes': '1621'}]}
require_relative '../../spec_helper' VALID_UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i UUID_STRING1 = 'de305d54-75b4-431b-adb2-eb6b9e546014' UUID_STRING2 = 'de305d54-75b4-431b-adb2-eb6b9e546020' UUID_PACKED_STRING1 = "\xde\x30\x5d\x54\x75\xb4\x43\x1b\xad\xb2\xeb\x6b\x9e\x54\x60\x14" UUID_PACKED_STRING2 = "\xde\x30\x5d\x54\x75\xb4\x43\x1b\xad\xb2\xeb\x6b\x9e\x54\x60\x20" RSpec.describe Lobster::Uuid do describe '::DEFAULT' do subject { Lobster::Uuid::DEFAULT } it 'is all zeroes' do expect(subject).to eq("\x0" * 16) end it 'is frozen' do is_expected.to be_frozen end end describe '#new' do context 'with a valid value' do subject(:uuid) { Lobster::Uuid.new(UUID_PACKED_STRING1) } describe 'the value' do subject { uuid.value } it 'is stored' do is_expected.to eq UUID_PACKED_STRING1 end end end context 'with an invalid value' do it 'rejects a malformed string' do expect { Lobster::Uuid.new('foobar') }.to raise_error(ArgumentError) end end end context '.generate' do subject(:uuid) { Lobster::Uuid.generate } describe 'the value' do subject { uuid.value } # The chances of a randomly generated empty UUID is virtually impossible. # Besides, the UUID standards don't allow generated UUID to be all zeroes. it 'is random' do is_expected.not_to eq("\x0" * 16) end end describe 'the string' do subject { uuid.to_s } it 'is valid' do is_expected.to match VALID_UUID_REGEX end end end describe '.parse' do context 'with a valid UUID' do subject { Lobster::Uuid.parse(UUID_STRING1) } it 'parses correctly' do expect(subject.to_s).to eq(UUID_STRING1) end end context 'with a malformed string' do it 'returns nil' do expect(Lobster::Uuid.parse('foobar')).to be_nil end end context 'with an invalid argument' do it 'rejects a non-string' do expect { Lobster::Uuid.parse(5) }.to raise_error(ArgumentError) end end end describe '#value' do subject(:uuid) { Lobster::Uuid.new(UUID_PACKED_STRING1).value } it 'is a string' do is_expected.to be_a(String) end it 'is frozen' do is_expected.to be_frozen end describe '.length' do subject { uuid.length } it 'is 16 bytes' do is_expected.to be 16 end end end describe '#eql?' do subject(:uuid) { Lobster::Uuid.new(UUID_PACKED_STRING1) } subject { uuid.eql?(other) } context 'with two identical UUIDs' do let(:other) { Lobster::Uuid.new(UUID_PACKED_STRING1) } it 'returns true' do is_expected.to eq true end end context 'with two different UUIDs' do let(:other) { Lobster::Uuid.new(UUID_PACKED_STRING2) } it 'returns false' do is_expected.to eq false end end context 'without a UUID' do let(:other) { 'foobar' } it 'returns false' do is_expected.to eq false end end end describe '#==' do subject { first == second } let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } context 'with equal UUIDs' do let(:second) { Lobster::Uuid.new(UUID_PACKED_STRING1) } it 'is true' do is_expected.to be true end end context 'with the same instance' do let(:second) { first } it 'is true' do is_expected.to be true end end context 'with unequal UUIDs' do let(:second) { Lobster::Uuid.new(UUID_PACKED_STRING2) } it 'is false' do is_expected.to be false end end context 'with nil' do let(:second) { nil } it 'is false' do is_expected.to be false end end context 'with a malformed string' do let(:second) { 'foobar' } it 'is false' do is_expected.to be false end end context 'with a non-string' do let(:second) { 5 } it 'is false' do is_expected.to be false end end context 'with identical value' do let(:second) { first.value } it 'is true' do is_expected.to be true end end context 'with identical string' do let(:second) { first.to_s } it 'is true' do is_expected.to be true end end end describe '#<=>' do subject { first <=> second } context 'with an equal UUID' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { Lobster::Uuid.new(UUID_PACKED_STRING1) } it 'is 0' do is_expected.to eq 0 end end context 'with the same instance' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { first } it 'is 0' do is_expected.to eq 0 end end context 'with a lesser UUID' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING2) } let(:second) { Lobster::Uuid.new(UUID_PACKED_STRING1) } it 'is 1' do is_expected.to eq 1 end end context 'with a greater UUID' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { Lobster::Uuid.new(UUID_PACKED_STRING2) } it 'is -1' do is_expected.to eq(-1) end end context 'with nil' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { nil } it 'is nil' do is_expected.to be_nil end end context 'with a number' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { 500 } it 'is nil' do is_expected.to be_nil end end context 'with an identical value' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { UUID_PACKED_STRING1 } it 'is 0' do is_expected.to eq 0 end end context 'with a lesser value' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING2) } let(:second) { UUID_PACKED_STRING1 } it 'is 1' do is_expected.to eq 1 end end context 'with a greater value' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { UUID_PACKED_STRING2 } it 'is -1' do is_expected.to eq(-1) end end context 'with an equal string' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { UUID_STRING1 } it 'is 0' do is_expected.to eq 0 end end context 'with a lesser string' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING2) } let(:second) { UUID_STRING1 } it 'is 1' do is_expected.to eq 1 end end context 'with a greater string' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1) } let(:second) { UUID_STRING2 } it 'is -1' do is_expected.to eq(-1) end end context 'with an invalid string' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING2) } let(:second) { 'foobar' } it 'is nil' do is_expected.to be_nil end end end describe '#hash' do subject { Lobster::Uuid.new(UUID_PACKED_STRING1).hash } it 'is a Fixnum' do is_expected.to be_a(Fixnum) end context 'with identical UUIDs' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1).hash } let(:second) { Lobster::Uuid.new(UUID_PACKED_STRING1).hash } it 'returns identical values' do expect(first).to eq(second) end end context 'with different UUIDs' do let(:first) { Lobster::Uuid.new(UUID_PACKED_STRING1).hash } let(:second) { Lobster::Uuid.new(UUID_PACKED_STRING2).hash } it 'returns different values' do expect(first).to_not eq(second) end end end describe '#to_s' do subject { Lobster::Uuid.new(UUID_PACKED_STRING1).to_s } it 'is a String' do is_expected.to be_a String end it 'is a valid UUID string' do is_expected.to match(VALID_UUID_REGEX) end it 'equals the initial value' do is_expected.to eq(UUID_STRING1) end context 'with bytes less than 16' do subject { Lobster::Uuid.new("\x05\x30\x5d\x54\x75\x02\x43\x1b\xad\xb2\xeb\x6b\x9e\x54\x60\x00").to_s } it 'pads with zeroes' do is_expected.to eq('05305d54-7502-431b-adb2-eb6b9e546000') end end end end
{'content_hash': '1642c878d4fcdc5ebd2a9e8b8905586d', 'timestamp': '', 'source': 'github', 'line_count': 357, 'max_line_length': 108, 'avg_line_length': 23.946778711484594, 'alnum_prop': 0.5853316177330682, 'repo_name': 'gachapon/lobster-common', 'id': 'ed5b0f0b607bf7c015be4f064dfa501f5129bfd2', 'size': '8549', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'spec/lib/lobster/uuid_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '44314'}]}
package com.asksunny.schema.parser; import java.util.HashMap; import java.util.Map; import java.util.Set; public class KeywordDictionary extends HashMap<String, Keyword> { /** * */ private static final long serialVersionUID = 1L; public KeywordDictionary() { this.put("CREATE", Keyword.CREATE); this.put("TABLE", Keyword.TABLE); this.put("NOT", Keyword.NOT); this.put("NULL", Keyword.NULL); this.put("PRIMARY", Keyword.PRIMARY); this.put("KEY", Keyword.KEY); this.put("VARCHAR", Keyword.VARCHAR); this.put("NUMBER", Keyword.NUMBER); this.put("INT", Keyword.INT); this.put("BIGINT", Keyword.BIGINT); this.put("INTEGER", Keyword.INTEGER); this.put("DOUBLE", Keyword.DOUBLE); this.put("VARCHAR2", Keyword.VARCHAR); this.put("BINARY", Keyword.BINARY); this.put("LONG", Keyword.LONG); this.put("DATE", Keyword.DATE); this.put("TIME", Keyword.TIME); this.put("TIMESTAMP", Keyword.TIMESTAMP); this.put("ALTER", Keyword.ALTER); this.put("ADD", Keyword.ADD); this.put("CHAR", Keyword.CHAR); this.put("CONSTRAINT", Keyword.CONSTRAINT); this.put("FOREIGN", Keyword.FOREIGN); this.put("REFERENCES", Keyword.REFERENCES); this.put("UNIQUE", Keyword.UNIQUE); this.put("INDEX", Keyword.INDEX); this.put("BYTE", Keyword.BYTE); this.put("NOPARALLELCREATE", Keyword.CREATE); this.put("NOPARALLEL", Keyword.NOPARALLEL); this.put("PARALLEL", Keyword.PARALLEL); this.put("*", Keyword.ASTERISK); this.put("IMAGE", Keyword.IMAGE); this.put("TEXT", Keyword.TEXT); this.put("IDENTITY", Keyword.IDENTITY); this.put("AUTOINCREMENT", Keyword.IDENTITY); this.put("AUTO_INCREMENT", Keyword.IDENTITY); this.put("DEFAULT", Keyword.DEFAULT); this.put("COLUMN_FORMAT", Keyword.FORMAT); this.put("FORMAT", Keyword.FORMAT); } @Override public Keyword get(Object key) { return super.get(key.toString().toUpperCase()); } @Override public Keyword put(String key, Keyword value) { return super.put(key.toUpperCase(), value); } @Override public void putAll(Map<? extends String, ? extends Keyword> m) { Set<? extends String> keys = m.keySet(); for (String string : keys) { super.put(string.toUpperCase(), m.get(string)); } } @Override public boolean containsKey(Object key) { return super.containsKey(key.toString().toUpperCase()); } }
{'content_hash': '17e0844e355090632f0e6aef8dd4ab5e', 'timestamp': '', 'source': 'github', 'line_count': 84, 'max_line_length': 65, 'avg_line_length': 28.75, 'alnum_prop': 0.6650103519668737, 'repo_name': 'devsunny/jscaffold', 'id': '0e5042958a41441b8acf16b22b7e71f333e3239b', 'size': '2415', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/asksunny/schema/parser/KeywordDictionary.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'FreeMarker', 'bytes': '37206'}, {'name': 'Java', 'bytes': '312644'}]}
#include "arm_math.h" /** * @ingroup groupMath */ /** * @defgroup offset Vector Offset * * Adds a constant offset to each element of a vector. * * <pre> * pDst[n] = pSrc[n] + offset, 0 <= n < blockSize. * </pre> * * There are separate functions for floating-point, Q7, Q15, and Q31 data types. */ /** * @addtogroup offset * @{ */ /** * @brief Adds a constant offset to a floating-point vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_f32( float32_t * pSrc, float32_t offset, float32_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #ifndef ARM_MATH_CM0 /* Run the below code for Cortex-M4 and Cortex-M3 */ float32_t in1, in2, in3, in4; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while(blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the results in the destination buffer. */ /* read samples from source */ in1 = *pSrc; in2 = *(pSrc + 1); /* add offset to input */ in1 = in1 + offset; /* read samples from source */ in3 = *(pSrc + 2); /* add offset to input */ in2 = in2 + offset; /* read samples from source */ in4 = *(pSrc + 3); /* add offset to input */ in3 = in3 + offset; /* store result to destination */ *pDst = in1; /* add offset to input */ in4 = in4 + offset; /* store result to destination */ *(pDst + 1) = in2; /* store result to destination */ *(pDst + 2) = in3; /* store result to destination */ *(pDst + 3) = in4; /* update pointers to process next samples */ pSrc += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #ifndef ARM_MATH_CM0 */ while(blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the result in the destination buffer. */ *pDst++ = (*pSrc++) + offset; /* Decrement the loop counter */ blkCnt--; } } /** * @} end of offset group */
{'content_hash': 'f2b978d8b36fff3a0eae28c44484593c', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 96, 'avg_line_length': 22.592, 'alnum_prop': 0.5439093484419264, 'repo_name': 'jys0305/highspeedlogger', 'id': 'd7ca663bbddb46767e61f4c926942e9b5892f6e8', 'size': '3945', 'binary': False, 'copies': '56', 'ref': 'refs/heads/master', 'path': 'sw/libs/STM32F4xx_DSP_StdPeriph_Lib_V1.1.0/Libraries/CMSIS/DSP_Lib/Source/BasicMathFunctions/arm_offset_f32.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '280928'}, {'name': 'C', 'bytes': '21114329'}, {'name': 'C++', 'bytes': '100991'}, {'name': 'HTML', 'bytes': '455966'}, {'name': 'LSL', 'bytes': '47664'}, {'name': 'Makefile', 'bytes': '4331'}, {'name': 'Objective-C', 'bytes': '1718'}]}
package javassist.bytecode.stackmap; import javassist.bytecode.*; import java.util.HashMap; import java.util.ArrayList; /** * A basic block is a sequence of bytecode that does not contain jump/branch * instructions except at the last bytecode. * Since Java7 or later does not allow JSR, this class throws an exception when * it finds JSR. */ public class BasicBlock { static class JsrBytecode extends BadBytecode { JsrBytecode() { super("JSR"); } } protected int position, length; protected int incoming; // the number of incoming branches. protected BasicBlock[] exit; // null if the block is a leaf. protected boolean stop; // true if the block ends with an unconditional jump. protected Catch toCatch; protected BasicBlock(int pos) { position = pos; length = 0; incoming = 0; } public static BasicBlock find(BasicBlock[] blocks, int pos) throws BadBytecode { for (int i = 0; i < blocks.length; i++) { int iPos = blocks[i].position; if (iPos <= pos && pos < iPos + blocks[i].length) return blocks[i]; } throw new BadBytecode("no basic block at " + pos); } public static class Catch { public Catch next; public BasicBlock body; public int typeIndex; Catch(BasicBlock b, int i, Catch c) { body = b; typeIndex = i; next = c; } } public String toString() { StringBuffer sbuf = new StringBuffer(); String cname = this.getClass().getName(); int i = cname.lastIndexOf('.'); sbuf.append(i < 0 ? cname : cname.substring(i + 1)); sbuf.append("["); toString2(sbuf); sbuf.append("]"); return sbuf.toString(); } protected void toString2(StringBuffer sbuf) { sbuf.append("pos=").append(position).append(", len=") .append(length).append(", in=").append(incoming) .append(", exit{"); if (exit != null) { for (int i = 0; i < exit.length; i++) sbuf.append(exit[i].position).append(","); } sbuf.append("}, {"); Catch th = toCatch; while (th != null) { sbuf.append("(").append(th.body.position).append(", ") .append(th.typeIndex).append("), "); th = th.next; } sbuf.append("}"); } static class Mark implements Comparable { int position; BasicBlock block; BasicBlock[] jump; boolean alwaysJmp; // true if an unconditional branch. int size; // 0 unless the mark indicates RETURN etc. Catch catcher; Mark(int p) { position = p; block = null; jump = null; alwaysJmp = false; size = 0; catcher = null; } public int compareTo(Object obj) { if (obj instanceof Mark) { int pos = ((Mark)obj).position; return position - pos; } return -1; } void setJump(BasicBlock[] bb, int s, boolean always) { jump = bb; size = s; alwaysJmp = always; } } public static class Maker { /* Override these two methods if a subclass of BasicBlock must be * instantiated. */ protected BasicBlock makeBlock(int pos) { return new BasicBlock(pos); } protected BasicBlock[] makeArray(int size) { return new BasicBlock[size]; } private BasicBlock[] makeArray(BasicBlock b) { BasicBlock[] array = makeArray(1); array[0] = b; return array; } private BasicBlock[] makeArray(BasicBlock b1, BasicBlock b2) { BasicBlock[] array = makeArray(2); array[0] = b1; array[1] = b2; return array; } public BasicBlock[] make(MethodInfo minfo) throws BadBytecode { CodeAttribute ca = minfo.getCodeAttribute(); if (ca == null) return null; CodeIterator ci = ca.iterator(); return make(ci, 0, ci.getCodeLength(), ca.getExceptionTable()); } public BasicBlock[] make(CodeIterator ci, int begin, int end, ExceptionTable et) throws BadBytecode { HashMap marks = makeMarks(ci, begin, end, et); BasicBlock[] bb = makeBlocks(marks); addCatchers(bb, et); return bb; } /* Branch target */ private Mark makeMark(HashMap table, int pos) { return makeMark0(table, pos, true, true); } /* Branch instruction. * size > 0 */ private Mark makeMark(HashMap table, int pos, BasicBlock[] jump, int size, boolean always) { Mark m = makeMark0(table, pos, false, false); m.setJump(jump, size, always); return m; } private Mark makeMark0(HashMap table, int pos, boolean isBlockBegin, boolean isTarget) { Integer p = new Integer(pos); Mark m = (Mark)table.get(p); if (m == null) { m = new Mark(pos); table.put(p, m); } if (isBlockBegin) { if (m.block == null) m.block = makeBlock(pos); if (isTarget) m.block.incoming++; } return m; } private HashMap makeMarks(CodeIterator ci, int begin, int end, ExceptionTable et) throws BadBytecode { ci.begin(); ci.move(begin); HashMap marks = new HashMap(); while (ci.hasNext()) { int index = ci.next(); if (index >= end) break; int op = ci.byteAt(index); if ((Opcode.IFEQ <= op && op <= Opcode.IF_ACMPNE) || op == Opcode.IFNULL || op == Opcode.IFNONNULL) { Mark to = makeMark(marks, index + ci.s16bitAt(index + 1)); Mark next = makeMark(marks, index + 3); makeMark(marks, index, makeArray(to.block, next.block), 3, false); } else if (Opcode.GOTO <= op && op <= Opcode.LOOKUPSWITCH) switch (op) { case Opcode.GOTO : makeGoto(marks, index, index + ci.s16bitAt(index + 1), 3); break; case Opcode.JSR : makeJsr(marks, index, index + ci.s16bitAt(index + 1), 3); break; case Opcode.RET : makeMark(marks, index, null, 2, true); break; case Opcode.TABLESWITCH : { int pos = (index & ~3) + 4; int low = ci.s32bitAt(pos + 4); int high = ci.s32bitAt(pos + 8); int ncases = high - low + 1; BasicBlock[] to = makeArray(ncases + 1); to[0] = makeMark(marks, index + ci.s32bitAt(pos)).block; // default branch target int p = pos + 12; int n = p + ncases * 4; int k = 1; while (p < n) { to[k++] = makeMark(marks, index + ci.s32bitAt(p)).block; p += 4; } makeMark(marks, index, to, n - index, true); break; } case Opcode.LOOKUPSWITCH : { int pos = (index & ~3) + 4; int ncases = ci.s32bitAt(pos + 4); BasicBlock[] to = makeArray(ncases + 1); to[0] = makeMark(marks, index + ci.s32bitAt(pos)).block; // default branch target int p = pos + 8 + 4; int n = p + ncases * 8 - 4; int k = 1; while (p < n) { to[k++] = makeMark(marks, index + ci.s32bitAt(p)).block; p += 8; } makeMark(marks, index, to, n - index, true); break; } } else if ((Opcode.IRETURN <= op && op <= Opcode.RETURN) || op == Opcode.ATHROW) makeMark(marks, index, null, 1, true); else if (op == Opcode.GOTO_W) makeGoto(marks, index, index + ci.s32bitAt(index + 1), 5); else if (op == Opcode.JSR_W) makeJsr(marks, index, index + ci.s32bitAt(index + 1), 5); else if (op == Opcode.WIDE && ci.byteAt(index + 1) == Opcode.RET) makeMark(marks, index, null, 4, true); } if (et != null) { int i = et.size(); while (--i >= 0) { makeMark0(marks, et.startPc(i), true, false); makeMark(marks, et.handlerPc(i)); } } return marks; } private void makeGoto(HashMap marks, int pos, int target, int size) { Mark to = makeMark(marks, target); BasicBlock[] jumps = makeArray(to.block); makeMark(marks, pos, jumps, size, true); } /* * We could ignore JSR since Java 7 or later does not allow it. * See The JVM Spec. Sec. 4.10.2.5. */ protected void makeJsr(HashMap marks, int pos, int target, int size) throws BadBytecode { /* Mark to = makeMark(marks, target); Mark next = makeMark(marks, pos + size); BasicBlock[] jumps = makeArray(to.block, next.block); makeMark(marks, pos, jumps, size, false); */ throw new JsrBytecode(); } private BasicBlock[] makeBlocks(HashMap markTable) { Mark[] marks = (Mark[])markTable.values() .toArray(new Mark[markTable.size()]); java.util.Arrays.sort(marks); ArrayList blocks = new ArrayList(); int i = 0; BasicBlock prev; if (marks.length > 0 && marks[0].position == 0 && marks[0].block != null) prev = getBBlock(marks[i++]); else prev = makeBlock(0); blocks.add(prev); while (i < marks.length) { Mark m = marks[i++]; BasicBlock bb = getBBlock(m); if (bb == null) { // the mark indicates a branch instruction if (prev.length > 0) { // the previous mark already has exits. prev = makeBlock(prev.position + prev.length); blocks.add(prev); } prev.length = m.position + m.size - prev.position; prev.exit = m.jump; prev.stop = m.alwaysJmp; } else { // the mark indicates a branch target if (prev.length == 0) { prev.length = m.position - prev.position; bb.incoming++; prev.exit = makeArray(bb); } else { // the previous mark already has exits. int prevPos = prev.position; if (prevPos + prev.length < m.position) { prev = makeBlock(prevPos + prev.length); prev.length = m.position - prevPos; // the incoming flow from dead code is not counted // bb.incoming++; prev.exit = makeArray(bb); } } blocks.add(bb); prev = bb; } } return (BasicBlock[])blocks.toArray(makeArray(blocks.size())); } private static BasicBlock getBBlock(Mark m) { BasicBlock b = m.block; if (b != null && m.size > 0) { b.exit = m.jump; b.length = m.size; b.stop = m.alwaysJmp; } return b; } private void addCatchers(BasicBlock[] blocks, ExceptionTable et) throws BadBytecode { if (et == null) return; int i = et.size(); while (--i >= 0) { BasicBlock handler = find(blocks, et.handlerPc(i)); int start = et.startPc(i); int end = et.endPc(i); int type = et.catchType(i); handler.incoming--; for (int k = 0; k < blocks.length; k++) { BasicBlock bb = blocks[k]; int iPos = bb.position; if (start <= iPos && iPos < end) { bb.toCatch = new Catch(handler, type, bb.toCatch); handler.incoming++; } } } } } }
{'content_hash': 'f1a0cceb83de5d2bb6046c9fcb64b93d', 'timestamp': '', 'source': 'github', 'line_count': 391, 'max_line_length': 107, 'avg_line_length': 35.18414322250639, 'alnum_prop': 0.4474085919895326, 'repo_name': 'oneliang/third-party-lib', 'id': '6213e22a64b2b627e9be31e387205d826fb1866d', 'size': '14461', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'javassist/javassist/bytecode/stackmap/BasicBlock.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '31084'}, {'name': 'Java', 'bytes': '14382753'}]}
/* System calls. */ #define SEND 1 /* function code for sending messages */ #define RECEIVE 2 /* function code for receiving messages */ #define BOTH 3 /* function code for SEND + RECEIVE */ #define ANY (NR_PROCS+100) /* receive(ANY, buf) accepts from any source */ /* Task numbers, function codes and reply codes. */ #define TTY -NR_TASKS /* terminal I/O class */ # define TTY_READ 3 /* fcn code for reading from tty */ # define TTY_WRITE 4 /* fcn code for writing to tty */ # define TTY_IOCTL 5 /* fcn code for ioctl */ # define TTY_SETPGRP 6 /* fcn code for setpgrp */ # define TTY_OPEN 7 /* fcn code for opening tty */ # define TTY_CLOSE 8 /* fcn code for closing tty */ # define SUSPEND -998 /* used in interrupts when tty has no data */ #ifdef AM_KERNEL #define AMOEBA #endif #ifdef AMOEBA /* There are AM_NTASK copies of the amoeba kernel task. * If you change AM_NTASKS be sure to adjust kernel/table.c and fs/table.c */ #define AM_NTASKS 4 /* number of kernel tasks of this class */ #define AMINT_CLASS (TTY+1) /* Amoeba event handler */ #define AMOEBA_CLASS (AMINT_CLASS+AM_NTASKS) /* transaction handlers */ # define ETHER_ARRIV 1 /* fcn code for packet arrival */ # define AM_TRANS 2 /* amoeba transaction */ # define AM_GETREQ 3 /* amoeba getrequest */ # define AM_PUTREP 4 /* amoeba putrep */ # define AM_REVIVE 6 /* used by kernel task to revive luser task */ # define AM_TIMEOUT 8 /* used to talk to clock task */ # define AM_PUTSIG 9 /* when the luser hits the DEL ! */ # define AM_TASK_DIED 10 /* sent if task died during a transaction */ #else /* if AMOEBA not defined */ #define AMOEBA_CLASS TTY #endif /* AMOEBA */ /* * New class definitions should go here and should be defined relative * to AMOEBA_CLASS (ie. as AMOEBA_CLASS+n, for the nth task added). */ #define IDLE (AMOEBA_CLASS+1) /* task to run when there's nothing to run */ #define PRINTER -7 /* printer I/O class */ /* The printer uses the same commands as TTY. */ #define WINCHESTER -6 /* winchester (hard) disk class */ #define FLOPPY -5 /* floppy disk class */ # define DISK_READ 3 /* fcn code to DISK (must equal TTY_READ) */ # define DISK_WRITE 4 /* fcn code to DISK (must equal TTY_WRITE) */ # define DISK_IOCTL 5 /* fcn code for setting up RAM disk */ # define SCATTERED_IO 6 /* fcn code for multiple reads/writes */ # define OPTIONAL_IO 16 /* modifier to DISK_* codes within vector */ #define MEM -4 /* /dev/ram, /dev/(k)mem and /dev/null class */ # define RAM_DEV 0 /* minor device for /dev/ram */ # define MEM_DEV 1 /* minor device for /dev/mem */ # define KMEM_DEV 2 /* minor device for /dev/kmem */ # define NULL_DEV 3 /* minor device for /dev/null */ #if (CHIP == INTEL) # define PORT_DEV 4 /* minor device for /dev/port */ #endif #define CLOCK -3 /* clock class */ # define SET_ALARM 1 /* fcn code to CLOCK, set up alarm */ # define GET_TIME 3 /* fcn code to CLOCK, get real time */ # define SET_TIME 4 /* fcn code to CLOCK, set real time */ # define REAL_TIME 1 /* reply from CLOCK: here is real time */ #define SYSTASK -2 /* internal functions */ # define SYS_XIT 1 /* fcn code for sys_xit(parent, proc) */ # define SYS_GETSP 2 /* fcn code for sys_sp(proc, &new_sp) */ # define SYS_SIG 3 /* fcn code for sys_sig(proc, sig) */ # define SYS_FORK 4 /* fcn code for sys_fork(parent, child) */ # define SYS_NEWMAP 5 /* fcn code for sys_newmap(procno, map_ptr) */ # define SYS_COPY 6 /* fcn code for sys_copy(ptr) */ # define SYS_EXEC 7 /* fcn code for sys_exec(procno, new_sp) */ # define SYS_TIMES 8 /* fcn code for sys_times(procno, bufptr) */ # define SYS_ABORT 9 /* fcn code for sys_abort() */ # define SYS_FRESH 10 /* fcn code for sys_fresh() (Atari only) */ # define SYS_KILL 11 /* fcn code for sys_kill(proc, sig) */ # define SYS_GBOOT 12 /* fcn code for sys_gboot(procno, bootptr) */ # define SYS_UMAP 13 /* fcn code for sys_umap(procno, etc) */ # define SYS_MEM 14 /* fcn code for sys_mem() */ # define SYS_TRACE 15 /* fcn code for sys_trace(req,pid,addr,data) */ #define HARDWARE -1 /* used as source on interrupt generated msgs*/ /* Names of message fields for messages to CLOCK task. */ #define DELTA_TICKS m6_l1 /* alarm interval in clock ticks */ #define FUNC_TO_CALL m6_f1 /* pointer to function to call */ #define NEW_TIME m6_l1 /* value to set clock to (SET_TIME) */ #define CLOCK_PROC_NR m6_i1 /* which proc (or task) wants the alarm? */ #define SECONDS_LEFT m6_l1 /* how many seconds were remaining */ /* Names of message fields used for messages to block and character tasks. */ #define DEVICE m2_i1 /* major-minor device */ #define PROC_NR m2_i2 /* which (proc) wants I/O? */ #define COUNT m2_i3 /* how many bytes to transfer */ #define POSITION m2_l1 /* file offset */ #define ADDRESS m2_p1 /* core buffer address */ /* Names of message fields for messages to TTY task. */ #define TTY_LINE m2_i1 /* message parameter: terminal line */ #define TTY_REQUEST m2_i3 /* message parameter: ioctl request code */ #define TTY_SPEK m2_l1 /* message parameter: ioctl speed, erasing */ #define TTY_FLAGS m2_l2 /* message parameter: ioctl tty mode */ #define TTY_PGRP m2_i3 /* message parameter: process group */ /* Names of messages fields used in reply messages from tasks. */ #define REP_PROC_NR m2_i1 /* # of proc on whose behalf I/O was done */ #define REP_STATUS m2_i2 /* bytes transferred or error number */ /* Names of fields for copy message to SYSTASK. */ #define SRC_SPACE m5_c1 /* T or D space (stack is also D) */ #define SRC_PROC_NR m5_i1 /* process to copy from */ #define SRC_BUFFER m5_l1 /* virtual address where data come from */ #define DST_SPACE m5_c2 /* T or D space (stack is also D) */ #define DST_PROC_NR m5_i2 /* process to copy to */ #define DST_BUFFER m5_l2 /* virtual address where data go to */ #define COPY_BYTES m5_l3 /* number of bytes to copy */ /* Field names for accounting, SYSTASK and miscellaneous. */ #define USER_TIME m4_l1 /* user time consumed by process */ #define SYSTEM_TIME m4_l2 /* system time consumed by process */ #define CHILD_UTIME m4_l3 /* user time consumed by process' children */ #define CHILD_STIME m4_l4 /* sys time consumed by process' children */ #define PROC1 m1_i1 /* indicates a process */ #define PROC2 m1_i2 /* indicates a process */ #define PID m1_i3 /* process id passed from MM to kernel */ #define STACK_PTR m1_p1 /* used for stack ptr in sys_exec, sys_getsp */ #define PR m6_i1 /* process number for sys_sig */ #define SIGNUM m6_i2 /* signal number for sys_sig */ #define FUNC m6_f1 /* function pointer for sys_sig */ #define MEM_PTR m1_p1 /* tells where memory map is for sys_newmap */ #define CANCEL 0 /* general request to force a task to cancel */ #define SIG_MAP m1_i2 /* used by kernel for passing signal bit map */ #ifdef AMOEBA /* Names of message fields for amoeba tasks */ #define AM_OP m2_i1 /* one of the above operators */ #define AM_PROC_NR m2_i2 /* process # of proc doing operation */ #define AM_COUNT m2_i3 /* size of buffer for operation */ #define AM_ADDRESS m2_p1 /* address of buffer for operation */ /* For communication between MM and AMOEBA_CLASS kernel tasks */ #define AM_STATUS m2_i3 /* same use as REP_STATUS but for amoeba */ #define AM_FREE_IT m2_l1 /* 1=not a getreq, 0=is a getreq */ /* Special for passing a physical address from the ethernet driver */ #define AM_PADDR m2_l1 /* to the transaction layer */ #endif /* AMOEBA */ #define HARD_INT 2 /* fcn code for all hardware interrupts */
{'content_hash': 'f9df1ef6dac46637021009afd24c97de', 'timestamp': '', 'source': 'github', 'line_count': 166, 'max_line_length': 79, 'avg_line_length': 47.506024096385545, 'alnum_prop': 0.6505199086989601, 'repo_name': 'macminix/MacMinix', 'id': '2096f8ba765448daed32f1f58c71692b6eaa5fdd', 'size': '7886', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'include/minix/com.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '360566'}, {'name': 'C', 'bytes': '3820041'}, {'name': 'C++', 'bytes': '18889'}, {'name': 'IDL', 'bytes': '54'}, {'name': 'Smalltalk', 'bytes': '3572'}]}
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/colorAccent"> <shape android:shape="rectangle"> <corners android:radius="4dp"/> <solid android:color="@android:color/white"/> </shape> </item> </selector>
{'content_hash': '0c5c532741b17d9555e504f006cb4d6f', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 69, 'avg_line_length': 37.77777777777778, 'alnum_prop': 0.6176470588235294, 'repo_name': 'coderwjq/ZhaZhaShop', 'id': '18d9057e931dc1eec93e181d35fb48d50721ab45', 'size': '340', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'shop/src/main/res/drawable/bg_tv_indicator.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '942134'}]}
#region Mr. Advice MVVM // // Mr. Advice MVVM // // A simple MVVM package using Mr. Advice aspect weaver // // https://github.com/ArxOne/MrAdvice.MVVM // // Released under MIT license http://opensource.org/licenses/mit-license.php #endregion namespace ArxOne.MrAdvice.MVVM.Properties { /// <summary> /// Marks a simple auto property to be bound to a DependencyProperty /// Note: use <see cref="Dependency"/>, this class will be deprecated soon /// </summary> public class DependencyProperty : Dependency { } }
{'content_hash': 'e6f968f6bcaa02164d63a014a40698b9', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 79, 'avg_line_length': 31.764705882352942, 'alnum_prop': 0.6888888888888889, 'repo_name': 'ArxOne/MrAdvice.MVVM', 'id': '44988b339a9dae3106bd24bb29f525eac790a6ff', 'size': '542', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MrAdvice.MVVM/MVVM/Properties/DependencyProperty.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '174074'}]}
package org.ringojs.util; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.debug.DebugFrame; import org.mozilla.javascript.debug.DebuggableScript; import org.mozilla.javascript.debug.Debugger; import java.util.logging.Level; import java.util.logging.Logger; /** * A base class for Debuggers and Profilers implemented in Javascript. * This allows to exclude the debugger/profiler module and all modules * it uses to be excluded from debugging/profiling. */ public abstract class DebuggerBase implements Debugger { String debuggerScript; int debuggerScriptDepth = 0; final Logger log = Logger.getLogger(DebuggerBase.class.getName()); public abstract DebuggerBase createDebugger(); public abstract Object createContextData(); public abstract void handleCompilationDone(Context cx, DebuggableScript fnOrScript, String source); public abstract DebugFrame getScriptFrame(Context cx, DebuggableScript fnOrScript); public void attach() { attach(createContextData()); } public void setDebuggerScript(String path) { debuggerScript = path; } public void install() { ContextFactory factory = Context.getCurrentContext().getFactory(); factory.addListener(new ContextFactory.Listener() { public void contextCreated(Context cx) { DebuggerBase debugger = createDebugger(); if (debugger != null) { debugger.attach(createContextData()); } } public void contextReleased(Context cx) { } }); } public void attach(Object contextData) { Context cx = Context.getCurrentContext(); cx.setDebugger(this, contextData); cx.setOptimizationLevel(-1); cx.setGeneratingDebug(true); } public void detach() { Context cx = Context.getCurrentContext(); cx.setDebugger(null, null); } public Object getContextData() { return Context.getCurrentContext().getDebuggerContextData(); } public synchronized void suspend() { try { wait(); } catch (InterruptedException ir) { Thread.currentThread().interrupt(); } } public synchronized void resume() { notify(); } public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript) { String path = fnOrScript.getSourceName(); if (log.isLoggable(Level.FINE)) { log.fine("Getting Frame for " + path + ", debugger script depth is " + debuggerScriptDepth); } if (debuggerScriptDepth > 0 || path.equals(debuggerScript)) { return new DebuggerScriptFrame(); } else { return getScriptFrame(cx, fnOrScript); } } /** * Get a string representation for the given script * @param script a function or script * @return the file and/or function name of the script */ static String getScriptName(DebuggableScript script) { if (script.isFunction()) { return script.getSourceName() + ": " + script.getFunctionName(); } else { return script.getSourceName(); } } class DebuggerScriptFrame implements DebugFrame { public void onEnter(Context cx, Scriptable activation, Scriptable thisObj, Object[] args) { log.fine("Entering debugger script frame"); debuggerScriptDepth ++; } public void onExit(Context cx, boolean byThrow, Object resultOrException) { log.fine("Exiting debugger script frame"); debuggerScriptDepth --; } public void onLineChange(Context cx, int lineNumber) {} public void onExceptionThrown(Context cx, Throwable ex) {} public void onDebuggerStatement(Context cx) {} } }
{'content_hash': '7bc72a3b9cca751d9857aa4ea38a39f2', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 103, 'avg_line_length': 31.275590551181104, 'alnum_prop': 0.6467774420946626, 'repo_name': 'ringo/ringojs', 'id': '28b86371965cce8c9e11aa1af139908c3c679f4d', 'size': '3972', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'src/org/ringojs/util/DebuggerBase.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '141'}, {'name': 'CSS', 'bytes': '613'}, {'name': 'Dockerfile', 'bytes': '1007'}, {'name': 'HTML', 'bytes': '2026'}, {'name': 'Java', 'bytes': '363438'}, {'name': 'JavaScript', 'bytes': '913850'}, {'name': 'Shell', 'bytes': '2989'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Facecat</title> <!-- Bootstrap --> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <link href="/static/css/facecat.css" rel="stylesheet"> </head> <body> <div id="main" class="container"> <!-- Navbar --> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Facecat</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="/"><span class="glyphicon glyphicon-big glyphicon-cloud-upload"></span> Upload</a></li> <li><a href="/all"><span class="glyphicon glyphicon-big glyphicon-picture"></span> Generated</a></li> </ul> </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </div> <!-- /Navbar --> <!-- Content --> % if 'error' in locals(): <div class="alert alert-danger">An error happend while processing your request.</div> % end <div> <h1>Upload a picture <small> It's more fun if it's the picture of someone.</small></h1> <form id="form-upload" class="padded" role="form" action="/upload" method="post" enctype="multipart/form-data"> <div class="row"> <div class="col-sm-12 col-md-5 center-block"> <div class="input-group"> <span class="input-group-btn"> <span class="btn btn-primary btn-file"> Browse&hellip; <input name="upload" id="upload" type="file"> </span> </span> <input type="text" class="form-control" readonly> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-5 center-block"> <button type="submit" class="form-control btn btn-primary" id="submit" role="button">Upload</button> </div> </div> </form> </div> <!-- /Content --> </div><!--/.container --> <script src="/static/js/jquery-1.11.0.min.js"></script> <script src="/static/js/bootstrap.min.js"></script> <script type="text/javascript"> $(document).on('change', '.btn-file :file', function() { var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1, label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); input.trigger('fileselect', [numFiles, label]); }); $(document).ready( function() { $('.btn-file :file').on('fileselect', function(event, numFiles, label) { var input = $(this).parents('.input-group').find(':text'), log = numFiles > 1 ? numFiles + ' files selected' : label; if( input.length ) { input.val(log); } else { if( log ) alert(log); } }); }); </script> </body> </html>
{'content_hash': '0ff5431891cb2864bd51ef0adfd0e451', 'timestamp': '', 'source': 'github', 'line_count': 110, 'max_line_length': 129, 'avg_line_length': 36.68181818181818, 'alnum_prop': 0.5241635687732342, 'repo_name': 'NicolasLM/python-runabove', 'id': 'c289353c9893e03aa4228b58f31f19256ca86a72', 'size': '4035', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'examples/facecat/views/index.html', 'mode': '33188', 'license': 'mit', 'language': []}
namespace AH.ModuleController.UI.DIET.Forms { partial class frmPatientListDietAssign { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.btnShow = new System.Windows.Forms.Button(); this.smartLabel4 = new AtiqsControlLibrary.SmartLabel(); this.cboReceivingNurseStation = new AtiqsControlLibrary.SmartComboBox(); this.dgvDietList = new AtiqsControlLibrary.SmartDataGridView(); this.dgvPatientList = new AtiqsControlLibrary.SmartDataGridView(); this.txtAdmissionID = new System.Windows.Forms.TextBox(); this.txtDeitID = new System.Windows.Forms.TextBox(); this.pnlMain.SuspendLayout(); this.pnlTop.SuspendLayout(); this.groupBox4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvDietList)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvPatientList)).BeginInit(); this.SuspendLayout(); // // btnTopClose // this.btnTopClose.Location = new System.Drawing.Point(1128, 12); // // frmLabel // this.frmLabel.Location = new System.Drawing.Point(393, 9); this.frmLabel.Size = new System.Drawing.Size(406, 33); this.frmLabel.Text = "Assign Diet For Admitted Patient "; // // pnlMain // this.pnlMain.Controls.Add(this.dgvDietList); this.pnlMain.Controls.Add(this.groupBox4); this.pnlMain.Controls.Add(this.dgvPatientList); this.pnlMain.Location = new System.Drawing.Point(0, 58); this.pnlMain.Size = new System.Drawing.Size(1260, 606); // // pnlTop // this.pnlTop.Controls.Add(this.txtDeitID); this.pnlTop.Controls.Add(this.txtAdmissionID); this.pnlTop.Size = new System.Drawing.Size(1260, 58); this.pnlTop.Controls.SetChildIndex(this.frmLabel, 0); this.pnlTop.Controls.SetChildIndex(this.btnTopClose, 0); this.pnlTop.Controls.SetChildIndex(this.txtAdmissionID, 0); this.pnlTop.Controls.SetChildIndex(this.txtDeitID, 0); // // btnEdit // this.btnEdit.Location = new System.Drawing.Point(110, 673); this.btnEdit.Size = new System.Drawing.Size(19, 27); this.btnEdit.Visible = false; // // btnSave // this.btnSave.Location = new System.Drawing.Point(135, 681); this.btnSave.Size = new System.Drawing.Size(33, 17); this.btnSave.Visible = false; // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(50, 673); this.btnDelete.Size = new System.Drawing.Size(21, 27); this.btnDelete.Visible = false; // // btnNew // this.btnNew.Location = new System.Drawing.Point(1026, 670); this.btnNew.Click += new System.EventHandler(this.btnNew_Click); // // btnClose // this.btnClose.Location = new System.Drawing.Point(1140, 670); this.btnClose.TabIndex = 3; // // btnPrint // this.btnPrint.Location = new System.Drawing.Point(77, 673); this.btnPrint.Size = new System.Drawing.Size(27, 27); this.btnPrint.Visible = false; // // groupBox1 // this.groupBox1.Location = new System.Drawing.Point(0, 709); this.groupBox1.Size = new System.Drawing.Size(1260, 25); // // groupBox4 // this.groupBox4.BackColor = System.Drawing.Color.PaleTurquoise; this.groupBox4.Controls.Add(this.btnShow); this.groupBox4.Controls.Add(this.smartLabel4); this.groupBox4.Controls.Add(this.cboReceivingNurseStation); this.groupBox4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox4.ForeColor = System.Drawing.Color.DarkBlue; this.groupBox4.Location = new System.Drawing.Point(3, 2); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(1256, 104); this.groupBox4.TabIndex = 5; this.groupBox4.TabStop = false; this.groupBox4.MouseHover += new System.EventHandler(this.groupBox4_MouseHover); // // btnShow // this.btnShow.BackColor = System.Drawing.Color.DarkSalmon; this.btnShow.Location = new System.Drawing.Point(540, 40); this.btnShow.Name = "btnShow"; this.btnShow.Size = new System.Drawing.Size(238, 30); this.btnShow.TabIndex = 158; this.btnShow.Text = "Click Patient List to Add Diet"; this.btnShow.UseVisualStyleBackColor = false; this.btnShow.Click += new System.EventHandler(this.btnShow_Click); // // smartLabel4 // this.smartLabel4.AutoSize = true; this.smartLabel4.BackColor = System.Drawing.Color.PaleTurquoise; this.smartLabel4.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Bold); this.smartLabel4.Location = new System.Drawing.Point(42, 46); this.smartLabel4.Name = "smartLabel4"; this.smartLabel4.Size = new System.Drawing.Size(120, 15); this.smartLabel4.TabIndex = 157; this.smartLabel4.Text = "Select Nurse Station"; // // cboReceivingNurseStation // this.cboReceivingNurseStation.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboReceivingNurseStation.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cboReceivingNurseStation.ForeColor = System.Drawing.Color.Blue; this.cboReceivingNurseStation.FormattingEnabled = true; this.cboReceivingNurseStation.Items.AddRange(new object[] { "1", "2"}); this.cboReceivingNurseStation.Location = new System.Drawing.Point(168, 43); this.cboReceivingNurseStation.Name = "cboReceivingNurseStation"; this.cboReceivingNurseStation.Size = new System.Drawing.Size(356, 26); this.cboReceivingNurseStation.TabIndex = 156; // // dgvDietList // this.dgvDietList.AllowUserToAddRows = false; this.dgvDietList.AllowUserToDeleteRows = false; this.dgvDietList.AllowUserToOrderColumns = true; this.dgvDietList.AllowUserToResizeColumns = false; this.dgvDietList.AllowUserToResizeRows = false; this.dgvDietList.BackgroundColor = System.Drawing.Color.White; this.dgvDietList.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.Color.LightGreen; dataGridViewCellStyle1.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle1.ForeColor = System.Drawing.Color.Black; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; this.dgvDietList.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.dgvDietList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle2.BackColor = System.Drawing.Color.White; dataGridViewCellStyle2.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Black; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.Color.Lavender; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.Color.Crimson; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dgvDietList.DefaultCellStyle = dataGridViewCellStyle2; this.dgvDietList.Location = new System.Drawing.Point(865, 75); this.dgvDietList.MultiSelect = false; this.dgvDietList.Name = "dgvDietList"; this.dgvDietList.RowHeadersVisible = false; dataGridViewCellStyle3.BackColor = System.Drawing.Color.White; this.dgvDietList.RowsDefaultCellStyle = dataGridViewCellStyle3; this.dgvDietList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgvDietList.Size = new System.Drawing.Size(272, 395); this.dgvDietList.TabIndex = 159; this.dgvDietList.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dgvDietList_CellMouseDoubleClick); // // dgvPatientList // this.dgvPatientList.AllowUserToAddRows = false; this.dgvPatientList.AllowUserToDeleteRows = false; this.dgvPatientList.AllowUserToOrderColumns = true; this.dgvPatientList.AllowUserToResizeColumns = false; this.dgvPatientList.AllowUserToResizeRows = false; this.dgvPatientList.BackgroundColor = System.Drawing.Color.White; this.dgvPatientList.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle4.BackColor = System.Drawing.Color.LightGreen; dataGridViewCellStyle4.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle4.ForeColor = System.Drawing.Color.Black; dataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText; this.dgvPatientList.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle4; this.dgvPatientList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle5.BackColor = System.Drawing.Color.White; dataGridViewCellStyle5.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle5.ForeColor = System.Drawing.Color.Black; dataGridViewCellStyle5.SelectionBackColor = System.Drawing.Color.Lavender; dataGridViewCellStyle5.SelectionForeColor = System.Drawing.Color.Crimson; dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dgvPatientList.DefaultCellStyle = dataGridViewCellStyle5; this.dgvPatientList.Location = new System.Drawing.Point(2, 106); this.dgvPatientList.MultiSelect = false; this.dgvPatientList.Name = "dgvPatientList"; this.dgvPatientList.RowHeadersVisible = false; dataGridViewCellStyle6.BackColor = System.Drawing.Color.White; this.dgvPatientList.RowsDefaultCellStyle = dataGridViewCellStyle6; this.dgvPatientList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgvPatientList.Size = new System.Drawing.Size(1253, 497); this.dgvPatientList.TabIndex = 6; this.dgvPatientList.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvPatientList_CellClick); // // txtAdmissionID // this.txtAdmissionID.Location = new System.Drawing.Point(916, 9); this.txtAdmissionID.Name = "txtAdmissionID"; this.txtAdmissionID.Size = new System.Drawing.Size(100, 20); this.txtAdmissionID.TabIndex = 161; this.txtAdmissionID.Visible = false; // // txtDeitID // this.txtDeitID.Location = new System.Drawing.Point(1022, 7); this.txtDeitID.Name = "txtDeitID"; this.txtDeitID.Size = new System.Drawing.Size(100, 20); this.txtDeitID.TabIndex = 162; this.txtDeitID.Visible = false; // // frmPatientListDietAssign // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.ClientSize = new System.Drawing.Size(1260, 734); this.isEnterTabAllow = true; this.Name = "frmPatientListDietAssign"; this.Load += new System.EventHandler(this.frmPatientList_Load); this.pnlMain.ResumeLayout(false); this.pnlTop.ResumeLayout(false); this.pnlTop.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvDietList)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvPatientList)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox4; private AtiqsControlLibrary.SmartDataGridView dgvPatientList; private AtiqsControlLibrary.SmartLabel smartLabel4; private AtiqsControlLibrary.SmartComboBox cboReceivingNurseStation; private System.Windows.Forms.Button btnShow; public System.Windows.Forms.TextBox txtAdmissionID; public System.Windows.Forms.TextBox txtDeitID; private AtiqsControlLibrary.SmartDataGridView dgvDietList; } }
{'content_hash': '7577a20e44e72cb7e2da2aed635be20c', 'timestamp': '', 'source': 'github', 'line_count': 286, 'max_line_length': 184, 'avg_line_length': 56.45454545454545, 'alnum_prop': 0.6495726495726496, 'repo_name': 'atiq-shumon/DotNetProjects', 'id': '63424a60f594df942497663d5c4bfb6bbaeb0f9a', 'size': '16148', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Hospital_ERP_VS13-WCF_WF/AH.ModuleController/UI/DIET/Forms/frmPatientListDietAssign.Designer.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '1059021'}, {'name': 'C#', 'bytes': '39389238'}, {'name': 'CSS', 'bytes': '683218'}, {'name': 'HTML', 'bytes': '44772'}, {'name': 'JavaScript', 'bytes': '1343054'}, {'name': 'PLpgSQL', 'bytes': '340074'}, {'name': 'Pascal', 'bytes': '81971'}, {'name': 'PowerShell', 'bytes': '175142'}, {'name': 'Puppet', 'bytes': '2111'}, {'name': 'Smalltalk', 'bytes': '9'}, {'name': 'XSLT', 'bytes': '12347'}]}
package org.medipi.clinical.dao; import java.util.List; import org.medipi.clinical.entities.PatientGroup; import org.springframework.stereotype.Repository; /** * Implementation of Data Access Object for Patient * @author rick@robinsonhq.com */ @Repository public class PatientGroupDAOImpl extends GenericDAOImpl<PatientGroup> implements PatientGroupDAO { @Override public List<PatientGroup> getAllGroups() { return this.getEntityManager().createNamedQuery("PatientGroup.findAll", PatientGroup.class) .getResultList(); } }
{'content_hash': '3bf94388278a7d76abcb340256e75471', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 99, 'avg_line_length': 29.63157894736842, 'alnum_prop': 0.7602131438721137, 'repo_name': 'Samuel789/MediPi', 'id': '33522f5a6540bd8fb6f89dd443207ac049bb383a', 'size': '1167', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Clinician/MediPiClinical/src/main/java/org/medipi/clinical/dao/PatientGroupDAOImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '10012'}, {'name': 'CSS', 'bytes': '847678'}, {'name': 'HTML', 'bytes': '4238145'}, {'name': 'Java', 'bytes': '1942198'}, {'name': 'JavaScript', 'bytes': '2308166'}, {'name': 'PHP', 'bytes': '1684'}, {'name': 'Python', 'bytes': '66091'}, {'name': 'Ruby', 'bytes': '1183'}, {'name': 'Shell', 'bytes': '17053'}]}
package enums; public enum GameStatusType { GAME_WAITING, GAME_READY, GAME_PAUSE, GAME_RUNNING, GAME_END }
{'content_hash': 'f493082fa8f2d360462e63e43976d837', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 28, 'avg_line_length': 12.555555555555555, 'alnum_prop': 0.7345132743362832, 'repo_name': 'ptutak/Warcaby', 'id': 'b49884d68c81fb001a43a5b878b7d5aac2c17e36', 'size': '701', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/enums/GameStatusType.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '103900'}]}
package com.taotao.model; import java.util.Date; /** * TITLE:广告的model * USER:TAOTK * DATA:2016/9/14 * TIME:10:48 * COMPANY:www.51pjia.com */ public class PjPoster { private Integer id; //int(11) NOT NULL, private Integer category_id;// int(11) DEFAULT NULL, private String category_name; //varchar(32) DEFAULT NULL, private Integer poster_sort; //int(11) DEFAULT NULL, private String poster_url; //varchar(50) DEFAULT NULL, private String poster_size; //varchar(32) DEFAULT NULL, private Date create_time;//datetime DEFAULT NULL, private Integer poster_status; //int(11) DEFAULT NULL, private Integer poster_address; private String categoryName; private String poster_small_url;//小图片 public String getPoster_small_url() { return poster_small_url; } public void setPoster_small_url(String poster_small_url) { this.poster_small_url = poster_small_url; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public Integer getPoster_address() { return poster_address; } public void setPoster_address(Integer poster_address) { this.poster_address = poster_address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCategory_id() { return category_id; } public void setCategory_id(Integer category_id) { this.category_id = category_id; } public String getCategory_name() { return category_name; } public void setCategory_name(String category_name) { this.category_name = category_name; } public Integer getPoster_sort() { return poster_sort; } public void setPoster_sort(Integer poster_sort) { this.poster_sort = poster_sort; } public String getPoster_url() { return poster_url; } public void setPoster_url(String poster_url) { this.poster_url = poster_url; } public String getPoster_size() { return poster_size; } public void setPoster_size(String poster_size) { this.poster_size = poster_size; } public Date getCreate_time() { return create_time; } public void setCreate_time(Date create_time) { this.create_time = create_time; } public Integer getPoster_status() { return poster_status; } public void setPoster_status(Integer poster_status) { this.poster_status = poster_status; } @Override public String toString() { return "PjPoster{" + "id=" + id + ", category_id=" + category_id + ", category_name='" + category_name + '\'' + ", poster_sort=" + poster_sort + ", poster_url='" + poster_url + '\'' + ", poster_size='" + poster_size + '\'' + ", create_time=" + create_time + ", poster_status=" + poster_status + ", poster_address=" + poster_address + ", categoryName='" + categoryName + '\'' + ", poster_small_url='" + poster_small_url + '\'' + '}'; } }
{'content_hash': '7ab49f595d4875b5c338cb3b1ae66c93', 'timestamp': '', 'source': 'github', 'line_count': 129, 'max_line_length': 66, 'avg_line_length': 25.88372093023256, 'alnum_prop': 0.5882000598981731, 'repo_name': '17755332301/Tao-', 'id': 'c90f72f6b45864fc59a103913265bc15df0b29bc', 'size': '3351', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'taotao-web/src/main/java/com/taotao/model/PjPoster.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '31784'}, {'name': 'C#', 'bytes': '16030'}, {'name': 'CSS', 'bytes': '625671'}, {'name': 'HTML', 'bytes': '558187'}, {'name': 'Java', 'bytes': '280551'}, {'name': 'JavaScript', 'bytes': '4548934'}, {'name': 'PHP', 'bytes': '32951'}]}
Q: How to modify non-configurable, non-writable properties in Javascript? I'm writing a simple EventEmitter is ES5. The objective is to ensure that all properties on EventEmitter instances are non-writable and non-configurable." After 6 hours of racking my brain I still can't figure out how to, increase the listenerCount, for example if the configurable descriptor is set to false. Here's an example of what I have: var eventEmitter = function(){ var listeners = listeners || 0; var events = events || {}; Object.defineProperties(this, { listeners: { value : 0, configurable: false, writable: false }, events: { value: {}, configurable : false, writable: false } }); return this; }; eventEmmitter.prototype.on = function(ev, cb) { if (typeof ev !== 'string') throw new TypeError("Event should be type string", "index.js", 6); if (typeof cb !== 'function' || cb === null || cb === undefined) throw new TypeError("callback should be type function", "index.js", 7); if (this.events[ev]){ this.events[ev].push(cb); } else { this.events[ev] = [cb]; } this.listeners ++; return this; }; A: I would recommend the use of an IIFE (immediatly invoked function expression): var coolObj=(function(){ var public={}; var nonpublic={}; nonpublic.a=0; public.getA=function(){nonpublic.a++;return nonpublic.a;}; return public; })(); Now you can do: coolObj.getA();//1 coolObj.getA();//2 coolObj.a;//undefined coolObj.nonpublic;//undefined coolObj.nonpublic.a;//undefined I know this is not the answer youve expected, but i think its the easiest way of doing sth like that. A: You can use a proxy which requires a key in order to define properties: function createObject() { var key = {configurable: true}; return [new Proxy({}, { defineProperty(target, prop, desc) { if (desc.value === key) { return Reflect.defineProperty(target, prop, key); } } }), key]; } function func() { var [obj, key] = createObject(); key.value = 0; Reflect.defineProperty(obj, "value", {value: key}); key.value = function() { key.value = obj.value + 1; Reflect.defineProperty(obj, "value", {value: key}); }; Reflect.defineProperty(obj, "increase", {value: key}); return obj; } var obj = func(); console.log(obj.value); // 0 try { obj.value = 123; } catch(err) {} try { Object.defineProperty(obj, "value", {value: 123}); } catch(err) {} console.log(obj.value); // 0 obj.increase(); console.log(obj.value); // 1
{'language': 'en', 'url': 'https://stackoverflow.com/questions/41069927', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '2'}
Q: Image hiding under button android Image view is hiding under the button what changes I can do so that the image view can be above the button view pager also have bottom padding so that button can properly accommodate. The image is showing on the other parts but not above the button. <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".McqActivity" android:id="@+id/fragment" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"> <ImageView android:id="@+id/starFirst" android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/ic_baseline_star_24" /> <com.google.android.material.button.MaterialButton android:id="@+id/right" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/questions_view_frag" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.0" android:orientation="horizontal" android:paddingBottom="20dp" android:paddingTop="50dp" > </androidx.viewpager2.widget.ViewPager2> </androidx.constraintlayout.widget.ConstraintLayout> A: layout_constraintBottom_toBottomOf and other layout_constraint... won't work inside RelativeLayout, these are desired to work with ConstraintLayout as strict parent. if you want to align two Views next to/below/above inside RelativeLayoyut you have to use other attributes, e.g. android:layout_below="@+id/starFirst" android:layout_above="@+id/starFirst" android:layout_toRightOf="@id/starFirst" android:layout_toLeftOf="@id/starFirst" note that every attr which starts with layout_ is desired to be read by strict parent, not by View which have such attrs set. every ViewGroup have own set of such edit: turned out that this is an elevation case/issue (Z axis), so useful attributes are android:translationZ="100dp" android:elevation="100dp"
{'language': 'en', 'url': 'https://stackoverflow.com/questions/70017985', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Handling multiple exceptions I have written a class which loads configuration objects of my application and keeps track of them so that I can easily write out changes or reload the whole configuration at once with a single method call. However, each configuration object might potentially throw an exception when doing IO, yet I do not want those errors to cancel the overall process in order to give the other objects still a chance to reload/write. Therefore I collect all exceptions which are thrown while iterating over the objects and store them in a super-exception, which is thrown after the loop, since each exception must still be handled and someone has to be notified of what exactly went wrong. However, that approach looks a bit odd to me. Someone out there with a cleaner solution? Here is some code of the mentioned class: public synchronized void store() throws MultipleCauseException { MultipleCauseException me = new MultipleCauseException("unable to store some resources"); for(Resource resource : this.resources.values()) { try { resource.store(); } catch(StoreException e) { me.addCause(e); } } if(me.hasCauses()) throw me; } A: If you want to keep the results of the operations, which it seems you do as you purposely carry on, then throwing an exception is the wrong thing to do. Generally you should aim not to disturb anything if you throw an exception. What I suggest is passing the exceptions, or data derived from them, to an error handling callback as you go along. public interface StoreExceptionHandler { void handle(StoreException exc); } public synchronized void store(StoreExceptionHandler excHandler) { for (Resource resource : this.resources.values()) { try { resource.store(); } catch (StoreException exc) { excHandler.handle(exc); } } /* ... return normally ... */ ] A: There are guiding principles in designing what and when exceptions should be thrown, and the two relevant ones for this scenario are: * *Throw exceptions appropriate to the abstraction (i.e. the exception translation paradigm) *Throw exceptions early if possible The way you translate StoreException to MultipleCauseException seems reasonable to me, although lumping different types of exception into one may not be the best idea. Unfortunately Java doesn't support generic Throwables, so perhaps the only alternative is to create a separate MultipleStoreException subclass instead. With regards to throwing exceptions as early as possible (which you're NOT doing), I will say that it's okay to bend the rule in certain cases. I feel like the danger of delaying a throw is when exceptional situations nest into a chain reaction unnecessarily. Whenever possible, you want to avoid this and localize the exception to the smallest scope possible. In your case, if it makes sense to conceptually think of storing of resources as multiple independent tasks, then it may be okay to "batch process" the exception the way you did. In other situations where the tasks has more complicated interdependency relationship, however, lumping it all together will make the task of analyzing the exceptions harder. In a more abstract sense, in graph theory terms, I think it's okay to merge a node with multiple childless children into one. It's probably not okay to merge a whole big subtree, or even worse, a cyclic graph, into one node.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/2444580', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '8'}
Q: What is the meaning of Duration in Amazon RDS Backup window What does Duration specify? Does it mean that the backup will start between 01:00 to 01:30 and keep running until it has completed? Or does it have a different meaning? A: The duration window indicates the time in which the backup will start. I can start anywhere between the time specified and could last longer than the window.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/58445170', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '-1'}
Q: Uncontrolled input of type text to be controlled warning I'm trying to create a multi step registration form using React and Redux. The main component is as follows : import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actionCreators from '../../actions/actionCreators'; import countries from '../../data/countries'; import RegistrationFormStepOne from './registrationFormStepOne'; import RegistrationFormStepTwo from './registrationFormStepTwo'; import RegistrationFormStepThree from './registrationFormStepThree'; import RegistrationFormStepFour from './registrationFormStepFour'; class RegistrationPage extends React.Component { constructor(props) { super(props); this.state = { user: Object.assign({}, this.props.userData), fileNames: {}, selectedFile: {}, icons: { idCard: 'upload', statuten: 'upload', blankLetterhead: 'upload', companyPhoto: 'upload' }, step: 1, errors: {} }; this.setUser = this.setUser.bind(this); this.onButtonClick = this.onButtonClick.bind(this); this.onButtonPreviousClick = this.onButtonPreviousClick.bind(this); this.changeCheckboxState = this.changeCheckboxState.bind(this); this.onFileChange = this.onFileChange.bind(this); this.routerWillLeave = this.routerWillLeave.bind(this); } componentDidMount() { this.context.router.setRouteLeaveHook(this.props.route, this.routerWillLeave); } routerWillLeave(nextLocation) { if (this.state.step > 1) { this.setState({step: this.state.step - 1}); return false; } } getCountries(){ return countries; } setUser(event) { const field = event.target.name; const value = event.target.value; let user = this.state.user; user[field] = value; this.setState({user: user}); } validation(){ const user = this.state.user; const languageReg = this.props.currentLanguage.default.registrationPage; let formIsValid = true; let errors = {}; if(!user.companyName){ formIsValid = false; errors.companyName = languageReg.companyNameEmpty; } if(!user.btwNumber){ formIsValid = false; errors.btwNumber = languageReg.btwNumberEmpty; } if(!user.address){ formIsValid = false; errors.address = languageReg.addressEmpty; } if(!user.country){ formIsValid = false; errors.country = languageReg.countryEmpty; } if(!user.zipcode){ formIsValid = false; errors.zipcode = languageReg.zipcodeEmpty; } if(!user.place){ formIsValid = false; errors.place = languageReg.placeEmpty; } if(!user.firstName){ formIsValid = false; errors.firstName = languageReg.firstnameEmpty; } this.setState({errors: errors}); return formIsValid; } onFileChange(name, event) { event.preventDefault(); let file = event.target.value; let filename = file.split('\\').pop(); //We get only the name of the file let filenameWithoutExtension = filename.replace(/\.[^/.]+$/, ""); //We get the name of the file without extension let user = this.state.user; let fileNames = this.state.fileNames; let selectedFile = this.state.selectedFile; let icons = this.state.icons; switch (name.btnName) { case "idCard" : fileNames[name.btnName] = filenameWithoutExtension; //Check if file is selected if(file){ selectedFile[name.btnName] = "fileSelected"; user["idCardFile"] = true; icons["idCard"] = "check"; }else{ selectedFile[name.btnName] = ""; user["idCardFile"] = false; icons["idCard"] = "upload"; } break; case "statuten" : fileNames[name.btnName] = filenameWithoutExtension; //Check if file is selected if(file){ selectedFile[name.btnName] = "fileSelected"; user["statutenFile"] = true; icons["statuten"] = "check"; }else{ selectedFile[name.btnName] = ""; user["statutenFile"] = false; icons["statuten"] = "upload"; } break; case "blankLetterhead" : fileNames[name.btnName] = filenameWithoutExtension; //Check if file is selected if(file){ selectedFile[name.btnName] = "fileSelected"; user["blankLetterheadFile"] = true; icons["blankLetterhead"] = "check"; }else{ selectedFile[name.btnName] = ""; user["blankLetterheadFile"] = false; icons["blankLetterhead"] = "upload"; } break; default: fileNames[name.btnName] = filenameWithoutExtension; //Check if file is selected if(file){ selectedFile[name.btnName] = "fileSelected"; user["companyPhotoFile"] = true; icons["companyPhoto"] = "check"; }else{ selectedFile[name.btnName] = ""; user["companyPhotoFile"] = false; icons["companyPhoto"] = "upload"; } } this.setState({user: user, fileNames: fileNames, selectedFile: selectedFile, icons: icons}); } changeCheckboxState(event) { let chcName = event.target.name; let user = this.state.user; switch (chcName) { case "chcEmailNotificationsYes": user["emailNotifications"] = event.target.checked; break; case "chcEmailNotificationsNo": user["emailNotifications"] = !event.target.checked; break; case "chcTerms": if(typeof this.state.user.terms === "undefined"){ user["terms"] = false; }else{ user["terms"] = !this.state.user.terms; } break; case "chcSmsYes": user["smsNotifications"] = event.target.checked; break; default: user["smsNotifications"] = !event.target.checked; } this.setState({user: user}); this.props.actions.userRegistration(this.state.user); } onButtonClick(name, event) { event.preventDefault(); this.props.actions.userRegistration(this.state.user); switch (name) { case "stepFourConfirmation": this.setState({step: 1}); break; case "stepTwoNext": this.setState({step: 3}); break; case "stepThreeFinish": this.setState({step: 4}); break; default: if(this.validation()) { this.setState({step: 2}); } } } onButtonPreviousClick(){ this.setState({step: this.state.step - 1}); } render() { const languageReg = this.props.currentLanguage.default.registrationPage; console.log(this.state.user); let formStep = ''; let step = this.state.step; switch (step) { case 1: formStep = (<RegistrationFormStepOne user={this.props.userData} onChange={this.setUser} onButtonClick={this.onButtonClick} countries={this.getCountries(countries)} errors={this.state.errors} step={step}/>); break; case 2: formStep = (<RegistrationFormStepTwo user={this.props.userData} onChange={this.setUser} onButtonClick={this.onButtonClick} onButtonPreviousClick={this.onButtonPreviousClick} errors={this.state.errors}/>); break; case 3: formStep = (<RegistrationFormStepThree user={this.props.userData} onFileChange={this.onFileChange} onButtonClick={this.onButtonClick} onButtonPreviousClick={this.onButtonPreviousClick} errors={this.state.errors} fileNames={this.state.fileNames} icons={this.state.icons} fileChosen={this.state.selectedFile}/>); break; default: formStep = (<RegistrationFormStepFour user={this.props.userData} onChange={this.setUser} onChangeCheckboxState={this.changeCheckboxState} onButtonClick={this.onButtonClick} onButtonPreviousClick={this.onButtonPreviousClick} errors={this.state.errors}/>); } return ( <div className="sidebar-menu-container" id="sidebar-menu-container"> <div className="sidebar-menu-push"> <div className="sidebar-menu-overlay"></div> <div className="sidebar-menu-inner"> <div className="contact-form"> <div className="container"> <div className="row"> <div className="col-md-10 col-md-offset-1 col-md-offset-right-1"> {React.cloneElement(formStep, {currentLanguage: languageReg})} </div> </div> </div> </div> </div> </div> </div> ); } } RegistrationPage.contextTypes = { router: PropTypes.object }; function mapStateToProps(state, ownProps) { return { userData: state.userRegistrationReducer }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actionCreators, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(RegistrationPage); The first step component is as follows import React from 'react'; import Button from '../../common/formElements/button'; import RegistrationFormHeader from './registrationFormHeader'; import TextInput from '../../common/formElements/textInput'; import SelectInput from '../../common/formElements/selectInput'; const RegistrationFormStepOne = ({user, onChange, onButtonClick, errors, currentLanguage, countries}) => { const language = currentLanguage; return ( <div className="contact_form"> <form role="form" action="" method="post" id="contact_form"> <div className="row"> <RegistrationFormHeader activeTab={0} currentLanguage={language}/> <div className="hideOnBigScreens descBox"> <div className="headerTitle">{language.businessInfoConfig}</div> <div className="titleDesc">{language.businessBoxDesc}</div> </div> <div className="col-lg-12"> <h6 className="registrationFormDesc col-lg-10 col-lg-offset-1 col-lg-offset-right-2 col-xs-12"> {language.businessDesc} </h6> <div className="clearfix"></div> <div className="col-sm-6"> <TextInput type="text" name="companyName" label={language.companyNameLabel} labelClass="control-label" placeholder={language.companyNameLabel} className="templateInput" id="company" onChange={onChange} value={user.companyName} errors={errors.companyName} /> </div> <div className="col-sm-6"> <TextInput type="text" name="btwNumber" label={language.vatNumberLabel} placeholder={language.vatNumberLabel} className="templateInput" id="btwNumber" onChange={onChange} value={user.btwNumber} errors={errors.btwNumber} /> </div> <div className="col-sm-12" style={{marginBottom: 25}}> <TextInput type="text" name="address" label={language.addressLabel} placeholder={language.address1Placeholder} className="templateInput" id="address" onChange={onChange} value={user.address} errors={errors.address} /> </div> <div className="col-sm-12" style={{marginBottom: 25}}> <TextInput type="text" name="address1" placeholder={language.address2Placeholder} className="templateInput" id="address" onChange={onChange} value={user.address1} errors="" /> </div> <div className="col-sm-12"> <TextInput type="text" name="address2" placeholder={language.address3Placeholder} className="templateInput" id="address" onChange={onChange} value={user.address2} errors="" /> </div> <div className="col-sm-3"> <SelectInput name="country" label={language.selectCountryLabel} onChange={onChange} options={countries} className="templateInput selectField" defaultOption={language.selectCountry} value={user.country} errors={errors.country} /> </div> <div className="col-sm-3"> <TextInput type="text" name="zipcode" label={language.zipcodeLabel} placeholder={language.zipcodeLabel} className="templateInput" id="zipcode" onChange={onChange} value={user.zipcode} errors={errors.zipcode} /> </div> <div className="col-sm-6"> <TextInput type="text" name="place" label={language.placeLabel} placeholder={language.placeLabel} className="templateInput" id="place" onChange={onChange} value={user.place} errors={errors.place} /> </div> </div> <div className="clearfix"></div> <div className="col-lg-12" style={{marginLeft: 15, marginTop: 30}}> <Button onClick={onButtonClick.bind(this)} name="stepOneNext" value={language.btnNext} icon="arrow-circle-right" style={{margin: '0 auto 60px'}}/> </div> </div> </form> </div> ); }; export default RegistrationFormStepOne; I try to add some simple validation and I've added validation function in my main component and then I check on button click if the returned value true or false is. If it's true, than I set step state to a appropriate value. And it works if I validate only the form fields of the first step, but when I try to also validate one or more form fields of the next step (now I'm trying to validate also the first field of the second step) if(!user.firstName){ formIsValid = false; errors.firstName = languageReg.firstnameEmpty; } I get than Warning: TextInput is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. Without the validation function works everything perfect. Any advice? EDIT import React, {propTypes} from 'react'; import _ from 'lodash'; const TextInput = ({errors, style, name, labelClass, label, className, placeholder, id, value, onChange, type}) => { let wrapperClass = "form-group"; if (errors) { wrapperClass += " " + "inputHasError"; } return ( <div className={wrapperClass} style={style}> <label htmlFor={name} className={labelClass}>{label}</label> <input type={type} className={className} placeholder={placeholder} name={name} id={id} value={value} style={{}} onChange={onChange} /> <div className="errorBox">{errors}</div> </div> ); }; TextInput.propTypes = { name: React.PropTypes.string.isRequired, label: React.PropTypes.string, onChange: React.PropTypes.func.isRequired, type: React.PropTypes.string.isRequired, id: React.PropTypes.string, style: React.PropTypes.object, placeholder: React.PropTypes.string, className: React.PropTypes.string, labelClass: React.PropTypes.string, value: React.PropTypes.string, errors: React.PropTypes.string }; export default TextInput; This is second step component : import React from 'react'; import Button from '../../common/formElements/button'; import RegistrationFormHeader from './registrationFormHeader'; import TextInput from '../../common/formElements/textInput'; const RegistrationFormStepTwo = ({user, onChange, onButtonClick, onButtonPreviousClick, errors, currentLanguage}) => { const language = currentLanguage; return ( <div className="contact_form"> <form role="form" action="" method="post" id="contact_form"> <div className="row"> <RegistrationFormHeader activeTab={1} currentLanguage={language}/> <div className="hideOnBigScreens descBox"> <div className="headerTitle">{language.personalInfoConfig}</div> <div className="titleDesc">{language.personalBoxDesc}</div> </div> <div className="col-lg-12"> <h6 className="registrationFormDesc col-lg-10 col-lg-offset-1 col-lg-offset-right-2 col-xs-12"> {language.personalDesc} </h6> <div className="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <TextInput type="text" name="firstName" label={language.firsnameLabel} placeholder={language.firsnameLabel} className="templateInput" id="name" onChange={onChange} value={user.firstName} errors={errors.firstName} /> </div> <div className="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <TextInput type="text" name="lastName" label={language.lastnameLabel} placeholder={language.lastnameLabel} className="templateInput" id="name" onChange={onChange} value={user.lastName} errors={errors.lastName} /> </div> <div className="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <TextInput type="text" name="phone" label={language.phoneLabel} placeholder={language.phoneLabel} className="templateInput" id="phone" onChange={onChange} value={user.phone} errors={errors.phone} /> </div> <div className="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <TextInput type="text" name="mobilePhone" label={language.mobileLabel} placeholder={language.mobileLabel} className="templateInput" id="phone" style={{}} onChange={onChange} value={user.mobilePhone} errors={errors.mobilePhone} /> </div> <div className="clearfix"></div> <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <TextInput type="text" name="email" id="email" label={language.emailLabel} placeholder={language.emailLabel} className="templateInput" style={{}} onChange={onChange} value={user.email} errors={errors.email} /> </div> <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <TextInput type="text" name="userName" label={language.usernameLabel} placeholder={language.usernameLabel} className="templateInput" id="name" onChange={onChange} value={user.userName} errors={errors.userName} /> </div> <div className="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <TextInput type="password" name="password" label={language.passwordLabel} placeholder={language.passwordLabel} className="templateInput" id="password" onChange={onChange} value={user.password} errors={errors.password} /> </div> <div className="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <TextInput type="password" name="confirmPassword" label={language.passwordConfirmLabel} placeholder={language.passwordConfirmLabel} className="templateInput" id="password" onChange={onChange} value={user.confirmPassword} errors={errors.confirmPassword} /> </div> </div> <div className="clearfix"></div> <div className="col-lg-6 col-xs-6" style={{marginTop: 30}}> <Button onClick={onButtonPreviousClick} name="btnPrevious" value={language.btnPrevious} icon="arrow-circle-left" style={{marginRight: 10, float: 'right'}}/> </div> <div className="col-lg-6 col-xs-6" style={{marginTop: 30}}> <Button onClick={onButtonClick} name="stepTwoNext" value={language.btnNext} icon="arrow-circle-right" style={{marginLeft: 10, float: 'left'}}/> </div> </div> </form> </div> ); }; export default RegistrationFormStepTwo; A: This is why the warning exists: When the value is specified as undefined, React has no way of knowing if you intended to render a component with an empty value or if you intended for the component to be uncontrolled. It is a source of bugs. You could do a null/undefined check, before passing the value to the input. a source A: @Kokovin Vladislav is right. To put this in code, you can do this in all your input values: <TextInput // your other code value={user.firstName || ''} /> That is, if you don't find the value of first name, then give it an empty value.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/38014397', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '6'}
Q: Interleaving the rows of two different SQL tables, group by one row My Sql query is like this $view = mysql_query ("SELECT domain,count(distinct session_id) as views FROM `statistik` left join statistik_strippeddomains on statistik_strippeddomains.id = statistik.strippeddomain WHERE `angebote_id` = '".(int)$_GET['id']."' and strippeddomain!=1 group by domain having count (distinct session_id) > ".(int)($film_daten['angebote_views']/100)." order count(distinct session_id$vladd) desc limit 25"); How can I write its Codeigniter Model I appreciate any Help A: try this $this->db->select('statistik.domain,statistik.count(DISTINCT(session_id)) as views'); $this->db->from('statistik'); $this->db->join('statistik_strippeddomains', 'statistik_strippeddomains.id = statistik.strippeddomain', 'left'); $this->db->where('angebote_id',$_GET['id']); $this->db->where('strippeddomain !=',1); $this->db->group_by('domain'); $this->db->having('count > '.$film_daten['angebote_views']/100, NULL, FALSE); $this->db->order_by('count','desc'); $this->db->limit('25'); $query = $this->db->get(); Comment me If you have any query.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/39852573', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Query conditions to insert data from a form What I'm trying to do is: If the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that? if($form_data->action == 'Insert') { $age=array(28, 30, 25, 21); $age_str=implode("','", $age); if($form_data->age == $age_str){ $query="INSERT INTO tbl (VE) VALUE ('8') WHERE id= '".$form_data->id."' "; $statement = $connect->prepare($query); $statement->execute(); } $data = array( ':date' => $date, ':first_name' => $first_name, ':last_name' => $last_name, ':age' => $age ); $query = " INSERT INTO tbl (date, first_name, last_name, age) VALUES (:date, :first_name, :last_name, :age) "; $statement = $connect->prepare($query); if($statement->execute($data)) { $message = 'Data Inserted'; } } Also, how do I insert the new row with the row id from the other form data going into tbl? A: Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement. if ($form_data->action == 'Insert') { // assuming $age, $date, $first_name, $last_name // already declared prior to this block $data = array( ':date' => $date, ':first_name' => $first_name, ':last_name' => $last_name, ':age' => $age ); $query = " INSERT INTO tbl (date, first_name, last_name, age) VALUES (:date, :first_name, :last_name, :age) "; $statement = $connect->prepare($query); if ($statement->execute($data)) { $message = 'Data Inserted'; // $id is the last inserted id for (tbl) $id = $connect->lastInsertID(); // NOW you can insert your child row in the other table $ages_to_insert = array(28, 30, 25, 21); // in_array uses your array...so you don't need // if($form_data->age == $age_str){ if (in_array($form_data->age, $ages_to_insert)) { $query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'"; $statement2 = $connect->prepare($query); $statement2->execute(); } } }
{'language': 'en', 'url': 'https://stackoverflow.com/questions/58903757', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Is the function $\ln(ax + b)$ increasing/decreasing, concave/convex? $h(x) = \ln(ax + b)$ NB. Examine your results acccording to values of $(a,b)$ I've differentiated twice in order to get the following: $$ h''(x) = -\frac{a^2}{(ax+b)^2} $$ I think this proves that $h(x)$ is concave for all value of $a$ and $b$ since $h''(x)\le0$. Is this correct? I don't know how to prove whether it's increasing/decreasing or what the NB really means so any help with that would be great. A: we now that the domain of the function is: $$ax+b\gt 0\Rightarrow x\gt\frac{-b}{a}\text{so the domain is:}(\frac{-b}{a},+\infty)$$ $$f'(x)=\frac{a}{ax+b}$$ in the domain of the function since we have $x\gt\frac{-b}{a}\Rightarrow ax+b>0 $ the sign of $f'(x)=\frac{a}{ax+b}$ will be dependent to the sign of $a$ so: if $a\gt 0\Rightarrow f'(x)\gt 0$ and $f(x)$ will be increasing in its domain if $a\lt 0\Rightarrow f'(x)\lt 0$ and $f(x)$ will be decreasing in its domain Note the phrases in its domain in the above expression, we always study the behaviors of functions in their domain $$f''(x)=\frac{-a^2}{(ax+b)^2}$$ as you said without we always have $f''(x)<0$ so without considering the sign of $a$, $f(x)$ will be a convex function The value of $b$ doesnot influence the first and second derivation and so will not affect concavity, convexity, increase or decrease of the function here is the diagram for $f(x)=\ln(2x+1)$ as you see $a=2\gt 0$ and $f(x)$ is increasing and convex here is the diagram for $f(x)=\ln(-2x+1)$ as you see $a=-2\lt 0$ and $f(x)$ is decreasing and convex A: $$h^{ \prime }\left( x \right) =\frac { a }{ ax+b } >0$$ $1$.if $a>0$ $ax+b>0$ $\Rightarrow $ $ax>-b$ $\Rightarrow $ $x>-\frac { b }{ a } $ function is increasing $2$.if $a<0 $ $x<-\frac { b }{ a } $ function is decreasing And about concavity you are right,find second derivative and check intervals
{'language': 'en', 'url': 'https://math.stackexchange.com/questions/1400530', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Accessing array value is null Hello I have decoded a json string that I sent to my server and Im trying to get the values from him. My problem is that I cant get the values from the inner arrays. This is my code: <?php $post = file_get_contents('php://input'); $arrayBig = json_decode($post, true); foreach ($arrayBig as $array) { $exercise = $array['exercise']; $response["exercise"] = $exercise; $response["array"] = $array; echo json_encode($response); } ?> When I get the answer from my $response I get this values: {"exercise":null,"array":[{"exercise":"foo","reps":"foo"}]} Why is $array['exercise'] null if I can see that is not null in the array Thanks. A: Because of the [{...}] you are getting an array in an array when you decode your array key. So: $exercise = $array['exercise']; Should be: $exercise = $array[0]['exercise']; See the example here. A: From looking at the result of $response['array'], it looks like $array is actually this [['exercise' => 'foo', 'reps' => 'foo']] that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity... $exercise = $array[0]['exercise'];
{'language': 'en', 'url': 'https://stackoverflow.com/questions/21893968', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Composer update show this error: VirtualAlloc() failed: [0x00000008] Composer worked find yesterday, but today after I trying install: composer require --prefer-dist "himiklab/yii2-recaptcha-widget" "*" While run composer update command it show me error: VirtualAlloc() failed: [0x00000008] VirtualAlloc() failed: [0x00000008] PHP Fatal error: Out of memory (allocated 956301312) (tried to allocate 201326600 bytes) in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php on line 84 Fatal error: Out of memory (allocated 956301312) (tried to allocate 201326600 bytes) in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php on line 84 I try update composer on my other projects, it is worked fine. After some researching I increased memory_limit: 4096M(also -1) in php.ini file. Then I tried to increase virtual memory in Computer->Properties, but still show error. I try to run next command: composer update -vvv --profile, result in attached image Composer error Any help would be greatly appreciated. A: You are probably using 32bit PHP. This version cannot allocate enough memory for composer even if you change the memory_limit to -1 (unlimited). Please use 64 bit PHP with the Composer to get rid of these memory problems.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/49994946', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '2'}
Q: How do I get the original values of in an Update SQL Trigger I'm not very familiar with triggers so thank you for your patience. I have a database table with four columns for user text input and just four date columns showing when the user text input was last changed. What I want the trigger to do is to compare the original and new values of the user text input columns and if they are different update the date column with getdate(). I don't know how to do this. The code I wrote can't get the pre-update value of the field so it can't be compared to the post-update value. Does anyone know how to do it? (Normally I would do this in a stored procedure. However this database table can also be directly edited by an Access database and we can't convert those changes to use the stored procedure. This only leaves us with using a trigger.) A: In sql server there are two special tables availble in the trigger called inserted and deleted. Same structure as the table on which the trigger is implemented. inserted has the new versions, deleted the old.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/10453001', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '3'}
Q: Create Executable progeam of addition in C on linux I am new to Linux. Sorry I am asking very basic question. On windows I have Main.cpp file having code for addition of two number. In Visual studio gives me .exe. But how to do it on Linux. On my Linux machine have gcc compiler no IDE. What I write in Make file and how to run. Main.cpp has code like #include <stido.h> #include <conio.h> // Static library file included //#include "Add.h" int main() { int a,b,c; a = 10; b = 20; c= a+b; //Add function in static lib (.a in case of linux) //c= Add(a,b); printf("Addition is :%d",c); return 0; } After that I want use Add function which is in Addition. How to use with above program removing commented in code? A: For c++ code, the command is usually something like: g++ Main.cpp -o FileNameToWriteTo Alternatively, if you just run g++ Main.cpp it will output to a default file called a.out. Either way, you can then run whichever file you created by doing: ./FileNameToWriteTo.out See this for more details: http://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html
{'language': 'en', 'url': 'https://stackoverflow.com/questions/39793206', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '-3'}
Q: QProgressBar updates as function progress How to initializa the operation of QProgressBar, I already declare her maximum, minimum, range and values. I want to assimilate the progress of QProgressBar with the "sleep_for" function. Current code: void MainPrograma::on_pushCorre_clicked() { QPlainTextEdit *printNaTela = ui->plainTextEdit; printNaTela->moveCursor(QTextCursor::End); printNaTela->insertPlainText("corrida iniciada\n"); QProgressBar *progresso = ui->progressBar; progresso->setMaximum(100); progresso->setMinimum(0); progresso->setRange(0, 100); progresso->setValue(0); progresso->show(); WORD wEndereco = 53606; WORD wValor = 01; WORD ifValor = 0; EscreveVariavel(wEndereco, wValor); //How to assimilate QProgressBar to this function: std::this_thread::sleep_for(std::chrono::milliseconds(15000)); //StackOverFlow help me please EscreveVariavel(wEndereco, ifValor); A: use a QTimer and in the slot update the value of the progressbar MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); t = new QTimer(this); t->setSingleShot(false); c = 0; connect(t, &QTimer::timeout, [this]() { c++; if (c==100) { c=0; } qDebug() << "T..."; ui->progressBar->setValue(c); }); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { t->start(100); } A: I'm not sure about your intentions with such sleep: are you simulating long wait? do you have feedback about progress during such process? Is it a blocking task (as in the example) or it will be asynchronous? As a direct answer (fixed waiting time, blocking) I think it is enough to make a loop with smaller sleeps, like: EscreveVariavel(wEndereco, wValor); for (int ii = 0; ii < 100; ++ii) { progresso->setValue(ii); qApp->processEvents(); // necessary to update the UI std::this_thread::sleep_for(std::chrono::milliseconds(150)); } EscreveVariavel(wEndereco, ifValor); Note that you may end waiting a bit more time due to thread scheduling and UI refresh. For an async task you should pass the progress bar to be updated, or some kind of callback that does such update. Keep in mind that UI can only be refreshed from main thread.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/64987457', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Preallocation and Vectorization Speedup I am trying to improve the speed of script I am trying to run. Here is the code: (my machine = 4 core win 7) clear y; n=100; x=linspace(0,1,n); % no y pre-allocation using zeros start_time=tic; for k=1:n, y(k) = (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2); end elapsed_time1 = toc(start_time); fprintf('Computational time for serialized solution: %f\n',elapsed_time1); Above code gives 0.013654 elapsed time. On the other hand, I was tried to use pre-allocation by adding y = zeros(1,n); in the above code where the comment is but the running time is similar around ~0.01. Any ideas why? I was told it would improve by a factor of 2. Am I missing something? Lastly is there any type of vectorization in Matlab that will allow me to forget about the for loop in the above code? Thanks, A: In your code: try with n=10000 and you'll see more of a difference (a factor of almost 10 on my machine). These things related with allocation are most noticeable when the size of your variable is large. In that case it's more difficult for Matlab to dynamically allocate memory for that variable. To reduce the number of operations: do it vectorized, and reuse intermediate results to avoid powers: y = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20)); Benchmarking: With n=100: Parag's / venergiac's solution: >> tic for count = 1:100 y=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2); end toc Elapsed time is 0.010769 seconds. My solution: >> tic for count = 1:100 y = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20)); end toc Elapsed time is 0.006186 seconds. A: You don't need a for loop. Replace the for loop with the following and MATLAB will handle it. y=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2); This may give a computational advantage when vectors become larger in size. Smaller size is the reason why you cannot see the effect of pre-allocation. Read this page for additional tips on how to improve the performance. Edit: I observed that at larger sizes, n>=10^6, I am getting a constant performance improvement when I try the following: x=0:1/n:1; instead of using linspace. At n=10^7, I gain 0.05 seconds (0.03 vs 0.08) by NOT using linspace. A: try operation element per element (.*, .^) clear y; n=50000; x=linspace(0,1,n); % no y pre-allocation using zeros start_time=tic; for k=1:n, y(k) = (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2); end elapsed_time1 = toc(start_time); fprintf('Computational time for serialized solution: %f\n',elapsed_time1); start_time=tic; y = (1-(3/5)*x+(3/20)*x.^2 -(x.^3/60)) / (1+(2/5)*x-(1/20)*x.^2); elapsed_time1 = toc(start_time); fprintf('Computational time for product solution: %f\n',elapsed_time1); my data Computational time for serialized solution: 2.578290 Computational time for serialized solution: 0.010060
{'language': 'en', 'url': 'https://stackoverflow.com/questions/21564052', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '2'}
Q: Scala and Akka HTTP: Request inside a request & issue with threads I am new to learning Scala, Akka Streams and Akka HTTP, so apologies beforehand if the question is too basic. I want to do an HTTP request inside an HTTP request, just like in the following piece of code: implicit val system = ActorSystem("ActorSystem") implicit val materializer = ActorMaterializer import system.dispatcher val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].map { case HttpRequest(HttpMethods.GET, Uri.Path("/api"), _, _, _) => val responseFuture = Http().singleRequest(HttpRequest(uri = "http://www.google.com")) responseFuture.onComplete { case Success(response) => response.discardEntityBytes() println(s"The request was successful") case Failure(ex) => println(s"The request failed with: $ex") } //Await.result(responseFuture, 10 seconds) println("Reached HttpResponse") HttpResponse( StatusCodes.OK ) } Http().bindAndHandle(requestHandler, "localhost", 8080) But in the above case the result looks like this, meaning that Reached HttpResponse is reached first before completing the request: Reached HttpResponse The request was successful I tried using Await.result(responseFuture, 10 seconds) (currently commented out) but it made no difference. What am I missing here? Any help will be greatly appreciated! Many thanks in advance! A: map is a function that takes request and produces a response: HttpRequest => HttpResponse The challenge is that response is a type of Future. Therefore, you need a function that deals with it. The function that takes HttpRequest and returns Future of HttpResponse. HttpRequest => Future[HttpResponse] And voila, mapAsync is exactly what you need: val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].mapAsync(2) { case HttpRequest(HttpMethods.GET, Uri.Path("/api"), _, _, _) => Http().singleRequest(HttpRequest(uri = "http://www.google.com")).map (resp => { resp.discardEntityBytes() println(s"The request was successful") HttpResponse(StatusCodes.OK) }) }
{'language': 'en', 'url': 'https://stackoverflow.com/questions/61038711', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '5'}
Q: Initial Boundary Value Problem for a Wave Equation $u_{tt}=4u_{xx}$ Solve the initial boundary value problem: \begin{equation} \begin{aligned} u_{tt} &= 4u_{xx} \quad x > 0, \, t > 0 \\ u(x, 0) &= x^2/8, \\ u_t(x, 0) &= x \quad x ≥ 0 \\ u(0,t) &= t^2, \quad t ≥ 0.\end{aligned} \end{equation} This question is from here. Seeing that that question is not active, how would we approach this?
{'language': 'en', 'url': 'https://math.stackexchange.com/questions/4581378', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Dealing with four digits: memcache sorts 1000 before 150 from least to greatest In app engine I retrieve a list of items stored in memcache: items = memcache.get("ITEMS") and sort them by amount and price: items.sort(key = lambda x:(x.price, x.amount)) Which works most of the time, when the amount is three digits. However, when I have 2 items with 150 and 1000 amounts for the same price, the entry with 1000 goes before other one. How can I fix this? A: fixed it: items.sort(key = lambda x:((float)(x.price), (int)(x.amount)))
{'language': 'en', 'url': 'https://stackoverflow.com/questions/21960862', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Do codigniter 3.1.7 support hmvc? I tried but no luck From the very first answer of this How to implement HMVC in codeigniter 3.0? I tried all steps with codigniter 3.7.1 but no luck. I am still getting 404. $config['modules_locations'] = array( APPPATH.'modules/' => '../modules/', ); Then I tried putting the above code in application/config/config.php but still 404
{'language': 'en', 'url': 'https://stackoverflow.com/questions/48606954', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Saving time - Compiling c++ and plotting at the same time gnuplot Hi in order to save time whene I execute the code I command this line : g++ name.cpp && ./a.out where nome,cpp is the name of the file that contains the code. If I succesively I need to plot some data generated by the exucatable with Gnuplot there is a way to add in the previous line instead of writing: gnuplot plot "name2.dat" ? A: you can: g++ name.cpp && ./a.out && gnuplot -e "plot 'name2.dat'; pause -1" gnuplot exits when you hit return (see help pause for more options) if you want to start an interactive gnuplot session there is a dirty way I implemented. g++ name.cpp && ./a.out && gnuplot -e "plot 'name2.dat' - (pay attention to the final minus sign)
{'language': 'en', 'url': 'https://stackoverflow.com/questions/50157509', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '-1'}
Q: How to put a Hyphen in column Total Cost Value in power bi I have a table with blank value, but i want a hyphen "-" to appear when the value is null. Using an expression similar to this: var VLGROUP = (Expression…… RETURN IF( ISBLANK(VLGROUP), BLANK(), VLGROUP) Someone know if is possible? Thanks!! enter image description here gur.com/C0u8s.png A: Try this below option- Sales for the Group = var sales = CALCULATE( SUM(Financialcostcenter[amount]), Financialcostcenter[partnercompany]= "BRE", Financialcostcenter[2 digits]=71, DATESYTD('Datas'[Date]) ) + CALCULATE( SUM(Financialcostcenter[amount]), Financialcostcenter[partnercompany]= "GRM", Financialcostcenter[2 digits]=71, DATESYTD('Datas'[Date]) ) RETURN IF(sales = BLANK(),"-", -(sales))
{'language': 'en', 'url': 'https://stackoverflow.com/questions/63953889', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Part time job at the vegetable/fruits shop. You recently applied for a job at the vegetable/fruits store and the shop owner called you for a small quiz.so you went there and everything was going apparently well… but then he asked you that since his favourite number is 10 and his favourite fruit is orange so he wants to make a pyramid of oranges where the triangle on the base is an equilateral triangle made having 10 oranges on each side, then the total number of oranges in the complete pyramid will be?? Note-this is a homework question from sequences and series and not something I picked from a puzzle book… I tried solving it but I am not able to visualise it properly so I am not able to get the correct answer. A: Triangle on base will have (1 + 2 + 3 + 4+ ... +10) Next one will have as above but only to 9 - and so on until you only have 1 at the top I have deliberately not done the entire calculation for you - if you are still confused after this attempt to help you visualize it, add a comment and I will clarify more A: Here is how I visualise it. Triangle on base will have ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 ) oranges and the next one will have ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 ). So the total amount will be : 10*1 + 9*2 + 8*3 + 7*4 + 6*5 + 5*6 + 4*7 + 3*8 + 2*9 + 1*10
{'language': 'en', 'url': 'https://math.stackexchange.com/questions/1509492', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '-1'}
Q: Constraints on an embedded subclass - Grails, GORM, Mongo I've been pulling my hair out with this issue for a couple of days. I have an embedded subclass with several specified constraints. My issue is that these constraints are never enforced, I'm using grails 2.3.11 and the mongodb plugin 3.0.2. Here is my setup (Simplified slightly). Media class class Media{ ObjectId id; String name; Film film; static mapWith = "mongo" static embedded = ["film"] } Film Class class Film{ ObjectId id; String name; static mapWith = "mongo" static belongsTo = [media : Media] static mapping = { lazy:false } static constraints = { name(nullable:false) //works as expected. Save fails if name is set to null } } ActionFilm Class class ActionFilm extends Film{ int score; String director; //These constraints are never enforeced. No matter what value I set the fields to the save is always successful static constraints = { score(min:50) director(nullable:true) } } Is this an issue with Mongo and Gorm? Is it possible to have contraints in bth a parent and subclass? Example code when saving public boolean saveMedia(){ ActionFilm film = new ActionFilm() film.setName("TRON"); film.setScore(2) film.setDirector("Ted") Media media = new Media() media.setName("myMedia") media.setFilm(film) media.save(flush:true, failOnError:false) //Saves successfully when it shouldn't as the score is below the minimum constrains } Edit I've played aroubd some more and the issue only persits when I'm saving the Media object with ActionFilm as an embedded object. If I save the ActionFilm object the validation is applied. ActionFilm film = new ActionFilm() film.setName("TRON"); film.setScore(2) film.setDirector("Ted") film.save(flush:true, failOnError:false) //Doesn't save as the diameter is wrong. Expected behaviour. So the constraints are applied as expected when I save the ActionFilm object but aren't applied if its an embedded object. A: I've solved my issue in case anyone else comes across this. It may not be the optimal solution but I haven't found an alternative. I've added a custom validator to the Media class that calls validate() on the embedded Film class and adds any errors that arise to the Media objects errors class Media{ ObjectId id; String name; Film film; static mapWith = "mongo" static embedded = ["film"] static constraints = { film(validator : {Film film, def obj, def errors -> boolean valid = film.validate() if(!valid){ film.errors.allErrors.each {FieldError error -> final String field = "film" final String code = "$error.code" errors.rejectValue(field,code,error.arguments,error.defaultMessage ) } } return valid } ) }
{'language': 'en', 'url': 'https://stackoverflow.com/questions/26994126', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: MySQL -> PHP Array -> Json need output in array plus object format i am trying to fetch data from MySQL and show it in JSON format This is the partial PHP code $sql = "SELECT item, cost, veg, spicy_level FROM food1"; $result = $conn->query($sql); while($row = $result->fetch_assoc()) { echo json_encode($row),"<br/>";} ?> i am getting output as {"item":"dosa","cost":"20","veg":"0","spicy_level":"1"} {"item":"idli","cost":"20","veg":"0","spicy_level":"2"} but i need it as food1:[ {"item":"dosa","cost":"20","veg":"0","spicy_level":"1"}, {"item":"idli","cost":"20","veg":"0","spicy_level":"2"} ] can anyone please guide me? i think what i am getting is in object format and i need output in array format i.e. with [ & ]. very new to this json and php. A: You can incapsulate query results in array and after print it; $sql = "SELECT item, cost, veg, spicy_level FROM food1"; $result = $conn->query($sql); $a = array(); while($row = $result->fetch_assoc()) { if($a['food1'] ==null) $a['food1'] = array(): array_push($a['food1'],$row);} echo json_encode($a); ?></i> A: Your code should be : $sql = "SELECT item, cost, veg, spicy_level FROM food1"; $result = $conn->query($sql); $food['food1'] = array(); while($row = $result->fetch_assoc()) { $food['food1'][] = $row; } echo json_encode($food); A: Don't call json_encode each time through the loop. Put all the rows into an array, and then encode that. $food = array(); while ($row = $result->fetch_assoc()) { $food[] = $row; } echo json_encode(array('food1' => $food));
{'language': 'en', 'url': 'https://stackoverflow.com/questions/28872111', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Find a relation between a,b and c $ a,b,c\in \Bbb R$ $2x_1+2x_2+3x_3=a$ $3x_1-x_2+5x_3=b$ $x_1-3x_2+2x_3=c$ if a,b and c is a solution of this linear equation system find the relation between a,b and c I dont understand the question. without knowing a,b and c is a solution of eq.syst. I found $$ \begin{matrix} 2 & 2 & 3 &a \\ 3 & -1 & 5&b \\ 0 & 0 & 0 &a+c-b\\ \end{matrix} $$ and therefore $b=a+c$ when I use a,b and c as a solution $2a+2b+3c=a$ $3a-b+5c=b$ $a-3b+2c=c$ reduced row echolon form is $$ \begin{matrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \\ \end{matrix} $$ it gives a=0 b=0 c=0
{'language': 'en', 'url': 'https://math.stackexchange.com/questions/1410531', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Firebase hosting randomly shows "Site Not Found" at custom domain We recently launched our firebase application at https://tnb-widgets.firebaseapp.com/ and https://thenextbid.com/ (the last one being our custom domain). It all works smoothly except for some seemingly random moments in which it shows a page stating "Site Not Found". This already happened multiple times and after a couple of minutes the site seems to be back again. The last time this happened was at 2:37AM GMT-5 and the last time I deployed a new release to this same firebase hosting project was at 3:45PM the day before. This release also contained 80 files in total, so it cannot possibly be "an empty directory". Our firebase.json file looks like this: { "firestore": { "rules": "firestore.rules", "indexes": "firestore.indexes.json" }, "hosting": { "public": "build", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "/api/**", "function": "app" }, { "source": "**", "destination": "/index.html" } ] }, "storage": { "rules": "storage.rules" } } There's no service workers registered. The "build" folder contains 80 files and most importantly it contains the "index.html" at its root. Does anyone have similar issues? I would appreciate any idea to solve this! Thanks.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/52877497', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '3'}
Q: Reduce Time for Checking Out Code in Visual Studio Online I'm trying out VSO and it's taking over 2 minutes to sync with a GitHub repository. It appears that it's checking out the whole thing on every build. I made sure that the "clean" box is unchecked but it had no effect. Any ideas on how to get it to cache the source or is this even possible in VSO? A: Each build in VSO uses a new VM that is spun up just for your build. Short of hosting your own Build Server connected your VSO, I don't think it can be avoided. Unless there are ways to speed up a the process of downloading the code from a git repo, I think you're stuck.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/31390786', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '-2'}
Q: How to skip a line when reading from a file I am reading stuff from a file and this is the format : c stands for circle and the double is the radius, r for rectangle and the double is width and height respectively and t for triangle and the double represents side length: c 12 c 2 r 3 4 c 2.4 t 2.9 3 c // wrong format t 2.9 10 r // wrong format I run this code: ifstream infile(names); while(infile >> names) { if(names.at(0) == 'c') { double r; infile >> r; cout << "radius = " << r << endl; } else if(names.at(0) == 'r') { double w; double h; infile >> w; infile >> h; cout << "width = " << w << ", height = " << h << endl; } else if(names.at(0) == 't') { double s; infile >> s; cout << "side = " << s << endl; } else { continue; } } infile.close() And this is the output: radius = 12 radius = 2 width = 3, height = 4 radius = 2.4 side = 2.9 radius = 0 I was wondering how I can skip the wrong format line. I have tried using geline but still no luck EDIT: radius, height, width and side have to be > 0 A: The biggest potential problems you are running up against is the fact that you assume a line is valid if it begins with a c, t or r without first validating the remainder of the line matches the format for a circle, triangle or rectangle. While not fatal to this data set, what happens if one of the lines was 'cat' or 'turtle'? By failing to validate all parts of the line fit the "mold" so to speak, you risk attempting to output values of r, h & w or s that were not read from the file. A simple conditional check of the read to catch the potential failbit or badbit will let you validate you have read what you think you read. The remainder is basically semantics of whether you use the niceties of C++ like a vector of struct for rectangles and whether you use a string instead of char*, etc. However, there are certain benefits of using a string to read/validate the remainder of each line (or you could check the stream state and use .clear() and .ignore()) Putting those pieces together, you can do something like the following. Note, there are many, many different approaches you can take, this is just one approach, #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> using namespace std; typedef struct { /* simple typedef for vect of rectangles */ int width, height; } rect_t; int main (int argc, char **argv) { vector<double> cir; /* vector of double for circle radius */ vector<double> tri; /* vector of double for triangle side */ vector<rect_t> rect; /* vector of rect_t for rectangles */ string line; /* string to use a line buffer */ if (argc < 2) { /* validate at least one argument given */ cerr << "error: insufficient input.\n" "usage: " << argv[0] << " filename\n"; return 1; } ifstream f (argv[1]); /* open file given by first argument */ if (!f.is_open()) { /* validate file open for reading */ cerr << "error: file open failed '" << argv[1] << "'.\n"; return 1; } while (getline (f, line)) { /* read each line into 'line' */ string shape; /* string for shape */ istringstream s (line); /* stringstream to parse line */ if (s >> shape) { /* if shape read */ if (shape == "c") { /* is it a "c"? */ double r; /* radius */ string rest; /* string to read rest of line */ if (s >> r && !getline (s, rest)) /* radius & nothing else */ cir.push_back(r); /* add radius to cir vector */ else /* invalid line for circle, handle error */ cerr << "error: invalid radius or unexpected chars.\n"; } else if (shape == "t") { double l; /* side length */ string rest; /* string to read rest of line */ if (s >> l && !getline (s, rest)) /* length & nothing else */ tri.push_back(l); /* add length to tri vector */ else /* invalid line for triangle, handle error */ cerr << "error: invalid triangle or unexpected chars.\n"; } else if (shape == "r") { /* is it a rect? */ rect_t tmp; /* tmp rect_t */ if (s >> tmp.width && s >> tmp.height) /* tmp & nohtin else */ rect.push_back(tmp); /* add to rect vector */ else /* invalid line for rect, handle error */ cerr << "error: invalid width & height.\n"; } else /* line neither cir or rect, handle error */ cerr << "error: unrecognized shape '" << shape << "'.\n"; } } cout << "\nthe circles are:\n"; /* output valid circles */ for (auto& i : cir) cout << " c: " << i << "\n"; cout << "\nthe triangles are:\n"; /* output valid triangles */ for (auto& i : tri) cout << " t: " << i << "\n"; cout << "\nthe rectangles are:\n"; /* output valid rectangles */ for (auto& i : rect) cout << " r: " << i.width << " x " << i.height << "\n"; } By storing values for your circles, triangles and rectangles independent of each other, you then have the ability to handle each type of shape as its own collection, e.g. Example Use/Output $ ./bin/read_shapes dat/shapes.txt error: unrecognized shape '3'. error: unrecognized shape '10'. the circles are: c: 12 c: 2 c: 2.4 the triangles are: t: 2.9 t: 2.9 the rectangles are: r: 3 x 4 Look things over and let me know if you have further questions. The main takeaway is to insure you validate down to the point you can insure what you have read is either a round-peg to fit in the circle hole, a square-peg to fit in a square hole, etc.. A: The only thing I added was a getline where I put a comment at the "else" of the loop. while(infile >> names) { if(names.at(0) == 'c') { double r; infile >> r; cout << "radius = " << r << endl; } else if(names.at(0) == 'r') { double w; double h; infile >> w; infile >> h; cout << "width = " << w << ", height = " << h << endl; } else if(names.at(0) == 't') { double s; infile >> s; cout << "side = " << s << endl; } else { // discard of the rest of the line using getline() getline(infile, names); //cout << "discard: " << names << endl; } } Output: radius = 12 radius = 2 width = 3, height = 4 radius = 2.4 side = 2.9 side = 2.9
{'language': 'en', 'url': 'https://stackoverflow.com/questions/49227626', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: How to filter post by join condition? I have a table called wpps_posts which have this structure: ID | post_title | post_type 1 foo zoacres-property 2 foo2 zoacres-property 3 foo3 post I would like to return all the posts with type zoacres-property and also I want filter them by price. Each price is stored inside the table wp_postmeta: meta_id | post_id | meta_key | meta_value 100 2 price 5000 100 1 price 0 How can I order all the posts by price ASC? I'm stuck with the following query: SELECT * FROM wpps_posts p INNER JOIN wpps_posts wp ON wp.ID = p.ID WHERE p.post_type = 'zoacres-property' ORDER BY wp.meta?? EXPECTED RESULT: ID | post_title | post_type 1 foo zoacres-property 2 foo2 zoacres-propertY A: SELECT * FROM wpps_posts p INNER JOIN wp_postmeta wp ON wp.post_ID = p.ID AND wp.meta_key='price' WHERE p.post_type = 'zoacres-property' ORDER BY wp.meta_value asc A: You could do something like this, depends what other type of meta type records you have. SELECT * FROM wpps_posts LEFT JOIN wp_postmeta ON wp_postmeta.post_id = wpps_posts.ID AND wp_postmeta.meta_key = 'price' WHERE wpps_posts.post_type = 'zoacres-property' ORDER BY wp_postmeta.meta_value
{'language': 'en', 'url': 'https://stackoverflow.com/questions/63576155', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Convert the existing nested dictionary output in string to a list to iterate over it I have a rest api which provides a list of key value pair's and we need to fetch all the id's from this json output file. Contents of the json file { "count": 6, "results": [ { "key": "roles", "id": "1586230" }, { "key": "roles", "id": "1586951" }, { "key": "roles", "id": "1586932" }, ], "roles": { "1586230": { "name": "Systems Engineer", "deleted_at": null, "created_at": "2022-04-22T03:22:24-07:00", "updated_at": "2022-04-22T03:22:24-07:00", "id": "1586230" }, "1586951": { "name": "Engineer- Software", "deleted_at": null, "created_at": "2022-05-05T01:51:29-07:00", "updated_at": "2022-05-05T01:51:29-07:00", "id": "1586951" }, "1586932": { "name": "Engineer- SW", "deleted_at": null, "created_at": "2022-05-05T01:38:37-07:00", "updated_at": "2022-05-05T01:38:37-07:00", "id": "1586932" }, }, "meta": { "count": 6, "page_count": 5, "page_number": 1, "page_size": 20 } } The rest call saves the contents to a file called p1234.json Opened the file in python: with open ('p1234.json') as file: data2 = json.load(file) for ids in data2['results']: res= ids['id'] print(res) Similarly with open ('p1234.json') as file: data2 = json.load(file) for role in data2['roles']: res= roles['name'] print(res) fails with errors. How to iterate over a nested array do I can only get the values of names listed in roles array roles --> 1586230 --> name --> System Engineer Thank you A: You have to loop over the items of the dictionary. for key, value in data2['roles'].items(): res= value['name'] print(res) A: There is nothing wrong with your code, I run it and I didn't get any error. The problem that I see though is your Json file, some commas shouldn't be there: { "count": 6, "results": [ { "key": "roles", "id": "1586230" }, { "key": "roles", "id": "1586951" }, { "key": "roles", "id": "1586932" } \\ here ], "roles": { "1586230": { "name": "Systems Engineer", "deleted_at": null, "created_at": "2022-04-22T03:22:24-07:00", "updated_at": "2022-04-22T03:22:24-07:00", "id": "1586230" }, "1586951": { "name": "Engineer- Software", "deleted_at": null, "created_at": "2022-05-05T01:51:29-07:00", "updated_at": "2022-05-05T01:51:29-07:00", "id": "1586951" }, "1586932": { "name": "Engineer- SW", "deleted_at": null, "created_at": "2022-05-05T01:38:37-07:00", "updated_at": "2022-05-05T01:38:37-07:00", "id": "1586932" } \\ here }, "meta": { "count": 6, "page_count": 5, "page_number": 1, "page_size": 20 } after that any parsing function will do the job.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/72434671', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '-1'}
Q: how to store Image profile(jpg file) and PDF documents in AWS DynamoDB? I am migrating my Spring MVC services to the AWS API Gateway using Python Lambda with Dynamo Db , I have endpoint where i can store or retrieve the people image and also the reports which is PDF file , can you please suggest me which is the best practice to store the images and pdf files in AWS . Your help is really appreciated!! A: Keep in mind, DynamoDB has a 400KB limit on each item. I would recommend using S3 for images and PDF documents. It also allows you to set up a CDN much more easily, rather than using something like DynamoDB. You can always link your S3 link to an item in DynamoDB if you need to store data related to the file. A: AWS DynamoDB has a limit on the row size to be max of 400KB. So, it is not advisable to store the binary content of image/PDF document in a column directly. Instead, you should store the image/PDF in S3 and have the link stored in a column in DynamoDB. If you were using Java, you could have leveraged the S3Link abstraction that takes care of storing the content in S3 and maintaining the link in DynamoDB column.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/47903547', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '2'}
Q: Split a column after specific characters I have a field data in mysql db. For example quot_number ==================== UMAC/ARC/161299/801 UMAC/LAK/151542/1051 UMAC/LAK/150958/00050 Iam expecting an output as below: 801 1051 00050 Actually the last numbers or characters after the last '/' has to be shown in my sql query. Any ways to achieve it? I tried to add something like this, but not getting expected result: LEFT(quotation.quot_number, 16) as quot_number4 right(quot_number,((CHAR_LENGTH(quot_number))-(InStr(quot_number,',')))) as quot_number5 A: Use function substring_index. select substring_index(quot_number, '/', -1) from yourtable
{'language': 'en', 'url': 'https://stackoverflow.com/questions/41219251', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '3'}
Q: HTTPS connection using PEM Certificate I'm trying to POST HTTPS requests using a PEM certificate like following: import httplib CERT_FILE = '/path/certif.pem' conn = httplib.HTTPSConnection('10.10.10.10','443', cert_file =CERT_FILE) conn.request("POST", "/") response = conn.getresponse() print response.status, response.reason conn.close() I have the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/httplib.py", line 914, in request self._send_request(method, url, body, headers) File "/usr/lib/python2.6/httplib.py", line 951, in _send_request self.endheaders() File "/usr/lib/python2.6/httplib.py", line 908, in endheaders self._send_output() File "/usr/lib/python2.6/httplib.py", line 780, in _send_output self.send(msg) File "/usr/lib/python2.6/httplib.py", line 739, in send self.connect() File "/usr/lib/python2.6/httplib.py", line 1116, in connect self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) File "/usr/lib/python2.6/ssl.py", line 338, in wrap_socket suppress_ragged_eofs=suppress_ragged_eofs) File "/usr/lib/python2.6/ssl.py", line 118, in __init__ cert_reqs, ssl_version, ca_certs) ssl.SSLError: [Errno 336265225] _ssl.c:339: error:140B0009:SSL routines:**SSL_CTX_use_PrivateKey_file**:PEM lib When I remove the cert_file from httplib, I've the following response: 200 ok When I add the Authentication header (like advised by MattH) with empty post payload, it works also. However, when I put the good request with the Path, the Body and the Header, like following (I simplified them...) body = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">blablabla</S:Envelope>' URLprov = "/syncaxis2/services/XXXsyncService" auth_header = 'Basic %s' % (":".join(["xxx","xxxxx"]).encode('Base64').strip('\r\n')) conn.request("POST",URLprov,body,{'Authenticate':auth_header}) I have 401 Unauthorized response ! As you can see, first, I'm asked to provide the PrivateKey ! why did I need the PrivateKey if I'm a client ? then, when I remove the PrivateKey and the certificate, and put the Path/Body/headers I have 401 Unauthorized error with the message WWW-Authenticate: Basic realm="SYNCNB Server Realm". Could any one explain this issue? Is there another way to send HTTPS request using a certificate in Python? A: It sounds like you need something similar to an answer I have provided before to perform simple client certificate authentication. Here is the code for convenience modified slightly for your question: import httplib import urllib2 PEM_FILE = '/path/certif.pem' # Renamed from PEM_FILE to avoid confusion CLIENT_CERT_FILE = '/path/clientcert.p12' # This is your client cert! # HTTPS Client Auth solution for urllib2, inspired by # http://bugs.python.org/issue3466 # and improved by David Norton of Three Pillar Software. In this # implementation, we use properties passed in rather than static module # fields. class HTTPSClientAuthHandler(urllib2.HTTPSHandler): def __init__(self, key, cert): urllib2.HTTPSHandler.__init__(self) self.key = key self.cert = cert def https_open(self, req): #Rather than pass in a reference to a connection class, we pass in # a reference to a function which, for all intents and purposes, # will behave as a constructor return self.do_open(self.getConnection, req) def getConnection(self, host): return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert) cert_handler = HTTPSClientAuthHandler(PEM_FILE, CLIENT_CERT_FILE) opener = urllib2.build_opener(cert_handler) urllib2.install_opener(opener) f = urllib2.urlopen("https://10.10.10.10") print f.code A: See http://docs.python.org/library/httplib.html httplib.HTTPSConnection does not do any verification of the server’s certificate. The option to include your private certificate is when the server is doing certificate based authentication of clients. I.e. the server is checking the client has a certificate signed by a CA that it trusts and is allowed to access it's resources. If you don't specify the cert optional argument, you should be able to connect to the HTTPS server, but not validate the server certificate. Update Following your comment that you've tried basic auth, it looks like the server still wants you to authenticate using basic auth. Either your credentials are invalid (have you independently verified them?) or your Authenticate header isn't formatted correctly. Modifying your example code to include a basic auth header and an empty post payload: import httplib conn = httplib.HTTPSConnection('10.10.10.10','443') auth_header = 'Basic %s' % (":".join(["myusername","mypassword"]).encode('Base64').strip('\r\n')) conn.request("POST", "/","",{'Authorization':auth_header}) response = conn.getresponse() print response.status, response.reason conn.close() A: What you're doing is trying to connect to a Web service that requires authentication based on client certificate. Are you sure you have a PEM file and not a PKCS#12 file? A PEM file looks like this (yes, I know I included a private key...this is just a dummy that I generated for this example): -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDDOKpQZexZtGMqb7F1OMwdcFpcQ/pqtCoOVCGIAUxT3uP0hOw8 CZNjLT2LoG4Tdl7Cl6t66SNzMVyUeFUrk5rkfnCJ+W9RIPkht3mv5A8yespeH27x FjGVbyQ/3DvDOp9Hc2AOPbYDUMRmVa1amawxwqAFPBp9UZ3/vfU8nxwExwIDAQAB AoGBAMCvt3svfr9zysViBTf8XYtZD/ctqYeUWEZYR9hj36CQyVLZuAnyMaWcS7j7 GmrfVNygs0LXxoO2Xvi0ZOxj/mZ6EcZd8n37LxTo0GcWvAE4JjPr7I4MR2OvGYa/ 1696e82xwEnUdpyBv9z3ebleowQ1UWP88iq40oZYukUeignRAkEA9c7MABi5OJUq hf9gwm/IBie63wHQbB2wVgB3UuCYEa4Zd5zcvJIKz7NfhsZKKcZJ6CBVxwUd84aQ Aue2DRwYQwJBAMtQ5yBA8howP2FDqcl9sovYR0jw7Etb9mwsRNzJwQRYYnqCC5yS nOaNn8uHKzBcjvkNiSOEZFGKhKtSrlc9qy0CQQDfNMzMHac7uUAm85JynTyeUj9/ t88CDieMwNmZuXZ9P4HCuv86gMcueex5nt/DdVqxXYNmuL/M3lkxOiV3XBavAkAA xow7KURDKU/0lQd+x0X5FpgfBRxBpVYpT3nrxbFAzP2DLh/RNxX2IzAq3JcjlhbN iGmvgv/G99pNtQEJQCj5AkAJcOvGM8+Qhg2xM0yXK0M79gxgPh2KEjppwhUmKEv9 o9agBLWNU3EH9a6oOfsZZcapvUbWIw+OCx5MlxSFDamg -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIDfjCCAuegAwIBAgIJAOYJ/e6lsjrUMA0GCSqGSIb3DQEBBQUAMIGHMQswCQYD VQQGEwJVUzELMAkGA1UECBMCRkwxDjAMBgNVBAcTBVRhbXBhMRQwEgYDVQQKEwtG b29iYXIgSW5jLjEQMA4GA1UECxMHTnV0IEh1dDEXMBUGA1UEAxMOd3d3LmZvb2Jh ci5jb20xGjAYBgkqhkiG9w0BCQEWC2Zvb0BiYXIuY29tMB4XDTExMDUwNTE0MDk0 N1oXDTEyMDUwNDE0MDk0N1owgYcxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJGTDEO MAwGA1UEBxMFVGFtcGExFDASBgNVBAoTC0Zvb2JhciBJbmMuMRAwDgYDVQQLEwdO dXQgSHV0MRcwFQYDVQQDEw53d3cuZm9vYmFyLmNvbTEaMBgGCSqGSIb3DQEJARYL Zm9vQGJhci5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMM4qlBl7Fm0 YypvsXU4zB1wWlxD+mq0Kg5UIYgBTFPe4/SE7DwJk2MtPYugbhN2XsKXq3rpI3Mx XJR4VSuTmuR+cIn5b1Eg+SG3ea/kDzJ6yl4fbvEWMZVvJD/cO8M6n0dzYA49tgNQ xGZVrVqZrDHCoAU8Gn1Rnf+99TyfHATHAgMBAAGjge8wgewwHQYDVR0OBBYEFHZ+ CPLqn8jlT9Fmq7wy/kDSN8STMIG8BgNVHSMEgbQwgbGAFHZ+CPLqn8jlT9Fmq7wy /kDSN8SToYGNpIGKMIGHMQswCQYDVQQGEwJVUzELMAkGA1UECBMCRkwxDjAMBgNV BAcTBVRhbXBhMRQwEgYDVQQKEwtGb29iYXIgSW5jLjEQMA4GA1UECxMHTnV0IEh1 dDEXMBUGA1UEAxMOd3d3LmZvb2Jhci5jb20xGjAYBgkqhkiG9w0BCQEWC2Zvb0Bi YXIuY29tggkA5gn97qWyOtQwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOB gQAv13ewjgrIsm3Yo8tyqTUHCr/lLekWcucClaDgcHlCAH+WU8+fGY8cyLrFFRdk 4U5sD+P313Adg4VDyoocTO6enA9Vf1Ar5XMZ3l6k5yARjZNIbGO50IZfC/iblIZD UpR2T7J/ggfq830ACfpOQF/+7K+LgFLekJ5dIRuD1KKyFg== -----END CERTIFICATE----- Read this question.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/5896380', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '8'}
Q: Flutter: Mensagem de erro Could not update files on device: HttpException Olá, estou estudando Flutter e recentemente tive um problema, quando tentei executar meu projeto com Flutter run recebi a mensagem de erro: Could not update files on device: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:50365/h3iViYQmEC4=/ Tentei com emulador e com meu próprio celular porém recebo o mesmo erro. O estranho é que quando eu crio um App em Flutter novo ele funciona, consigo fazer todas as modificações porem se eu parar e tentar executar novamente o erro aparece e o App não roda. Já tentei reiniciar os dispositivos. Flutter clean Flutter doctor [Exibe que está tudo certo] Até meus app antigos que tinha feito pra estudar acontece a mesma coisa, sendo que estavam funcionando. Mensagem completa com Flutter run: * *Estou usando Android. *Mensagem que aparece no celular é a padrão 'O app parou de funcionar, deseja encerrar?' A: [RESOLVIDO] - O problema era uma fonte externa que eu estava importando que aparentemente se corrompeu, percebi que aparece uma mensagem : Eu retirei todo lugar que eu usava ela e voltou ao normal.
{'language': 'pt', 'url': 'https://pt.stackoverflow.com/questions/448434', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: TFS configure variables on Release definition instantiation I have a release definition setup with several tasks. When a developer wants to create a release from this definition, i'd like to give them the option of selecting which features they'd like to release (turn on/off tasks). Ideally this would be via the Create Release dialog using a variable or similar. Can this be done? Or is the only way to achieve this to create a draft release and enable/disable the tasks on each environment? Believe this is prone to error (toggle task on one environment but forget to on another) and this is not an option as administrator has locked editing of definitions (prevent incorrect setup of production releases). Understand I can create separate release definitions to cover the options but it seems like a lot of duplication. A: Unfortunately, this is not supported in TFS currently. The workarounds are just like you mentioned above, to disable and enable those steps or use draft release. This is a user voice about your request you could vote: https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/19165690-select-steps-when-create-release
{'language': 'en', 'url': 'https://stackoverflow.com/questions/43777906', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: AWS S3 Internal Server Error: Tyring to upload pdf file on after another I'm trying to generate PDF file using FPDF and PHP and later upload to AWS-s3 and generate the url. When I executed the below code in my local-machine Using XAMPP it's generating files and uploading it to S3. But When I deployed in AWS server as an API it's uploading only first file and for other its giving 500 server error Below is my code that I used in Local Machine require '../fpdf/fpdf.php'; require 'start.php'; use Aws\Exception\AwsException; $location = "bangalore"; $db = getConnection(); $query = "SELECT first_name FROM customer_info where location = '$location'"; $execute = $db->query($query); $result = $execute->fetchAll(PDO::FETCH_ASSOC); for($i = 0; $i < $len; $i++) { $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial', 'B', 14); $txt = "Legal Document of ".$result[$i]['first_name']; $pdf->Cell(180, 0, $txt, 0, 1, 'C'); $pdf->Line(5, 20, 200, 20); $docname = $result[$i]['first_name'] . ".pdf"; $filepath = "../file/{$docname}"; $pdf->Output($filepath, 'F'); //s3 client try { $res = $S3->putObject([ 'Bucket' => $config['S3']['bucket'], 'Key' => "PATH_TO_THE_DOCUMENT/{$docname}", 'Body' => fopen($filepath, 'rb'), 'ACL' => 'public-read' ]); var_dump($res["ObjectURL"]); } catch (S3Exception $e) { echo $e->getMessage() . "\n"; } } Output: Array ( [0] => Array ( [first_name] => Mohan ) [1] => Array ( [first_name] => Prem ) [2] => Array ( [first_name] => vikash ) [3] => Array ( [first_name] => kaushik ) ) string(70) "https://streetsmartb2.s3.amazonaws.com/PATH_TO_THE FILE/Mohan.pdf" string(72) "https://streetsmartb2.s3.amazonaws.com/PATH_TO_THE FILE/Prem%20.pdf" API CODE //pdf generation another api $app->post('/pdfmail', function() use($app){ //post parameters $location = $app->request->post('loc'); $id = $app->request->post('id'); $db = getConnection(); $query = "SELECT * FROM customer_info where location = '$location'"; $execute = $db->query($query); $result = $execute->fetchAll(PDO::FETCH_ASSOC); $len = sizeof($result); //request array $request = array(); if($result != Null) { for($i = 0; $i < $len; $i++) { $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial', 'B', 14); $txt = "Document of Mr." . $result[$i]['first_name']; $pdf->Cell(180, 0, $txt, 0, 1, 'C'); $pdf->Line(5, 20, 200, 20); $docname = $result[$i]['first_name'] . ".pdf"; var_dump($docname); $filepath = "../file/{$docname}"; var_dump($filepath); $pdf->Output($filepath, 'F'); //s3 client require '../aws/aws-autoloader.php'; $config = require('config.php'); //create s3 instance $S3 = S3Client::factory([ 'version' => 'latest', 'region' => 'REGION', 'credentials' => array( 'key' => $config['S3']['key'], 'secret' => $config['S3']['secret'] ) ]); try { $res = $S3->putObject([ 'Bucket' => $config['S3']['bucket'], 'Key' => "PATH_TO_FILE{$docname}", 'Body' => fopen($filepath, 'rb'), 'ACL' => 'public-read' ]); var_dump($res["ObjectURL"]); } catch (S3Exception $e) { echo $e->getMessage() . "\n"; } } } OUTPUT WHEN TESTED IN POSTMAN string(10) "vikash.pdf" string(18) "../file/vikash.pdf" string(71) "https://streetsmartb2.s3.amazonaws.com/PATH_TO_FILE/vikash.pdf" string(13) "pradeepan.pdf" string(21) "../file/pradeepan.pdf" After this I'm getting internal server error. A: Instead of using require_once I've use require...So as the code traversed it was creating AWS Class again and again. Code //s3 client require '../aws/aws-autoloader.php'; //use require_once $config = require('config.php'); //create s3 instance $S3 = S3Client::factory([ 'version' => 'latest', 'region' => 'REGION', 'credentials' => array( 'key' => $config['S3']['key'], 'secret' => $config['S3']['secret'] ) ]);
{'language': 'en', 'url': 'https://stackoverflow.com/questions/48921630', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Auto-generate @version value in javadoc For the @version tag in javadoc, I use the same value as in BuildConfig.VERSION_NAME. I would like to inject that value, instead of changing every file for each release. I tried: * @version {@value BuildConfig#VERSION_NAME} and * @version @versionName (and add -tag versionName:a:"2.2.2") but none of these works. I could run sed just before the doc gets generated, but I would rather prefer something 'officially' supported. Any ideas how to solve this? A: For the second form, you can put your custom tag at the beginning of a javadoc line. /** * This is a class of Foo<br/> * * @version * * @configVersion. */ Then use command javadoc -version -tag configVersion.:a:"2.2.2" to generate your javadoc, the custom tag should be handled in this way. Note the last dot(.) character in custom tag name, as the command javadoc suggests Note: Custom tags that could override future standard tags: @configVersion. To avoid potential overrides, use at least one period character (.) in custom tag names.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/58002547', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: How to retrieve data from MongoDb Atlas and display in an ejs file using mongoose and Nodejs Thanks for the help in advance. I am trying to retrieve data from my database- myFirstDatabase and collection named as 'shipment' in mongondb. This is a nested schema but I am only interested in the parent data for now. I have this code which retrieves data to the console log. But how can I display or access the data in my orders.ejs file? Shipment.find({}, function (err, data) { if (err) throw err console.log(data) }) MongoDB connected... [ { _id: new ObjectId("61353311261da54811ee0ca5"), name: 'Micky Mouse', phone: '5557770000', email: 'g@gmail.com', address: { address: '10 Merrybrook Drive', city: 'Herndon', state: 'Virginia', zip: '21171', country: 'United States', _id: new ObjectId("61353311261da54811ee0ca6") }, items: { car: 'Honda Pilot 2018', boxItem: '3 uHaul boxes', furniture: 'None', electronics: '1 50" Samsung TV', bags: '2 black suites cases', _id: new ObjectId("61353311261da54811ee0ca7") }, date: 2021-09-05T21:13:53.484Z, __v: 0 } ] This is the ejs file, a table I am trying to populate the data i get from my mongodb <div class="mt-5 m-auto> <h3 class="mt-5">This is the order table</h3> <%- include ("./partials/messages"); %> <div class="col-sm"> <table class="table table-striped table-hover"> <thead> <tr> <th>#</th> <th>Customer</th> <th>Address</th> <th>City</th> <th>State</th> <th>Zip</th> <th>Phone</th> <th>Status</th> </tr> </thead> <tbody> <tr class="success"> <td>1</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> </div> A: server.js const express = require('express') const mongoose = require('mongoose') const Shipment= require('./models/shipment') const app = express() mongoose.connect('mongodb://localhost/myFirstDatabase ', { useNewUrlParser: true, useUnifiedTopology: true }) app.set('view engine', 'ejs') app.use(express.urlencoded({ extended:false })) app.get('/', async (req,res) => { const data= await Shipment.find() res.render('index', { data: data}) }) app.listen(process.env.PORT || 5000); index.ejs below is part of your ejs file <table class="table table-striped table-hover"> <thead> <tr> <th>#</th> <th>Customer</th> <th>Address</th> <th>City</th> <th>State</th> <th>Zip</th> <th>Phone</th> <th>Status</th> </tr> </thead> <tbody> <% data.forEach((e, index)=> { %> <tr> <td><%= index %></td> <td><%= e.Customer %></td> <td><%= e.Address %></td> <td><%= e.City %></td> <td><%= e.State %></td> <td><%= e.Zip %></td> <td><%= e.Phone %></td> <td><%= e.Status %></td> </tr> <% }) %> </tbody> </table>
{'language': 'en', 'url': 'https://stackoverflow.com/questions/69067410', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: node.js app running using forever inaccessible after a while I have a node.js server and a java client communicating using socket.io. I use this api https://github.com/Gottox/socket.io-java-client for the java client. I am using forever module to run my server. Everything works well but after some time , my server becomes inaccessible and I need to restart it, Also, most of the times i need to update/edit my node.js server file in order to make my server work again (restarted). Its been two weeks already and im still keep restarting my server :(. Has anyone run into the same problem ? and solution or advice please. Thanks
{'language': 'en', 'url': 'https://stackoverflow.com/questions/17628274', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Populating Fields in Table with GUIDs from Feature Class? Is there a way to add GUIDs from a feature class to a table based on specific attributes? I have a large maintenance record table that is tied to specific points through the GUID of that point. I have added new records but they are not tied to a point yet. Instead of going through and copy/pasting each pole GUID to the appropriate maintenance record manually, I was hoping to use model builder or python to populate the fields in the table automatically. The data that overlaps between the two is the name of the line and the pole number. I think this is a relationship (many to many), but both the line name and the pole number need to match. I'm also new to using model builder and python. A: ModelBuilder does not provide a solution where you can create an editable join based on multiple fields. Your question is virtually the same as Auto populating field in attribute table, using several fields of record information from another table? and the answers are the same. You must either concatenate the fields into a single new field, run my Multi-field Key to Single-field Key tool to create a new numeric field that represents the multi-field key or use the Make Query Table tool. I do not consider the Make Query Table option workable, since it cannot be edited, it drops unmatched records, and it requires that you constantly recreate your entire feature class each time to update it. A Python script could do it using a cursor and dictionary. See my Blog on Turbo Charging Data Manipulation with Python Cursors and Dictionaries. In particular look at the example of Creating a Multi-Field Python Dictionary Key to Replace a Concatenated Join Field. Once a working script has been writen, this is actually the fastest of the methods and since once it completed you would have a single field key through your GUID, it is probably the best for your particular data. The concatenated field or single field key would be redundant once your GUID was transferred. The python script underlying the Multi-field key to Single field key tool has a more sophisticated method of doing the multi-field matching, since it preserves the sort order native to each field type rather than using the sorting that occurs when values are converted to strings. So if you want a single key that sorts the same way that the separate fields would sort, this tool is the best.
{'language': 'en', 'url': 'https://gis.stackexchange.com/questions/193524', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '2'}
Q: No 'Access-Control-Allow-Origin' header is present on the requested resource. Laravel 5.4 with cors package Hi I was following this tutorial regarding Laravel and VueJs communication. https://www.youtube.com/watch?v=5hOMkFMxY90&list=PL3ZhWMazGi9IommUd5zQmjyNeF7s1sP7Y&index=8 I have done exactly like it was said in the tutorial. It uses a CORS package https://github.com/barryvdh/laravel-cors/ I have added the service provider middlewares everything as it was told in the tutorial but it just doesnt seem to work. I have tried it in Laravel 5.4 and Laravel 5.3 as well. This is my RouetServiceProvider: namespace App\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { // parent::boot(); } /** * Define the routes for the application. * * @return void */ public function map() { $this->mapApiRoutes(); $this->mapWebRoutes(); // } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protected function mapWebRoutes() { Route::group([ 'middleware' => 'web', 'namespace' => $this->namespace, ], function ($router) { require base_path('routes/web.php'); }); } /** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::group([ 'middleware' => ['api' , 'cors'], 'namespace' => $this->namespace, 'prefix' => 'api', ], function ($router) { require base_path('routes/api.php'); }); } } This is my middleware code in kernel protected $middleware = [ \Barryvdh\Cors\HandleCors::class, \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ]; I have added its service provider too. I have seen all the solutions here on stackoverflow but none of them seems to work. I do not need theoretical answer but a practical solution Thanks
{'language': 'en', 'url': 'https://stackoverflow.com/questions/43503718', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '2'}
Q: no partition after installing ubuntu I cannot boot back my windows 8 disk after Ubuntu install. I installed Ubuntu. Probably I selected my main disk (I wanted to used the diskonkey disk). After about 3-4 screens (selecting time zone) I noticed that is using the wrong partition and I powered down the laptop. Now I don’t have a partition table with windows 8. It cannot boot. I think I have to recover my MBR and partition table. I used the boot repair - this is what it showed: http://paste.ubuntu.com/9659707/ A: Powering down in the middle of an installation because you've taken the wrong choice is always the worst decision you can take. That is like powering down your car in the middle of a busy cross-road because you took a wrong turn. (Just believe me: don't try this!) The easiest way to solve this situation is to: * *Enable UEFI in the BIOS and reboot. *If that didn't work, take the recovery DVD that came with your machine and boot with that to get your system back. Warning this will destroy all of your data still remaining on the drive. (You did make a back-up before starting the install didn't you?) The more difficult way: * *Attach your back-up drive to the computer *Boot with the Ubuntu LiveCD *Press Ctrl+Alt+T and type: sudo apt-get install testdisk testdisk *Follow testdisk step-by-step instructions to save as much of your data as possible. *Recover using the Recovery DVD *Follow these instructions on how to efficiently partition a Windows-Ubuntu dual-boot and how to install Ubuntu on a pre-installed Windows 8 machine.
{'language': 'en', 'url': 'https://askubuntu.com/questions/585361', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: How to pass outside function to WP_REST_Request Learning with WP REST I'm unsure how to properly pass what is typically at the beginning of a PHP page form to WP_REST_Response. For example: At the beginning of page-foobar.php if I have: // IP ADDRESS function ipAddress() { if (isset($_SERVER['REMOTE_ADDR'])) : $ip_address = $_SERVER['REMOTE_ADDR']; else : $ip_address = "undefined"; endif; return $ip_address; } /* Template Name: Foobar */ and need to use $ip_address in: function foobar(\WP_REST_Request $request) { if ($ip_address == "undefined") : return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) ); endif; } how would I go about doing that? When I searched I ran across: Pass a Variable from one file to another in WordPress but I dont think it would be a good idea to pass as a global. Further researching Passing variables between files in WordPress or PHP but I've already called the template in functions.php. How can I pass a function from the template to the function request if it's stored in a different file? A: My approach would be, to declare the function in functions.php and then call it whenever you need. Since you are trying to use superglobals, you can access them anywhere. Move the code from your page-foobar.php to your theme's functions.php, and use this whenever you need to access it: ipAddress(); So, in your REST function you can have: function foobar(\WP_REST_Request $request) { $ip_address = ipAddress(); if ($ip_address == "undefined") : return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) ); endif; }
{'language': 'en', 'url': 'https://wordpress.stackexchange.com/questions/277095', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Swift: How to not load AppDelegate during Tests I have an OS X application which on startup loads some data from a server and pushes notifications to the NSUserNotificationCenter. Now I have the problem that this also happens during my unit tests. I found no way yet to prevent this. Of course I could stub the HTTP loads. But in some cases I want to test the loading and then the notifications get sent anyway. What I'm trying to do is to make the test runs not load the AppDelegate but a fake one that I'm only using for tests. I found several examples [1] on how to do that with UIApplicationMain, where you can pass a specific AppDelegate class name. The same is not possible with NSApplicationMain [2]. What I've tried is the following: Removed @NSApplicationMain from AppDelegate.swift, then added a main.swift with the following content: class FakeAppDelegate: NSObject, NSApplicationDelegate { } NSApplication.sharedApplication() NSApp.delegate = FakeAppDelegate() NSApplicationMain(Process.argc, Process.unsafeArgv) This code runs before tests but has no effect at all. I might have to say: My AppDelegate is almost empty. To handle the MainMenu.xib stuff I made a separate view controller which does the actual loading and notification stuff in awakeFromNib. [1] http://www.mokacoding.com/blog/prevent-unit-tests-from-loading-app-delegate-in-swift/ [2] https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Miscellaneous/AppKit_Functions/#//apple_ref/c/func/NSApplicationMain A: Just an update on the previous accept answer, this is my main.swift: private func isTestRun() -> Bool { return NSClassFromString("XCTestCase") != nil } if isTestRun() { // This skips setting up the app delegate NSApplication.shared.run() } else { // For some magical reason, the AppDelegate is setup when // initialized this way _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv) } A bit more compact! I'm using Swift 4.1 and XCode 9.4.1 A: After days of trying and failing I found an answer on the Apple forums: The problem was that my main.swift file was initializing my AppDelegate before NSApplication had been initialized. The Apple documentation makes it clear that lots of other Cocoa classes rely on NSApplication to be up and running when they are initialized. Apparently, NSObject and NSWindow are two of them. So my final and working code in main.swift looks like this: private func isTestRun() -> Bool { return NSClassFromString("XCTest") != nil } private func runApplication( application: NSApplication = NSApplication.sharedApplication(), delegate: NSObject.Type? = nil, bundle: NSBundle? = nil, nibName: String = "MainMenu") { var topLevelObjects: NSArray? // Actual initialization of the delegate is deferred until here: application.delegate = delegate?.init() as? NSApplicationDelegate guard bundle != nil else { application.run() return } if bundle!.loadNibNamed(nibName, owner: application, topLevelObjects: &topLevelObjects ) { application.run() } else { print("An error was encountered while starting the application.") } } if isTestRun() { let mockDelegateClass = NSClassFromString("MockAppDelegate") as? NSObject.Type runApplication(delegate: mockDelegateClass) } else { runApplication(delegate: AppDelegate.self, bundle: NSBundle.mainBundle()) } So the actual problem before was that the Nib was being loaded during tests. This solution prevents this. It just loads the application with a mocked application delegate whenever it detects a test run (By looking for the XCTest class). I'm sure I will have to tweak this a bit more. Especially when a start with UI Testing. But for the moment it works.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/39116318', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '7'}
Q: How to use std::transform with a lambda function that takes additional parameters In C++ 11 (or higher) can I use std::transform and a lambda function to transform a vector that also takes other parameters? For example, how do I pass param to the lambda function below? std::vector<double> a{ 10.0, 11.0, 12.0 }; std::vector<double> b{ 20.0, 30.0, 40.0 }; std::vector<double> c; double param = 1.5; //The desired function is c = (a-b)/param transform(a.begin(), a.end(), b.begin(), std::back_inserter(c), [](double x1, double x2) {return(x1 - x2)/param; }); std::transform wants a function with two input parameters. Do I need to use std::bind? A: You just need to capture param in your capture list: transform(a.begin(), a.end(), b.begin(), std::back_inserter(c), [param](double x1, double x2) {return(x1 - x2)/param; }); Capturing it by reference also works - and would be correct if param was a big class. But for a double param is fine. A: This is what the lambda capture is for. You need to specify & or = or param in the capture block ([]) of the lambda. std::vector<double> a{ 10.0, 11.0, 12.0 }; std::vector<double> b{ 20.0, 30.0, 40.0 }; std::vector<double> c; double param = 1.5; //The desired function is c = (a-b)/param transform(a.begin(), a.end(), b.begin(), std::back_inserter(c), [=](double x1, double x2) {return(x1 - x2)/param; }); // ^ capture all external variables used in the lambda by value In the above code we just capture by value since copying a double and having a reference is pretty much the same thing performance wise and we don't need reference semantics.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/53011875', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '2'}
Q: How can I add an intranet-only endpoint to my IIS hosted WCF service? I have a WCF service hosted in IIS that uses basicHttpBindings. I'm adding a new method to the ServiceContract that will be called from a console app to perform an administrative task. I got to thinking, well wouldn't it be nice if I gave this method its own endpoint. Then I thought and what if that endpoint wasn't even publicly accessible. It would be much better if only a computer on our LAN could access it. It might even be cool if only an AD administrator was authorized to use it, but I don't want to get too elaborate. So I added a new ServiceContract interface that includes my new method. How can I restrict it to LAN access only? Do I need a NetTcpBinding? Networking is not my strong suit and I'm a little confused, conceptually, on how a TCP endpoint could be hosted from IIS. Additionally, when hosting multiple endpoints, does each have to have its own address or can they be at the same address? A: I am gonna answer some of your questions * *there is no binding that would limit access to LAN network though you can use windows authentication to allow users from your network to use the service *the nettcpbinding is only a tcp connection and you can host it on IIS pof course check this link for more information hosting nettcp on IIS *you can have one base address for multiple endpoints , example: https://localhost:8080/calculator.svc net.tccp://localhost:8080/calculator.svc
{'language': 'en', 'url': 'https://stackoverflow.com/questions/29483797', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: A Quickselect C Algorithm faster than C Qsort I have tried to implement a C QuickSelect algorithm as described in this post (3 way quicksort (C implementation)). However, all I get are performances 5 to 10 times less than the default qsort (even with an initial shuffling). I tried to dig into the original qsort source code as provide here (https://github.com/lattera/glibc/blob/master/stdlib/qsort.c), but it's too complex. Does anybody have a simpler, and better algorithm? Any idea is welcomed. Thanks, NB: my original problem is to try to get the Kth smallest values of an array to the first Kth indices. So I planned to call quickselect K times EDIT 1: Here is the Cython Code as copied and adapted from the link above cdef void qswap(void* a, void* b, const size_t size) nogil: cdef char temp[size]# C99, use malloc otherwise #char serves as the type for "generic" byte arrays memcpy(temp, b, size) memcpy(b, a, size) memcpy(a, temp, size) cdef void qshuffle(void* base, size_t num, size_t size) nogil: #implementation of Fisher cdef int i, j, tmp# create local variables to hold values for shuffle for i in range(num - 1, 0, -1): # for loop to shuffle j = c_rand() % (i + 1)#randomise j for shuffle with Fisher Yates qswap(base + i*size, base + j*size, size) cdef void partition3(void* base, size_t *low, size_t *high, size_t size, QComparator compar) nogil: # Modified median-of-three and pivot selection. cdef void *ptr = base cdef size_t lt = low[0] cdef size_t gt = high[0] # lt is the pivot cdef size_t i = lt + 1# (+1 !) we don't compare pivot with itself cdef int c = 0 while (i <= gt): c = compar(ptr + i * size, ptr + lt * size) if (c < 0):# base[i] < base[lt] => swap(i++,lt++) qswap(ptr + lt * size, ptr + i * size, size) i += 1 lt += 1 elif (c > 0):#base[i] > base[gt] => swap(i, gt--) qswap(ptr + i * size, ptr + gt* size, size) gt -= 1 else:#base[i] == base[gt] i += 1 #base := [<<<<<lt=====gt>>>>>>] low[0] = lt high[0] = gt cdef void qselectk3(void* base, size_t lo, size_t hi, size_t size, size_t k, QComparator compar) nogil: cdef size_t low = lo cdef size_t high = hi partition3(base, &low, &high, size, compar) if ((k - 1) < low): #k lies in the less-than-pivot partition high = low - 1 low = lo elif ((k - 1) >= low and (k - 1) <= high): #k lies in the equals-to-pivot partition qswap(base, base + size*low, size) return else: # k > high => k lies in the greater-than-pivot partition low = high + 1 high = hi qselectk3(base, low, high, size, k, compar) """ A selection algorithm to find the nth smallest elements in an unordered list. these elements ARE placed at the nth positions of the input array """ cdef void qselect(void* base, size_t num, size_t size, size_t n, QComparator compar) nogil: cdef int k qshuffle(base, num, size) for k in range(n): qselectk3(base + size*k, 0, num - k - 1, size, 1, compar) I use python timeit to get the performance of both method pyselect(with N=50) and pysort. Like this def testPySelect(): A = np.random.randint(16, size=(10000), dtype=np.int32) pyselect(A, 50) timeit.timeit(testPySelect, number=1) def testPySort(): A = np.random.randint(16, size=(10000), dtype=np.int32) pysort(A) timeit.timeit(testPySort, number=1) A: The answer by @chqrlie is the good and final answer, yet to complete the post, I am posting the Cython version along with the benchmarking results. In short, the proposed solution is 2 times faster than qsort on long vectors! cdef void qswap2(void *aptr, void *bptr, size_t size) nogil: cdef uint8_t* ac = <uint8_t*>aptr cdef uint8_t* bc = <uint8_t*>bptr cdef uint8_t t while (size > 0): t = ac[0]; ac[0] = bc[0]; bc[0] = t; ac += 1; bc += 1; size -= 1 cdef struct qselect2_stack: uint8_t *base uint8_t *last cdef void qselect2(void *base, size_t nmemb, size_t size, size_t k, QComparator compar) nogil: cdef qselect2_stack stack[64] cdef qselect2_stack *sp = &stack[0] cdef uint8_t *lb cdef uint8_t*ub cdef uint8_t *p cdef uint8_t *i cdef uint8_t *j cdef uint8_t *top if (nmemb < 2 or size <= 0): return top = <uint8_t *>base if(k < nmemb): top += k*size else: top += nmemb*size sp.base = <uint8_t *>base sp.last = <uint8_t *>base + (nmemb - 1) * size sp += 1 cdef size_t offset while (sp > stack): sp -= 1 lb = sp.base ub = sp.last while (lb < ub and lb < top): #select middle element as pivot and exchange with 1st element offset = (ub - lb) >> 1 p = lb + offset - offset % size qswap2(lb, p, size) #partition into two segments i = lb + size j = ub while 1: while (i < j and compar(lb, i) > 0): i += size while (j >= i and compar(j, lb) > 0): j -= size if (i >= j): break qswap2(i, j, size) i += size j -= size # move pivot where it belongs qswap2(lb, j, size) # keep processing smallest segment, and stack largest if (j - lb <= ub - j): sp.base = j + size sp.last = ub sp += 1 ub = j - size else: sp.base = lb sp.last = j - size sp += 1 lb = j + size cdef int int_comp(void* a, void* b) nogil: cdef int ai = (<int*>a)[0] cdef int bi = (<int*>b)[0] return (ai > bi ) - (ai < bi) def pyselect2(numpy.ndarray[int, ndim=1, mode="c"] na, int n): cdef int* a = <int*>&na[0] qselect2(a, len(na), sizeof(int), n, int_comp) Here are the benchmark results (1,000 tests): #of elements K #qsort (s) #qselect2 (s) 1,000 50 0.1261 0.0895 1,000 100 0.1261 0.0910 10,000 50 0.8113 0.4157 10,000 100 0.8113 0.4367 10,000 1,000 0.8113 0.4746 100,000 100 7.5428 3.8259 100,000 1,000 7,5428 3.8325 100,000 10,000 7,5428 4.5727 For those who are curious, this piece of code is a jewel in the field of surface reconstruction using neural networks. Thanks again to @chqrlie, your code is unique on The Web. A: Here is a quick implementation for your purpose: qsort_select is a simple implementation of qsort with automatic pruning of unnecessary ranges. Without && lb < top, it behaves like the regular qsort except for pathological cases where more advanced versions have better heuristics. This extra test prevents complete sorting of ranges that are outside the target 0 .. (k-1). The function selects the k smallest values and sorts them, the rest of the array has the remaining values in an undefinite order. #include <stdio.h> #include <stdint.h> static void exchange_bytes(uint8_t *ac, uint8_t *bc, size_t size) { while (size-- > 0) { uint8_t t = *ac; *ac++ = *bc; *bc++ = t; } } /* select and sort the k smallest elements from an array */ void qsort_select(void *base, size_t nmemb, size_t size, int (*compar)(const void *a, const void *b), size_t k) { struct { uint8_t *base, *last; } stack[64], *sp = stack; uint8_t *lb, *ub, *p, *i, *j, *top; if (nmemb < 2 || size <= 0) return; top = (uint8_t *)base + (k < nmemb ? k : nmemb) * size; sp->base = (uint8_t *)base; sp->last = (uint8_t *)base + (nmemb - 1) * size; sp++; while (sp > stack) { --sp; lb = sp->base; ub = sp->last; while (lb < ub && lb < top) { /* select middle element as pivot and exchange with 1st element */ size_t offset = (ub - lb) >> 1; p = lb + offset - offset % size; exchange_bytes(lb, p, size); /* partition into two segments */ for (i = lb + size, j = ub;; i += size, j -= size) { while (i < j && compar(lb, i) > 0) i += size; while (j >= i && compar(j, lb) > 0) j -= size; if (i >= j) break; exchange_bytes(i, j, size); } /* move pivot where it belongs */ exchange_bytes(lb, j, size); /* keep processing smallest segment, and stack largest */ if (j - lb <= ub - j) { sp->base = j + size; sp->last = ub; sp++; ub = j - size; } else { sp->base = lb; sp->last = j - size; sp++; lb = j + size; } } } } int int_cmp(const void *a, const void *b) { int aa = *(const int *)a; int bb = *(const int *)b; return (aa > bb) - (aa < bb); } #define ARRAY_SIZE 50000 int array[ARRAY_SIZE]; int main(void) { int i; for (i = 0; i < ARRAY_SIZE; i++) { array[i] = ARRAY_SIZE - i; } qsort_select(array, ARRAY_SIZE, sizeof(*array), int_cmp, 50); for (i = 0; i < 50; i++) { printf("%d%c", array[i], i + 1 == 50 ? '\n' : ','); } return 0; }
{'language': 'en', 'url': 'https://stackoverflow.com/questions/52016431', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '-3'}
Q: What is eating up my disk space? I have very recently installed Ubuntu 15.10. I have been watching the available amount of memory over two days, and i noticed that the free memory goes on decreasing at a slow rate. Initially the used memory was 5GB, Then it went on increasing to 6 to 6.5 and now it stands around 6.8. I haven't installed anything significant over this period (except some small packages worth a few MBs) .My home folder is just few 100kbs. What is eating up my disk space? How can find out if something is going on? A: The indicated amount seems to be .deb cache in majority. Issue this command: sudo apt-get clean and after that check again the disk usage. A: You can find out how much space sub-directories occupy using the following command: sudo du -hxd 1 YOUR_PATH 2>/dev/null | sort -hr What it does: * *sudo: run the du command as root - only needed/recommended if you want to list stuff outside your own home directory. *du: disk usage analyzing tool. Arguments: * *-h: use human readable numeric output (i.e. 2048 bytes = 2K) *-x: stay on the same file system, do not list directories which are just mounted there *-d 1: display recursion depth is set to 1, that means it will only print the given directory and the direct subdirectories. *YOUR_PATH: The path which should be analyzed. Change this to whatever path you want. *2>/dev/null: we do not want error output (e.g. from when it tries to get the size of virtual files), so we pipe that to the digital nirvana a.k.a. /dev/null. *|: use the output of the previous command as input for the next command *sort: sort the input. Arguments: * *-h: recognize numbers like 2K and sort them according to their real value *-r: reversed order: print the largest numbers first Example for my file system root /: $ sudo du -hxd 1 / 2>/dev/null | sort -hr 5,7G / 4,0G /usr 1,3G /var 358M /lib 49M /opt 15M /etc 13M /sbin 13M /bin 840K /tmp 32K /root 16K /lost+found 8,0K /media 4,0K /srv 4,0K /mnt 4,0K /lib64 4,0K /cdrom Note that the given directory's total size is also included, not only the subdirectories.
{'language': 'en', 'url': 'https://askubuntu.com/questions/725797', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Get values with no repeated data I have a query like this: SELECT P.LegacyKey ,D.DesignNumber FROM tbl1 AS [SO] GROUP BY D.DesignNumber,P.LegacyKey ORDER BY LegacyKey it returning values like: +-----------+--------------+ | LegacyKey | DesignNumber | +-----------+--------------+ | 17134 | 1 | | 17134 | 2 | | 18017 | 7 | +-----------+--------------+ That I want to do is to find duplicate LegacyKeys and get only values who legacyKey is exist one time, so I use HAVING COUNT: SELECT P.LegacyKey ,D.DesignNumber , COUNT([P].[LegacyKey]) FROM tbl1 AS [SO] GROUP BY D.DesignNumber,P.LegacyKey HAVING COUNT([P].[LegacyKey]) = 1 ORDER BY LegacyKey But this is returning bad data, because it is returning LegacyKey = 17134 again and desire result is to get values where LegacyKey exists one time. So desire result should be only 18017 | 7 What am I doing wrong? A: You can simply do: SELECT P.LegacyKey, MAX(D.DesignNumber) as DesignNumber FROM tbl1 AS [SO] GROUP BY P.LegacyKey HAVING COUNT(DISTINCT D.DesignNumber) = 1; ORDER BY LegacyKey; No subquery is necessary. A: You need something like this: select t2.LegacyKey, t2.DesignNumber from ( select t.LegacyKey from tbl1 t group by t.LegacyKey having count(t.LegacyKey ) = 1 )x join tbl1 t2 on x.LegacyKey = t2.LegacyKey or select t2.LegacyKey, t2.DesignNumber from tbl1 t2 where t2.LegacyKey in ( select t.LegacyKey from tbl1 t group by t.LegacyKey having count(t.LegacyKey ) = 1 ) A: You could try this NB - This is untested SELECT * FROM ( SELECT P.LegacyKey AS LegacyKey, D.DesignNumber AS DesignNumber, COUNT([P].[LegacyKey]) AS cnt FROM tbl1 AS [SO] GROUP BY D.DesignNumber,P.LegacyKey HAVING COUNT([P].[LegacyKey]) = 1 ) a WHERE COUNT() OVER (PARTITION BY LegacyKey) = 1
{'language': 'en', 'url': 'https://stackoverflow.com/questions/54993000', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: @IBDesignable doesn't work in "old" project I have UIView subclass, for example, this: @IBDesignable class GradientView: UIView { @IBInspectable var firstColor: UIColor = UIColor.red @IBInspectable var secondColor: UIColor = UIColor.green @IBInspectable var vertical: Bool = true override func awakeFromNib() { super.awakeFromNib() applyGradient() } func applyGradient() { let colors = [firstColor.cgColor, secondColor.cgColor] let layer = CAGradientLayer() layer.colors = colors layer.frame = self.bounds layer.startPoint = CGPoint(x: 0, y: 0) layer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0) self.layer.addSublayer(layer) } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() applyGradient() } } It successfully renders in Interface Builder for a new project, but it doesn't work for my "old" project. Does anyone know why it happens?
{'language': 'en', 'url': 'https://stackoverflow.com/questions/45217918', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: How do I refer to the people living in the particular city? Is it random always? Where do demonyms come from? At times they take -ite, some times -an, -er and this one is jaw-dropping '-siders!' A person living in New York is a New Yorker (-er) A person living in Delhi is Delhiite (-ite) A person living in Sydney is Sydneysider (-sider -OMG! Really?) A person living in Las Vegas is Las Vegan (-an) There are innumerable cities across the world and remembering a demonym for each of them does not seem practical. I don't get demonyms without searching them on the Internet (and trust me, even after searching I fail to get them for some cities' residents!). This becomes further difficult when the city name is long - say St. Louis, Amsterdam, Rio de Janeiro (Cariocas -full marks who knew this!) and many more. Is there any way we can assume/know the demonym of the city by looking at its spelling? A: Is there a hard and fast rule? Sadly, no. But there is a rule of thumb--which means it works, except when it doesn't. First: if the city is outside of the United States, US English usually (but not always) uses the naming convention of the native country. So "Liverpudlian" and "Muenchner" don't follow these rules; you need to learn that country's rules. Within the United States, look at the sound (not the spelling!) of the last syllable of the city's name. Does it end in a vowel sound? Add -n or -an. * *Atlantan *Cincinattian *Kenoshan *Pennsylvanian Does it end in a hard d or k? Add -er. * *New Yorker *Oaklander *Portlander *Salt Laker Does it end in an -l, or -r sound? Consider adding -ite. * *Seattleite *New Hampshirite Does it end in an -s sound preceded by a schwa? Replace the s with an n. * *Kansan *Texan For all other consonants, the most common rule is to add an -ian * *Oregonian *Bostonian *Knoxvillian As always with English, there are then a ton of exceptions that you just have to learn.
{'language': 'en', 'url': 'https://ell.stackexchange.com/questions/21370', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '4'}
Q: Passing object messages in Azure Queue Storage I'm trying to find a way to pass objects to the Azure Queue. I couldn't find a way to do this. As I've seen I can pass string or byte array, which is not very comfortable for passing objects. Is there anyway to pass custom objects to the Queue? Thanks! A: You can use the following classes as example: [Serializable] public abstract class BaseMessage { public byte[] ToBinary() { BinaryFormatter bf = new BinaryFormatter(); byte[] output = null; using (MemoryStream ms = new MemoryStream()) { ms.Position = 0; bf.Serialize(ms, this); output = ms.GetBuffer(); } return output; } public static T FromMessage<T>(CloudQueueMessage m) { byte[] buffer = m.AsBytes; T returnValue = default(T); using (MemoryStream ms = new MemoryStream(buffer)) { ms.Position = 0; BinaryFormatter bf = new BinaryFormatter(); returnValue = (T)bf.Deserialize(ms); } return returnValue; } } Then a StdQueue (a Queue that is strongly typed): public class StdQueue<T> where T : BaseMessage, new() { protected CloudQueue queue; public StdQueue(CloudQueue queue) { this.queue = queue; } public void AddMessage(T message) { CloudQueueMessage msg = new CloudQueueMessage(message.ToBinary()); queue.AddMessage(msg); } public void DeleteMessage(CloudQueueMessage msg) { queue.DeleteMessage(msg); } public CloudQueueMessage GetMessage() { return queue.GetMessage(TimeSpan.FromSeconds(120)); } } Then, all you have to do is to inherit the BaseMessage: [Serializable] public class ParseTaskMessage : BaseMessage { public Guid TaskId { get; set; } public string BlobReferenceString { get; set; } public DateTime TimeRequested { get; set; } } And make a queue that works with that message: CloudStorageAccount acc; if (!CloudStorageAccount.TryParse(connectionString, out acc)) { throw new ArgumentOutOfRangeException("connectionString", "Invalid connection string was introduced!"); } CloudQueueClient clnt = acc.CreateCloudQueueClient(); CloudQueue queue = clnt.GetQueueReference(processQueue); queue.CreateIfNotExist(); this._queue = new StdQueue<ParseTaskMessage>(queue); Hope this helps! A: Extension method that uses Newtonsoft.Json and async public static async Task AddMessageAsJsonAsync<T>(this CloudQueue cloudQueue, T objectToAdd) { var messageAsJson = JsonConvert.SerializeObject(objectToAdd); var cloudQueueMessage = new CloudQueueMessage(messageAsJson); await cloudQueue.AddMessageAsync(cloudQueueMessage); } A: I like this generalization approach but I don't like having to put Serialize attribute on all the classes I might want to put in a message and derived them from a base (I might already have a base class too) so I used... using System; using System.Text; using Microsoft.WindowsAzure.Storage.Queue; using Newtonsoft.Json; namespace Example.Queue { public static class CloudQueueMessageExtensions { public static CloudQueueMessage Serialize(Object o) { var stringBuilder = new StringBuilder(); stringBuilder.Append(o.GetType().FullName); stringBuilder.Append(':'); stringBuilder.Append(JsonConvert.SerializeObject(o)); return new CloudQueueMessage(stringBuilder.ToString()); } public static T Deserialize<T>(this CloudQueueMessage m) { int indexOf = m.AsString.IndexOf(':'); if (indexOf <= 0) throw new Exception(string.Format("Cannot deserialize into object of type {0}", typeof (T).FullName)); string typeName = m.AsString.Substring(0, indexOf); string json = m.AsString.Substring(indexOf + 1); if (typeName != typeof (T).FullName) { throw new Exception(string.Format("Cannot deserialize object of type {0} into one of type {1}", typeName, typeof (T).FullName)); } return JsonConvert.DeserializeObject<T>(json); } } } e.g. var myobject = new MyObject(); _queue.AddMessage( CloudQueueMessageExtensions.Serialize(myobject)); var myobject = _queue.GetMessage().Deserialize<MyObject>(); A: In case the storage queue is used with WebJob or Azure function (quite common scenario) then the current Azure SDK allows to use POCO object directly. See examples here: * *https://learn.microsoft.com/en-us/sandbox/functions-recipes/queue-storage *https://github.com/Azure/azure-webjobs-sdk/wiki/Queues#trigger Note: The SDK will automatically use Newtonsoft.Json for serialization/deserialization under the hood. A: I liked @Akodo_Shado's approach to serialize with Newtonsoft.Json. I updated it for Azure.Storage.Queues and also added a "Retrieve and Delete" method that deserializes the object from the queue. public static class CloudQueueExtensions { public static async Task AddMessageAsJsonAsync<T>(this QueueClient queueClient, T objectToAdd) where T : class { string messageAsJson = JsonConvert.SerializeObject(objectToAdd); BinaryData cloudQueueMessage = new BinaryData(messageAsJson); await queueClient.SendMessageAsync(cloudQueueMessage); } public static async Task<T> RetreiveAndDeleteMessageAsObjectAsync<T>(this QueueClient queueClient) where T : class { QueueMessage[] retrievedMessage = await queueClient.ReceiveMessagesAsync(1); if (retrievedMessage.Length == 0) return null; string theMessage = retrievedMessage[0].MessageText; T instanceOfT = JsonConvert.DeserializeObject<T>(theMessage); await queueClient.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt); return instanceOfT; } } The RetreiveAndDeleteMessageAsObjectAsync is designed to process 1 message at time, but you could obviously rewrite to deserialize the full array of messages and return a ICollection<T> or similar. A: That is not right way to do it. queues are not ment for storing object. you need to put object in blob or table (serialized). I believe queue messgae body has 64kb size limit with sdk1.5 and 8kb wih lower versions. Messgae body is ment to transfer crutial data for workera that pick it up only.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/8550702', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '28'}
Q: Help needed renaming custom post I really have very little Wordpress knowledge and I need help with the following: I have a theme which uses a custom post called 'services'. I needed another custom post created which worked exactly the same as services so I went through all the code and copied and pasted wherever I found references to services and changed it to "signage". This worked ok, however on the WP admin screen, "signage" is called "posts" as is the original "posts", and I cant work out how to change the name to signage. I have been able to change the original "posts" name but not the custom post. A: It could be the 'name' in the labels array of the register post type. It would be much easier to help if you can show us your code.
{'language': 'en', 'url': 'https://wordpress.stackexchange.com/questions/116728', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '-1'}
Q: How to add FTP site in IIS 7 in Windows Vista Home premium edition How to add the FTP server in IIS 7 using Windows vista Home Premium Edition? A: Please check if FTP 7.5 can be used on your Windows Vista machine, http://www.iis.net/expand/FTP If not, FileZilla is a free alternative, http://filezilla-project.org/download.php?type=server
{'language': 'en', 'url': 'https://stackoverflow.com/questions/2524250', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Unable to install any program Total newbie here, I installed Kubuntu about three days ago and have been trying to install some programmes, to date no success. No matter what I try to install I get the same error. I would be very grateful if someone could explain what is happening and how to resolve it, or point me to a document that can help. Thanks in advance for your help, Noel sudo apt-get install muon [sudo] password for nleric: Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: muon : Depends: apt-xapian-index but it is not going to be installed E: Unable to correct problems, you have held broken packages. A: the package "apt-xapian-index" is in the universe repository since Ubuntu 16.04 Xenial (see http://packages.ubuntu.com/xenial/apt-xapian-index). Before Ubuntu 16.04 Xenial the package "apt-xapian-index" was in the main repository, so it was always available, even if the user had the "universe" repository disabled. It's not the case anymore. To confirm what is above just run the following: apt-cache policy apt-xapian-index If the result is not available it's because apt-get can't find it in the present repositories present in the file /etc/apt/sources.list. My guess is that you have removed/disabled the universe repository from your APT /etc/apt/sources.list file. Make sure to add "universe" at the end of the the lines starting with "deb" in that file. Example, change the following line to have the universe repository enabled, in the file /etc/apt/sources.list file: deb http://archive.ubuntu.com/ubuntu/ xenial main To something like (add the last word in the line): deb http://archive.ubuntu.com/ubuntu/ xenial main universe Then update apt-get repositories: sudo apt-get update Apt-get will update its sources of available packages, now with the universe repository enabled. Then try to fix the problem: sudo apt-get install -f
{'language': 'en', 'url': 'https://askubuntu.com/questions/796482', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: NLog not creating a log file inside AWS ec2 Linux I have a .net core application in AWS ec2 linux and it does NOT create a log file. The application on AWS ec2 linux is published with Deployment Mode: Self-contained and Target Runtime: linux-x64. I tried it on windows and it does create a log file but somehow it's not working in AWS ec2 linux. Heres what I did. * *Open ubuntu machine terminal (CLI) and Go to the project directory *Provide execute permissions: chmod 777 ./appname *Execute application *./appname Note: It displays the Hello World. public static void Main(string[] args) { try { using (var logContext = new LogContextHelper(null, "MBP", "MBP", new JObject() { { "ASD", "asd" }, { "ZXC", "asd" }, { "QWE", "asd" }, { "POI", "" } }, setAsContextLog: true)) { } } catch (Exception e) { Console.WriteLine("Error: {0}", e); } //sample s = new sample("consuna") { objectinitial = "objuna"}; Console.WriteLine("Hello World!"); Console.ReadLine(); } } Here is the NLog.config <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log"> <variable name="myvar" value="myvalue"/> <targets> <target xsi:type="File" name="fileMBP" fileName="/home/ec2-user/mbpTESTING.log"`enter code here` layout="Logger=&quot;MBP API&quot;, TimeStamp=&quot;${event-context:item=datetime}&quot;, TimeStampMel=&quot;${event-context:item=datetimeMel}&quot;, Message=&quot;${message}&quot;, Context=&quot;${basedir}&quot;, Command=&quot;${event-context:item=command}&quot;, ${event-context:item=properties}" archiveFileName="/home/ec2-user/MBP.{#}.txt" archiveEvery="Day" archiveNumbering="DateAndSequence" maxArchiveFiles="7" concurrentWrites="true" keepFileOpen="false"/> </targets> <rules> <logger name="MBP" minlevel="Trace" writeTo="fileMBP"/> </rules> </nlog> I expect that it will create a log file with logs on it just like on windows.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/57800735', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: EditText length with "exceptions" I have an EditText and I'd like to set maxLength to four numbers (in range -9999 to 9999). Problem is that if I setandroid:maxLength="4" in xml I can write there e.q "9999" but it doesn't accept "-9999" because of length (5 char). Is there any opportunity how to solve it (programatically or anyhow) Thanks
{'language': 'en', 'url': 'https://stackoverflow.com/questions/36794789', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Understanding hashCode(), equals() and toString() in Java I am beginner in Java and although I have a look at several questions and answers in SO, I am not sure if I completely understand the usage of hashCode(), equals() and toString() in Java. I encountered the following code in a project and want to understand the following issues: 1. Is it meaningful to define these methods and call via super like return super.hashCode()? 2. Where should we defines these three methods? For each entity? Or any other place in Java? 3. Could you please explain me the philosophy of defining these 3 (or maybe similar ones that I have not seen before) in Java? @Entity @SequenceGenerator(name = "product_gen", sequenceName = "product_id_seq") @Table @Getter @Setter @ToString(callSuper = true) @NoArgsConstructor public class Product extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_gen") private long id; @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object other) { return super.equals(other); } } A: * *toString() method returns the String representation of an Object. The default implementation of toString() for an object returns the HashCode value of the Object. We'll come to what HashCode is. Overriding the toString() is straightforward and helps us print the content of the Object. @ToString annotation from Lombok does that for us. It Prints the class name and each field in the class with its value. The @ToString annotation also takes in configuration keys for various behaviours. Read here. callSuper just denotes that an extended class needs to call the toString() from its parent. hashCode() for an object returns an integer value, generated by a hashing algorithm. This can be used to identify whether two objects have similar Hash values which eventually help identifying whether two variables are pointing to the same instance of the Object. If two objects are equal from the .equals() method, they must share the same HashCode *They are supposed to be defined on the entity, if at all you need to override them. *Each of the three have their own purposes. equals() and hashCode() are majorly used to identify whether two objects are the same/equal. Whereas, toString() is used to Serialise the object to make it more readable in logs. From Effective Java: You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and HashTable.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/69024813', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: How to reference a variable from one activity to another I'm trying to get a variable string and integer from Main2Activity.java to MainActivity.java But the problem is that I don't want to use the: startActivity(intent); For it to work. I just want the information to be passed so I can use it in my current activity. Is there any way to do this? What am I missing. This is how my MainActivity looks like: btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView = (TextView)findViewById(R.id.textView7); Intent intent = getIntent(); String A = intent.getStringExtra("Apples"); textView.setText(A); } }); And my Main2Activty: Intent intent = new Intent(Main2Activity.this, MainActivity.class); intent.putExtra("Apples", "Red"); Thanks for helping. Please only comment if you know what you're talking about. A: There is an other way, you can define a Class DataHolder and static variable for sharing variable between Activity Example class DataHolder { public static String appleColor = ""; } Then you can use like this: Intent intent = new Intent(Main2Activity.this, MainActivity.class); DataHolder.appleColor = "RED"; Then btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView = (TextView)findViewById(R.id.textView7); Intent intent = getIntent(); textView.setText(DataHolder.appleColor); } });
{'language': 'en', 'url': 'https://stackoverflow.com/questions/48392826', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Replace black boot screen with Purple ( default ) I used to have Gnome and Cinnamon on my laptop. Maybe because of that, the boot screen has changed to a black one than default Purple boot screen. I have since then upgraded to 16.04 from 14.04 and everything was good. But recently, I am facing frequent boot failure. The boot screen flashes, goes transparent and shows some terminal like activities in the background. In the end, mostly it will say some process failed and I never get to the GUI. This is happening so frequently that I am not able to use my PC at all. Will replacing black boot screen with Purple solve this problem ? If no, kindly suggest a solution for the same. Thanks. PS: I now use Unity alone with 16.04
{'language': 'en', 'url': 'https://askubuntu.com/questions/855301', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Only grep img tags that contain a keyword, but not img tags that don't? Using grep/regex, I am trying to pull img tags out of a file. I only want img tags that contain 'photobucket' in the source, and I do not want img tags that do not contain photobucket. Want: <img src="/photobucket/img21.png"> Do Not Want: <img src="/imgs/test.jpg"> <img src="/imgs/thiswillgetpulledtoo.jpg"><p>We like photobucket</p> What I have tried: (<img.*?photobucket.*?>) This did not work, because it pulled the second example in "Do Not Want", as there was a 'photobucket' and then a closing bracket. How can I only check for 'photobucket' up until the first closing bracket, and if photobucket is not contained, ignore it and move on? 'photobucket' may be in different locations within the string. A: Just add a negation of > sign: (<img[^>]*?photobucket.*?>) https://regex101.com/r/tZ9lI9/2 A: grep -o '<img[^>]*src="[^"]*photobucket[^>]*>' infile -o returns only the matches. Split up: <img # Start with <img [^>]* # Zero or more of "not >" src=" # start of src attribute [^"]* # Zero or more or "not quotes" photobucket # Match photobucket [^>]* # Zero or more of "not >" > # Closing angle bracket For the input file <img src="/imgs/test.jpg"> <img src="/imgs/thiswillgetpulledtoo.jpg"><p>We like photobucket</p> <img src="/photobucket/img21.png"> <img alt="photobucket" src="/something/img21.png"> <img alt="something" src="/photobucket/img21.png"> <img src="/photobucket/img21.png" alt="something"> <img src="/something/img21.png" alt="photobucket"> this returns $ grep -o '<img[^>]*src="[^"]*photobucket[^>]*>' infile <img src="/photobucket/img21.png"> <img alt="something" src="/photobucket/img21.png"> <img src="/photobucket/img21.png" alt="something"> The non-greedy .*? works only with the -P option (Perl regexes). A: Try the following: <img[^>]*?photobucket[^>]*?> This way the regex can't got past the '>' A: Try with this pattern: <img.*src=\"[/a-zA-Z0-9_]+photobucket[/a-zA-Z0-9_]+\.\w+\".*> I´m not sure the characters admited by the name folders, but you just need add in the ranges "[]" before and after the "photobucket".
{'language': 'en', 'url': 'https://stackoverflow.com/questions/34882511', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Maximum number reached for Sharepoint 2007 number-type column In a SharePoint 2007 List, there is a number-type column which have a maximum value 1000. Suppose that the column is used for a auto-increment ID, what will happen if the ID exceed 1000? Will the next ID be reset to 0 or a error will occur?
{'language': 'en', 'url': 'https://sharepoint.stackexchange.com/questions/19840', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Q: Icon color of html5 input date picker How can I change the icon color of the native HTML5 date input (<input type="date" />)? Is it possible to change the calendar icon color to HEX: #018bee or RGB: (1, 139, 238)? I saw a post saying that it was possible using filters, but I was unsuccessful. Codepen Example: https://codepen.io/gerisd/pen/VwPzqMy HTML: <input type="date" id="deadline" name="deadline" value="2021-01-01" required> CSS: #deadline{ width: 100%; min-width: 100px; border: none; height: 100%; background: none; outline: none; padding-inline: 5px; resize: none; border-right: 2px solid #dde2f1; cursor: pointer; color: #9fa3b1; text-align: center; } input[type="date"]::-webkit-calendar-picker-indicator { cursor: pointer; border-radius: 4px; margin-right: 2px; filter: invert(0.8) sepia(100%) saturate(10000%) hue-rotate(240deg); } A: Have you tried using webkit? I found a similar qustion from enter link description here try this code from that question maybe: ::-webkit-calendar-picker-indicator { filter: invert(1); }
{'language': 'en', 'url': 'https://stackoverflow.com/questions/66974856', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: how can i display data in detail component from list component? i have problem to display data from one component to another component. i put the data which i fetch from the serve in prova and i display the list of all work. but I can't transfer the data that is on "prova" to another component to make the details visible through their own id. this is my apicall service import { Injectable } from '@angular/core'; import {HttpClient,HttpClientModule,HttpResponse} from '@angular/common/http'; import {Observable} from "rxjs"; import {map} from "rxjs/operators"; import {results} from "./results" @Injectable({ providedIn: 'root' }) export class GetApiService { constructor( private http:HttpClient, ) { } apiCall():Observable<results[]> { return this.http.get('https://www.themuse.com/api/public/jobs?category=Engineering&page=10') .pipe(map ( (response:any) => { const data = response.results; console.log (data) return data ; } ) ); } } this is my observable results export interface results { categories : any; company: string; contents:string; id : number; levels:string; locations:string; model_type: string; name: string; refs: string; short_name: string; type:string; } this is my component where are a list of works import {results} from "../results"; import {GetApiService} from '../get-api.service'; import {switchMap} from "rxjs/operators"; import { Observable } from 'rxjs'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-work-list', templateUrl: './work-list.component.html', styleUrls: ['./work-list.component.css'] }) export class WorkListComponent implements OnInit { prova: results[]=[] ; item: any; selectedId: any ; constructor( private api :GetApiService, private route: ActivatedRoute, ) { } ngOnInit(){ this.api.apiCall() .subscribe ( (data:results[]) => { this.prova=data; console.log (data); }); } } and the respectiv html connected by id <div *ngFor="let item of prova " [class.selected]="item.id === selectedId"> <a [routerLink]="['/details',item.id]"> <h1> {{ item.name }}</h1> </a> <h1> {{ item.id }}</h1> <h1> {{ item.categories[0].name }}</h1> <h1> {{ item.name }}</h1> </div> this is the details where i can't display the selected work with its own details import { ActivatedRoute } from '@angular/router'; import {results} from '../results'; import {GetApiService} from '../get-api.service'; import {switchMap} from "rxjs/operators"; @Component({ selector: 'app-work-details', templateUrl: './work-details.component.html', styleUrls: ['./work-details.component.css'] }) export class WorkDetailsComponent implements OnInit { @Input() item: { categories: any; company: string; contents: string; id: number; levels: string; locations: string; model_type: string; name: string; refs: string; short_name: string; type: string; } | undefined; @Input () prova: results[]=[]; selectedId:string | undefined; constructor( private route: ActivatedRoute, private api: GetApiService, ) { } ngOnInit():void { this.route.paramMap.subscribe (params => { this.item=this.prova[+params.get('selectedId')]; **// it should be somewthing like this but prova is empty.** }) ; } } A: It looks like you're mixing two different mechanisms? One is of a parent -> child component relationship where you have your WorkDetailsComponent with an @Input() for prova, but at the same time, it looks like the component is its own page given your <a [routerLink]="['/details',item.id]"> and the usage of this.route.paramMap.subscribe.... Fairly certain you can't have it both ways. You either go parent -> child component wherein you pass in the relevant details using the @Input()s: <div *ngIf="selectedItem"> <app-work-details [prova]="prova" [selectedItem]="selectedItem"></app-work-details> </div> OR you go with the separate page route which can be done one of two ways: * *Use the service as a shared service; have it remember the state (prova) so that when the details page loads, it can request the data for the relevant id. *Pass the additional data through the route params For 1, it would look something like: private prova: results[]; // Save request response to this as well public getItem(id: number): results { return this.prova.find(x => x.id === id); } And then when you load your details page: ngOnInit():void { this.route.paramMap.subscribe (params => { this.selectedId=+params.get('selectedId'); this.item = this.service.getItem(this.selectedId); }); } For 2, it involves routing with additional data, something like this: <a [routerLink]="['/details',item.id]" [state]="{ data: {prova}}">..</a> This article shows the various ways of getting data between components in better detail.
{'language': 'en', 'url': 'https://stackoverflow.com/questions/65146369', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '0'}
Q: Shifting elements of an array to the right I am aware that there are solutions for shifting arrays out there. However no solution works for me. The code should achieve the following: The method shift(int[] array, int places) takes in an array, shifts the elements places - times to the right and replaces the "leftover" elements with "0". So far I have: public static int[] shiftWithDrop(int[] array, int places) { if (places == 0 || array == null) { return null; } for (int i = array.length-places-1; i >= 0; i-- ) { array[i+places] = array[i]; array[i] = 0; } return array; } This code does only somehow work, but it does not return the desired result. What am I missing? A: There are several issues in this code: * *It returns null when places == 0 -- without shift, the original array needs to be returned *In the given loop implementation the major part of the array may be skipped and instead of replacing the first places elements with 0, actually a few elements in the beginning of the array are set to 0. Also it is better to change the signature of the method to set places before the vararg array. So to address these issues, the following solution is offered: public static int[] shiftWithDrop(int places, int ... array) { if(array == null || places <= 0) { return array; } for (int i = array.length; i-- > 0;) { array[i] = i < places ? 0 : array[i - places]; } return array; } Tests: System.out.println(Arrays.toString(shiftWithDrop(1, 1, 2, 3, 4, 5))); System.out.println(Arrays.toString(shiftWithDrop(2, new int[]{1, 2, 3, 4, 5}))); System.out.println(Arrays.toString(shiftWithDrop(3, 1, 2, 3, 4, 5))); System.out.println(Arrays.toString(shiftWithDrop(7, 1, 2, 3, 4, 5))); Output: [0, 1, 2, 3, 4] [0, 0, 1, 2, 3] [0, 0, 0, 1, 2] [0, 0, 0, 0, 0]
{'language': 'en', 'url': 'https://stackoverflow.com/questions/70135652', 'timestamp': '2023-03-29', 'source': 'stackexchange', 'question_score': '1'}
Луе́рр () — колишній муніципалітет у Франції, у регіоні Пеї-де-ла-Луар, департамент Мен і Луара. Населення — осіб (2011). Муніципалітет був розташований на відстані близько 270 км на південний захід від Парижа, 95 км на схід від Нанта, 27 км на південний схід від Анже. Історія 1 січня 2016 року Луерр, Амбію-Шато i Нуаян-ла-Плен було об'єднано в новий муніципалітет Тюффален. Демографія Розподіл населення за віком та статтю (2006): Економіка У 2010 році в муніципалітеті числилось 182 оподатковані домогосподарства, у яких проживали 464,0 особи, медіана доходів виносила євро на одного особоспоживача Галерея зображень Посилання [ Розташування муніципалітету Луерр на мапі Франції та сусідні муніципалітети] Див. також Список муніципалітетів департаменту Мен і Луара Примітки Колишні муніципалітети департаменту Мен і Луара
{'title': 'Луерр', 'url': 'https://uk.wikipedia.org/wiki/%D0%9B%D1%83%D0%B5%D1%80%D1%80', 'language': 'uk', 'timestamp': '20230320'}
Coat-Méal (en bretó Koz-Meal) és un municipi francès, situat a la regió de Bretanya, al departament de Finisterre. L'any 2006 tenia 934 habitants. El consell municipal ha aprovat la carta Ya d'ar brezhoneg. Demografia Administració Referències Municipis del districte de Brest
{'title': 'Coat-Méal', 'url': 'https://ca.wikipedia.org/wiki/Coat-M%C3%A9al', 'language': 'ca', 'timestamp': '20230320'}
Tenzin Tsundue is een Tibetaans dichter, schrijver en activist. In 2001 won hij de eerste Outlook-Picador Award voor non-fictie. Hij publiceerde drie boeken die werden vertaald in andere talen. Achtergrond Zijn ouders ontvluchtten Tibet tijdens de Tibetaanse diaspora. Bij aankomst in India in 1959 werkten ze eerst in de wegenbouw van bergwegen in Masumari, Bir, Kullu en Manali. Honderden Tibetanen die naar India vluchtten kwamen in de eerste tijd om, omdat ze de hitte van de zomer en de vochtigheid van de moesson niet konden verdragen. Het kamp van de wegenbouw trok verder en ergens onderweg werd Tenzin Tsundue langs de kant van de weg geboren in een noodtent. Zijn geboortedatum is niet bevestigd en er bestaan drie verschillende registraties van. Hij ging naar school in Dharamsala en ging naar de universiteiten van Chennai en Mumbai. Werk Zijn eerste boek, Crossing the Border, gaf hij uit met behulp van geld dat hij van medestudenten gekregen en geleend had, terwijl hij zijn voor zijn master studeerde aan de Universiteit van Mumbai. In 2001 won hij de eerste Outlook-Picador Award voor non-fictie. Zijn tweede boek Kora werd vertaald naar het Frans en Malayalam. Zijn derde boek, Semshook, is een compilatie van essays over de Tibetaanse vrijheidsbeweging. In 2005 vertegenwoordigde hij Tibet in New Delhi tijdens de tweede Zuid-Aziatische literatuurconferentie. Media Tenzin Tsundue wordt vaak gezien als een opinieleider binnen de Tibetaanse gemeenschap in ballingschap. Geschriften van Tenzin Tsundue verschijnen geregeld in Indiase en internationale tijdschriften en andere media. Hij schreef onder ander voor The International PEN, The Indian PEN, Sahitya Akademi’s Indian Literature, The Little Magazine, Outlook, The Times of India, The Indian Express, Hindustan Times, Better Photography, The Economic Times, Tehelka, The Daily Star (Bangladesh), Today (Singapore), Tibetan Review en Gandhi Marg. In 2002 noemde de Indiase editie van het modeblad Elle hem een van de 50 best geklede mannen van India. Hij is onder meer te zien in de documentaire Tibet: 50 Years After the Fall uit 2009 van het regisseursduo Ritu Sarin en Tenzin Sönam. Activisme Vanaf zijn studietijd was Tenzin Tsundue een voorvechter van de onafhankelijkheid van Tibet. Januari 2002 kreeg hij internationale aandacht van de media, omdat hij een banier uitrolde op de veertiende verdieping van het vijfsterrenhotel in Mumbai, toen de Chinese premier Zhu Rongji binnen was. April 2005 herhaalde hij dezelfde stunt, toen premier Wen Jiabao Bangalore bezocht. Hier ontrolde hij een grote rode banier met de tekst Free Tibet terwijl hij riep: "Wen Jiaboa, you cannot silence us." Tenzin Tsundue bracht Indiase bestuurders in verlegenheid en de Indiase politie gelastte hem Dharamsala niet te verlaten tijdens het bezoek van de Chinese president Hu Jintao aan India in november 2006. Sinds 2000 draagt hij een rode band om zijn hoofd waarmee hij wil uitdrukken dat hij werkt aan de vrijheid van zijn land en die hij niet eerder af wil doen dan Tibet vrij is. Uitspraken Ik ben een verknocht gelover in geweldloosheid. We zijn bereid om te sterven, maar niet bereid om te doden. Vrijheidsstrijd is mijn leven Bibliografie Tsundue, Tenzin & Woeser & Jampa & Bhuchung D Sonam & Jane Perkins (2006) Nyima Tsering's Tears ?: Crossing the Border 2007: Semshook 2008: Kora Tibetaans activist Tibetaans schrijver
{'title': 'Tenzin Tsundue', 'url': 'https://nl.wikipedia.org/wiki/Tenzin%20Tsundue', 'language': 'nl', 'timestamp': '20230320'}
Kristian Hovde (6 December 1903 – 19 August 1969) was a Norwegian cross-country skier who competed in the late 1920s in the early 1930s. He was born in Vikersund. Hovde won a silver in the 18 km event at the 1931 FIS Nordic World Ski Championships. At the 1932 Winter Olympics he finished 13th in the 18 km cross-country skiing event. Cross-country skiing results All results are sourced from the International Ski Federation (FIS). Olympic Games World Championships 1 medal – (1 silver) References External links 1903 births Norwegian male cross-country skiers Olympic cross-country skiers of Norway Cross-country skiers at the 1932 Winter Olympics 1969 deaths FIS Nordic World Ski Championships medalists in cross-country skiing People from Modum Sportspeople from Viken (county) 20th-century Norwegian people
{'title': 'Kristian Hovde', 'url': 'https://en.wikipedia.org/wiki/Kristian%20Hovde', 'language': 'en', 'timestamp': '20230320'}
Пол Кагаме () е политик от Руанда и бивш военен лидер. Той е президент на Руанда, след като пое поста си през 2000 г., когато неговият предшественик Пастьор Бизимунгу подаде оставка. Кагаме преди това командва бунтовническите сили, които слагат край на геноцида в Руанда през 1994 година. Той е считан за фактически лидер на Руанда, когато е бил вицепрезидент и министър на отбраната от 1994 до 2000 г. Той е преизбран през август 2017 г. с официален резултат от почти 99% на изборите, критикувани за множество нередности. Той е описан като „най-впечатляващ“ и „сред най-репресивните“ африкански лидери. Биография Кагаме е роден в семейство тутси в Южна Руанда. Когато е на две години, Руандийската революция завършва вековете на политическо господство на тутси; семейството му бяга в Уганда, където прекара остатъка от детството си. През 80-те години Кагаме се бие в бунтовническата армия на Йовери Мусевени, ставайки старши офицер от армията на Уганда, след като военните победи на Мусевени го довеждат до президентството на Уганда. Кагаме се присъединява към Патриотичния фронт на Руанда (RPF), който нахлува в Руанда през 1990 година. Кагаме е женен и има четири деца. Политическа кариера Бил е министър на отбраната от 1994 до 2000 г. През този период е бил също вицепрезидент на Руанда. От 2018 до началото на 2019 е председател на Африканския съюз. От 2000 до днес е президент на Руанда. Награди Орден Мухамадия (Мароко, 21.06.2016) Източници Президенти Руандийци Политика на Руанда
{'title': 'Пол Кагаме', 'url': 'https://bg.wikipedia.org/wiki/%D0%9F%D0%BE%D0%BB%20%D0%9A%D0%B0%D0%B3%D0%B0%D0%BC%D0%B5', 'language': 'bg', 'timestamp': '20230320'}
Cochliomyia macellaria, also known as the secondary screwworm, is a species of blow fly in the family Calliphoridae. These screwworms are referred to as "secondary" because they typically infest wounds after invasion by primary myiasis-causing flies. While blow flies may be found in every terrestrial habitat, C. macellaria is primarily found in the United States, American tropics, and sometimes southern Canada. They are most common in the southeastern United States in states like Florida. C. macellaria have a metallic greenish-blue thorax and a red-orange head and eyes. These adult blowflies range from 5–8 mm in size. Since the fly larvae infect the wounds and dead tissue of animals, these flies pose a grave medical and economic risk to humans and livestock. C. macellaria are attracted to carrion and garbage and are often found in slaughterhouses and outdoor markets in the tropics. While these flies carry many various types of Salmonella and viruses like the swine influenza, C. macellaria can also serve as important decomposers in our ecosystem. Description Cochliomyia macellaria are classified as intermediate sized flies with a dull or bright metallic, blue-green coloration. On their thorax, there are three black longitudinal stripes that interrupt the blue-green color. The eye and head of these flies are orange-red in color. C. macellaria also has pale setae on the fronto-orbital plate outside of the frontal bristles. On C. macellaria the frontal row of bristles extend anteriorly to the base of the first antennal segment and consist of 12-14 bristles. The legs of the fly are orange brown to dark brown, and the coxae are orange brown to black with a green metallic luster. C. macellaria possess a dark reddish brown anterior femur and an orange-red anterior tibia. The anterior tibia also has four short bristles that are placed on the dorsal side. The color of the wings of the fly is orange brown tint towards the base. On these wings, the veins in the fly are orange brown to dark brown. The costal sessions 2 to 6 are in the proportions 78:56:96:30:6:6. The first genital section is black with a metallic green luster. On the fly, the scattered setae and a defined marginal row of bristles; the second segment is smaller with a dark brown to black tint with scattered setae. Distinguishing features Cochliomyia macellaria is closely related to C. hominivorax but can be distinguished from C. hominivorax in three primarily ways: two of which are seen in adults and one which is seen in the larvae. In adults, the hairs on the fronto-orbital plate are black in C. hominivorax, but are pale in C. macellaria. Additionally, the central black stripe on the thorax extends only slightly in front of the mesonotal suture in C. hominivorax and well in front of the suture in C. macellaria. C. macellaria larvae, unlike like C. hominivorax larvae, do not have pigmented tracheal trunks but instead have V-shaped spines on the anal protuberance. C. macellaria also does not have an oral sclerite. Distribution and territory Cochliomyia macellaria is most often found in the southeastern part of the United States, in states like Florida, Louisiana, and Georgia. Despite the high concentration in these states, these flies have been found as far north as Southern Canada and as south as the Neotropics, with the exclusion of countries like Chile and Argentina. While they have been found in this large expanse of areas, they have been shown to thrive most in warm and humid areas like the Southern United States, Caribbean Islands, Central America, and northern South America. In these areas, the population size typically increases during periods of extended rainfall. The territories of these blowflies are relatively small, especially during the time of mating. In this period, these flies will stay within a couple meters of one another. Life cycle and history The average life span of an adult C. macellaria is 2–6 weeks. In this time period, the females try to increase the chances of producing as many surviving offspring as possible. In a lifetime, C. macellaria may lay up to 1000 or more eggs. These eggs are typically laid in groups of 40 to 250. Females may also lay their eggs with other females, leading to an accumulation of thousands of eggs. Eggs The eggs of C. macellaria are laid in large groups (40–250 eggs at one time) and typically hatch in about 24 hours. The time taken for eggs to hatch often depends on moisture, temperature, and precipitation. In favorable conditions, the eggs may hatch in just four hours. These eggs are about 1 mm long and appear white to pearl white in color. Larvae The larval stage of C. macellaria is referred to by the common name of secondary screwworms; this is due to the presence of small spines on each body segment that resemble parts of a screw. The larval stage of C. macellaria immediately follows the egg stage and is typically broken down into three substages or instars. Upon hatching, the larve appear a cream color, have cylindrical bodies with 10 or more spines around the spiracular area, possess incomplete peritremes (an indistinct or absent button), and have bands of small spines on each segment. C. macellaria, unlike like C. hominivorax, do not have pigmented tracheal trunks; instead, they have V-shaped spines on the anal protuberance. C. macellaria also does not have an oral sclerite. Cochliomyia macellaria larvae will feed on the decaying flesh of the animal that they have been laid on until they reach maturity. This stage of maturity is during the third instar and by this time point, the larvae may be as long as 17 mm. The entire larval stage is about four to seven days long, and afterwards, the larvae fall off the food source to pupate in the top layer of the soil. Pupae The C. macellaria larvae will typically burrow underneath the top layer of soil, leaves, garbage and begin to pupate there. During this stage, the outer layer begins to turn brown from the cream white that it used to be. The outer skin will begin to shrink and harden while the pupa develops entirely in the hardened shell. Based on the temperature, the length of this stage will vary greatly. In warmer temperatures, the stage may last as short as seven days, but in colder temperatures, it may last as long as two months. Adults Adult C. macellaria are considered to be medium-sized flies because they are about 6 to 9 mm in size and appear bright metallic blue-green to blueish purple in color. These adults typically spend one to two days maturing after leaving the pupae stage. Within four days of emerging from the pupa stage, the adult C. macellaria become sexually mature and start looking for mates. The males will typically mate rapidly and will spend most of their time eating nearby vegetation and nectar from flowers. The females, on the other hand, will feed on the fluids of live wounds from animals. Contrary to the males, the females will travel long distances to find mates. Food resources Depending on the gender and stage in their development, C. macellaria will utilize different resources for energy and nutrients. During the larval stage, the C. macellaria will dig deeper into the necrotic wounds of their host animal and feed on the dead tissue. Both males and females will feast through this method. This time period is extremely crucial to the flies, as they must gather enough nutrients in order to last through the pupal stage without any food sources. This is one reason why the larvae are much larger than the size of the adult C. macellaria. As adults, the food specifications of the flies change. Female flies will continue to feed on tissues of animals; however, now they preferentially feed off of live tissue and tissue plasma. Males, at this point, will no longer consume tissue, but instead will eat nearby vegetation and intake nutrients from the nectar of flowers. Mating Although there are few studies on the mating patterns of C. macellaria, there is some information on the interactions between the males and females. Adult female C. macellaria have been observed to will release pheromones that will stimulate the males copulatory attempts on contact. Even though depriving the C. macellaria adults of dietary proteins did not impact the potency of the female extracts, there was a reduced response in males for the pheromones. Parental care Male C. macellaria do not provide parental care. The males will typically mate quickly and have the females bear the young. Since the females lay so many eggs, there is little care provided by the actual mothers after laying the eggs. The females do strategically lay the eggs in dead skin flesh so that once the eggs hatch into larvae, nutrition will be readily available. Social behavior Traditional social behavior like lekking has not been observed in C. macellaria; however, other social behaviors have been observed. Egg laying It is common for female C. macellaria to lay eggs with other females. Since females may lay up to 250 eggs, it is common for aggregations of thousands of eggs to infest entire animal carcasses. Pheromone selectivity While C. hominivorax is closely related to C. macellaria, there are evolutionary developed methods that lead to reproductive isolation. One of these mechanisms is the interspecies response to the C. macellaria female pheromone. Studies on newly colonized C. hoinivorax males have demonstrated that the males do not response to the C. macellaria pheromone. Enemies Larval predation When studying the larval dispersal and predation for C. macellaria, studies have shown that there is interspecies competition and predation. It has been demonstrated that C. albiceps larvae attack C. macellaria larvae during their dispersal process. Additionally, C. macellaria showed higher aggregation level in single than in double species. This may be explained by an evolutionary mechanism used to conserve and protect C. macellaria from predation. Human depredation Due to the medical and economic impact of the C. macellaria and other blowflies, an array of pesticides have been developed to reduce the C. macellaria population, including pyrethrin aerosol. Mimicry and protective coloration While there are theories for protective coloration, there is no clear mimicry done by C. macellaria or by other insects specifically mimicking C. macellaria. The metallic green coloration may be a form of warding off predators, but this still in the process of being analyzed. Impact Medical Cochliomyia macellaria has extensive medical and economic implications. When C. macellaria larvae infest the dead and decaying tissues of animals or humans, myiasis may often occur. Once infestation occurs, a dark brown discharge will start to leaking from the wound. As the infestation increases, there is more agitation and inflamed tissue, which is accompanied by unpleasant smells. After the process of clinical diagnosis begins and the myiasis is recognized, then the larvae are easier to identify. Treatment of these infestations can be time intensive and leads to increased chances of reoccurrences. The first step is manual removal of the larvae followed by an antibiotic smear. Economic The livestock industry considers the secondary screwworm an important pest because of the enormous economic losses caused by cases of myiasis and disease transmission. The medical and pesticide treatment costs the United States millions of dollars annually. Forensic importance Cochliomyia macellaria is the most common species of blow flies found on carrion in the southern United States. C. macellaria has recently gained recognition in forensic entomology because of its occurrence on decomposing remains. Since the analysis of the succession and occurrence has been well defined, it is possible to create postmortem interval estimations, which are crucial for forensic entomology. Adult C. macellaria in the southeastern United States are only attracted to the dead tissue on animals minutes after the death. In other regions of the United States, the adult flies are attracted to the dead flesh after a 24-hour delay. References Further reading External links Calliphoridae Articles created by Qbugbot Insects described in 1775 Taxa named by Johan Christian Fabricius Diptera of North America Insects of the United States
{'title': 'Cochliomyia macellaria', 'url': 'https://en.wikipedia.org/wiki/Cochliomyia%20macellaria', 'language': 'en', 'timestamp': '20230320'}
Opalenica – dawna gromada, czyli najmniejsza jednostka podziału terytorialnego Polskiej Rzeczypospolitej Ludowej w latach 1954–1972. Gromady, z gromadzkimi radami narodowymi (GRN) jako organami władzy najniższego stopnia na wsi, funkcjonowały od reformy reorganizującej administrację wiejską przeprowadzonej jesienią 1954 do momentu ich zniesienia z dniem 1 stycznia 1973, tym samym wypierając organizację gminną w latach 1954–1972. Gromadę Opalenica z siedzibą GRN w mieście Opalenicy (nie wchodzącym w skład gromady) utworzono 31 grudnia 1971 w powiecie krotoszyńskim w woj. poznańskim z obszarów zniesionych gromad Opalenica-Wschód i Opalenica-Zachód w tymże powiecie; równocześnie do nowo utworzonej gromady Opalenica włączono miejscowości Bukowiec Stary i Porażyn-stacja ze zniesionej gromady Bukowiec tamże. 1 stycznia 1972 do gromady Opalenica włączono część wsi Białawieś o nazwie Porażyn-Tartak z gromady Grodzisk Wielkopolski w tymże powiecie 1 stycznia 1973 w powiecie nowotomyskim reaktywowano zniesioną w 1954 roku gminę Opalenica. Przypisy Opalenica
{'title': 'Opalenica (gromada)', 'url': 'https://pl.wikipedia.org/wiki/Opalenica%20%28gromada%29', 'language': 'pl', 'timestamp': '20230320'}
Coleophora setipalpella é uma espécie de mariposa do gênero Coleophora pertencente à família Coleophoridae. Bibliografia Australian Biological Resources Study (ABRS) (2008): Australian Faunal Directory — Coleophoridae. Pitkin, Brian & Jenkins, Paul (2004): Butterflies and Moths of the World, Generic Names and their Type-species — Coleophora. Savela, Markku (2010): Markku Savela's Lepidoptera and some other life forms — Coleophoridae. Tree of Life Web Project (ToL) (2009): Coleophoridae. Ligações externas Natural History Museum Coleophoridae Coleophora
{'title': 'Coleophora setipalpella', 'url': 'https://pt.wikipedia.org/wiki/Coleophora%20setipalpella', 'language': 'pt', 'timestamp': '20230320'}
Los Machucambos sind eine Band, die sich im August 1959 im Pariser Quartier Latin gründete und die vor allem in den 1960er Jahren in Europa und in den USA großen Erfolg mit ihren Boleros, Cha-Cha-Chas, Rumba- und Merengue-Liedern hatte. Das Trio nannte sich ursprünglich Los Acapulcos. Der Name Los Machucambos entstammt dem südamerikanischen Gürteltier, dessen Schale zur Herstellung der Charango benötigt wird. Von der Originalformation mit der Costa-Ricanerin Julia Cortes, dem Spanier Rafaël Gayoso und dem Peruaner Romano Zanotti sind noch die beiden Musiker und Sänger Gayoso und Zanotti dabei, zusammen mit zwei Sängerinnen, die seit den 1970er Jahren dazugekommen sind: Mariana Gilbert und Maria Licata. Die Formation veröffentlichte bisher 19 Alben und 9 Kompilationen, zuletzt mit dem Titel Pepito im Jahre 2009. Diskografie Alben Singles Weblinks Einzelnachweise Französische Band
{'title': 'Los Machucambos', 'url': 'https://de.wikipedia.org/wiki/Los%20Machucambos', 'language': 'de', 'timestamp': '20230320'}
El torillo moteado (Turnix maculosus) es una especie de ave charadriforme de la familia Turnicidae que habita en Oceanía. Distribución Se extiende por las islas menores de la Sonda, Célebes, algunas Molucas, el norte y este de Australia, Nueva Guinea, las islas Bismarck y las Salomón. Referencias Enlaces externos maculosus Aves de Australasia Animales descritos en 1815 Taxones descritos por Coenraad Jacob Temminck
{'title': 'Turnix maculosus', 'url': 'https://es.wikipedia.org/wiki/Turnix%20maculosus', 'language': 'es', 'timestamp': '20230320'}
Acanthoscurria natalensis är en spindelart som beskrevs av Chamberlin 1917. Acanthoscurria natalensis ingår i släktet Acanthoscurria och familjen fågelspindlar. Inga underarter finns listade i Catalogue of Life. Källor Fågelspindlar natalensis
{'title': 'Acanthoscurria natalensis', 'url': 'https://sv.wikipedia.org/wiki/Acanthoscurria%20natalensis', 'language': 'sv', 'timestamp': '20230320'}
Аналогова обчислювальна машина (АОМ) () — обчислювальна машина, яка обробляє інформацію, представлену в аналоговій (неперервній) формі. Опис Загалом, аналогові машини — спеціально сконструйовані матеріальні системи (моделі), призначені для відтворювання (моделювання) певних, характерних для даного класу задач, співвідношень між неперервно змінними фізичними величинами (машинними змінними)  — аналогами відповідних відправних математичних змінних розв'язуваної задачі. В залежності від фізичного процесу, покладеного в основу математичної моделі розрізняють електронні (електричні), електромеханічні, механічні, гідравлічні, пневматичні та ін. Найпоширеніші електронні аналогові машини, в яких машинними змінними є електрична напруга і струм, а співвідношення, що визначаються, моделюються фізичними процесами, що протікають у електричних колах. Аналогові комп'ютери працюють у режимі реального часу і тому використовуються для спостереження і керування іншими подіями по мірі їх виникнення. Це обчислювальна машина, в якій кожному миттєвому значенню змінної величини, що бере участь у вихідних співвідношеннях, ставиться у відповідність миттєве значення іншої (машинної) величини, що часто відрізняється від вихідної фізичною природою і масштабним коефіцієнтом. Кожній елементарній математичній операції над машинними величинами, як правило, відповідає деякий фізичний закон що встановлює математичні залежності між фізичними величинами на виході і вході вирішального елементу (наприклад, закони Ома і Кірхгофа для електричних ланцюгів, вираження для ефекту Холла, лоренцової сили тощо). Особливості представлення вихідних величин і побудови окремих вирішальних елементів значною мірою зумовлюють порівняно велику швидкість роботи АОМ, простоту програмування і набору завдань, проте обмежуючи сферу застосування і точність отримуваного результату. АОМ відрізняється також малою універсальністю (алгоритмічна обмеженість) — при переході від рішення завдань одного класу до іншого потрібно змінювати структуру машини і число вирішальних елементів. Історична довідка Першим аналоговим обчислювальним пристроєм зазвичай називають логарифмічну лінійку, що з'явилася близько 1600. Графіки й номограми — наступний різновид аналогових обчислювальних пристроїв — для визначення функцій декількох змінних; вперше зустрічаються в керівництві з навігації в 1791. У 1814 англійський учений Дж. Герман розробив аналоговий прилад — планіметр, призначений для визначення площі, обмеженої замкнутої кривої на площині. Планіметр був вдосконалений в 1854 німецьким ученим А. Амслером. Його інтегруючий прилад з колесом, що котиться, привів пізніше до винаходу англійським фізиком Дж. Томсоном фрикційного інтегратора. У 1876 інший англійський фізик В. Томсон застосував фрикційний інтегратор в проекті гармонійного аналізатора для аналізу і передбачення висоти припливів в різних портах. Він показав в принципі можливість вирішення диференціальних рівнянь шляхом з'єднання декількох інтеграторів, проте через низький рівень техніки того часу ідея не була реалізована. Перша механічна обчислювальна машина для вирішення диференціальних рівнянь при проектуванні кораблів була побудована А. Н. Криловим в 1904. У основу її була покладена ідея інтеграфа — аналогового інтегруючого приладу, розробленого польським математиком Абданк-Абакановичем (1878) для здобуття інтеграла довільної функції, викресленої на плоскому графіку. Подальший розвиток механічних інтегруючих машин пов'язаний з роботами американського вченого С. Буша, під керівництвом якого була створена чисто механічна інтегруюча машина (1931), а потім її електромеханічний варіант (1942). У 1936 російський інженер Н. Мінорський запропонував ідею електродинамічного аналога. Поштовх розвитку сучасних АОМ постійного струму дала розробка Б. Расселом (1942—44, США) вирішального підсилювача. Завдання АОМ ОМ в основному застосовується при вирішенні наступних завдань: Контроль і керування. У системах автоматичного керування АОМ користуються, як правило, для визначення або формування закону керування, для обчислення звідних параметрів процесу (ккд, потужність, продуктивність і ін.). Якщо задано математичний вираз, що визначає зв'язок звідного параметра або дії, що управляє, з координатами об'єкта, АОМ служать для вирішення відповідного рівняння. Результат обчислень поступає або на виконавчий механізм (замкнута система), або до оператора. У останньому випадку АОМ працює як інформаційний пристрій. Наприклад, АОМ широко поширені для оцінки економічної ефективності енергетичних систем, і ті ж АОМ можуть управляти виконавчими механізмами, тобто служити автоматичними регулювальниками. Коли закон керування заздалегідь не визначений, а задані лише деякий критерій оптимальності і граничні умови, АОМ застосовуються в системах пошуку оптимального керування і служать математичною моделлю об'єкта. Випереджаючий аналіз, заснований на швидкодії. Багато разів вирішуючи систему рівнянь, що описують керований процес, враховуючи його поточні характеристики, АОМ за короткий час «переглядає» велике число варіантів рішень, параметрів, що відрізняються значеннями, підлягають зміні при управлінні процесом. Набагато випереджаючи хід процесу, АОМ прогнозує сигнали керування які можуть забезпечити необхідну якість протікання процесу. Знайдені машиною значення передаються на регулюючі пристрої, наприклад у вигляді положень їхніх уставок, після чого пошук найкращого варіанту продовжується. У режимі випереджаючого аналізу АОМ виконують функції або машин-порадників, коли оператор користується результатами отриманих на машині розрахунків для ручного або напівавтоматичного керування, або машин, що управляють, автоматично враховують поточні характеристики процесу і керівників ним за оптимальними показниками. Вибір найкращого режиму технологічного процесу здійснюється також самоналагоджувальними математичними машинами в режимі випереджаючого аналізу. Експериментальне дослідження поведінки системи з апаратурою керування або регулювання в лабораторних умовах. За допомогою АОМ відтворюється та частина системи, яка за якими-небудь причинами не може бути відтворена в лабораторних умовах. Зв'язок АОМ з апаратурою керування або регулювання в основному здійснюється перетворюючими пристроями, в яких машинні змінні змінюються за масштабом і формою представлення. Аналіз динаміки систем керування або регулювання. Задані рівняння вирішуються у вибраному масштабі часу з метою знаходження основних параметрів, що забезпечують необхідне протікання процесу. Особливо важливі швидкодіючі АОМ, з допомогою яких в прискореному масштабі часу можна вирішувати деякі ітеративні завдання, завдання оптимізації, а також реалізувати метод Монте-Карло, що вимагає багатократного вирішення стохастичних диференціальних рівнянь. Тут АОМ різко скорочує час проведення розрахунків і робить наочними результати. Вирішення завдань синтезу систем керування і регулювання зводиться до підбору за заданими технічними умовами структури змінної частини системи, функціональних залежностей необхідного вигляду і значень основних параметрів. Остаточний результат виходить багатократним повторенням рішення і зіставленням його з прийнятим критерієм близькості. Завдання цього типа часто зводяться до відшукання екстремуму деякого функціонала. Вирішення завдань за визначенням обурень або корисних сигналів, що діють на систему. В цьому разі за диференціальними рівняннями, що описують динамічну систему, за значеннями початкових умов, за відомим з експерименту характером зміни вихідної координати і статистичними характеристикам шумів у вимірюваному сигналі визначається значення збурення або корисного сигналу на вході. АОМ може також служити для побудови приладів, що автоматично реєструють збурення і виробляють сигнал керування залежно від характеру і розміру збурень. Класифікація АОМ складаються з деякого числа вирішальних елементів, які за характером виконуваних математичних операцій діляться на лінійні, нелінійні і логічні. Лінійні вирішальні елементи виконують операції підсумовування, інтеграції, зміни знаку, множення на постійну величину і ін. Нелінійні (функціональні перетворювачі) відтворюють нелінійні залежності. Розрізняють вирішальні елементи, призначені для відтворення заданої функції від одного, двох і більшого числа аргументів. З цього класу зазвичай виділяють пристрої для відтворення розривних функцій одного аргументу (типові нелінійності) і розмножувально-ділильні пристрої. До логічних вирішальних елементів відносяться пристрої безперервної логіки, наприклад призначені для виділення найбільшою або найменшою з декількох величин, а також пристрою дискретної логіки, релейні перемикальні схеми і деякі ін. спеціальні блоки. Для зв'язку пристроїв безперервної і дискретної логіки широко користуються гібридними логічними пристроями (наприклад, компараторами). Всі логічні пристрої зазвичай об'єднуються в одному, що отримав назву пристрою паралельної логіки. Воно забезпечується своїм набірним полем для з'єднання окремих логічних пристроїв між собою і з останніми вирішальними елементами АОМ. Залежно від фізичної природи машинних величин розрізняють механічні, пневматичні, гідравлічні, електромеханічні і електронні АОМ. Найпоширеніші електронні АОМ, такі, що відрізняються значно ширшою смугою пропускання, зручністю сполучення декількох машин між собою і з елементами апаратури керування. Ці машини збираються з готових радіотехнічних вузлів і напівфабрикатів. Вирішальні елементи АОМ будуються в основному на базі багатокаскадних електронних підсилювачів постійного струму з великим коефіцієнтом посилення в розімкненому стані і глибоким негативним зворотним зв'язком. Залежно від структури і характеру вхідного ланцюга і ланцюга зворотного зв'язку операційний підсилювач виконує лінійну або нелінійну математичну операцію або комбінацію цих операцій. Унаслідок неідеальної роботи окремих вирішальних елементів, неточності установки їхніх коефіцієнтів передачі і початкових умов, рішення, знайдене за допомогою АОМ, має похибку. Результуюча похибка залежить не лише від перерахованих первинних джерел, але і від характеру і особливостей вирішуваного завдання. Як правило, похибка збільшується із зростанням числа вирішальних (особливо нелінійних) елементів, включених послідовно. Практично можна вважати, що похибка під час дослідження стійких нелінійних систем автоматичного керування не перевищує декілька %, якщо порядок системи диференціальних рівнянь не вище 10-ти. За структурою розрізняють АОМ з ручним і з автоматичним програмним керуванням. У першому випадку вирішальні елементи перед початком рішення з'єднуються між собою відповідно до послідовності виконання математичних операцій, що задаються вихідним завданням. У машинах з програмним керуванням послідовність виконання окремих математичних операцій міняється в процесі рішення задачі відповідно до заданого алгоритму рішення. Зміну в ході рішення порядку виконання окремих операцій обумовлює переривистий характер роботи машини: період рішення змінявся періодом останову (для виконання необхідних комутацій). При такому режимі АОМ повинна забезпечуватися аналоговим пристроєм, що запам'ятовує. Наявність пам'яті і дискретність характеру роботи машини дають можливість організувати багатократне використання окремих вирішальних елементів і тим скоротити їхню кількість, не обмежуючи класу вирішуваних завдань, правда, за рахунок зниження швидкодії. Значний інтерес представляють машини: з великою частотою повторення вирішення (30—1000 гц) у зв'язку із створенням систем автоматичного керування, а також з необхідністю організації пошуку оптимальних в деякому розумінні структур і параметрів систем керування. Підвищення ефективності Підвищення ефективності АОМ пов'язане з впровадженням в аналогову техніку цифрових методів, зокрема цифрових диференціальних аналізаторів, в яких окремі вирішальні елементи виконують математичні операції над приростами змінних, представлених в одному з цифрових кодувань, з передачею результатів від елемента до елемента за принципами АОМ. Вживання цифрових диференціальних аналізаторів, особливо послідовних, для спеціальних АОМ, не вимагаючих високої швидкодії, знижує загальний об'єм апаратури, хоча в останніх випадках вони за всіма технічними показниками і можливостями істотно поступаються цифровим обчислювальним машинам. Набагато більшими можливостями володіють гібридні обчислювальні системи, в яких вихідні величини представлені одночасно в цифровій і аналоговій формі. Перспективні для повної автоматизації АОМ так звані матричні моделі. Їхній основний недолік — велика кількість апаратури — у зв'язку з появою інтегральних схем вже не має вирішального значення. Технічні характеристики Основні технічні характеристики деяких типів електронних АОМ загального призначення(див. табл.). Перші 5 типів установок — портативні малогабаритні настільні пристрої. ІПТ-5 виконана з окремих блоків — з лінійних вирішальних елементів. Блокову конструкцію має також ЕМУ-8, кожен блок якої складається з 4 вирішальних елементів. Блоки ЕМУ-8 не вимагають стабілізованих джерел живлення. ЛМУ-1 складається з окремих секцій; ІПТ-5 і ЛМУ-1 у поєднанні з набором нелінійних блоків дозволяють вирішувати також і нелінійні завдання. МН-7 (настільного типа) має обмежений фіксований склад вирішальних елементів, що обмежує її вживання. Установки МН-8, МН-14, МН-17, ЕМУ-10 — багатосекційні, розраховані на вирішення складних завдань. Так, МН-8 має 80 операційних підсилювачів і 28 нелінійних вирішальних елементів; МН-14 — 360 підсилювачів, 92 нелінійних вирішальних елементів; ЕМУ-10 —48 операційних підсилювачів, 30 нелінійних вирішальних елементів. Установки МН-14 і ЕМУ-10 забезпечені змінними набірними полями, цифровими вольтметрами, системою керування, що полегшує набір завдання і установку початкових умов. У МН-14 передбачена можливість керування від перфострічки. ЕМУ-10 відрізняється широкою смугою пропускання основних вирішальних елементів і забезпечена вирішальними підсилювачами з трьома паралельними каналами посилення. Література Kriloff A., Sur un intégrateur des équations différentielles ordinaires, «Ізв. Академії наук», 1904, с. 5, т. 20 № 1; Гутенмахер Л. І., Електричні моделі, М. — Л., 1949; Тараса В С., Основи теорії і конструювання математичних машин безперервної дії, ст 1, Л., 1961; Коган Би. Я., Електронні моделюючі пристрої і їх вживання для дослідження систем автоматичного регулювання, 2 вид., М., 1963; Льовін Л., Методи вирішення технічних завдань з використанням аналогових обчислювальних машин, пер.(перев.) з англ., М., 1966; Корн Р. А., Корн Т. М., Електронні аналогові і аналого-цифрові обчислювальні машини, пер. з англ., ч. 1 — 2, М., 1967 — 68; Buvh V. A., The differential analyzer, а new machine for solving differential equations, «Journal of the Franklin Institute», 1931, v. 212 № 10; Fifer St., Analogue computation, L., 1961. Посилання АНАЛОГОВА ОБЧИСЛЮВАЛЬНА МАШИНА Див. також Гідравлічний інтегратор Квантовий комп'ютер
{'title': 'Аналогова обчислювальна машина', 'url': 'https://uk.wikipedia.org/wiki/%D0%90%D0%BD%D0%B0%D0%BB%D0%BE%D0%B3%D0%BE%D0%B2%D0%B0%20%D0%BE%D0%B1%D1%87%D0%B8%D1%81%D0%BB%D1%8E%D0%B2%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%20%D0%BC%D0%B0%D1%88%D0%B8%D0%BD%D0%B0', 'language': 'uk', 'timestamp': '20230320'}
La Société de gymnastique de Caen est un club omnisports fondé à Caen le par Armand Paris. C'est le premier club sportif de la ville. Histoire La Société de gymnastique, de tir, de préparation militaire de Caen est créée . Son premier président est le député du Calvados Henri Legoux-Longpré. Lui succèdent messieurs Meunier puis André Detolle. Elle est agréée par le ministère de la guerre le pour la préparation au brevet d'aptitude militaire. Elle compte des équipes de gymnastique, de football (couleurs verte et blanche) - qui atteint la finale du championnat de Basse-Normandie en 1919 et de basket. En octobre 1918, des sections football et athlétisme sont créées. En 1919, une section féminine est créée. En 1922, la société compte 205 membres dont 60 filles ; dix ans auparavant, elle comptait 150 membres. Son cinquantenaire est fêté au stade Hélitas le puis par un banquet à l'hôtel de ville. Palmarès La section féminine remporte le championnat de France de basket en 1920-1921, le championnat de France de hockey sur gazon en 1922 et s'adjuge en 1920 le record de France de saut en hauteur. Notes Annexes Articles connexes Caen Club sportif à Caen Sport amateur Association sportive fondée sous la Troisième République Club de gymnastique
{'title': 'Société de gymnastique de Caen', 'url': 'https://fr.wikipedia.org/wiki/Soci%C3%A9t%C3%A9%20de%20gymnastique%20de%20Caen', 'language': 'fr', 'timestamp': '20230320'}
Karl Ortlob (auch: Carl Ortlob; * 17. Januar 1628 in Oels; † 17. August 1678 in Breslau) war ein deutscher evangelischer Geistlicher und Kirchenlieddichter. Werke Siebenmahl sieben Geistliche Gedancken in gebundener Rede, 1651 De variis Germanae Poeseos aetatibus exercitatio, 1657 Literatur Hanspeter Marti: Die Geschichte der deutschen Literatur als Thema einer Disputation in der Barockzeit. Die wiederaufgefundene Dissertation des Schlesiers Karl Ortlob (1628–1678). In: Wolfenbütteler Barock-Nachrichten 20/1, 1993, 5–9. Kirchenlieddichter Lutherischer Geistlicher (17. Jahrhundert) Deutscher Geboren 1628 Gestorben 1678 Mann
{'title': 'Karl Ortlob', 'url': 'https://de.wikipedia.org/wiki/Karl%20Ortlob', 'language': 'de', 'timestamp': '20230320'}
Sydney Cecil Newman, född den 1 april 1917, död den 30 oktober 1997, var en kanadensisk film- och TV-producent som spelade en stor roll för den brittiska dramaproduktionen under 1950- och 1960-talet. 1970 återvände han till Kanada där han fortsatte sin karriär. Karriären i Storbritannien Han arbetade först med Associated British Corporation (ABC). Därefter började han 1962 att arbeta för BBC in 1962. Under åren i Storbritannien initierade han två populära TV-serier, The Avengers och Doctor Who. Han arbetade också med socialrealistiska dramaproduktioner såsom Armchair Theatre och The Wednesday Play. Karriären i Kanada Efter återkomsten till Kanada fick han en ledande tjänst vid Canadian Radio and Television Commission (CRTC). Därefter arbetade som ledare för National Film Board of Canada (NFB). Han innehade också ledande positioner vid Canadian Film Development Corporation och Canadian Broadcasting Corporation och var rådgivande till Secretary of State for Canada. Referenser Män Födda 1917 Avlidna 1997 Kanadensiska TV-producenter
{'title': 'Sydney Newman', 'url': 'https://sv.wikipedia.org/wiki/Sydney%20Newman', 'language': 'sv', 'timestamp': '20230320'}
Luís Oliveira (* 24. März 1969 in São Luís, Maranhão, Brasilien), mit vollem Namen Luís Airton Barroso Oliveira, ist ein ehemaliger brasilianisch-belgischer, offensiver Fußballspieler, der die meiste Zeit seiner bisherigen Laufbahn in Italien spielte. Nach dem Ende seiner aktiven Karriere startete er eine Laufbahn als Fußballtrainer. Karriere Im Verein Oliveira begann seine Laufbahn als Jugendspieler beim brasilianischen Klub Tupan, wechselte aber schon als Sechzehnjähriger 1985 nach Belgien in die Jugendabteilung des RSC Anderlecht. 1988 gelang ihm der Sprung in den Profikader des Brüsseler Vorortvereins, mit dem er 1991 Belgischer Meister wurde. 1992 zog es ihn nach Italien, wo er bis heute lebt und Fußball spielt. Seine erste Station dort war der sardische Serie-A-Verein Cagliari Calcio. Die Jahre 1996 bis 1999 sahen ihn dann bei der Fiorentina, bevor er noch einmal für eine Saison nach Cagliari zurückkehrte. Nach einer weiteren Spielzeit beim FC Bologna war seine Laufbahn in der Serie A beendet und Oliveira heuerte für die Saison 2001/2002 beim Serie-B-Verein Como Calcio an, mit dem er als Erstplatzierter der Serie B den Aufstieg in die Serie A erreichte. Oliveira aber verließ Como zum Ende der Saison, um in der Folgezeit für die Vereine Catania (Serie B, 2002–2004), Foggia (Serie C1, 2004/2005), Venezia (Serie B, 2005) und AS Lucchese Libertas (Serie C1, 2005/2006) zu spielen. 2006 kehrte er in seine Wahlheimat Sardinien zurück, wo er in der bis 2008 für Nuorese Calcio in der Serie C2 spielte. Nach weiteren Stationen bei FBC Derthona und Muravera beendete er 2011 seine Karriere als Aktiver, nachdem er zwischenzeitlich 2010 bereits als Spielertrainer bei Muravera im Einsatz war. 2012 wurde er als neuer Cheftrainer des unterklassigen Klubs vorgestellt. In der Nationalmannschaft Nach seiner Einbürgerung in Belgien absolvierte er zwischen 1992 und 1999 31 Spiele für die belgische Nationalmannschaft und erzielte dabei 7 Tore. 1998 war er Weltmeisterschaftsteilnehmer, die belgische Mannschaft schied aber schon in der Vorrunde nach drei Unentschieden mit drei Punkten als Gruppendritter aus. Erfolge 1991: Belgischer Meister mit dem RSC Anderlecht 1998: Weltmeisterschaftsteilnahme mit der belgischen Nationalmannschaft 2002: Aufstieg in die Serie A mit Como Calcio Weblinks Karrierestatistik bei tuttocalciatori.net Luís Oliveira in der Datenbank des belgischen Fußballverbands (englisch) Fußballnationalspieler (Belgien) Teilnehmer an einer Fußball-Weltmeisterschaft (Belgien) Fußballspieler (Brasilien) Fußballspieler (AC Florenz) Fußballspieler (Cagliari Calcio) Fußballspieler (Como 1907) Fußballspieler (Catania Calcio) Fußballspieler (FC Bologna) Fußballspieler (Foggia Calcio) Fußballspieler (AC Venedig) Fußballspieler (AS Lucchese Libertas) Fußballspieler (FBC Derthona) Fußballspieler (RSC Anderlecht) Fußballtrainer (Italien) Belgier Brasilianer Geboren 1969 Mann
{'title': 'Luís Oliveira', 'url': 'https://de.wikipedia.org/wiki/Lu%C3%ADs%20Oliveira', 'language': 'de', 'timestamp': '20230320'}