text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Sum of sequence of random variables infinitely often equals 1
Let $ X_1,X_2,… $ be an infinite sequence of independent identically distributed random variables that get the values ${-1,0,1}$ with probability $1/3$. Set $Sn=∑X_i$. I want to show that the event $S_n = 1 $ i.o. (infintely often) is in the tail-sigma-algebra of $ X_1,X_2,… $
Any ideas?
A:
It is not an event in the tail-sigma-algebra since you can take the event $X_2=X_3=...=0$ and still cannot know if it happens or not.
| {
"pile_set_name": "StackExchange"
} |
Q:
Second router or middleware path in express.js
I have the usual middleware stack for my app:
app.configure(function() {
app.use(express.static(PUBLIC_DIR));
app.use(express.favicon());
app.use(express.bodyParser({
keepExtensions: true,
uploadDir: '/tmp/neighr'
}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
secret: '***REDACTED***',
store: sessionStore,
}));
app.use(express.csrf());
app.use((require('connect-flash'))());
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
app.locals({
_csrf: req.session._csrf,
url: req.url,
user: req.user,
authenticated: req.isAuthenticated(),
messages: {
info: req.flash('info'),
error: req.flash('error'),
success: req.flash('success')
}
});
next();
});
app.use(app.router);
app.use(express.logger());
app.use(express.errorHandler());
});
As you can see, the express.static is one of the first in the stack, so that static resources will be served without going through the entire session stuff which only makes loading times longer.
I do have, however, some dynamic data I'd like to serve without all the session stuff:
app.get('/avatar/:id', function(req, res) {
var fid = res.params.id;
/* load binary from database */
res.send(data);
});
This route is within app.router, at the end of the stack. I would like to keep the way to declare this and other routes, but how can I get express to parse these before the session middleware?
There might be more such dynamic routes in the future, with more parameters.
A:
Once you declare a route, Express inserts the router middleware into the middleware stack at that point, so if you were to declare a single route before loading the session middleware, all route requests would skip the session middleware:
app.get('/one', ...); // inserts `app.router` into the stack at this point
app.use(express.session(...));
app.get('/two', ...); // will skip the session middleware
There's two solutions I can think of: create your own middleware to handle the requests which shouldn't be passed through the session middleware, or explicitly set the session middleware for each route you want to run through it.
First solution:
app.use(function(req, res, next) {
if (req.path.indexOf('/avatar/') === 0) {
// parse out the `id` and return a response
}
next();
});
This obviously isn't very flexible.
Second solution:
// instantiate the session middleware:
var sessionMiddleware = express.session(...);
// default setup: insert the router before the session middleware:
app.use(app.router);
app.use(sessionMiddleware);
// Pass it explicitly to the route:
app.get('/two', sessionMiddleware, function(req, res) {
...
});
In your situation, where you also use Passport, you might want an array of middleware:
var authMiddleware = [
express.session(...),
passport.initialize(),
passport.session()
];
app.get('/two', authMiddleware, ...);
Looking at how Express is implemented, I don't think it's possible to instantiate a second router (and get it to function properly).
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the pattern of extending createStore of Redux with enhancers?
While writing a blog post about decoupling Redux state from components, I have noticed the usage of enhancer used in createStore link:
export default function createStore(reducer, preloadedState, enhancer) {
/* .... */
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.')
}
return enhancer(createStore)(reducer, preloadedState)
}
/* ... */
return store;
}
The generic pattern, accordingly, is:
function func(arg1, /* ... */, argN, enhancer) {
/* .... */
if (typeof enhancer === 'function') {
return enhancer(func)(arg1, /* ... */, argN);
}
/* ... */
return result;
}
I was excited about this. Now I am wondering how would you classify / name it, and whether it is an ad-hoc excellent piece of code or a result of some systematic approach that is part of something bigger that I'd like to learn and start to apply.
A:
I think you would call this a Decorator.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to simplify an if statement String checking?
I have a method that takes a string and I would like to return true or false depending whether the string has been recorded previously.
So far I have it as follows:
string one = "abc";
string two = "def";
string three = "ghi";
MethodOne(string s)
{
if (s == one || s == two || s == three)
return true;
else
return false;
}
Now is there a simpler way to simplify this without using a lot of || and single string checking?
Would it better to put it in a string array and just use
if (array.contains(s))
or something similar where array is the list of strings to check against?
A:
If you want to compare a string with few other strings, you can simplify your code using a Collection e.g. an Array.Then you can check whether the string you are looking for is present in the array:
return new [] { one, two, three }.Contains(s);
Another alternative would be using Any method:
return new [] { one, two, three }.Any(x => x == s);
Ofcourse there are numerous ways to do that.But the main point is choosing the right data structure to simplify your code and keep it as simple and readable as possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ler arquivo html e pegar o valor de um select selecionado
Estou lendo um arquivo html e preciso pegar o valor de value do select selecionado pelo usuário, como fazer ?
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
var select = doc.DocumentNode.SelectNodes("//table//tr//td//select[@class='CC_CxComboBox']");
foreach (var item in select)
{
var _value = item... //"como pegar o valor do atributo value do select"
}
Este é o HTML
<table>
<tr>
<td Class='Tit08'>CNPJ: 09876543210000 - JOÃO DA SILVA </td>
<td Class='Tit08'>Grupo:
<select id='grupo' class='CC_CxComboBox'>
<option value=''>Selecione</option>
<option value=02161 selected>SÃO PAULO</option>
</select>
</td>
</tr>
</table>
A:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(str);
var select = doc.DocumentNode.SelectNodes("//table//tr//td//select[@class='CC_CxComboBox']//option[@selected]");
foreach (var item in select)
{
var _value = item.Attributes["value"].Value;
var _description = item.InnerHtml;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
maven: How to load tools.jar/classes.jar in an OS independent way?
I am using a maven plugin that requires a class that is contained in the jdk's (windows) tools.jar (mac it's in classes.jar).
I add this as an explicit dependency of the plugin as follows:
<dependencies>
<dependency>
<groupId>sun.jdk</groupId>
<artifactId>classes</artifactId>
<version>1.6.0</version>
<scope>system</scope>
<systemPath>${java.home}/../Classes/classes.jar</systemPath>
</dependency>
</dependencies>
This works if I'm using OS X. However, it does not work if I'm developing on a Windows machine. Moreover, I dislike the use of ../Classes.
Is there perhaps a better way to load in the JDK provided classes?
note: I understand the default (Sun, now Oracle) is to ship the JDK with these classes in lib/tools.jar and that the only real outlier is those who develop using the repackaged Apple JDK. Be that as it may, I am still interested in a -system independent approach- that does not depend so much on the specific path.
A:
You can achieve this by defining different build profiles for Windows VS Mac OS.
See here for more details.
http://maven.apache.org/guides/introduction/introduction-to-profiles.html
| {
"pile_set_name": "StackExchange"
} |
Q:
How come the event handlers on this are not getting invoked?
I have a menu as follows:
<button id="button" onclick="DropDown(event)">Drop down the menu</button>
<div id="menu">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
The JavaScript for the menu is:
// To close the menu when clicked outside
$(document).click(function() { $('#menu').hide(); });
// When clicking on the items
$('#menu li').click(function () {
$(document).append('<code>Clicked item!</code>');
});
function DropDown(event) {
// Position of the menu
var position = $('#button').offset();
// Position the menu and slide it down
$('#menu').css('top',
(position.top + $('#button').height() + 4) + 'px')
.css('left',
position.left + 'px')
.slideToggle();
event.stopPropagation();
}
Most of the code works as expected: clicking the button drops down the menu and clicking anywhere makes the menu disappear. However, the event handler assigned to the <li> items is not getting invoked at all, despite the fact that the onclick handler for the document is being invoked.
jsFiddle: http://jsfiddle.net/W5SqD/4/
A:
Try attaching the event either in a $(document).ready() block or via using the live handler. This will ensure that the event is being attached when the element exists. The below worked for me.
// When clicking on the items
$('#menu li').live("click",function () {
alert("Hello!");
$(document).append('<code>Clicked item!</code>');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
SlickGrid CollapseAllGroups
I am trying to get dataView.collapseAllGroups() to work with SlickGrid.
The post In SlickGrid, how do I collapse grouping via javascript says to just use collapseAllGroups() but it doesn't seem to work.
Even when going to the current demo page http://mleibman.github.io/SlickGrid/examples/example5-collapsing.html and typing dataView.collapseAllGroups() into the console, it doesn't seem to do anything. Is there something else that I need to do to refresh the grid?
Edit
I was trying to get the Grid to display a tree where the groups are collapsed by default. Although I cannot get CollapseAllGroups() to work, I was able to do a hack by adding "if (item._collapsed == null) item._collapsed = true;" to myFilter function that is in the example above.
This is a rough worksound but it does the job for now until I find the real solution:
function myFilter(item) {
// Added this line:
if (item._collapsed == null) item._collapsed = true;
if (item.parent != null) {
var parent = gridData[item.parent];
while (parent) {
if (parent._collapsed) {
return false;
}
parent = gridData[parent.parent];
}
}
return true;
}
A:
That particular example demonstrates how to implement hierarchies using custom formatters and a filter. It does NOT use the DataView's grouping feature, so the collapseAllGroups() call has no effect.
| {
"pile_set_name": "StackExchange"
} |
Q:
My SDK Manager recognizes the SDK but Eclipse doesn't when debugging
As the title says, i tried to use Eclipse for android programming.I installed ADT plugin and set SDK directory.When i open SDK Manager in eclipse it recognizes and shows every SDK version that i'm expecting, but as it appears the IDE doesn't recognize the SDKs and i see this error in console:
Unable to resolve target 'android-19'
I even tried to set SDK target version in my project's "Properties". But there, in the "Android" window's "Project Bundle Target" box, i have only API 23 Option(that was default in the Eclipse's version that i installed).
Now what is the problem and why i get that error and all API 19 classes can't be found in repository even though the SDK Manager recognize the SDK ?
Thank you in advance.
A:
But did you actually download API 19 through SDK Manager? When you extract Android 4.4.2 (API 19) in SDK Manager tree does it said Status Installed? If not then go to the android-sdk folder and run SDK manager.exe as administrator and download API 19 first. Then you should be able to set it as default in project properties in eclipse.
And you should also check this thread:
Unable to resolve target 'android-19'
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to accomplish a custom group and having query?
I'm looking to only pull collections where all related tags exist. This is the query that returns what I need. Now I need to figure out a way to get this to work with tastypie.
Currently I can query like this, but It pulls all collections that have those associated tags (even if the collection only has one). I need to pull collections that have both.
/collection/?tag__name__in=Tag1,Tag2
The query that accomplishes what I need is:
select * from collection
join tag
on tag.collection_id = tag.id
where tag.name in ('Tag1', 'Tag2')
group by
collection.name
having
COUNT(DISTINCT tag.name) = 2;
Would build_filters be the way to go for this?
A:
See this question and answer here
You basically need to annotate/aggregate and then filter. The order is important.
Filtering after annotating creates the having clause you need
| {
"pile_set_name": "StackExchange"
} |
Q:
How to interpret Quotas for Google Services
We have a Sheets add-on that makes an API call to an external URL. The external application is taking more than six minutes to respond. At six minutes, we hit the script runtime per execution limit (as specified at https://developers.google.com/apps-script/guides/services/quotas ) and fail. The external application's API does not take callback functions for asynchronous processing, so we want to understand what account has to be upgraded to get the 30 minute execution limit instead of 6. Is it we, the provider of the add-on, who upgrade our own account to Business, for a cost of $10/month? Or is it each user of the add-on who has to have Business Edition or better, at a much higher cost of $10/user/month? We asked this question at the G Suite Help Forum and were referred to ask it at stackoverflow.
A:
Answer: The User (not the maker of the add-on).
The way add-ons work is to do with which account (i.e. "user" account) is invoking it's services / functions and accordingly, regardless of the architecture of the code / add-on script, it is the user against whom the quota limit would be applicable.
Plus, just worked on an add-on on a G Suite domain where I was presented with exactly this scenario - tested this both ways and concluded that the users ought to be on a 30 min. threshold and not the maker of add-ons.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Question about $\sum_{k=1}^{\infty}\frac{\sin{(k)}\tan (1/k)}{\sqrt{k}}.$
This is an alternating series because of $\sin{k}$. But if there is no $\pi/2$ in the argument for $\sin$, can I still replace $\sin{k}$ with $(-1)^k$? I don't think so.
Here is what I tried instead; the triangle inequality gives
$$\left|\sum_{k=1}^{\infty}\frac{\sin{(k)}\tan (1/k)}{\sqrt{k}}\right|\leq\sum_{k=1}^{\infty}\left|\frac{\sin{(k)}\tan (1/k)}{\sqrt{k}}\right|=\sum_{k=1}^{\infty}\frac{|\sin{(k)}|\tan (1/k)}{\sqrt{k}}.$$
I dont really know how to proceed and if this even makes sense because the triangle inequality applied like this requires that the series is absolutely convergent, and I've not shown that.
A:
Hint: We have $|\sin x|\le 1$, and for small $x$ we have $\tan x\approx x$.
A:
It ought to converge absolutely. Note that $\tan(1/k)\sim 1/k$ for large $k$.
So you have
$$
\sum_{k=1}^\infty \left|\frac{\sin(k)}{\sqrt{k}}\tan(1/k)\right|=\sum_{k=1}^\infty \frac{|\sin(k)|}{\sqrt{k}}\tan(1/k)\leq\sum_{k=1}^\infty\frac{1}{\sqrt{k}}\tan(1/k)\sim\sum_{k=1}^\infty k^{-3/2}
$$
convergent by the p test.
| {
"pile_set_name": "StackExchange"
} |
Q:
$A=90^\circ$ creating a problem in the $\tan(A\pm B)$ formulas
As the title suggests I am having problem using $\tan(90^\circ)$ in identities of $\tan(A+B),\tan(A-B)$. We can easily see that we get $\frac{\infty}{\infty}$.
Suppose I don't know value of $\tan(150^\circ)$. So one option is just $\tan(90^\circ+60^\circ)$ but that doesn't yield any answer.
Can anyone explain how to do calculations for $\tan(150^\circ),$ using $\tan(A+B)$?
A:
Perhaps you want this $$tan150=\frac{tan90+tan60}{1-tan90tan60} $$Divide by $tan90$ $$\frac{1+\frac{tan60}{tan90}}{\frac{1}{tan90}-tan60} $$ Now $\frac{1}{tan90}=cot90=0$
Hence you get $tan150=\frac{-1}{\sqrt3}$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to select data from a mysql table using Hibernate
I have my hibernate.cfg.xml file as,
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">123789</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/ofm_mnu_jvs</property>
<property name="hibernate.connection.username">user1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="org/ofm/mnu/mappings/ActMonths.hbm.xml"></mapping>
</session-factory>
Mapping,
<hibernate-mapping>
<class name="org.ofm.mnu.mappings.ActMonths" table="act_months" catalog="ofm_mnu_jvs">
<composite-id name="id" class="org.ofm.mnu.mappings.ActMonthsId">
<key-property name="year" type="int">
<column name="year" />
</key-property>
<key-property name="monthNo" type="int">
<column name="month_no" />
</key-property>
</composite-id>
<property name="lastDay" type="java.lang.Integer">
<column name="last_day" />
</property>
<property name="month" type="string">
<column name="month" length="20" />
</property>
<property name="user" type="string">
<column name="user" length="20" />
</property>
<property name="sysDateTime" type="timestamp">
<column name="sys_date_time" length="19" not-null="false" />
</property>
<property name="status" type="boolean">
<column name="status" not-null="true" />
</property>
</class>
</hibernate-mapping>
When I am trying to select data from the database as,
Session session = HibernateUtil.getSessionFactory().openSession();
String SQL_QUERY = "from act_months";
Query query = session.createQuery(SQL_QUERY);
session.getTransaction().commit();
for (Iterator it = query.iterate(); it.hasNext();) {
Object[] row = (Object[]) it.next();
System.out.println("ID: " + row[0]);
}
I get following error,
INFO: Not binding factory to JNDI, no JNDI name configured
Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: act_months is not mapped [from act_months]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70)
at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:255)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2945)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
please tell me where I am wrong.
A:
say it
from ActMonths instead of from table_name
| {
"pile_set_name": "StackExchange"
} |
Q:
last.fm API pagination
I'm creating a last.fm/ google maps mashup, plotting gig map markers for whatever city you search for.
A last.fm API response is like this:
<events location="New York" page="1" totalpages="105" total="1050">
<event>
<id>640418</id>
<title>Nikka Costa</title>
<artists> etc.
Currently, you can search for Edinburgh, for example - and it will bring back the first 10 gigs coming soon. I'm using PHP and simple XML to return the results.
I want to add pagination - so first 10 gigs would be page 1; I would like to have a list of other pages so that users can look forward for later gigs.
There are many useful resources out there for mysql/php pagination but not so much for dynamic PHP/XML and API. What would be the best way to approach this?
A:
The last.fm API allows for parameters, including page number. So you would structure your request something like this:
http://ws.audioscrobbler.com/2.0/?method=geo.getevents&location=new+york&api_key=api key&page=2
You could pass the page number using $_GET in your PHP code and update the request URL accordingly.
$page = 1;
if (isset($_GET['lfm_pageid'])) {
$page = $_GET['lfm_pageid'];
}
$lfm_events = new SimpleXMLElement("http://ws.audioscrobbler.com/2.0/?method=geo.getevents&location=new+york&api_key=b25b959554ed76058ac220b7b2e0a026&page=$page", NULL, TRUE);
foreach ($lfm_events->events->event as $event) {
echo $event->title . '<br />';
}
This is obviously a VERY basic example without any kind of error handling for GET parameters etc, don't use it in production.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show DBMS version in hibernate log
the problem I posed the in following question. becomes blocking,
I tried to change the version of ojdbc14 to ojdbc6.
I want to display the version of the DBMS in the log,
what properties I should add that to the JpaProperties displays the version of DBMS
A:
Hibernate should print out the dialect that it is using in the log files. I have my root logger set to INFO for the following to print out.
I imagine if you set log4j.logger.org.hibernate=INFO it should work.
Have a look in your server logs for the following lines:
HHH000412: Hibernate Core {4.2.8.Final} 04:33:28:0.472
HHH000206: hibernate.properties not found 04:33:28:0.475
HHH000021: Bytecode provider name : javassist 04:33:28:0.477
//The line below will tell you what dialect Hibernate is using to connect
//to your database. From there you should be able to work out what kind of
//database it is
HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect 04:33:29:0.320
HHH000399: Using default transaction strategy (direct JDBC transactions) 04:33:29:0.547
HHH000397: Using ASTQueryTranslatorFactory 04:33:29:0.557
HV000001: Hibernate Validator 4.3.1.Final 04:33:29:0.632
HHH000229: Running schema validator 04:33:30:0.171
HHH000102: Fetching database metadata 04:33:30:0.171
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem related to a differential equation
I am stuck with the following problem:
Let $Y(x)=(y_{1}(x),y_{2}(x))$ and let $A$ is given by $$\begin{pmatrix}
-3 &1 \\
k& -1
\end{pmatrix}.$$
Further, let $S$ be the set of values of $k$ for which all the solutions of the system of equations $Y'(x)=AY(x)$ tend to $0$ as $x$ tends to $\infty.$ Then $S$ is given by:
(a) $\{k:k\leq -1\}$
(b) $\{k:k\leq 3\}$
(c) $\{k:k<3\}$
(d) $\{k:k<-1\}.$
Please help. Thanks in advance for your time.
A:
Recalling the general solution of your equation,
$$ Y(x)=c_1 v_1 e^{\lambda_1 x} + c_2 v_1 e^{\lambda_2 x}, $$
where $\lambda_1,\lambda_2$ are the eigenvalues and $v_1,v_2$ are the eigenvectors. Now, what matters in your problem is the eigenvalues, since you have the condition that the solution $Y(x)$ goes to $0$ as $x\to \infty$. This requires the following condition on the eigenvalues
$$ Real(\lambda_1) < 0, Real( \lambda_2 ) < 0 . $$
The eigenvalues of your matrix are
$$ \lambda_1=-2+\sqrt{k+1}, \,, \lambda_2=-2-\sqrt{k+1}, $$
and
$$ \lambda_1=-2+\sqrt{k+1}<0, \,, \lambda_2=-2-\sqrt{k+1}<0. $$
Work this out and you will find the answer is $(c)$?
Note: When you take the limit of $e^{(a+ib)x}$ as $x \to \infty$, what matters is the real part, since
$$ |e^{(a+ib)x}|= | e^{ax}|| e^{ibx}|=e^{ax} . $$
| {
"pile_set_name": "StackExchange"
} |
Q:
When trying to install valet and composer I get this message. Installation failed, reverting ./composer.json to its original content
I'm trying to get valet working but when I run
composer global require cretueusebiu/valet-windows
I get this error:
Your requirements could not be resolved to an installable set of packages. Installation failed, reverting ./composer.json to its original content.
Here is the full output:
C:\Users\Shadow\Desktop
λ composer global require cretueusebiu/valet-windows
Changed current directory to C:/Users/Shadow/AppData/Roaming/Composer
Using version ^2.1 for cretueusebiu/valet-windows
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- cretueusebiu/valet-windows 2.1.0 requires nategood/httpful ~0.2 -> satisfiable by nategood/httpful[0.2.0, 0.2.1, 0.2.10, 0.2.11, 0.2.13, 0.2.16, 0.2.17, 0.2.19, 0.2.2, 0.2.20, 0.2.3, 0.2.5, 0.2.6, 0.2.7, 0.2.8, 0.2.9].
- cretueusebiu/valet-windows 2.1.1 requires nategood/httpful ~0.2 -> satisfiable by nategood/httpful[0.2.0, 0.2.1, 0.2.10, 0.2.11, 0.2.13, 0.2.16, 0.2.17, 0.2.19, 0.2.2, 0.2.20, 0.2.3, 0.2.5, 0.2.6, 0.2.7, 0.2.8, 0.2.9].
- nategood/httpful 0.2.9 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.8 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.7 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.6 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.5 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.3 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.20 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.2 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.19 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.17 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.16 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.13 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.11 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.10 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- nategood/httpful 0.2.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- Installation request for cretueusebiu/valet-windows ^2.1 -> satisfiable by cretueusebiu/valet-windows[2.1.0, 2.1.1].
To enable extensions, verify that they are enabled in your .ini files:
- C:\php7\php.ini
You can also run `PHP --ini` inside terminal to see which files are used by PHP in CLI mode.
Installation failed, reverting ./composer.json to its original content.
A:
The error message is pretty clear. valet-windows depends on nategood/httpful. Every listed version of nategood/httpful depends on PHP's curl extension, which your system doesn't have:
nategood/httpful 0.2.9 requires ext-curl * -> the requested PHP extension curl is missing from your system.
curl probably comes with whatever version of PHP you have installed, and enabling it probably just involves uncommenting
;extension=php_curl.dll
in your php.ini by removing the leading ;.
See Enable cURL in Windows 10.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript: Automatically maximize browser window and switch to full screen mode?
I am working on a Flash app that is 900x700 pixels. When viewed in misc. browsers at 1024x768, the browser chrome causes robs too much of the vertical space and the app appears in a window with a vertical scrollbar. Unacceptable.
The flash app will be launched via a link emailed to the viewers.
I'd like to avoid resizing the flash app and am wondering if there's a way to do the following via javascript, with no clicks involved:
maximize the current browser window
remove current window address bar and tabs / switch browser to full screen view (equivalent to pressing F11).
An alternative would be to resize the flash app vertically to match the browser canvas height to avoid scrolling. This may cause the app to become unreadable, so not the best approach in my case.
Thank you!
UPDATE: Seems that browser resizing and autoswitch to full screen won't work and neither will the flash app auto resize. What is the best approach then? And, some users may have browsers with toolbars or open a small browser window.
The only idea I have is to use javascript and display a message to users with small browser windows to pres F11 manually. The audience is executes and some may not even know what an F11 means...
A:
There is no way to maximize the browser window to full screen with JavaScript. While this is unfortunate for your genuine requirement, it is considered a security restriction.
Sources:
Stack Overflow - To view the silverlight app in fullscreen mode(F11)
SitePoint Forums - Trigger F11 using javascript
Webmaster World - F11 Fullscreen using Javascript
A:
To answer the question in the comment you made to your own post. Yes. You can have a button whose click handler does this
stage.displayState = StageDisplayState.FULL_SCREEN;
| {
"pile_set_name": "StackExchange"
} |
Q:
Python mySQL Update, Working but not updating table
I have a python script which needs to update a mysql database, I have so far:
dbb = MySQLdb.connect(host="localhost",
user="user",
passwd="pass",
db="database")
try:
curb = dbb.cursor()
curb.execute ("UPDATE RadioGroups SET CurrentState=1 WHERE RadioID=11")
print "Row(s) were updated :" + str(curb.rowcount)
curb.close()
except MySQLdb.Error, e:
print "query failed<br/>"
print e
The script prints Row(s) were updated : with the correct number of rows which have a RadioID of 11. If I change the RadioID to another number not present in the table it will say Row(s) were updated :0. However the database doesn't actually update. The CurrentState field just stays the same. If I copy and past the SQL statement in to PHPMyAdmin it works fine.
A:
use
dbb.commit()
after
curb.execute ("UPDATE RadioGroups SET CurrentState=1 WHERE RadioID=11")
to commit all the changes that you 'loaded' into the mysql server
A:
As the @Lazykiddy pointed out, you have to commit your changes after you load them into the mysql.
You could also use this approach to enable the auto commit setting, just after the MySQL connection initialization:
dbb.autocommit(True)
Then, it will automatically commit the changes you made during your code execution.
A:
the two answers are correct. However, you can also do this:
dbb = MySQLdb.connect(host="localhost",
user="user",
passwd="pass",
db="database",
autocommit=True)
add autocommit=True
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is jQuery.extend() faster than Lodash .clone()
For a very large JSON object with up to for nested levels, jQuery.extend() seems to be significantly faster than the lodash clone method when deep cloning the object. How are these two methods different from each other, and what leads to the discrepancy?
A:
jQuery.extend does not deep clone. It simply copies properties from the source objects into the target object. If the properties are object references, they get copied too. This is known as a shallow copy.
It may look like a deep copy if you inspect each object, but the properties are references to the same underlying objects.
The deep option for jQuery.extend results in a merge, not a copy, meaning that objects will not be over-ridden, but have their properties copied onto.
For details, see the documentation for jQuery.extend:
http://api.jquery.com/jquery.extend/
| {
"pile_set_name": "StackExchange"
} |
Q:
How is BAB calculated for a Fused being?
How do you calculate the BAB on the fused being created by the fusion power? If you fuse together two half bab characters does it make a full bab character?
A:
You get the best bonus.
Relevant clauses:
1.
class features are pooled
2.
this effectively means the fused being uses the better...attack bonus...of either member
The pattern is that bonuses of the same type do not stack, they overlap, and you get the best bonus available to you. If you have a Psion 20 and a Wilder 20, you get 10 BAB. If you have a Psion 20 and another Psion 18, you get 10 BAB. If you have a Psion 20 and a Fighter 14, you get 14 BAB.
| {
"pile_set_name": "StackExchange"
} |
Q:
Backporting Sigils and make it work with variables
So I'm just starting out in Elixir and saw that the current master adds support for a ~U[2015-01-13 13:00:07Z] sigil to create/parse UTC date.
Code follows:
defmodule MySigils do
defmacro sigil_U(datetime_string, modifiers)
defmacro sigil_U({:<<>>, _, [string]}, []) do
Macro.escape(datetime_from_utc_iso8601!(string))
end
defp datetime_from_utc_iso8601!(string) do
case DateTime.from_iso8601(string) do
{:ok, utc_datetime, 0} ->
utc_datetime
{:ok, _datetime, _offset} ->
raise ArgumentError,
"cannot parse #{inspect(string)} as UTC datetime, reason: :non_utc_offset"
{:error, reason} ->
raise ArgumentError,
"cannot parse #{inspect(string)} as UTC datetime, reason: #{inspect(reason)}"
end
end
end
In my code I'm trying to use this with a variable timestamp
timestamp = Map.get(item, "timestamp")
~U[timestamp]
** (ArgumentError) cannot parse "timestamp" as UTC datetime, reason: :invalid_format
but timestamp is being interpreted as is, not the previous match.
Is there a way I can make it work? Do I need to quote/unquote something? Beside using DateTime.from_iso8601/1 directly.
A:
Everything between sigil delimiters is sent as a string. So timestamp variable is sent to sigil_U as the string "timestamp". There are some sigils that allow interpolation which are by convention in lowercase. For example ~r versus ~R:
iex(1)> x = "foo"
"foo"
iex(2)> ~R/#{x}/
~r/\#{x}/
iex(3)> ~r/#{x}/
~r/foo/
But in this case no lowercase version of sigil_U is defined so you can't interpolate timestamp.
| {
"pile_set_name": "StackExchange"
} |
Q:
Qt Designer, missing "go to slot" in context menu?
I've been watching a Qt tutorial series on YouTube, in which the author shows how to call a function, when a button is pressed. He right-clicked on the button in Qt Creator IDE and chose "Go to slot", from where he chose the signal which would fire the generated function. Since I am used to develop with Netbeans, I simply tried to follow his example using the embedded Qt Designer. Unfortunately, there is no "Go to slot..." entry when I right-click on my button or any widget. I could, of course, create a new slot for my main window and then connect the button's signal to it, but doing it with a single function just seems way more convenient and clean to me. Is there a way to fix is, or if not, at least a way to do with via code entirely, without having to add a new slot to the main window for every single button that servers a different purpose? Thanks for your help.
A:
While I don't know why the QtDesigner in Netbeans doesn't provide this feature, I know what the feature does: It just creates a slot with a special name in your widget class. Note that it does not add a connect statement. It uses the automatic connection feature, which works like this:
For each slot which name matches this pattern:
void on_X_Y(...)
it will be connected to the signal named Y of the object named X. So if you have a QPushButton named button, and you want to handle the signal pressed, simply create a slot with the following signature:
void on_button_pressed()
If you wonder how this slot gets connected to the signal: This happens in the ui_...h file at the end of setupUi():
QMetaObject::connectSlotsByName(WidgetName);
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento 2 Custom Cli comand Area not set
I am geting this error comand "[Magento\Framework\Exception\LocalizedException]
Area code is not set
"
this is my code which I want to add a product. Tip if a comment " $product->save();" I am not getinng erros and I can see my output.
My code:
<?php
namespace Bachus\BackgroundImport\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Importpr extends Command
{
const NAME_ARGUMENT = "name";
const NAME_OPTION = "option";
/**
* {@inheritdoc}
public function __construct(
\Magento\Framework\App\State $state
) {
$state->setAreaCode('frontend'); // or 'adminhtml', depending on your needs
}
*/
protected function execute(
InputInterface $input,
OutputInterface $output
) {
$name = $input->getArgument(self::NAME_ARGUMENT);
$option = $input->getOption(self::NAME_OPTION);
// parent::__construct();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create('\Magento\Catalog\Model\Product');
$product->setSku($name); // Set your sku here
$product->setName('Sample Simple Product'); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
$product->setTaxClassId(0); // Tax class id
$product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice(100); // price of product
$product->setStockData(
array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 999999999
)
);
$product->save();
/* */
$output->writeln("Product added sku " . $name);
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName("bachus_cli:importpr");
$this->setDescription("imports-produts");
$this->setDefinition([
new InputArgument(self::NAME_ARGUMENT, InputArgument::OPTIONAL, "Name"),
new InputOption(self::NAME_OPTION, "-a", InputOption::VALUE_NONE, "Option functionality")
]);
parent::configure();
}
}
A:
use Magento\Framework\App\State;
protected $_appState;
public function __construct(
...
State $appState
....
) {
....
$this->_appState = $appState;
....
}
Now in your code set area which want (i.e frontend or adminhtml) for example,
$this->_appState->setAreaCode('adminhtml');
| {
"pile_set_name": "StackExchange"
} |
Q:
jmockit, openJDK and UnsatisfiedLinkError
When trying to run test with JMockit on OpenJDK 6, I'm facing the error:
[junit] Exception in thread "main" java.lang.ExceptionInInitializerError
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:353)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
[junit] Caused by: java.lang.IllegalStateException: Native library for Attach API not available in this JRE
[junit] at mockit.internal.startup.JDK6AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(JDK6AgentLoader.java:81)
[junit] at mockit.internal.startup.JDK6AgentLoader.loadAgent(JDK6AgentLoader.java:54)
[junit] at mockit.internal.startup.AgentInitialization.initializeAccordingToJDKVersion(AgentInitialization.java:21)
[junit] at mockit.internal.startup.Startup.initializeIfNeeded(Startup.java:200)
[junit] at mockit.internal.startup.Startup.initializeIfPossible(Startup.java:215)
[junit] at junit.framework.TestResult.<clinit>(TestResult.java:19)
[junit] ... 3 more
[junit] Caused by: java.lang.UnsatisfiedLinkError: sun.tools.attach.LinuxVirtualMachine.isLinuxThreads()Z
[junit] at sun.tools.attach.LinuxVirtualMachine.isLinuxThreads(Native Method)
[junit] at sun.tools.attach.LinuxVirtualMachine.<clinit>(LinuxVirtualMachine.java:364)
[junit] at mockit.internal.startup.JDK6AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(JDK6AgentLoader.java:71)
[junit] ... 8 more
I looked inside folder /usr/local/openjdk6/jre/lib/amd64/ and found libattach.so there
However adding -Djava.library.path=/usr/local/openjdk6/jre/lib/amd64 didn't solve the problem. What else I can try?
A:
Try adding <jdk6home>/lib/tools.jar to the classpath, before jmockit.jar. If that doesn't solve the problem, passing -javaagent:jmockit.jar as a JVM initialization parameter definitely should.
| {
"pile_set_name": "StackExchange"
} |
Q:
Word, expression or idiom for looking at nothing in particular
Sometimes, when people are absorbed in thinking about something they appear as if their gaze is fixed, but they look at nothing in particular. In my language there is an expression that translated word for word would sound like "looking at the void". Maybe a vacant look would describe this in English. Are there any expressions or idioms that would mean describe that kind of gaze?
A:
to look/stare into space is close to your description:
to look in front of you for a long time without seeing the things that are there because you are thinking about something else:
He sat quietly for a while, staring into space.
MacMillan Dictionary
A:
How about zone out?
M-W:
zone out: to become oblivious to one's surroundings especially in order to relax
It's applicability extends beyond relaxing. One gets lost in one's own thoughts in many other contexts, during a conversation or at a meeting.
A:
You could also use the thousand-yard stare
a vacant or unfocused gaze into the distance, seen as characteristic of a war-weary or traumatized soldier
| {
"pile_set_name": "StackExchange"
} |
Q:
Information on the .MI File Extension?
I recently noticed the .mi file extension in the url "http://www.marriott.com/default.mi". It spawned some questions:
What does "MI" stand for?
Where is it used? What programs IO this file?
How is the file used in website production?
A:
Per the Mason documentation, the .mi extension could indicate a Mason internal component.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get a activeFocusItem property in qml from main.cpp?
I'm looking for a way to retrieve qml item properties which are not in type of base types in C++.
I've found this:
QWindow *w = (QWindow *)engine.rootObjects().first();
QVariant p = w->property("color");
but the result is a instance of QVariant. I want to get properties like activeFocusItem.
A:
Well, in fact you can get the value of activeFocusItem if you use the required toT() function for the QVariant.
In you case it should be something like
QQuickWindow *w = (QQuickWindow*) engine.rootObjects().first();
qDebug() << w->activeFocusItem()->property("activeFocus").toBool(); // true obviously
qDebug() << w->activeFocusItem()->property("objectName").toString();
In this code, we're getting the properties activeFocus and objectName, but it's just an example.
Another way,
QQuickWindow *w = (QQuickWindow*) engine.rootObjects().first();
QQuickItem *wi = w->property("activeFocusItem").value<QQuickItem*>();
qDebug() << wi->property("activeFocus").toBool();
qDebug() << wi->property("objectName").toString();
According to the documentation,
Because C++ forbids unions from including types that have non-default
constructors or destructors, most interesting Qt classes cannot be
used in unions. Without QVariant, this would be a problem for
QObject::property() and for database work, etc.
Usually, you interact with C++ using signals. In that case, when a QML object type is used as a signal parameter, the parameter should use var as the type, and the value should be received in C++ using the QVariant type. More info and examples here.
So QVariant is necessary and as I stated before the right way of getting QML objects to be used in C++.
I've uploaded a complete example to GitHub. I hope this may help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
real-time updating screen by media query
I was expecting that my web would change when screen size changes like I coded below
@media (min-width: 1200px) {
.container {
max-width: 1170px;
}
}
@media (min-width: 900px) {
.container {
max-width: 870px;
}
}
@media (min-width: 600px) {
.container {
max-width: 570px;
}
}
But it doesn't work. I shrank browser size, looking closely at the screen size's change with developer tool. I thought screen would be updated according to the media queries when screen size reaches the break points.
It works only once when loading the document.
What should I do to do this as a real-time? should I use some script?
A:
The problem is the rules. When browser reaches 1200px, it qualifies for all 3 rules.
http://jsfiddle.net/jonms83/5q6etqex/
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.container {background-color:black;}
@media all and (min-width: 1200px) {
.container {
max-width: 1170px;
}
}
@media all and (max-width: 1199px) and (min-width: 601px){
.container {
max-width: 870px;
}
}
@media all and (max-width: 600px) {
.container {
max-width: 570px;
}
}
</style>
</head>
<body>
<div class="container"> </div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
how can i use a helper in different views
i am using refinery cms at the moment. I created an engine and with it some helpers in app/helpers/admin/.
now i would like to use those helpers in my frontend view (ie. app/views/myapp/index) as well. but i can not...undefined methode error.
what do i have to do short of copying the whole thing to app/helpers/?
the helper looks like this
module Admin
module myHelper
def somefunc
end
end
end
so is it possible to use somefunc outside of the Admin module?
A:
The "Rails way" to include a helper from a non-standard path in a view is to use the .helper method within your controller.
class MyController < ApplicationController
helper Admin::MyHelper
...
end
http://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper
A:
In your application_helper.rb:
module ApplicationHelper
include Admin::MyHelper
end
This will import those helper methods into the ApplicationHelper, thus making them available in your views. You could do this in any of your helpers really.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does this Code show that the Mouse has clicked?
Seen this somewhere in StackOverflow. Just want to know how it works...
public void mouseClicked(MouseEvent e){
int x = e.getX();
int y = e.getY();
}
x and y are coordinates and can be shown to screen using JLabel, but the method name is mouseClicked. How does java know the mouse has been clicked?
(Hope this makes sense)...
A:
The method mouseClicked is likely from java.awt.event.MouseListener interface (https://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html)
A listener is a type of callback that follows the observer pattern, something happens, you get notified.
You can attach listener to items that support it. For example:
MouseListener listener = new MouseListener() { /* see example code below */ };
JLabel label = new JLabel("This is a clickable lable");
label.addMouseListener(listener);
See the following answer to get more info and reference to reading articles.
https://stackoverflow.com/a/17415300/132121
@transformer here is an empty implementation of the MouseListener you would create in Java code.
MouseListener listener = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// This is the method where you would get your callback
// whenever somebody clicked on the view that has this listener
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS - Aligning the child of a flex container to center of screen not working properly
I'm making a small Etch-a-Sketch-esque webpage.
For now, I'm just trying to get the CSS of the page right before moving onto the Javascript that will generate a canvas of a designated size, so I'm working with a 16x16 grid of divs statically on the webpage.
See this codepen for what I have so far. Sorry about the ridiculously long HTML, as I said for now I'm just working on the formatting and put in a 16x16 grid (800px by 800px) of divs with class .tabletCanvas. Basically, just 256 divs that have that class.
As you can see, the "canvas" is sticking to the left-hand side, and I want it to look like it does in this picture (very rough outline done in 5 minutes using photoshop).
What I've tried so far:
Many different values for flex:. What happens is that, without setting a max-width or max-height (from my understanding of flexbox, specifying specific heights and widths defeats the purpose of using it and that everything should be handled through the flex: property), the grid will simply overflow to the right and fill up the rest of the screen. Obviously not ideal, as I want it contained within the 800x800 pixels, and even after specifying the max-width and height, it will still hang to the left.
Making the tabletContainer a flex parent (container) itself, and trying all possible variations of align-content, align-items and justify-content within it. None of them had a visible effect
Many different values of align-self, justify-self on the .tabletCanvas class.
One thing that sprung to mind would be absolutely positioning the canvas div, but this defeats the purpose of using a flex container in the first place, I imagine
Something that I think might work would be to use the align-content or align-items properties on the #bodyWrapper to get all of its children to be centered, however if I do this then I risk ruining the flow of every other property and putting myself more or less back to square one where I started.
Another thing that sprung to mind was just to add a lot of padding-left to the #sketchButtons, however this also seems like a hilariously wrong and hacky approach to take.
Any and all help will be greatly appreciated.
A:
One way to do it would be to:
set .tabletContainers position to absolute,
set margin to auto,
set left and right to 0,
and then set your top property as desired.
.tabletContainer {
position: absolute;
color: white;
padding: 5px;
margin: 5px;
max-width: 800px;
display: flex;
flex-flow: row wrap;
margin: auto;
left: 0;
right: 0;
top: 111px;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Exponential of approximate quadratic variation of Brownian motion
Let $X_t$ be a Brownian motion or a Brownian Bridge on a (\edit: compact) Riemannian manifold. Let $T>0$ be given.
The question is: Does there exists a constant $C>0$ such that for all partitions $0 = \tau_0 < \tau_1 < \dots < \tau_N \leq T$, we have
$$ \mathbb{E}\left[ \exp \left(\sum_{j=1}^N d(X_{\tau_{j-1}}, X_{\tau_j})^2 \right) \right] \leq C~~~~~~?$$
I can prove so far that for all $p \in [1, \infty)$, there exists a constant $C_p$ such that
$$\mathbb{E}\left[ \left(\sum_{j=1}^N d(X_{\tau_{j-1}}, X_{\tau_j})^2 \right)^p \right] \leq C_p,$$
but I cannot control the constants $C_p$ so that the "brute force proof" using the exponential series fails.
A:
Yes, there is a bound like that for $T \le \mathrm{const}$. I'll do the case of Brownian motion, since the Brownian bridge reduces to it.
The proof consists of two stages: proving the bound in hyperbolic space and reducing the general case to it.
In order to redue the general case to the constant curvature case we can use the comparison theorem for the Laplacian of the distance function (Theorem 1.1 in cvgmt.sns.it/media/doc/paper/2113/HessBV.pdf). Namely:
Theorem: Fix a point $p$ and take the distance function $d_p(\cdot) := d(p, \cdot)$. Then a curvature bound
$$\operatorname{Ric} \ge (n-1) K$$
for some constant $K$ implies a bound
$$\Delta d_p(r, \theta) \le \Delta^K d^K(r)$$
outside of the cut locus. Here $\Delta^K$ and $d^K$ refers to the Laplacian and distance function of the simply connected constant curvature $K$ space.
For our purposes we won't need to touch the cut locus, so this most naive version suffices.
Recall that the distance process $d_p(X_t)$ (resp. its constant curvature counterpart $d^K(X_t^K)$) is a semimartingale with drift $\frac{1}{2} \Delta d_p(X_t)$ (resp. $\Delta^K d^K(X_t^K)$) and quadratic variation $t$, so they can be represented as solutions to SDEs
$$d (d_p(X_t)) = \frac{1}{2} \Delta d_p(X_t) dt + dB_t$$
$$d (d^K(X_t^K)) = \frac{1}{2} \Delta^K d^K(X_t^K) dt + dB_t$$
where $B$ is a standard $1$-dimensional Brownian motion. By the Laplacian comparison theorem we have an inequality between the drift terms, and I intentionally used the same driving noise $dB$ in both SDEs. This way the processes become coupled so that
$d_p(X_0) \le d_p^K(X_0^K)$ implies $d_p(X_t) \le d_p^K(X_t^K)$ for all $t$ at least until $X_t$ meets the cut locus.
(see e.g. the proof of Theorem 20.5 in Kallenberg's "Foundations of modern probability")
So let's start $X_t$ at the point $p$ and consider the stopped process $X_{t \wedge \theta}$, $\theta := \inf\{t : d_p(X_t) = R\}$, where $R$ is the injectivity radius of our manifold. Similarly, take $\theta^K := \inf\{t : d^K(X_t^K) = R\}$. From the above reasoning, $d_p(X_{t \wedge \theta}) \le d^K(X^K_{t \wedge \theta^K})$ for all $t$, so
$$\mathsf{E} \exp (d(X_0, X_{t\wedge\theta}))^2 \le \mathsf{E} \exp (d^K(X_0^K, X^K_{t\wedge\theta^K}))^2,$$
$$\theta \ge \theta^K$$
In order to get rid of this $\theta$ stopping, just use the trivial inequality
$$\mathsf{E} \exp (d(p, X_t))^2 \le \mathsf{E} \exp (d(p, X_{t \wedge \theta}))^2 + \exp D^2 \cdot \mathsf{P} \{\theta \le t\},$$
where $D$ is the diameter of our manifold.
Finally, this gives:
$$\mathsf{E} \exp (d(p, X_t))^2 \le \mathsf{E} \exp(d^K(X_t^K))^2 + \exp D^2 \cdot \mathsf{P}\{\theta_K \le t\}$$
Denote the right-hand side by $F(t)$.
Now note that whenever we have a sequence of times $0 = \tau_0 < \dots \le \tau_N$ we can use the Markov property of the BM to get the same bound conditionally on $X_{\tau_{N-1}}$, then on $X_{\tau_{N-2}}$, etc.:
$$\mathsf{E} \prod_{k < N} \exp (d(X_{\tau_k}, X_{\tau_{k+1}}))^2 \le \dots \le F(\tau_1 - \tau_0) \dots F(\tau_N - \tau_{N-1})$$
Now, in order to deal with the constant curvature case one can use the same approach as above: use a bound like $\Delta^K d^K(r) \le \frac{n-1}{r} + O(1)$ in order to dominate $d^K(X_t^K)$ by a Bessel($n$) process with constant drift, to reduce everything to the trivial case of Brownian motion in $\mathbb{R}^n$.
Similarly, the Brownian bridge case reduces to Brownian motion. Indeed, Brownian bridge on a time interval $[0,T/2]$ is just a Brownian motion with bounded drift, and $[T/2, T]$ it's a time-reversed Brownian motion with bounded drift.
| {
"pile_set_name": "StackExchange"
} |
Q:
FTP LIST command fails between between host OS and guest OS
I'm having trouble setting up FTP between my host OS (Windows 7) and guest OS (Ubuntu 10.04). I used the network settings in VirtualBox to setup port forwarding on 80, 21, and 22. Accessing the webserver on port 80 works great but I'm having some problems with FTP on port 21 and SFTP on 22.
This is the output when I try connecting on port 21 in FileZilla:
Status: Connecting to 127.0.0.1:21...
Status: Connection established, waiting for welcome message...
Response: 220 (vsFTPd 2.2.2)
Command: USER menuplus
Response: 331 Please specify the password.
Command: PASS *****
Response: 230 Login successful.
Status: Connected
Status: Retrieving directory listing...
Command: PWD
Response: 257 "/srv/www/vhosts/mp"
Command: TYPE I
Response: 200 Switching to Binary mode.
Command: PASV
Response: 227 Entering Passive Mode (10,0,2,15,205,164).
Command: LIST
Error: Connection timed out
Error: Failed to retrieve directory listing
A connection is established, but the LIST command fails which makes me thing maybe the permissions on the guest OS are setup wrong, but the FTP user has full access to its home directory.
What could be wrong?
A:
Command: PASV
Response: 227 Entering Passive Mode (10,0,2,15,205,164).
Command: LIST
Error: Connection timed out
The error message is "Connection timed out", as you can hopefully see. If there was a permission problem, LIST would immediately fail with a "Access denied" or "Permission denied" response from the remote side.
FTP does not work well with NATs. It uses separate control and data connections – and each time a data connection is needed, the FTP client must connect to the address provided by the server's PASV result. In this case, your server tells the client to connect to 10.0.2.15 for LIST output – this does not work due to your virtual machine being behind the VirtualBox NAT. (More advanced NAT implementations, such as those found in home routers, "adjust" the FTP traffic to work around this.)
Your choices are to use VirtualBox "bridged" networking, which makes your VM part of the real network, or to use SFTP, which always uses a single control/data connection and should not have the same problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cant display color images in navigation menu with theme set as DarkActionBar
I have set DarkActionBar as the theme of my app. With this theme i am not able to display images like jpg or png in navigation menu. I am only able to display the vector graphics in black or white. Any colored image is replaced with a dark rectangle. Does any one has an idea what must be changed in this theme to get the color images display in navigation menu. Below is the style which i am applying.
style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:buttonStyle">@style/button</item>
</style>
<style name="button" parent="@android:style/Widget.Button">
<item name="android:gravity">center_vertical|center_horizontal</item>
<item name="android:textColor">@drawable/color_selector</item>
<item name="android:shadowColor">#FF000000</item>
<item name="android:shadowDx">0</item>
<item name="android:shadowDy">-1</item>
<item name="android:shadowRadius">0.2</item>
<item name="android:textSize">16dip</item>
<item name="android:textStyle">normal</item>
<item name="android:background">@drawable/button</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
</style>
The xml code of my item is as under
<item android:title="Regional">
<menu>
<item
android:id="@+id/language"
android:icon="@drawable/ic_language_black_24dp"
android:title="Set Language" />
</menu>
</item>
I have spent a lot of time without but not able to solve the issue. Expecting any kind of help or suggestions!!!!
A:
try this
yournavigationview.setItemIconTintList(null);
that should disable the default tinting
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple Django admin sites redirects to each other
firstly, sorry if this problem was already solved, but I couldn't find solution anywhere.
I created two admin instances in Django, here's my admin.py sample code:
class ConferenceRoomAdmin(admin.ModelAdmin):
readonly_fields = ('token', 'image_tag')
class ConferenceRoomSuperAdmin(admin.ModelAdmin):
readonly_fields = ('token', 'image_tag')
class ConferenceAdmin(admin.AdminSite):
def get_urls(self):
urls = super(ConferenceAdmin, self).get_urls()
return urls
admin_site = ConferenceAdmin()
admin_site.register(ConferenceContext)
admin_site.register(ConferenceRoom, ConferenceRoomAdmin)
class ConferenceSuperAdmin(admin.AdminSite):
pass
super_admin_site = ConferenceSuperAdmin()
super_admin_site.register(ConferenceRoom, ConferenceRoomSuperAdmin)
and urls.py file:
url(r'^admin/', include(admin.admin_site.urls)),
url(r'^myadmin/', include(admin.super_admin_site.urls)),
url(r'^login/', views.login_view),
url(r'^test/', views.test_view),
I'm able to login to both admin instances, however, if I log into 'myadmin' instance and click on any link (i.e. change password or edit users, etc. etc) I'm redirected to 'admin' site. What may be wrong here?
Thanks in advance!
A:
Try adding a name attribute to the second admin site, like so:
super_admin_site = ConferenceSuperAdmin(name = 'super_admin')
That is the only difference between your code and mine, as far as I can tell.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prevent a combo box from droppping down in HTML?
The user sees a web form with a bunch of controls. One of them is a combo box (drop down list) with several options.
He selects one and hits the submit button. My PHP form action validates the input & shows the submission as a read-only version of the input form for confirmation.
I would like to prevent the combobox from dropping down, using only HTML generated by PHP.
Can I?
Edit: I need to display it as it was in the original form (WYSIWYG), so can't just use plain text
A:
I think this is what you're looking for:
select#some-id { color: black; }
<select id='some-id' disabled='disabled'><option value='some-value'>Text to Show</option></select>
The CSS is to prevent the "grayed out" behaviour of a disabled form element. The little tick next to the text field will still be grayed out, which intuitively suggests that drop-down is not available.
| {
"pile_set_name": "StackExchange"
} |
Q:
What transforms a beer into a Barley Wine?
Is it merely high alcohol content or some change, alteration or addition to the brewing process, mandated by law or otherwise that requires the brew be called Barley Wine?
A:
Barley wine is a style of beer: it isn't something that is made using beer as an ingredient (as you might describe whisky).
There are a number of varieties of barley wine (some hoppy, and some with almost no hop characteristics), but they all have a relatively high alcohol content compared to most beers. The alcohol is produced via fermentation, the same as any other beer, and without distillation. Note that not all high alcohol beers are necessarily described as "barley wine" though.
As for the legal aspects, I don't know of any regulations that specifically target barley wine. The law usually deals with alcoholic beverages based on the alcohol content, and from that point of view barley wines would usually be treated similar to normal wines due to the similar ABV.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server remove trailing comma from XML path
I have the following code that pulls what my columns are called within a given table of mine:
SELECT
column_name + ','
FROM
information_schema.columns
WHERE
table_name = 'maintReq'
FOR XML PATH('')
And I am wanting to place that into my current query:
SET IDENTITY_INSERT maintReq ON;
GO
INSERT INTO maintReq
OUTPUT Inserted.ID
VALUES ((SELECT ISNULL(MAX(id) + 1, 0)
FROM maintReq WITH(SERIALIZABLE, UPDLOCK)
),'MAYBE', 'true');
SET IDENTITY_INSERT maintReq OFF;
I've tried to do the following myself:
SET IDENTITY_INSERT maintReq ON;
GO
INSERT INTO maintReq (
SELECT
column_name + ','
FROM
information_schema.columns
WHERE
table_name = 'maintReq'
for
xml path('')
)
OUTPUT Inserted.ID
VALUES (
(
SELECT
ISNULL(MAX(id)+1,0)
FROM
maintReq WITH(SERIALIZABLE, UPDLOCK)
),'MAYBE', 'true'
);
SET IDENTITY_INSERT maintReq OFF;
But with that I am getting the error of:
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ')'.
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ','.
Not sure if that error is called by the extra comma that was added to the output of the XML path or if its something else?
My full stored procedure looks like this:
DECLARE @SQLQuery VARCHAR(MAX);
SET @SQLQuery = 'SET IDENTITY_INSERT ' + @val1 + ' ON
INSERT INTO ' +
@val1 + '
OUTPUT Inserted.ID
VALUES ' +
'(
(
SELECT
ISNULL(MAX(id)+1,0)
FROM
' + @val1 + ' WITH(SERIALIZABLE, UPDLOCK)
),''' + @val2 + ''', ''' + @val3 + '''
) ' +
'SET IDENTITY_INSERT ' + @val1 + ' OFF;'
EXEC [dbo].[_chkQ] @SQLQuery
The above SP is what I am currently getting this error:
An explicit value for the identity column in table 'maintReq' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
Thanks to @Pரதீப் this is the final working query code:
SET @SQLQuery = 'SET IDENTITY_INSERT ' + @val1 + ' ON
INSERT INTO ' + @val1 + '(' +
Stuff(
(SELECT
',' + quotename(column_name)
FROM
information_schema.columns
WHERE
table_name = '' + @val1 + ''
FOR xml path('')
), 1, 1, ''
) +
')
OUTPUT Inserted.ID
VALUES ' +
'(
(
SELECT
ISNULL(MAX(id)+1,0)
FROM
' + @val1 + ' WITH(SERIALIZABLE, UPDLOCK)
),''' + @val2 + ''', ''' + @val3 + '''
) ' +
'SET IDENTITY_INSERT ' + @val1 + ' OFF;'
A:
You need to use dynamic sql
DECLARE @col_list VARCHAR(8000)= ''
SET @col_list = Stuff((SELECT ',' + quotename(column_name) --"quotename" is to escape illegal characters
FROM information_schema.columns
WHERE table_name = 'maintReq'
FOR xml path('')), 1, 1, '')
SET IDENTITY_INSERT maintReq ON;
EXEC ('
INSERT INTO maintReq ('+@col_list+')
OUTPUT Inserted.ID
VALUES (
(SELECT
ISNULL(MAX(id)+1,0)
FROM
maintReq WITH(SERIALIZABLE, UPDLOCK)
),''MAYBE'', ''true''
); ')
SET IDENTITY_INSERT maintReq OFF;
| {
"pile_set_name": "StackExchange"
} |
Q:
A thought experiment about Heisenberg's Uncertainty Principle
If there is a box full of magnetized particles which are taking random movement continuously, then I put a coil connected to a device that can detect the value of current in it and it's designed to only allow one particle to pass(the coil is like digging a hole in a metal plate). Now when a particle passes through this coil, I can know it's velocity by calculating the current, and I know where the coil is, so I have exact velocity and location of this particle, then what's the problem?
A:
There is a basic misunderstanding of the Heisenberg Uncertainty Principle here.
$$\sigma_x\sigma_p\geq \frac{\hslash}{2}$$
It is an inequality on the product of two measurements.
One can do a measurement on a particle in a magnetic field and get the momentum and there are many $x,y,z$ points in the picture.
Pi mu e decay in bubble chamber
The HUP does not say the measurements cannot be done. It just predicts a limit to the product of the two measurements, by the very small number $\hslash\;.$
In the picture the big circle is a pion (identified by ionisation) turning in a magnetic field perpendicular to the picture. There are two views of the event and both momentum and all the $x,y,z$ of the circle are known. The HUP is fulfilled because the space errors are in microns , the momentum is in $\rm{MeV}$ and there is no problem in fulfilling the HUP, as $\hslash$ is $\thicksim 6.582\times 10^{-16}~\mathrm{eVs}.$
The limitations of the HUP enter in specific measurements where the measurement errors are very small. It says that because of the quantum mechanical uncertainty the momentum and position measurement will have a delta spread due to the HUP, even though the experimental measurement errors may be very small.
| {
"pile_set_name": "StackExchange"
} |
Q:
I can be doughnut? Well rhyming is hard. - What am I?
I can walk and jump and make things me,
I can bring happiness, play sports and cut,
I can possess great poise and beauty,
I can be baked, loud and doughnut.
What am I?
HINT:
If we all need to wait, should we form a cue?
A:
Dunno how to spoiler but;
Are you a stick?
I can walk and jump and make things me,
walking stick, pogo stick , make things stick
I can bring happiness, play sports and cut,
a large variety of sticks can be smoked (in dutch a joint is aka a "sticky") to make you "happy", there are polo sticks and hockey sticks, and in fact cutting sticks used in the printing industry.
I can possess great poise and beauty,
lipstick and walking sticks both fit the bill imo.
I can be baked, loud and doughnut.
some ***** invented a "donut stick" wich can in fact be baked! And a boomstick is either slang for a gun, tnt or a device to make your headphones go louder.
No idea what the hint is though... stick around while we find out...
OP's Intended Explanation
I can walk and jump and make things me,
Walking stick, pogo stick, glue stick
I can bring happiness, play sports and cut,
Joy stick, hockey stick, chop stick
I can possess great poise and beauty,
Majestic (Sorry!)
I can be baked, loud and doughnut.
Bread stick, drum stick, doughnut stick (because it rhymes but it does exist!)
And the hint was
A cue stick
A:
Are you
high ?
I can walk and jump and make things me,
highwalk (on a rope?) highjumping and placing things on a high place
I can bring happiness, play sports and cut,
happiness = being in high spirits, playing sports on a high level, a high cut (i.e. in clothing)
I can possess great poise and beauty,
highness (as with royalty)
I can be baked, loud and doughnut.
being high/stoned, with high volume... and doughnuts?
Don't know for sure, English is not my first language.
A:
Are you
A trick shot in a game of pool?
I can walk and jump and make things me,
Trick shots like walk the dog, jumping the cue ball
I can bring happiness, play sports and cut,
Happiness if you win, pool is a sport, cut is another type of shot
I can possess great poise and beauty,
Trick shots require poise and have a certain beauty
I can be baked, loud and doughnut.
I'm at a loss here, other pool jargon?
It fits with the hint though.
If we all need to wait, should we form a cue?
Pool has a cue ball.
| {
"pile_set_name": "StackExchange"
} |
Q:
Summary of N recent values
I am trying to get summary statistics (sum and max here) with most N recent values.
Starting data:
dt = data.table(id = c('a','a','a','a','b','b','b','b'),
week = c(1,2,3,4,1,2,3,4),
value = c(2, 3, 1, 0, 5, 7,3,2))
Desired result:
dt = data.table(id = c('a','a','a','a','b','b','b','b'),
week = c(1,2,3,4,1,2,3,4),
value = c(2, 3, 1, 0, 5, 7,3,2),
sum_recent2week = c(NA, NA, 5, 4, NA, NA, 12, 10),
max_recent2week = c(NA, NA, 3, 3, NA, NA, 7, 7))
With the data, I would like to have sum and max of 2 (N=2) most recent values for each row by id. 4th(sum_recent2week) and 5th (max_recent2week) columns are my desired columns
A:
You can use rollsum and rollmax from the zoo package.
dt[, `:=`(sum_recent2week =
shift(rollsum(value, 2, align = 'left', fill = NA), 2),
max_recent2week =
shift(rollmax(value, 2, align = 'left', fill = NA), 2))
, id]
For the sum, if you're using data table version >= 1.12, you can use data.table::frollmean. The default for frollmean is fill = NA, so no need to specify that in this case.
dt[, `:=`(sum_recent2week =
shift(frollmean(value, 2, align = 'left')*2, 2),
max_recent2week =
shift(rollmax(value, 2, align = 'left', fill = NA), 2))
, id]
| {
"pile_set_name": "StackExchange"
} |
Q:
SAILS JS 1.0 model callback lifecycle is not called
well, I'm trying to create a user with Sails 1.0.0-42, the problem is that the callback lifecycle of the user model is not called. I have tried in many ways and nothing is called. Thanks in advance.
this is the code of Action2 "signup":
module.exports = {
friendlyName: 'Create User',
description: 'user create action2',
inputs: {
name: {
description: 'user create',
type: 'string',
required: true
},
email: {
description: 'user create',
type: 'string',
required: true
},
password: {
description: 'user create',
type: 'string',
required: true
},
},
exits: {
notFound: {
description: 'ERRO create user.',
responseType: 'notFound'
}
},
fn: async function (inputs, exits) {
const {name, email, password} = inputs;
var user = await User.create({name, email, password}).fetch();
if(!user) return exits.notFound();
return exits.success(user);
}
};
this is the user model code
var bcrypt = require('bcrypt');
module.export = {
attributes: {
name: {
type: 'string',
required: true,
},
email: {
type: 'string',
required: true,
},
password: {
type: 'string',
minLength: 6,
required: true,
columnName: 'hashed_password'
},
},
// Lifecycle Callbacks
beforeCreate: function (values, cb) {
// Hash password
bcrypt.hash(values.password, 10, function(err, hash) {
if(err) return cb(err);
values.password = hash;
cb();
});
}
};
the user is created, but the password is not encrypted, and in the tests the beforeCreate is not called.
A:
Your model file declares:
module.export
But it needs to be:
module.exports
That s makes a big difference!
The reason it works at all with your current code is that, by default, the built-in sails-disk database is schemaless, so even though your User.js file wasn't exporting anything, it still lets you create records with whatever fields you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Página de erro no AngularJS
Bom, sou novo para AngularJS. Eu tenho um projeto, uma única página com rotas configuradas com um controlador. As views são carregados dentro do elemento da página index.html. Dentro do controlador Eu estou fazendo uma chamada http para obter os dados e ligação de dados com o $ escopo. Conforme jogo o módulo, ele é aplicado na ng-view. Até ai tudo bem.. porém necessito fazer uma página de erro, caso o usuário acesse na url qualquer coisa que não seja encontrada, seja direcionado para uma página de erro.. onde posso personalizar o erro e sugerir para o usuário voltar a página principal.
A:
Caso você esteja utilizando angular-ui/ui-router, o provedor $urlRouter oferece a possibilidade de configuração da rota de fallback durante o estágio config - que é utilizada sempre que o usuário tenta acessar uma rota não configurada:
app.config(
function ($urlRouterProvider) {
$urlRouterProvider.otherwise("/notFound");
});
(O exemplo acima assume que /notFound é sua rota de tratamento para página não encontrada.)
A vantagem deste método é que você pode implementar um estado sem Url, permitindo assim que a URL originalmente informada pelo usuário seja mantida na barra de navegação. Exemplo:
$stateProvider.
state("notFound", {
templateUrl: "statusNotFound.html",
controller:
function ($scope, $http) {
// Seu código aqui
});
}
});
Exemplo:
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this Jython loop fail after a single run?
I've got the following code:
public static String getVersion()
{
PythonInterpreter interpreter = new PythonInterpreter();
try
{
interpreter.exec(IOUtils.toString(new FileReader("./Application Documents/Scripts/Version.py")));
PyObject get_version = interpreter.get("get_latest_version");
PyObject result = get_version.__call__(interpreter.get("url"));
String latestVersion = (String) result.__tojava__(String.class);
interpreter.close();
return latestVersion;
} catch (IOException ex) {
ex.printStackTrace();
interpreter.close();
return Version.getLatestVersionOnSystem();
}
For the sake of completeness, I'm adding the Python code:
import urllib2 as urllib
import warnings
url = 'arcticlights.ca/api/paint&requests?=version'
def get_latest_version(link=url):
request = urllib.Request(link)
handler = urllib.urllopen(request)
if handler.code is not 200:
warnings.warn('Invalid Status Code', RuntimeWarning)
return handler.read()
version = get_latest_version()
It works flawlessly, but only 10% of the time. If I run it with a main like follows:
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
System.out.println(getVersion());
}
}
It works the first time. It gives me the output that I want, which is the data from the http request that is written in my Versions.py file, which the java code above calls. After the second time, it throws this massive error (which is 950 lines long, but of course, I won't torture you guys). Here's the gist of it:
Aug 26, 2015 10:41:21 PM org.python.netty.util.concurrent.DefaultPromise execute
SEVERE: Failed to submit a listener notification task. Event loop shut down?
java.util.concurrent.RejectedExecutionException: event executor terminated
My Python traceback that is supplied at the end of the 950 line Java stack trace is mostly this:
File "<string>", line 18, in get_latest_version
urllib2.URLError: <urlopen error [Errno -1] Unmapped exception: java.util.concurrent.RejectedExecutionException: event executor terminated>
If anyone is curious, the seemingly offending line in my get_latest_version is just:
handler = urllib2.urlopen(request)
Since the server that the code is calling is being run (by cherrypy) on the localhost on my network, I can see how it is interacting with my server. It actually sends two requests (and throws the exception right after the second).
127.0.0.1 - - [26/Aug/2015:22:41:21] "GET / HTTP/1.1" 200 3 "" "Python-urllib/2.7"
127.0.0.1 - - [26/Aug/2015:22:41:21] "GET / HTTP/1.1" 200 3 "" "Python-urllib/2.7"
While I'm never going to run this code in a loop likely, I'm quite curious as to two things:
Is the offending code my Python or Java code? Or could it just be an issue with Jython altogether?
What does the exception mean (it looks like a java exception)? Why is it being thrown when it is? Is there a way to make a loop like this work? Could this be written better?
A:
The python library urllib2, which you use, uses Netty.
Netty has a problem, which is widely known:
Hopper: java.util.concurrent.RejectedExecutionException: event executor terminated
Error recurrent : DefaultPromise Failed to notify a listener. Event loop shut down?
Calling HttpClient.shutdown() causes problem to later created clients
Shutting down netty 4 application throws RejectedExecutionException
According to all of these links Netty HttpClient fails from time to time after closing. It looks like Netty recovers after some time and some applications work just normally with this problem. Anyway it looks unstable.
Q: Is the offending code my Python or Java code? Or could it just be an issue with Jython altogether?
A: The problem is caused by Jython library urllib2, which uses Netty.
Q: What does the exception mean (it looks like a java exception)? Why is it being thrown when it is?
A: urllib2 uses internally Netty. Netty is written in Java and throws this Java exception. Netty uses its own Thread Executor, which is shut down and unusable for some time after closing a request. You hit exactly this time.
Q: Is there a way to make a loop like this work? Could this be written better?
A: I would try to use Requests library.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android dim Dialog background doesn't work as expected
I'm trying to create a simple Dialog with a custom progress bar.
But for some reason, I can only get the background fully translucent (by adding Theme_Translucent_NoTitle) or fully darkned (by removing Translucent from theme).
What I want to do though, is to be able to play with the dim amount. Here's the code:
public class ProgressWheelDialog extends Dialog{
private ProgressWheel pw;
public ProgressWheelDialog(final Context ctx) {
// to make transparent background, add Translucent after Theme_
super(ctx, android.R.style.Theme_NoTitleBar);
setContentView(R.layout.dialog_progresswheel);
// dim background
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.dimAmount = .5f;
getWindow().setAttributes(layoutParams);
// get and spin progress wheel
pw = (ProgressWheel) findViewById(R.id.pw_spinner);
pw.setVisibility(ProgressWheel.VISIBLE);
pw.spin();
}
What am I doing wrong? Code above darkens the screen completely (except the progress bar of course)
A:
You need to set dim after you show dialog.
dialog.show();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.dimAmount=0.5f; // Dim level. 0.0 - no dim, 1.0 - completely opaque
dialog.getWindow().setAttributes(lp);
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting GradientDrawable to Bitmap
Sorry if I sound too noob. Is there any way to convert a GradientDrawable like
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation orientation, int[] colors);
into a Bitmap format. I am trying to set the GradientDrawable as the device wallpaper.
Thank you soo much. :)
A:
Try this:
It's not a perfect solution as i've had to hard code the width/height for the GradientDrawable but it seems to work ok regardless.
public static Bitmap drawableToBitmap(Context mContext, int drawableInt) {
Bitmap bitmap;
Drawable drawable = getDrawable(mContext, drawableInt);
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}else if(drawable instanceof GradientDrawable){
GradientDrawable gradientDrawable = (GradientDrawable) drawable;
bitmap = Bitmap.createBitmap(140, 140, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
gradientDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
gradientDrawable.draw(canvas);
return bitmap;
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Session Handling for in WCF for ASP.net Client
I have a asp.net client for a WCF Service . WCF Service is PerSession. How to maintain WCF Service Session for different asp.net pages ?
A:
As I understand it the session will be maintained in the ASP.Client only and not the WCF Service. That is you will manage all of your state in your client only.
| {
"pile_set_name": "StackExchange"
} |
Q:
firebase serve: From a locally served app, call locally served functions
How can I properly simulate a cloud function locally so that it has all data as when being invoked on firebase servers? (e.g. the context.auth)
I am serving my project with firebase serve, it runs ok on http://localhost:5000/, however, my cloud functions are being called from https://us-central1-<my-app>.cloudfunctions.net/getUser. (The function is not even deployed.)
To avoid XY problem, I am trying to debug my function, but calling it from firebase shell results in context.auth being undefined, same when calling via postman from http://localhost:5000/<my-app>/us-central1/getUser.
This is my ./functions/src/index.ts file
import * as functions from 'firebase-functions'
import admin from 'firebase-admin'
import { inspect } from 'util'
admin.initializeApp()
export const getUser = functions.https.onCall((data, context) => {
console.debug('== getUser called =========================================')
console.log('getUser', inspect(data), inspect(context.auth))
return admin.database().ref('userRights/admin').child(context.auth.uid).once('value', snapshot => {
console.log(snapshot.val())
if (snapshot.val() === true) {
return 'OK'
// return {status: 'OK'}
} else {
return 'NOK'
// return {status: 'error', code: 401, message: 'Unauthorized'}
}
})
})
file ./firebase.functions.ts
import { functions } from '~/firebase'
export const getUser = functions.httpsCallable('getUser')
Consumer ./src/pages/AdminPanel/index.tsx
import { getUser } from '~/firebase.functions'
//...
getUser({myDataX: 'asd'}).then(response => console.debug('response', response))
A:
There is currently no support for local testing of callable functions like this. The team is working on a way for you to specify the URL endpoint of a callable function so that you can redirect it to a different location for testing.
A:
By default, firebase serve sends queries to CLOUD function instead of localhost, but it is possible to change it to to point to localhost.
@gregbkr found a workaround for that at this github thread.
You basically add this after firebase initialization script (firebase/init.js) in html head.
<script>
firebase.functions().useFunctionsEmulator("http://localhost:5001");
</script>
Make sure to REMOVE it when deploying to SERVER
| {
"pile_set_name": "StackExchange"
} |
Q:
eclipse plugin modifying launch configuration files
I have a problem. I moved from Eclipse Helios to Eclipse Indigo and there is one problem. The old launch configurations doesnt works, because in Indigo is a different maven plugin. so when i run a program i get an following Error message:
Referenced classpath provider does not exist: org.maven.ide.eclipse.launchconfig.classpathProvider
I know, how to fix it but I need write a plugin which can do it for me without changing the launch configuration. So probably need to add to an new eclipse classpath which can point to new version of maven. something like:
when configuration containts "org.maven.ide.eclipse.launchconfig.classpathProvider" use "org.eclipse.m2e.launchconfig.classpathProvider".
Is anyone know ho to expand launchconfiguration classpaths ?
A:
Below in the launch file works for me
<stringAttribute
key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER"
value="org.eclipse.m2e.launchconfig.classpathProvider"/>
earlier it was this:
<stringAttribute
key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER"
value="org.maven.ide.eclipse.launchconfig.classpathProvider"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
Unreadable block in multiblock reading on dd / ddrescue: How does it handle it?
Let's say that I set the block size of dd or ddrescue to 256K.
A sector of flash drives usually has 512 bytes, a sector on optical data discs has 2048 bytes.
Let's assume that in the next 256 KB, just one sector is unreadable. Every other sector is readable.
What happens to the multiblock transfer?
Does it transfer anything at all?
Does it transfer the readable parts as usual?
It would be great if it did transfer all readable blocks as usual.
A:
Example command without abbreviating options/switches:
sudo ddrescue --direct --sector-size=20480 --verbose --verbose --retry-passes="-1" /dev/sr5
If one out of the ten sectors in the 20480 next bytes is damaged, the entire 20480 bytes will not be saved.
Finer grain: sudo ddrescue --direct --sector-size=2048 --verbose --verbose --retry-passes="-1" /dev/sr5
Sending a request for each sector might put a cap on the reading speed. However, ddrescue is lesser about speed than about recoverability. But it can also be seen as a more comfortable, convenient and verbose version of dd.
Note: A second --verbose adds more verbosity, according to the manual at man ddrescue.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get cell value from DataGridView in VB.Net?
I have a problem, how can i get value from cell of datagridview
----------------------------------
id | p/w | post |
----------------------------------
1 | 1234 | A |
----------------------------------
2 | 4567 | S |
----------------------------------
3 | 6789 | A |
----------------------------------
I want to get 3 into the textbox,how to do that? Can anyone give some example coding?
than you~
A:
The line would be as shown below:
Dim x As Integer
x = dgvName.Rows(yourRowIndex).Cells(yourColumnIndex).Value
| {
"pile_set_name": "StackExchange"
} |
Q:
WIX: copy file to custom dir in another partition
I need to install my app's files to usual location like C:\Program Files\MyApp
and also need to copy several of them into custom folder in another partition
(let's say D:\CustomFolder, it's allowed to hardcode it).
Install should be silent - no gui or wizard. And alose everything should be in one *.msi file.
I can do that via CustomActions, but elegant-declarative way is preferable.
Has anyone tried this before?
Thanks.
UPDATE:
Forgot to mention, that it's allowed for files that should be on separate partition to be in C:\Program Files\MyApp
A:
Solved. The approach is:
Specify custom folder where file should be put:
<Property Id="MY_CUSTOM_DESTINATION" Value="D:\MyCustomFolder" />
Put <Copy ..> directive into <File ...> which should be copied
<DirectoryRef Id="MyAppFolderThatIsInProgramFiles">
<Component Id="MyComponent" Guid="some_guid">
<File Id="MyFileXml" Source="MyFile.xml" KeyPath="yes" >
<CopyFile Id="Copy_MyFileXml" DestinationProperty="MY_CUSTOM_DESTINATION"/>
</File>
</Component>
</DirectoryRef>
p.s. as a side-effect, file specified in <File Id="MyFileXml" ... /> will be put into both location: C:\Program Files\MyApp and D:\MyCustomFolder, but that's correct for my task.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Rest Template creating multipart form/data client working like a postman throws non convertable exception
I want to turn this postman client with multipart/form-data header request to a spring template client.
Right now, I have a basic rest controller which works well.
@RestController
@RequestMapping("/api")
public class MainConroller {
private static final Logger log = LoggerFactory.getLogger(MainConroller.class);
@Autowired
private MainService mainService;
public MainConroller(MainService mainService) {
this.mainService = mainService;
}
@PostMapping("/mails/send")
public void send(
@RequestParam("usertoken") String usertoken,
@RequestParam("sendTo") String sendTo,
@RequestParam("subject") String subject,
@RequestParam("content") String content,
@RequestParam(required = false, name = "files") List<MultipartFile> multipartFiles) {
log.debug("{}, {}, {}, {}", usertoken, sendTo, subject, content);
mainService.processMessage(usertoken, sendTo, subject, content, multipartFiles);
}
}
I need to, however, create a rest client so I used a rest template, it right now looks like this:
ArrayList<HttpMessageConverter<?>> converters = new ArrayList<>(
Arrays.asList(new MappingJackson2HttpMessageConverter(), new ResourceHttpMessageConverter(), new FormHttpMessageConverter()));
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(converters);
}
File file = new File("*********");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> fileValueMap = new LinkedMultiValueMap<>();
fileValueMap.add(file.getName(), file);
fileValueMap.add(file.getName(), file);
fileValueMap.add(file.getName(), file);
HttpEntity<MultiValueMap<String, Object>> filesPart = new HttpEntity<>(fileValueMap, httpHeaders);
// String key values part
MultiValueMap<String, String> stringPart = new LinkedMultiValueMap<>();
stringPart.add("usertoken", "test");
stringPart.add("sendTo", "test");
stringPart.add("subject", "test");
stringPart.add("content", "test");
HttpEntity<MultiValueMap<String, String>> objectPart = new HttpEntity<>(stringPart, httpHeaders);
MultiValueMap<String, Object> multiPartRequest = new LinkedMultiValueMap<>();
multiPartRequest.add("ObjectPart", objectPart);
multiPartRequest.add("FilesPart", filesPart);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multiPartRequest, httpHeaders);
String serverUrl = "****";
restTemplate().postForEntity(serverUrl, requestEntity, String.class);
The problem is when I try to send the post request, It throws
Exception in thread "main" org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [multipart/form-data]
Update
The solution on the client side is very simple, you can just send String values in the object values, which are going to be automatically casted to Strings via generics.
Also, the files cannot be send just as files but you have to create FileSystemResource instead, here is the complete code of the client side:
@Service
public class RestTemplatePost {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public void prepareMessage() throws Exception {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("usertoken", "test");
form.add("sendTo", "test");
form.add("subject", "test");
form.add("content", "test");
form.add("files", getTestFile());
form.add("files", getTestFile());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(form, httpHeaders);
String serverUrl = "******";
restTemplate().postForEntity(serverUrl, requestEntity, String.class);
}
public static Resource getTestFile() throws IOException {
Path testFile = Paths.get("C****");
System.out.println("Creating and Uploading Test File: " + testFile);
Files.write(testFile, "Hello World !!, This is a test file.".getBytes());
return new FileSystemResource(testFile.toFile());
}
}
A:
You are making things too complex. You should use a single map to hold the form values not a map of maps. Next to that Spring Boot already provides a RestTemplate so you don't need to configure your own again.
File file = new File("*********");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("files", file);
form.add("files", file);
form.add("files", file);
form.add("usertoken", "test");
form.add("sendTo", "test");
form.add("subject", "test");
form.add("content", "test");
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(form, httpHeaders);
String serverUrl = "****";
restTemplate().postForEntity(serverUrl, requestEntity, String.class);
The RestTemplate (or actually the FormHttpMessageConverter) will transform it into a correct request.
A:
The default RestTemplate constructor does not include any message converters, you need to add it. For example, you can do it like:
HttpEntity<MultiValueMap<String, Object>> requestEntity = new
HttpEntity<MultiValueMap<String, Object>>(parts, requestHeaders);
RestTemplate restTemplate = getRestTemplate();
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
return restTemplate.postForObject(apiURI, requestEntity, String.class);
| {
"pile_set_name": "StackExchange"
} |
Q:
how to remove class if array list is empty inside jsp page?
i have following code i want to remove tbl-content class if recordList array is empty
<table id="gradient-style">
<tbody class="tbl-content">
<tr>
<%
for (RecordBean record : recordList) {
// some code here to get result
}
%>
<%
if (recordList.isEmpty())
{
%>
<tr>
<td colspan="12" align="center" style="color: red;font-family: verdana">
<h3>No Search records </h3>
</td>
</tr>
<%
}
%>
</tbody>
</table>
here is css
.tbl-content{
height: 650px;;
overflow: auto;
position: absolute;
border: 1px solid gray;
border-top: none;
}
A:
Try this server side inline code
<tbody class="<%= recordList.isEmpty()?"":"tbl-content" %>">
A:
You can write JSTL code directly in script tag.
<script>
<c:if test="${empty recordList}">
//write code here to remove class
</c:if>
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Botões - ID - Carousel não funcionando
Não entendo muito de jQuery, mas o que pode estar acontecendo?
Eu gostaria apenas que as setas conseguissem funcionar corretamente, não liguem pro estilo.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Teste Caroulsel</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<style type="text/css">
/* carousel */
#quote-carousel {
padding: 0 10px 30px 10px;
margin-top: 30px;
text-align:center;
}
/* indicator position */
#quote-carousel .carousel-indicators {
right: 50%;
top: auto;
bottom: -10px;
margin-right: -19px;
}
/* indicator color */
#quote-carousel .carousel-indicators li {
background: #c0c0c0;
}
/* active indicator */
#quote-carousel .carousel-indicators .active {
background: #333333;
height:10px;
width:10px;
margin-bottom:1px;
}
/* typography */
h1 {
text-align:center;
margin-bottom:-20px !important;
}
p {
font-style:italic;
}
</style>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js" type="text/javascript"></script>
<h1>Malesuada</h1>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="carousel slide" data-ride="carousel" id="quote-carousel">
<!-- Bottom Carousel Indicators -->
<ol class="carousel-indicators">
<li data-target="#quote-carousel" data-slide-to="0" class="active"></li>
<li data-target="#quote-carousel" data-slide-to="1"></li>
<li data-target="#quote-carousel" data-slide-to="2"></li>
</ol>
<!-- Carousel Slides / Quotes -->
<div class="carousel-inner">
<!-- Quote 1 -->
<div class="item active">
<div class="row">
<div class="col-sm-12">
<p>“Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed diam eget risus varius blandit sit amet non magna. Etiam porta sem malesuada magna mollis euismod. Nulla vitae elit libero, a pharetra augue. Donec id elit non mi porta gravida at eget metus.”</p>
<small><strong>Vulputate M., Dolor</strong></small>
</div>
</div>
</div>
<!-- Quote 2 -->
<div class="item">
<div class="row">
<div class="col-sm-12">
<p>“Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.”</p>
<small><strong>Fringilla A., Vulputate Sit</strong></small>
</div>
</div>
</div>
<!-- Quote 3 -->
<div class="item">
<div class="row">
<div class="col-sm-12">
<p>“Aenean lacinia bibendum nulla sed consectetur. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Maecenas faucibus mollis interdum. Cras mattis consectetur purus sit amet fermentum.”</p>
<small><strong>Aenean A., Justo Cras</strong></small>
</div>
</div>
</div>
</div>
<style type="text/css">
.carousel-control-prev {
left: 45%;
background-color: #000;
position: absolute;
top: none;
bottom: none;
display: -ms-flexbox;
display: flex;
-ms-flex-align: center;
align-items: center;
-ms-flex-pack: center;
justify-content: center;
width: 15%;
}
.carousel-control-next {
right: 45%;
background-color: #000;
position: absolute;
top: none;
bottom: none;
display: -ms-flexbox;
display: flex;
-ms-flex-align: center;
align-items: center;
-ms-flex-pack: center;
justify-content: center;
width: none;
}
</style>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script type="text/javascript">
// When the DOM is ready, run this function
$(document).ready(function() {
//Set the carousel options
$('#quote-carousel').carousel({
pause: true,
interval: 1000,
});
$('.carousel-control.prev').click(function() {
$('#carouselExampleIndicators').carousel('prev');
});
$('.carousel-control.next').click(function() {
$('#carouselExampleIndicators').carousel('next');
});
});
</script>
</html>
A:
Basta corrigir o href dos botões: href="#quote-carousel"
<a class="carousel-control-prev" href="#quote-carousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#quote-carousel" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to bind members of an array of objects from input field
I have a form field from which I want to bind my data inserted by the user to the object created in the typescript file.
<form (ngSubmit)="onSubmitTest()">
<div class="form-group">
<label for="name"><strong>Name</strong></label>
<input type="text" [(ngModel)]="testBody.test_name" class="form-control" name="name">
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="date"><strong>Date</strong></label>
<div class="input-group">
<input type="date" class="form-control" name="date">
</div>
</div>
<div class="form-group">
<label for="duration"><strong>Duration</strong></label>
<div class="input-group">
<input type="number" [(ngModel)]="testBody.test_duration" class="form-control" name="duration">
<span class="input-group-addon" id="basic-addon2">mins</span>
</div>
</div>
<div class="form-group">
<label for="class"><strong>Class</strong></label>
<input type="text" [(ngModel)]="testBody.test_class" class="form-control" name="class">
</div>
<div class="form-group">
<label for="lang"><strong>Language</strong></label>
<input type="text" [(ngModel)]="testBody.test_language" class="form-control" name="lang">
</div>
<div class="form-group">
<label for="strTag"><strong>Store Tag</strong></label>
<input type="text" class="form-control" name="strTag">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="time"><strong>Time range</strong></label>
<div class="input-group">
<input type="time" class="form-control" name="timestart">
<span class="input-group-addon" id="basic-addon2">TO</span>
<input type="time" class="form-control" name="timeend">
</div>
</div>
<div class="form-group">
<label for="code"><strong>Code</strong></label>
<div class="input-group">
<input type="text" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-search" aria-hidden="true"></i></button>
</span>
</div>
</div>
<div class="form-group">
<label for="exam"><strong>Exam</strong></label>
<input type="text" [(ngModel)]="testBody.test_exam" class="form-control" name="exam">
</div>
<div class="form-group">
<label for="board"><strong>Board</strong></label>
<input type="text" [(ngModel)]="testBody.test_board" class="form-control" name="board">
</div>
<div class="form-group">
<label for="price"><strong>Price</strong></label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">Rs.</span>
<input type="number" class="form-control" name="price">
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="desc"><strong>Description</strong></label>
<input type="text" [(ngModel)]="testBody.test_instruction" class="form-control" name="desc">
</div>
<div>
<label for="section"><strong>SECTION</strong></label>
<div *ngFor="let i of sectionNumber; let section of testBody.test_sections_data">
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">{{i}}</span>
<input type="text" [(ngModel)]="section.section_name" class="form-control" [ngModelOptions]="{standalone: true}">
<label for="questionNo"><strong>Ques.</strong></label>
<input type="number" [(ngModel)]="section.section_number_of_questions" class="form-control" [ngModelOptions]="{standalone: true}">
<label for="maxMarks"><strong>Max marks</strong></label>
<input type="number" [(ngModel)]="section.section_max_marks" class="form-control" [ngModelOptions]="{standalone: true}">
<label for="cuttOff"><strong>Cut off</strong></label>
<input type="number" [(ngModel)]="section.section_cut_off" class="form-control" [ngModelOptions]="{standalone: true}">
<label for="cuttOff"><strong>Topper mark</strong></label>
<input type="number" [(ngModel)]="section.section_topper_marks" class="form-control" [ngModelOptions]="{standalone: true}">
</div>
</div>
<button type="button" style="margin:10px" (click)="incrementSection()" class="btn btn-sm btn-info">+</button>
</div>
<div class="row">
<div class="col-md-6">
<p><strong>MARKS RANGE</strong></p>
<div class="form-group">
<div class="input-group">
<input type="number" class="form-control" id="from">
<span class="input-group-addon" id="basic-addon2">TO</span>
<input type="number" class="form-control" id="to">
</div>
<div class="input-group">
<input type="number" class="form-control" id="from">
<span class="input-group-addon" id="basic-addon2">TO</span>
<input type="number" class="form-control" id="to">
</div>
</div>
</div>
<div class="col-md-6">
<p><strong>RANK RANGE</strong></p>
<div class="input-group">
<input type="number" class="form-control" id="from">
<span class="input-group-addon" id="basic-addon2">TO</span>
<input type="number" class="form-control" id="to">
</div>
<div class="input-group">
<input type="number" class="form-control" id="from">
<span class="input-group-addon" id="basic-addon2">TO</span>
<input type="number" class="form-control" id="to">
</div>
</div>
</div>
<div class="form-group">
<label for="visible"><strong>Visible</strong></label>
<input type="checkbox" [(ngModel)]="testBody.test_visibility" name="visibleTest" [checked]="isVisible" (change)="isVisible=!isVisible">
</div>
<button type="submit" class="btn btn-default">Add</button>
<button type="submit" class="btn btn-default pull-right">Export File</button>
</form>
And here is what it is bind to in backend.
export class TestDetailComponent implements OnInit {
sectionSno = 1;
sectionNumber = [1];
isVisible = true;
program_id: string;
testCategory: string[];
testName: string[];
closeResult: string;
body: {
category_name: string,
description: string,
code: string,
store_tag: string,
visible: number,
client_id: string,
program_id: string
};
testBody: {
test_category: string,
test_instruction: string,
test_duration: string,
test_name: string,
test_class: string,
test_language: string,
test_exam: string,
test_board: string,
client_id: string,
program_id: string,
test_visibility: number,
test_sections_data: [{
section_name: string,
section_max_marks: number,
section_cut_off: number,
section_topper_marks: number,
section_number_of_questions: number
}]
}
// tslint:disable-next-line:max-line-length
constructor(private modalService: NgbModal, private route: ActivatedRoute, private dragulaService: DragulaService, private http: HttpClient) {
const bag: any = this.dragulaService.find('bag-task1');
this.body = {
category_name: '',
description: '',
code: '',
store_tag: '',
visible: null,
client_id: allGlobals.client_id,
program_id: this.program_id
};
this.testBody = {
test_category: '',
test_instruction: '',
test_duration: '',
test_name: '',
test_class: '',
test_language: '',
test_exam: '',
test_board: '',
client_id: allGlobals.client_id,
program_id: this.program_id,
test_visibility: null,
test_sections_data: null
};
this.body.visible = 0;
if (bag !== undefined) {
this.dragulaService.destroy('bag-task1');
}
this.dragulaService.setOptions('bag-task1', {
copy: false
});
this.http.get(allGlobals.url_server + '/getTestCategories?client_id=' + allGlobals.client_id).subscribe(data => {
// Read the result field from the JSON response.get response
this.testCategory = data['rows'];
});
this.http.get(allGlobals.url_server + '/getTestList?client_id=' + allGlobals.client_id).subscribe(data => {
// Read the result field from the JSON response.
this.testName = data['rows'];
});
}
open(content) {
this.modalService.open(content).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
getVisibleInt() {
if (this.isVisible === true) {
this.body.visible = 1;
} else {
this.body.visible = 0;
}
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
incrementSection() {
this.sectionSno++;
this.sectionNumber.push(this.sectionSno);
}
setCategoryId(category) {
this.testBody.test_category = category.testCategories_id;
}
onSubmit() {
this.http.post(allGlobals.url_server + '/addTestCategory', this.body)
.subscribe(data => {
this.http.get(allGlobals.url_server + '/getTestCategories?client_id=' + allGlobals.client_id).subscribe(data => {
// Read the result field from the JSON response.get response
this.testCategory = data['rows'];
});
this.http.get(allGlobals.url_server + '/getTestList?client_id=' + allGlobals.client_id).subscribe(data => {
// Read the result field from the JSON response.
this.testName = data['rows'];
});
},
err => {
console.log(err);
},
() => {
this.body = {
category_name: '',
description: '',
code: '',
store_tag: '',
visible: null,
client_id: allGlobals.client_id,
program_id: this.program_id
}
}
);
}
onSubmitTest() {
this.http.post(allGlobals.url_server + '/addTest', this.testBody)
.subscribe(data => {
this.http.get(allGlobals.url_server + '/getTestCategories?client_id=' + allGlobals.client_id).subscribe(data => {
// Read the result field from the JSON response.get response
this.testCategory = data['rows'];
});
this.http.get(allGlobals.url_server + '/getTestList?client_id=' + allGlobals.client_id).subscribe(data => {
// Read the result field from the JSON response.
this.testName = data['rows'];
});
},
err => {
console.log(err);
},
() => {
this.testBody = {
test_category: '',
test_instruction: '',
test_duration: '',
test_name: '',
test_class: '',
test_language: '',
test_exam: '',
test_board: '',
client_id: allGlobals.client_id,
program_id: this.program_id,
test_visibility: null,
test_sections_data: null
};
}
)
}
ngOnInit() {
this.route.params.subscribe(params => {
this.program_id = params['id']; // --> Name must match wanted parameter
this.body.program_id = this.program_id;
this.testBody.program_id = this.program_id;
});
}
}
Now when I am adding test sections I am getting null in the backend whereas all other fields are getting assigned. I don't know if I am doing it right but test_sections_data is an array of object in which the number of the section is incremented each time the + button is clicked.
A:
Try this:
<div *ngFor="let section of testBody.test_sections_data; let i = index">
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">{{i}}</span>
<input type="text" [(ngModel)]="testBody.test_sections_data[i].section_name" class="form-control" [ngModelOptions]="{standalone: true}">
<label for="questionNo"><strong>Ques.</strong></label>
<input type="number" [(ngModel)]="testBody.test_sections_data[i].section_number_of_questions" class="form-control" [ngModelOptions]="{standalone: true}">
<label for="maxMarks"><strong>Max marks</strong></label>
<input type="number" [(ngModel)]="testBody.test_sections_data[i].section_max_marks" class="form-control" [ngModelOptions]="{standalone: true}">
<label for="cuttOff"><strong>Cut off</strong></label>
<input type="number" [(ngModel)]="testBody.test_sections_data[i].section_cut_off" class="form-control" [ngModelOptions]="{standalone: true}">
<label for="cuttOff"><strong>Topper mark</strong></label>
<input type="number" [(ngModel)]="testBody.test_sections_data[i].section_topper_marks" class="form-control" [ngModelOptions]="{standalone: true}">
</div>
</div>
Edit your Add section function:
incrementSection() {
let sec:any = {};
this.testBody.test_sections_data.push(sec);
}
constructor(){
this.testBody = {
test_category: '',
test_instruction: '',
test_duration: '',
test_name: '',
test_class: '',
test_language: '',
test_exam: '',
test_board: '',
client_id: allGlobals.client_id,
program_id: this.program_id,
test_visibility: null,
test_sections_data: [{
section_name: '',
section_max_marks: 0,
section_cut_off: 0,
section_topper_marks: 0,
section_number_of_questions: 0
}]
};
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use property placeholders in Jetty-env.xml?
I am working on a project that uses jetty-env.xml to define some resources in the test environment. It requires that I hijack it and put in my username and password for the resources. Is there a way to define my credentials in an external way and use a property placeholder instead? Like in the Spring applicationConfig.xml I can use ${username} as defined in my system properties.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd">
<Configure id="wac" class="org.mortbay.jetty.webapp.WebAppContext">
<New id="validation_mail" class="org.mortbay.jetty.plus.naming.Resource">
<Arg>mail/exampleMail</Arg>
<Arg>
<New class="org.mortbay.naming.factories.MailSessionReference">
<Set name="user"></Set>
<Set name="password"></Set>
<Set name="properties">
<New class="java.util.Properties">
<Put name="mail.smtp.host">mail.example.edu</Put>
</New>
</Set>
</New>
</Arg>
</New>
<New id="datasource" class="org.mortbay.jetty.plus.naming.Resource">
<Arg>jdbc/DataSource</Arg>
<Arg>
<New class="com.sybase.jdbc3.jdbc.SybDataSource">
<Set name="databaseName">example</Set>
<Set name="serverName">testip.example.edu:2025</Set>
<Set name="portNumber">2025</Set>
<Set name="user">username</Set> <!-- put username here -->
<Set name="password">password</Set> <!-- put password here -->
</New>
</Arg>
</New>
I new to these tools so I might be closer to an answer than I think. Any help would be appreciated.
Enviroment:
Spring Tool Suite 3.4.0 RELEASE
Maven 3
Jetty Plugin 6.1
Spring 3
A:
If you're using the jetty maven plugin, then you can define your properties in a properties file.
Configure the jetty plugin like this:
<configuration>
<systemPropertiesFile>${project.basedir}/src/test/conf/jetty-env.properties</systemPropertiesFile>
</configuration>
And then your jetty-env.xml can be like this:
<New id="dsDatasource" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>jdbc/dsProtWb</Arg>
<Arg>
<New class="org.apache.commons.dbcp.BasicDataSource">
<Set name="driverClassName">net.sourceforge.jtds.jdbc.Driver</Set>
<Set name='url'>jdbc:jtds:sqlserver://ROPFDN812Q:4900/dlmp_proteomics_wb_dev;instance=FDNDEV18;domain=mfad</Set>
<Set name="username"><SystemProperty name="LANID" /></Set>
<Set name="password"><SystemProperty name="LANPW" /></Set>
</New>
</Arg>
</New>
A:
You can define environment variables and use the Env tag as a placeholder.
<New id="dsDatasource" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>jdbc/dsProtWb</Arg>
<Arg>
<New class="org.apache.commons.dbcp.BasicDataSource">
<Set name="driverClassName">net.sourceforge.jtds.jdbc.Driver</Set>
<Set name='url'>jdbc:jtds:sqlserver://ROPFDN812Q:4900/dlmp_proteomics_wb_dev;instance=FDNDEV18;domain=mfad</Set>
<Set name="username"><Env name="LANID"/></Set>
<Set name="password"><Env name="LANPW"/></Set>
</New>
</Arg>
</New>
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS not loaded || Spring
After logging in on my page, spring redirects me to my main site using the following controller:
//Login Success
@GetMapping("/login-success")
public ModelAndView loginSuccess() {
return new ModelAndView("/cont/home.html");
}
the URL looks like:
http://localhost:8080/login-success
It is the HTML structure of home.html but the CSS is not loaded.
If I navigate to http://localhost:8080/cont/home.html it is styled.
Thanks for the help. :)
A:
Try like this below
return new ModelAndView("/CONTEXT_PATH/cont/home.html");
OR
response.sendRedirect("/cont/home.html");
return;
specify with context path so that the page will be loaded
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Avoid Delay On First Time Start up of js setInterval() Function
Can you please take a look at following code and let me know how I can avoid the delay on only FIRST time of this counting down process?
As you can see the counter works fine but there is a delay on first time starting.
var sec = 20;
var timer = setInterval(function() {
$('#box').text(sec--);
if (sec == -1) {
$('#box').css('color','blue');
clearInterval(timer);
}
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">20</div>
A:
Use --sec instead of sec--, so that the changed value will be set.
The reason why this is working is well described here: ++someVariable Vs. someVariable++ in Javascript
So your code should look like this:
var sec = 20;
var timer = setInterval(function() {
$('#box').text(--sec);
if (sec == -1) {
$('#box').css('color','blue');
clearInterval(timer);
}
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">20</div>
A:
Another option - move piece of code to separate function
var sec = 20;
var execution = function() {
$('#box').text(sec--);
if (sec == -1) {
$('#box').css('color','blue');
clearInterval(timer);
}
}
execution(); // Run first time without delay
var timer = setInterval(function() {
execution(); // every next run should be done with delay
}, 1000);
| {
"pile_set_name": "StackExchange"
} |
Q:
Building Spring & Spring Security 3.1 With Maven
I came to a grinding halt in trying to debug a problem I am having with Spring 3.1 ( I put a bounty on it FWIW ). So, I would like to take the spring-security and spring-ldap source code, put my own log4j statments in, compile it and run my webapp in Tomcat 6.
What is the most sensible way to do this?
Include my "customized" libraries in the WEB-INF/lib of my Maven based project or do I put the altered libs in the tomcat\lib dir?
Can I do this using only Maven? I recently learned Maven to fix a proble and I would like to catch my breath before learning gradle if I can.
I don't want to do this for all of Spring and all of Spring-Security.
How would I set it up in maven/my pom.xml?
I realize the new tools make all of this easier than it probably feels to me, but compiling libraries from source has been a terror most of my life so I would like some tips and instructions to make it as easy/fast as possible.
Thanks
A:
You can do this using only maven:
Either: Use the same POM as the spring people do. That way the new jar that falls out of your code will overwrite the one delivered by spring.
Or: Use the same POM, but increase the Version Number (to the next SNAPSHOT ) and change the dependency in your pom to that version. (EDIT: read Roy-Truelove 's comment below, its very correct indeed.)
I would recommend the latter variant.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find examples of non-unique euclidean division in $\Bbb Z[i]$?
The euclidean division of $1+8i$ by $2-4i$ can be one of two things:
$$1+8i=(2-4i)(i-1)-1+2i\tag{1}$$ $$\underbrace{1+8i}_\text{a}=\underbrace{(2-4i)}_\text{b}(\underbrace{-2+i}_\text{q})+\underbrace{1-2i}_\text{r}\tag{2}$$
And we have that $N(r)<N(b)$ where $N(a+bi)=a^2+b^2$ and the $b$'s aren't associated so those are really two different euclid divisions. (do the $r$'s have to be associated? here one is $(-1)$ times the other...)
What's the mindset in which we have to be to look for and find such examples?
A:
You even have non-unique Euclidean division in the integers. Dividing $9$ by $4$ could be either:
$$ 9 = 4 \cdot 2 + 1 $$
$$ 9 = 4 \cdot 3 + (-3) $$
You pretty much always have these examples, except for the special case that the remainder is zero. In cases like $\mathbb{Z}$ and $\mathbb{Z}[i]$, given any one quotient-remainder pair, you can find others by adjusting the quotient by testing out the other numbers near the quotient.
I don't recall for sure how this all works out, but I think for $\mathbb{Z}[i]$, that on average you should expect there to be $\pi$ different remainders satisfying $N(r) < N(b)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
wso2 micro integrator clustering for a service - creating another question, since first one was closed for no eason
Let's say we have a micro integrator communicating with several services.
We want to be able to cluster one of the services, for example if we send two requests to a service we want each of these requests to be processed by a different node of a service, is that possible?
Services are third party REST API, we want to send requests to two different URL.
There is Load-BalanceEndPoint element in the Integration studio element, but it's not clear how it works, or even if it permit us to solve the issue above.
Could anyone help us resolve this problem/explain how we should use mentioned endpoint?
A:
Yes, you can use Load-Balance Endpoint for your usecase. Have a look at the following sample configurations.
API configuration :
<?xml version="1.0" encoding="UTF-8"?>
<api context="/loadbalance" name="checkLoadBalance" xmlns="http://ws.apache.org/ns/synapse">
<resource methods="GET">
<inSequence>
<call>
<endpoint key="testLoadBalance"/>
</call>
<respond/>
</inSequence>
<outSequence/>
<faultSequence/>
</resource>
</api>
Endpoint Configuration :
<?xml version="1.0" encoding="UTF-8"?>
<endpoint name="testLoadBalance" xmlns="http://ws.apache.org/ns/synapse">
<loadbalance algorithm="org.apache.synapse.endpoints.algorithms.RoundRobin">
<endpoint name="endpoint_urn_uuid_6179155B57847314A657084710149040-304004407">
<http method="GET" uri-template="http://www.mocky.io/v2/5e574b1c3000006000fd38cd">
<suspendOnFailure>
<initialDuration>-1</initialDuration>
<progressionFactor>1</progressionFactor>
</suspendOnFailure>
<markForSuspension>
<retriesBeforeSuspension>0</retriesBeforeSuspension>
</markForSuspension>
</http>
</endpoint>
<endpoint name="endpoint_urn_uuid_6179155B57847314A657084710149040-304004407">
<http method="GET" uri-template="http://www.mocky.io/v2/5185415ba171ea3a00704eed">
<suspendOnFailure>
<initialDuration>-1</initialDuration>
<progressionFactor>1</progressionFactor>
</suspendOnFailure>
<markForSuspension>
<retriesBeforeSuspension>0</retriesBeforeSuspension>
</markForSuspension>
</http>
</endpoint>
</loadbalance>
<description/>
</endpoint>
Here I have used two different mocky endpoints. They will return {"Hello": "World"} and {"hello": "world"}.
After deploying, if I invoke checkLoadBalance API for first time, I will get response from the first endpoint. If I invoke for the second time, I will get response from the second endpoint. Here I have given the algorithm as Roundrobin. Hence it will scheduled in a RoundRobin manner.
| {
"pile_set_name": "StackExchange"
} |
Q:
Boost property tree: Remove a node
How would you remove a node from boost xml property tree?
I have a document like this:
<folders>
<folder>some/folder</folder>
<folder>some/folder</folder>
<folder>some/folder</folder>
</folders>
I know how to itereate and print all folders, but how would i remove one of the items and save the xml back?
A:
I would probably try:
boost::property_tree::ptree pt;
pt.erase(key);
| {
"pile_set_name": "StackExchange"
} |
Q:
Convex set in $\mathbb{R}^2$
I want to show that the set $A=\{(x, y)\in\mathbb{R}^2: x^2\leq y\} $ is convex.
A:
Definition: a convex function is a function $f:\Bbb{R}\to\Bbb{R}$ such that $A_f = \{(x,y):y\geq f(x)\}$ is convex.
Proposition: If for any $x_1, x_2\in \Bbb{R}$ and $t\in [0,1]$ we have $f(tx_1+(1-t)x_2)\leq tf(x_1)+(1-t)f(x_2)$, then $f$ is convex.
Proof: Suppose the hypothesis holds. Pick $(u_1,u_2), (v_1,v_2)\in A_f$, so $u_2\geq f(u_1)$ and $v_2\geq f(v_1)$ *. Pick $t\in [0,1]$. We wish to show that $t\mathbf{u}+ (1-t)\mathbf{v}\in A$, i.e. $tu_2+(1-t)v_2\geq f(tu_1+(1-t)v_1)$. By hypothesis, we have
$$f(tu_1+(1-t)v_1) \leq tf(u_1)+(1-t)f(v_1) \leq tu_2 + (1-t)v_2$$
Where the last inequality is by *. This completes the proof.
Now we show that the proposition holds for $f(x) = x^2$. Let $x,y\in \Bbb{R}$, $t\in [0,1]$. Then
$$tf(x)+(1-t)f(y) - f(tx+(1-t)y) = $$
$$tx^2 + (1-t)y^2 - t^2x^2 - (1-t)^2y^2-2t(1-t)xy = $$
$$t(1-t)x^2+t(1-t)y^2-2t(1-t)xy = $$
$$t(1-t)(x-y)^2 \geq 0$$
Verifying that $f$ is convex. The proposition here is very useful for proving functions are convex; it's actually an "if and only if", but I omitted the other half as it wasn't necessary here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Speed of [].forEach.call(...?
I'm a big fan of using the forEach method on nodeLists like this:
var nodes = document.querySelectorAll(".foo");
[].forEach.call(nodes, function (item) {
//do stuff with item
});
I was wondering though, does doing it that way take longer than the regular way?
e.g.
for(var i=0;i<nodes.length;i++){
//do stuff with nodes[i];
}
A:
Here's a nice performance comparison. According to it Array.forEach is slower than a native for loop.
A:
I know it's an old post but using the forEach method can be done by stealing the Array prototype as well.
NodeList.prototype.forEach = Array.prototype.forEach;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get all non-formula and non-blank cells in VSTO Excel?
Taking a look at this answer Getting Cells with Formulas in Excel file, there is an elegant solution to get all cells in an Excel worksheet which contain formulas. But what if I want all the cells that do NOT contain formulas? (I do not want blank cells either - I just want the plain cell with a value and that is not a formula).
Is there an elegant solution which does not include checking each and every cell in C# VSTO environment?
A:
If I understand your question, you want the constants, which is sort of the opposite of the formulas. There is a special cell type for this as well:
Range nonFormulas = ws.Cells.SpecialCells(XlCellType.xlCellTypeConstants);
foreach (Range r in nonFormulas)
{
// Do some stuff
}
I think you know this already, but the formulas are just:
ws.Cells.SpecialCells(XlCellType.xlCellTypeFormulas);
| {
"pile_set_name": "StackExchange"
} |
Q:
hidden title if data empty in blade laravel
I want to hide the title if there is no data show in foreach result. so, where should i place the section title?
this is the code
<div class="title">
//section title
<div class="navigation-bar">
<h3>Title</h3>
</div>
@foreach($similar_posts as $related_post)
//data
@endforeach
</div>
thanks
A:
Try this
<div class="title">
@if( ! $similar_posts->isEmpty() )
//section title
<div class="navigation-bar">
<h3>Title</h3>
</div>
@foreach($similar_posts as $related_post)
//data
@endforeach
@endif
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Data Projection size()
Is there a way to return the size of a collection via rest api projection?
Consider this example:
The data:
@Entity
@Table
public class MyData {
// id
// ...
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "mydata")
private final Set<User> users = new HashSet<>();
// getters/setters ...
}
the repository:
@RepositoryRestResource
public interface MyDataRepository extends PagingAndSortingRepository<MyData, Long> {
}
the projection:
@Projection(name = "short", types = {MyData.class})
public interface MyDataProjection {
// neither of those work
// @Value("#{target.getUsers().size()}")
@Value("#{target.users.size()}")
Integer nrUsers();
}
I want to get the number of Users in a MyData-Object returned via REST api.
For example: my-domain/my-service/mydatas/123/?projection=short
should return:
{
"nrUsers": 4;
...
}
Is it possible anyway?
A:
The naming convention ist to start with a "get" since the attributes of the projection are methods, not fields. So this works:
@Value("#{target.users.size()}")
Integer getNrUsers();
(instead of the previous "nrUsers()")
| {
"pile_set_name": "StackExchange"
} |
Q:
count the frequency of elements in list of lists in Python
Say, I have the following sorted list of lists :
List 1 : (12,24,36)
List 2 : (3,5,12,24)
List 3 : (36,41,69)
I want to find out the frequency of each element in the entire list of lists. I came up with an ugly module for the same in python but I was wondering if there is some library function..
Edit : Please find the code below
def find_frequency(transactions,list):
freq = 0
for items_transaction in transactions:
flag = 0
for candidate in list:
if candidate not in items_transaction:
flag = 1
break
if flag == 0:
freq += 1
return freq
A:
Counter does what I believe you are looking for:
>>> from itertools import chain
>>> from collections import Counter
>>> list1, list2, list3 = [12,24,36], [3,5,12,24], [36,41,69]
>>> Counter(chain(list1, list2, list3))
Counter({3: 1, 5: 1, 12: 2, 24: 2, 36: 2, 41: 1, 69: 1})
A:
You need to flatten a list - that is, transform it to a single long sequence of all values. It can be done using itertools.chain
import collections, itertools
l = [[12,24,36], [3,5,12,24], [36,41,69]]
freq = collections.defaultdict(int) # 0 by default
for x in itertools.chain.from_iterable(l):
freq[x] += 1
print(freq)
| {
"pile_set_name": "StackExchange"
} |
Q:
Tcl equivalent for UNIX "cp -pL" command
What is Tcl equivalent for UNIX "cp -pL" command?
I cannot find it in file command description
A:
For a single file:
a) Get the real path to the file.
b) Copy it.
c) Set the attributes, modification time and access time.
Unfortunately, there does not appear to be any way to set the change time (creation time on Windows).
set fn sourcefn
set tofn targetfn
set nfn [file normalize [file readlink $fn]]
file copy -force $nfn $tofn
foreach {key} [list attributes mtime atime] {
set temp [file $key $nfn]
file $key $tofn {*}$temp
}
This is the pure Tcl solution that will work on unix, Mac OS X and Windows. Of course you could just do:
exec cp -pLf $from $to
References: file
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel Collection. Combine same key
I want to combine same keys in Laravel collection, that are stored in an array.
I can't "invent" a proper neat and short pipeline for such a transformation.
Data array
Example Result
A:
It looks like you have two equal arrays inside and you need concat [0] and [1] keys to week days (from - to). Here is the solution for your collection-as-array:
<?php
$youHaveArray = [
0 => [
'mon' => [
3 => '10:00',
4 => '11:00',
5 => '12:00',
],
'tue' => [
3 => '11:00',
4 => '12:00',
],
],
1 => [
'mon' => [
3 => '10:30',
4 => '11:30',
5 => '12:30',
],
'tue' => [
3 => '11:30',
4 => '12:30',
],
]
];
$daysOfWeekYouHave = array_keys($youHaveArray[0]) + array_keys($youHaveArray[1]);
$weekFormated = [];
foreach ($daysOfWeekYouHave as $dayName) {
if (! isset($weekFormated[$dayName])) {
$weekFormated[$dayName] = [];
}
if (isset($youHaveArray[0][$dayName])) {
foreach ($youHaveArray[0][$dayName] as $dayKey => $dayStart) {
if (isset($youHaveArray[1][$dayName][$dayKey])) {
$dayEnd = $youHaveArray[1][$dayName][$dayKey];
$weekFormated[$dayName][$dayKey] = $dayStart.' - '.$dayEnd;
}
}
}
}
var_dump($weekFormated);
Result is:
array(2) {
'mon' =>
array(3) {
[3] =>
string(13) "10:00 - 10:30"
[4] =>
string(13) "11:00 - 11:30"
[5] =>
string(13) "12:00 - 12:30"
}
'tue' =>
array(2) {
[3] =>
string(13) "11:00 - 11:30"
[4] =>
string(13) "12:00 - 12:30"
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Electron with java how to package?
I need to build a desktop application which the GUI just to modify a configuration file and java application running as a window service (or cron job in linux) to do processing.
I was thinking to use electron as GUI and java as background.
I quite like the idea of electron where I can use html and other web frameworks compare to JavaFX.
How can I package it together as an installer?
Or any other ideas is welcome.
Thanks
A:
I made something similar using sockets.
I connect my Electron to my Java application via Socket (nodejs "net library).
I can communicate bidirectional and sending a Java command I can open electron Window.
I think this can be a solution even in your case.
| {
"pile_set_name": "StackExchange"
} |
Q:
jbas015852 could not index class java.lang.IllegalStateException: Unknown tag
This error happens when deploying to a local JBOSS server. Is there a way to resolve this warning?
22:31:22,992 WARN [org.jboss.as.server.deployment] (MSC service thread 1-13) JBAS015852: Could not index class com/company/core/security/AuthRealm.class at /C:/DevTools/jboss-eap-6.3/bin/content/platform-ws-0.1.war/WEB-INF/lib/com.company.platform-platform-core-0.1.jar: java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133
at org.jboss.jandex.Indexer.processConstantPool(Indexer.java:606) [jandex-1.0.3.Final-redhat-2.jar:1.0.3.Final-redhat-2]
at org.jboss.jandex.Indexer.index(Indexer.java:640) [jandex-1.0.3.Final-redhat-2.jar:1.0.3.Final-redhat-2]
at org.jboss.as.server.deployment.annotation.ResourceRootIndexer.indexResourceRoot(ResourceRootIndexer.java:100) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
at org.jboss.as.server.deployment.annotation.AnnotationIndexProcessor.deploy(AnnotationIndexProcessor.java:51) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:159) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1980) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1913) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_31]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_31]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_31]
An explanation of what is going on would be much appreciated, too.
A:
I'm using JBoss EAP 6.3 with patch 6.3.3 but to solve the problem I need to use jandex from JBoss EAP 6.4. I just replace "jandex-1.0.3.Final-redhat-2.jar" for "jandex-1.2.2.Final-redhat-1.jar" in JBoss modules and problem was solved.
There is a issue in JBoss of it, maybe problems with Java 8 or lambda expressions that Jandex can´t index. See this link
This is the link of the issue Bug 1193113
I hope that help you
| {
"pile_set_name": "StackExchange"
} |
Q:
Order Set by attribute String
I want to sort a Set<TailleDetail> by one of its string attributes (mesure), but the only solutions I saw in the internet (TreeSet and Comparator) don't work, can you help me?
My class:
public class TailleDetail {
private Integer id;
private String sexe;
private String mesure;
private Taille Taille;
}
EDIT -
For TreeSet I just try this:
Set<TailleDetail> tailles = new TreeSet<TailleDetail>();
to remplace :
Set<TailleDetail> tailles = new HashSet<TailleDetail>();
And For Comparator I try this :
Set<TailleDetail> tailles = new HashSet<TailleDetail>();
Comparator<TailleDetail> comparatorTaille = new Comparator<TailleDetail>() {
@Override
public int compare(TailleDetail left, TailleDetail right) {
return left.toString().compareToIgnoreCase(right.toString());
}
};
List<TailleDetail> tai = tailleDetailViewManager.search(param, true);
Collections.sort(tai, comparatorTaille);
tailles = new HashSet<TailleDetail>(tai);
A:
The following code should make the trick :
final Set tailleDetails = new TreeSet(new TailleDetailComparator());
tailleDetails.add(...);
public class TailleDetailComparator implements Comparator {
@Override
public int compare(final TailleDetail o1, final TailleDetail o2) {
return o1.mesure.compareTo(o2.mesure);
}
}
Note that comparison is going to be done using the string comparison rules (alphabetically).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to make these queries shorter?
I am just beginning, the following queries work but they seem to long and messy.
How can I make these queries shorter?
Here is my code:
if ($result = $mysqli->query("select bestelling.datum,klant.klant_code,klant.adres,klant.naam,reis.bestemming,reis.klasse,reis.prijs_in_euro,reis.geannuleerd from klant,reis,bestelling where bestelling.bestelling_code = klant.klant_code and klant.klant_code = reis.reis_code"))
if ($stmt = $mysqli->prepare("UPDATE bestelling,klant,reis SET datum = ?, naam = ?, adres = ?, bestemming = ?, klasse = ?, prijs_in_euro = ?
WHERE klant.klant_code=? and bestelling.bestelling_code = klant.klant_code and klant.klant_code = reis.reis_code"))
if($stmt = $mysqli->prepare("SELECT * FROM bestelling,klant,reis WHERE klant.klant_code=? and bestelling.bestelling_code = klant.klant_code and klant.klant_code = reis.reis_code"))
A:
shorter could be not but more clear yes .. you should not use ancient join based on implicit where condition
you should use explicit inner join
if ($result = $mysqli->query("
select bestelling.datum
,klant.klant_code
,klant.adres
,klant.naam
,reis.bestemming
,reis.klasse
,reis.prijs_in_euro
,reis.geannuleerd
from klant
INNER JOIN reis ON klant.klant_code = reis.reis_code
INNER JOIN bestelling ON bestelling.bestelling_code = klant.klant_code
"))
and you could use alias of table name
if ($result = $mysqli->query("
select b.datum
,k.klant_code
,k.adres
,k.naam
,r.bestemming
,r.klasse
,r.prijs_in_euro
,r.geannuleerd
from klant k
INNER JOIN reis r ON k.klant_code = r.reis_code
INNER JOIN bestelling b ON b.bestelling_code = k.klant_code
"))
| {
"pile_set_name": "StackExchange"
} |
Q:
Same query different execution plans
I am trying to optimize performance for a server and this particular query was causing huge reads from database, in turn causing timeout for queries. This query is generated from EF6 in Asp.Net MVC.
Here is the problematic query:
exec sp_executesql N'SELECT
[Project1].[C1] AS [C1],
[Project1].[Date] AS [Date],
[Project1].[AssetID] AS [AssetID],
[Project1].[EventData] AS [EventData]
FROM ( SELECT
[Extent1].[AssetID] AS [AssetID],
[Extent1].[Date] AS [Date],
[Extent1].[EventData] AS [EventData],
1 AS [C1]
FROM [dbo].[Alarm] AS [Extent1]
WHERE ([Extent1].[AssetID] IN (cast(''c6e3142e-5b1f-4a91-90d2-03a504e86ece'' as uniqueidentifier), cast(''4de25e8a-7401-49ae-bd6d-0861d67f0d2f'' as uniqueidentifier), cast(''455e3a5f-1091-4784-9964-0a1a54eaa644'' as uniqueidentifier), cast(''04b46c21-c44f-4b67-b64b-12f2764c0448'' as uniqueidentifier), cast(''a350992b-8548-4bf1-bd22-131c114a5343'' as uniqueidentifier), cast(''98ec1f36-cc54-45d2-a0e3-22aa1b669373'' as uniqueidentifier), cast(''27abcf37-2093-43d5-ae62-2e7b10fe4692'' as uniqueidentifier), cast(''c9f43598-2b9c-47b0-9230-37440e6aea54'' as uniqueidentifier), cast(''c5964caa-5c73-4c0e-bb80-4c1dc7e11039'' as uniqueidentifier), cast(''6ac30678-3876-43c9-b708-61ef19b5ea17'' as uniqueidentifier), cast(''e69d870a-87de-4e3d-b4fc-62c962489a7b'' as uniqueidentifier), cast(''a7c2f407-c605-4491-85fe-66c16fc15586'' as uniqueidentifier), cast(''a38f452e-ee3a-4be7-94ad-99c1474a417f'' as uniqueidentifier), cast(''b0f65616-d5d1-4af9-bffd-9c4b2b7f52e7'' as uniqueidentifier), cast(''3940fed6-9c40-4db6-bdc2-9dc5ef7b49ea'' as uniqueidentifier), cast(''e09f7618-c7d7-414d-b5d7-9ec22b3e9b64'' as uniqueidentifier), cast(''62c91349-d33f-42ed-b16d-a63424acca4a'' as uniqueidentifier), cast(''46812e72-45af-426e-9d72-aafdbcc9c4a7'' as uniqueidentifier), cast(''2a1d2b2a-0471-4f57-adc5-b42a03eb5e01'' as uniqueidentifier), cast(''2797d370-b237-4d2c-bede-b7af67f2b0f4'' as uniqueidentifier), cast(''0c50bb44-133e-4434-b403-c172873564e9'' as uniqueidentifier), cast(''dda75f7a-d366-472e-81b5-c4f3119dd715'' as uniqueidentifier), cast(''cc469264-a706-49c6-961b-d6520437e796'' as uniqueidentifier), cast(''ee2d7ea0-1f94-4cc3-9f64-d8d56374cae5'' as uniqueidentifier), cast(''f7dc6b77-3735-479d-b420-e145d4e3d66f'' as uniqueidentifier), cast(''8a7dbe93-ed1a-49f3-a3d0-e19c6dd4e4ef'' as uniqueidentifier), cast(''b0524a60-f980-4b82-a799-e788a9a4d04b'' as uniqueidentifier), cast(''ceaf8a0b-f410-4f88-9062-e804b76b6e78'' as uniqueidentifier))) AND ([Extent1].[EventCode] = @p__linq__0) AND ([Extent1].[Date] >= @p__linq__1) AND ([Extent1].[Date] <= @p__linq__2) AND (([Extent1].[SiteID] = @p__linq__3) OR (([Extent1].[SiteID] IS NULL) AND (@p__linq__3 IS NULL)))
) AS [Project1]
ORDER BY [Project1].[Date] DESC',N'@p__linq__0 int,@p__linq__1 datetime2(7),@p__linq__2 datetime2(7),@p__linq__3 uniqueidentifier',@p__linq__0=1799,@p__linq__1='2018-04-22 10:00:00',@p__linq__2='2018-04-23 10:00:00',@p__linq__3='B02A51FE-2248-E611-A64E-782BCB72ACED'
go
So what I did was remove the parameters from query and run it as a single unit like this.
select * from ( SELECT 1 as c1, [Extent1].[Date] AS [Date],
[Extent1].[AssetID] AS [AssetID],
[Extent1].[EventData] AS [EventData]
FROM [dbo].[Alarm] AS [Extent1]
WHERE ([Extent1].[AssetID] IN (cast('c6e3142e-5b1f-4a91-90d2-03a504e86ece' as uniqueidentifier), cast('4de25e8a-7401-49ae-bd6d-0861d67f0d2f' as uniqueidentifier), cast('455e3a5f-1091-4784-9964-0a1a54eaa644' as uniqueidentifier), cast('04b46c21-c44f-4b67-b64b-12f2764c0448' as uniqueidentifier), cast('a350992b-8548-4bf1-bd22-131c114a5343' as uniqueidentifier), cast('98ec1f36-cc54-45d2-a0e3-22aa1b669373' as uniqueidentifier), cast('27abcf37-2093-43d5-ae62-2e7b10fe4692' as uniqueidentifier), cast('c9f43598-2b9c-47b0-9230-37440e6aea54' as uniqueidentifier), cast('c5964caa-5c73-4c0e-bb80-4c1dc7e11039' as uniqueidentifier), cast('6ac30678-3876-43c9-b708-61ef19b5ea17' as uniqueidentifier), cast('e69d870a-87de-4e3d-b4fc-62c962489a7b' as uniqueidentifier), cast('a7c2f407-c605-4491-85fe-66c16fc15586' as uniqueidentifier), cast('a38f452e-ee3a-4be7-94ad-99c1474a417f' as uniqueidentifier), cast('b0f65616-d5d1-4af9-bffd-9c4b2b7f52e7' as uniqueidentifier), cast('3940fed6-9c40-4db6-bdc2-9dc5ef7b49ea' as uniqueidentifier), cast('e09f7618-c7d7-414d-b5d7-9ec22b3e9b64' as uniqueidentifier), cast('62c91349-d33f-42ed-b16d-a63424acca4a' as uniqueidentifier), cast('46812e72-45af-426e-9d72-aafdbcc9c4a7' as uniqueidentifier), cast('2a1d2b2a-0471-4f57-adc5-b42a03eb5e01' as uniqueidentifier), cast('2797d370-b237-4d2c-bede-b7af67f2b0f4' as uniqueidentifier), cast('0c50bb44-133e-4434-b403-c172873564e9' as uniqueidentifier), cast('dda75f7a-d366-472e-81b5-c4f3119dd715' as uniqueidentifier), cast('cc469264-a706-49c6-961b-d6520437e796' as uniqueidentifier), cast('ee2d7ea0-1f94-4cc3-9f64-d8d56374cae5' as uniqueidentifier), cast('f7dc6b77-3735-479d-b420-e145d4e3d66f' as uniqueidentifier), cast('8a7dbe93-ed1a-49f3-a3d0-e19c6dd4e4ef' as uniqueidentifier), cast('b0524a60-f980-4b82-a799-e788a9a4d04b' as uniqueidentifier), cast('ceaf8a0b-f410-4f88-9062-e804b76b6e78' as uniqueidentifier))) AND ([Extent1].[EventCode] = 1799) AND ([Extent1].[Date] >= '2018-04-22 10:00:00') AND ([Extent1].[Date] <= '2018-04-23 10:00:00') AND (([Extent1].[SiteID] = 'B02A51FE-2248-E611-A64E-782BCB72ACED') OR (([Extent1].[SiteID] IS NULL) AND ('B02A51FE-2248-E611-A64E-782BCB72ACED' IS NULL)))
) as proeject1 order by proeject1.Date desc
These are the respective IO costs for queries.
(3721 row(s) affected)
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Alarm'. Scan count 5, logical reads 69032, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Better plan
(3721 row(s) affected)
Table 'Alarm'. Scan count 28, logical reads 564, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Actual execution plan with good performance
Actual execution plan with bad performance
Indexes:
CREATE NONCLUSTERED INDEX [IX_Alarm_Lat]
ON [dbo].[Alarm] ( [lat] ASC )
INCLUDE ( [AssetID], [Date])
CREATE NONCLUSTERED INDEX [IX_AlarmEventDate]
ON [dbo].[Alarm] ( [AssetID] ASC, [EventCode] ASC, [Date] ASC, [Ended] ASC )
INCLUDE ( [ID], [EventData], [No], [AlarmTS], [ResetID], [lat], [lon],
[StartTime], [SiteID], [AlarmStatus])
I have tried:
Option recompile
DBCC FREEPROCCACHE
sp_updatestats
Rebuilding corresponding index
But query always picks this plan causing a huge load on server disk.
I have read Slow in the Application, Fast in SSMS? - Understanding Performance Mysteries by Erland Sommarskog but it hasn't answered my question:
I have two queries, both running in SSMS, that have different performance. The main difference is that one is parameterized and the other is a plain query. I totally understand the differences between the queries, but my question is about picking the wrong index.
A:
The first query calls parameterized dynamic SQL which makes it eligible for parameter sniffing:
<ParameterList>
<ColumnReference Column="@p__linq__3" ParameterCompiledValue="{guid'B02A51FE-2248-E611-A64E-782BCB72ACED'}" ParameterRuntimeValue="{guid'B02A51FE-2248-E611-A64E-782BCB72ACED'}" />
<ColumnReference Column="@p__linq__2" ParameterCompiledValue="'2018-04-23 10:00:00.0000000'" ParameterRuntimeValue="'2018-04-23 10:00:00.0000000'" />
<ColumnReference Column="@p__linq__1" ParameterCompiledValue="'2018-04-22 10:00:00.0000000'" ParameterRuntimeValue="'2018-04-22 10:00:00.0000000'" />
<ColumnReference Column="@p__linq__0" ParameterCompiledValue="(1799)" ParameterRuntimeValue="(1799)" />
</ParameterList>
The second query doesn't use dynamic SQL. It has hardcoded values instead of parameters. The question, as I understand it, is why does SQL Server pick a less efficient plan with dynamic SQL even with sniffed parameter values that match the other query? This is a reasonable question.
First let me convince you that sometimes SQL Server must give different plans. Even with parameter sniffing, SQL Server still must cache a plan that's safe for all possible parameter values. For a simple example consider the following query:
CREATE TABLE #DEMO (
ID INT NOT NULL,
PRIMARY KEY (ID)
);
exec sp_executesql N'
SELECT *
FROM #DEMO
WHERE (@id IS NULL OR id = @id)'
, N'@id int'
, @id=1;
We get parameter sniffing:
<ParameterList>
<ColumnReference Column="@id" ParameterDataType="int" ParameterCompiledValue="(1)" ParameterRuntimeValue="(1)" />
</ParameterList>
But the query plan uses a scan:
A seek would be more efficient (if the table had any data). If I try to force a seek:
exec sp_executesql N'
SELECT *
FROM #DEMO WITH (FORCESEEK)
WHERE (@id IS NULL OR id = @id)'
,N'@id int'
,@id=1;
I get the following error:
Msg 8622, Level 16, State 1, Line 15 Query processor could not produce
a query plan because of the hints defined in this query. Resubmit the
query without specifying any hints and without using SET FORCEPLAN.
The cached plan needs to be valid for all possible parameter values. If the parameter has a value of NULL then a seek cannot be performed. Therefore, a scan is the only safe choice. If I use literal values:
SELECT *
FROM #DEMO
WHERE (1 IS NULL OR id = 1);
The query optimizer can simplify away the impossible part of the predicate (1 IS NULL) and I get a seek:
As far as I can tell you aren't running into this situation with your query. The point of this example is to show that you can't always expect to get the same query plan with the type of transformation you applied to your original query.
For your particular query I think the problem has to do with the data types of the parameters. When you write SQL with hardcoded parameter values you might be inadvertently using different data types from what you hardcoded. In the dynamic SQL version of the query you have @p__linq__1 and @p__linq__2 defined as datetime2(7). Does that match the column definition for Alarm.[Date]? If not then you might be ineligible for an index seek. Your query with literal values doesn't cast the dates to datetime2(7), so there's definitely a difference there. I suspect that this is the cause of your issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento: limit product max quantity to 1 per order. quantity 2 = 2 orders
Is it anyhow possible to limit specific products in Magento to a max quantity of one per order? This means the user can only order one product at a time. If he wants to order the product twice he has to do a second order. This is very important for me for the later order workflow.
Thx for your help, I appreciate it!
Kind regards, Manu
A:
Yes, you can limit the maximum quantity of a product in the shopping cart by editing the value on the Inventory tab when editing a product. See screenshot below. In your case, you'd want to uncheck Use Config Settings and set the value to 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Zend Date DST Bug: Test whether a date is a "time change" date
I found a workaround for Zend Date's DST Bug, but the workaround introduces another bug. The workaround simply sets the time twice. This introduces another bug, if the resulting date crosses the date boundary, the the day get incremented or decremented.
I am wondering if there's a way to determine that the date at hand is a "time change" date, so that I can come up with a solid workaround to the Zend Date DST bug.
A:
It turns out that PHP's function localtime() returns whether or not the date is in DST. I've used that info update my sub-classed version of Zend_Date::setTime(). I've updated my post for Zend Date DST Bug to include this in the solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get result of the previous action
Hi Inside rails console you can get the result of the previous operation with _ Is there any way to do such a thing inside ruby program?
A:
everything in Ruby is an object, so think about it, if any returned object is not assigned a reference then it will be marked for garbage collection, so no there is no way other than to assign a returned object to a variable!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set relative uri from xaml in wpf?
So I am wondering where the relative uri should be set relative to. I had assumed it was the main project.
I have the image stored under a folder images. The images folder is directly under the project DaedalusGraphViewer under the solution which also has the same name (DaedalusGraphViewer).
I had assumed that the relative uri was relative to the project, but I don't seem to be having any luck. Alternative ideas such as doing it from code behind are also welcome. I have done it from code behind before so I can probably figure that out since I will be able to debug it better there, but I would prefer to just do it in xaml.
I am using
<ResourceDictionary Source="DaedalusGraphViewer/ResourceDictionaries/GraphViewerBrushes.xaml" />
to do the same thing elsewhere, so I don't see what I'm doing wrong.
<Button
Height="50"
VerticalAlignment="Top"
>
<Image Width="50" Height="50" Source="Images/zoominbutton.bmp" Stretch="Fill"/>
</Button>
edit: still no luck, not sure what I'm doing wrong.
i've revised the code to use a much smaller test case.
ideally i would like to be able to set the image path from xaml, but for now i'm trying code behind just to see if I can figure out anything that will make it work.
<Window
x:Class="TestApp.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
Loaded="Window_Loaded"
>
<Canvas x:Name="MainCanvas">
<!--<Image x:Name="ImageSource2" Width="50" Height="50" Source="/DaedalusGraphViewer;component/images.jpg" Stretch="Fill"/>-->
<!--<Image x:Name="imagetest" Stretch="Fill" Width="50">
<Image.Source>
<BitmapImage
DecodePixelWidth="200"
UriSource="/Images/images.jpg"/>
</Image.Source>
</Image>-->
<!--<Image Width="50" Source="../../Images/images.jpg" Stretch="Fill"/>-->
</Canvas>
</Window>
namespace TestApp
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Image i1 = new Image();
Uri relativeuri = new Uri("/DaedalusGraphViewer;component/images.jpg", UriKind.Relative);
BitmapImage bmi = new BitmapImage(relativeuri);
i1.Source = bmi;
MainCanvas.Children.Add(i1);
}
}
}
My goal for now is just to display an image on the main canvas. When do I need to use an absolute uri and when can I use a relative Uri. I have read lots of examples of xaml using relative uris so I thought that would be possible.
A:
Replace YOURAPPNAME
<Image Width="50" Height="50" Source="/YOURAPPNAME;component/Images/zoominbutton.bmp" Stretch="Fill"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove that $U=Y - E[Y|X]$ and $X$ are uncorrelated
Let $U = Y - E[Y|X]$. How can I prove that $U$ and $X$ are not correlated?
I've been doing a lot of things but when I calculate $\text{cov}(U,X)$ I finish with $EXY - EXEY$ and not $0$ which would be the result.
Any help, guys?
Thanks
A:
Hints:
Verify that $E(X Y \mid X) = X E(Y \mid X)$.
Use the tower property of conditional expectation to show that $$ E(Y) = E \big[ E(Y \mid X) \big].$$
Conclude from Step 2 that $E(U)=0$.
Use Step 1+2 and the linarity of the expectation to prove that $$E(UX) = 0.$$
Combining Step 3 and 4 yields $$E(UX) = E(U) E(X),$$ i.e. $U$ and $X$ are uncorrelated.
Remark: You will need some integrability conditions on $X$ and $Y$ to ensure that the (conditional) expectations and the covariance are well-defined.
| {
"pile_set_name": "StackExchange"
} |
Q:
Выравнивание блоков внутри таблицы
Есть таблица из 4 столбцов, внутри каждого блока столбцов есть изображение, в последнем столбце кроме изображений есть текстовые строки, их может быть произвольное количество. Как сделать так, что бы вне зависимости от количества строк в последнем столбце таблицы, изображения во всех столбцах были на одном уровне ?
<table style="height: 59px;" border="1" width="477">
<tbody>
<tr>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td>
<p>Рыба</p>
<p>Рыба<img alt="" width="114" height="86" /></p>
</td>
</tr>
<tr>
<td style="width: 112px;"><img alt="" width="114" height="86" /></td>
<td style="width: 112px;"><img alt="" width="114" height="86" /></td>
<td style="width: 112px;">
<p><img alt="" width="114" height="86" /></p>
</td>
<td>
<p>Рыба<img alt="" width="114" height="86" /></p>
</td>
</tr>
<tr>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td>
<p>Рыба<img alt="" width="114" height="86" /></p>
</td>
</tr>
</tbody>
</table>
A:
vertical-align: bottom;
td {
vertical-align: bottom;
}
<table style="height: 59px;" border="1" width="477">
<tbody>
<tr>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td>
<p>Рыба</p>
<p>Рыба<img alt="" width="114" height="86" /></p>
</td>
</tr>
<tr>
<td style="width: 112px;">
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p><img alt="" width="114" height="86" /></p>
</td>
<td>
<p>Рыба<img alt="" width="114" height="86" /></p>
</td>
</tr>
<tr>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td style="width: 112px;">
<p> </p>
<p><img alt="" width="114" height="86" /></p>
</td>
<td>
<p>Рыба<img alt="" width="114" height="86" /></p>
</td>
</tr>
</tbody>
</table>
| {
"pile_set_name": "StackExchange"
} |
Q:
WP ACF auto create shortcodes from multiple fields
GOAL
I currently have an acf field group with some fields for generic data like phonenumber, email, etc. (all simple text fields).
My goal is to have one function that will loop over all the fields and create a shortcode based on their respective name/label.
EDIT: PROGRESS
I think I am getting closer, simplified the whole thing and I believe I am on the right path..
I attached the field group to a post and if I log them like so:
$testing = get_field_objects(22);
do_action( 'php_console_log', $testing );
I get all the names, values etc. With the help of another snippet I found the shortcodes seem to be at least dynamic since they all stop showing just that there is no value somehow so it all stays blank.
This is the function now:
$hlfields = get_field_objects( 22 );
foreach ( $hlfields as ['name' => $name, 'value' => $value] ) {
${"{$name}_fn"} = function() {
$field = get_field($name, 22);
return $field;
};
add_shortcode($name, ${"{$name}_fn"});
}
Original attempt, not working and over complicated:
I currently have an acf field group with some fields for generic data like phonenumber, email, etc. (all simple text fields).
To be able to insert them all easily using a shortcode, I create one for each field like so:
function adresse_shortcode( $adresse ) {
$adresse = get_field( "adresse", 'option' );
return $adresse;
}
add_shortcode('adresse', 'adresse_shortcode');
While this works fine, I feel like I am repeating myself unnecessarily and also I need to add a function whenever I add a new field.
My goal is to have one function that will loop over all the fields and create a shortcode based on their respective name/label.
I found this snippet to get all fields of a field group by ID:
function get_specifications_fields() {
global $post;
$specifications_group_id = 13; // Post ID of the specifications field group.
$specifications_fields = array();
$fields = acf_get_fields( $specifications_group_id );
foreach ( $fields as $field ) {
$field_value = get_field( $field['name'] );
if ( $field_value && !empty( $field_value ) ) {
$specifications_fields[$field['name']] = $field;
$specifications_fields[$field['name']]['value'] = $field_value;
}
}
return $specifications_fields;
}
But I can't figure out how to create the shortcodes now, I have been trying everything I could think of along these lines:
function adresse_shortcode( $value ) {
$specifications_fields = get_specifications_fields();
foreach ( $specifications_fields as $name => $field ) {
$value = $field['value'];
$label = $field['label'];
$name = $field['name'];
return $name;
}
add_shortcode($value, 'adresse_shortcode');
}
I am not well versed in PHP so I am sure it's all sorts of wrong but I have been trying to figure it out for hours and was hoping someone might be able point me in the right direction.
A:
Here's an example using anonymous functions that should do the trick
$hlfields = get_field_objects( 22 );
foreach ( $hlfields as ['name' => $name, 'value' => $value] ) {
$cb = function() use ($name) {
$field = get_field($name, 22);
return $field;
};
add_shortcode( $name, $cb );
}
Here's the sources i referred to while answering: Dynamic function name in php, Dynamic shortcodes and functions in WordPress, PHP: Variable functions
| {
"pile_set_name": "StackExchange"
} |
Q:
Language files and translation in EE 3
i'm trying to change the names of the months from english to greek language in EE3... is there any file that i can modify somewhere in the installation?
Thanks in advance
A:
You can modify the languages used by EE using language packs. However there does not (yet) appear to be a Greek language pack. The language packs are open-source and so you maybe can contribute a suitable pack for Greek to the shared activity - it is located on the Ellis Labs' Github pages. There are also tools you can use to help with the translation of core elements of the EE system - more details here.
HTH
| {
"pile_set_name": "StackExchange"
} |
Q:
$a_{n+1}=a_n-a^2_n$ show the recursion sequence is convergent and find its limit
Let $a_1=\frac 2 3 , \ a_{n+1}=a_n-a^2_n$ for $n\ge 1$.
Show the sequence is convergent and find its limit.
In order to show convergence, I need to show that it's monotone and bounded.
Showing it's bounded: $0\le a_{n+1}\le 1$ by induction, for $n=1$ it's true, so suppose it's true for $n$ and prove for $n+1$ so: $a_{n+1} = a_n-a^2_n\le 1$, by the induction hypothesis, define $0<b<1$ so: $a_{n+1} \le 1-b \Rightarrow 0\le a_{n+1} \le 1$.
I tried the usual method of showing the sequence is monotone: $\dfrac {a_{n+1}}{a_n}\ge 1$ but that doesn't lead anywhere.
As for the limit, since $\displaystyle\lim_{n\to\infty} a_n=\lim_{n\to\infty} a_{n+1} = L$ so: $L=L-L^2\Rightarrow L^2=0 \Rightarrow L=0$.
Other than showing the sequence is monotone, please let me know if I missed anything regarding formality.
A:
Clearly if $0<a_n<1$ then $0<a_n(1-a_n)=a_{n+1}<a_n<1$
$\{a_n\}$ is bounded below by $0$ and decreasing. Hence converges to $l$ such that $l=l-l^2\Rightarrow l=0$
| {
"pile_set_name": "StackExchange"
} |
Q:
Incompatible types when using GSON
First: this is my first time using GSON.
Trying to parse some JSON, I got "incompatible types"...
Gson gson = new Gson();
PlayerData data = gson.fromJson(response, PlayerData.class); // Incompatible types...
PlayerData is an inner class:
class PlayerData {
public Point position;
public String mapname;
public int level;
public PlayerData() {}
}
What causes it? In the GSON docs there is clearly a method public <T> T fromJson(String json,
Class<T> classOfT)
throws JsonSyntaxException and I am doing at (AFAIK) just like Google in it's GSON User Guide.
Edit:
XCode was doing something strange, when I tried to compile this with Terminal everything worked, except for my request to the server, what resulted in a couple of NPE's, because response remained empty. Thanks to maaartinus I learned that there shouldn't be an compiler error so I tried to compile it without XCode.
A:
Try making your inner class static or you'll need a custom InstanceCreator for it as stated in the Gson User Guide
Gson can not automatically deserialize the pure inner classes since
their no-args constructor also need a reference to the containing
Object which is not available at the time of deserialization. You can
address this problem by either making the inner class static or by
providing a custom InstanceCreator for it.
A:
For me it compiles, but I had to replace GSON by Gson. Either you were sloppy when writing this question or you're using some "GSON" I've never heard about.
Is your response a String???
Once you get it running, you'll need the answer by Vrushank Desai.
| {
"pile_set_name": "StackExchange"
} |
Q:
It's all Greek to me
Something doesn't just add up.
And this is barely a puzzle.
How can everything be so important?
Each line must provide a clue.
Maybe there's an alternate way to find the answer...
To what this OP is craving.
HINT:
The sum of the parts is equal to the whole.
HINT 2:
Something does actually add up. But if at first you don't succeed, try again.
HINT 3:
Lines 1 and 3 require only one word each.
HINT 4:
There happens to be an entirely different and unrelated answer from what I had in mind that I will accept as well. By happenstance I stumbled upon it and it nearly fits perfectly if you ignore HINT 3.
A:
I think the answer is
SETS
Considering only the first para is relevant-
Something doesn't add up ... Plus this is barely a puzzle . How can everything be so important ? There must be an alternate way to find the answer ...
Assuming there is a Morse Code hidden in the para. And, ?=Dash & .=DOT
we get ... . - ... -> SETS So OP is craving for SETS :)
A:
I don't have hard evidence, but I think the OP is craving
Pie
Reasoning below, admittedly, this is essentially guesswork.
The terms "Add up" and "Plus" point to something mathematical.
The question asks about a craving, indicating food.
Considering the title, "It's all Greek to me", we're looking for something Greek, mathematical and alimentary.
Therefore, Pi, as a Greek letter, a mathematical constant, and phonetically, a dish, fits pretty well.
A:
All the clues seem to point towards it being:
Sigma (a greek letter)
For the reasons that
The symbol $\Sigma$ is used for summation in mathematics, also from hint number two "If you first don't succeed" seems to be talking about error, the lower case sigma $\sigma$ is usually used to denote errors.
However I'm not sure what this ties into as far as something the OP desires unless:
They want to be 18 (sigma is the 18th letter of the greek alphabet or make-up brushes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dojo populate combo box widget dynamically
Could someone please explain to me why this simple straight forward code isnt working,
var serviceStore = new dojo.data.ItemFileWriteStore({
data: {identifier: "serviceCode",items:[]}
});
//jsonObj is a json object that I obtain from the server via AJAX
for(var i = 0; i<jsonObj.length;i++){
serviceStore.newItem({serviceCode: jsonObj[i]});
}
var serviceFilterSelect = dojo.byId('serviceSelect');
serviceFilterSelect.store = serviceStore;
There is no error at all displayed but my combobox with the id "serviceSelect" doesn't display any options, the combo is declared in the html section of my code,
<input dojoType = "dijit.form.ComboBox" id="serviceSelect"></input>
Any pointers towards the right direction will be much appreciated.
A:
First of all you should use dijit.byId to get dojo widget instead of dojo.byId.
Also every item in jsonObj should contains field "name". This field will be displayed in combobox. E.g:
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.ComboBox");
var storeData = {
identifier: 'serviceCode',
items: []
}
var jsonObj = [{
serviceCode: 'sc1',
name: 'serviceCode1'
},
{
serviceCode: 'sc2',
name: 'serviceCode2'
}]
dojo.addOnLoad(function () {
var serviceStore = new dojo.data.ItemFileWriteStore({ data: storeData });
for (var i = 0; i < jsonObj.length; i++) {
serviceStore.newItem(jsonObj[i]);
}
var serviceFilterSelect = dijit.byId('serviceSelect');
serviceFilterSelect.attr('store', serviceStore);
});
And HTML:
<select dojotype="dijit.form.ComboBox" id="serviceSelect" ></select>
It seems that it works.
| {
"pile_set_name": "StackExchange"
} |
Q:
Boost assign list_of for a structure
I have a question regarding the boost::assign_list
struct AClass{
AClass();
};
struct BClass{
BClass();
};
typedef AInfo{
string infoname;
AClass m_nAClass;
BClass m_nBClass;
};
typedef list<AInfo> listOfAInfo;
listOfAInfo m_mlistOfAInfo =
boost::assign::list_of("AInfoName1", AClass(), BClass() );
How do I initialise the array of map_lists for the structs. This is a version of the legacy code, where the some classes are defined as structs with the constructors.
thanks,
pdk
A:
I'm not sure what "where the some classes are defined as structs with the constructors" means.
What I see is aggregates, which can be initialized with aggregate initializer syntax even in C++03 (or C++98 IIRC):
AInfo obj = { "AInfoName1", AClass(), BClass() };
Perhaps you can just use
typedef std::map<int, AInfo> listOfAInfo;
listOfAInfo m_mlistOfAInfo =
boost::assign::map_list_of
( 1, { "AInfoName1", AClass(), BClass() })
( 2, { "AInfoName2", AClass(), BClass() });
or
typedef std::list<AInfo> listOfAInfo;
listOfAInfo m_mlistOfAInfo =
boost::assign::list_of
( AInfo { "AInfoName1", AClass(), BClass() })
( AInfo { "AInfoName2", AClass(), BClass() });
Here it is Live On Coliru (c++11).
It does seem that you cannot use the uniform initiliazation syntax (AInfo {...}) which is subtly different from an aggregate initializer = { ... }) with Boost Assign, because the compiler doesn't know what you're initializing, unlike the obj declaration shown above.
| {
"pile_set_name": "StackExchange"
} |
Q:
docker-compose remove services on exit (or recreate on start)
I have docker-compose file that runs 4 services:
web
db
redis
selenium
I would like the containers of services redis and selenium to always start fresh when I execute docker-compose, while preserving the state of web and db.
I don't mind if this is achieved destroyng the containers on exit or recreating new ones on start. At the moment I run this command:
docker-compose rm selenium && docker-compose rm redis && docker-compose up
I would prefer to have the same behavior using the docker-compose.yml file, instead of the command line.
A:
You can use docker-compose --force-recreate flag when executing up, to always recreate containers and configure volumes to persist databases data (on a local directory or a docker volume).
| {
"pile_set_name": "StackExchange"
} |
Q:
Does a deleted constructor in base class influences on child class?
I deleted a copy constructor in base class but I can't get if the compiler will create an implicit copy constructor in child classes? Or does a deleted constructor in the base class prevent it?
template <typename val_t>
class exp_t {
public:
using vals_t = std::vector<val_t>;
exp_t() {}
exp_t(const exp_t<val_t> &) = delete;
exp_t(exp_t &&) = default;
virtual ~exp_t() {}
exp_t<val_t> &operator=(const exp_t<val_t> &) = delete;
exp_t<val_t> &operator=(exp_t<val_t> &) = delete;
exp_t<val_t> &operator=(exp_t &&) = default;
};
template <typename val_t>
class fact_t: public exp_t<val_t> {
using vals_t = std::vector<val_t>;
val_t m_value;
public:
fact_t(val_t &&value) : m_value{std::forward<val_t>(value)} {}
fact_t(fact_t &&) = default;
};
Will fact_t have an implicit copy constructor? (GCC 7)
A:
No, as the default copy constructor would call the parent's copy constructor (which is deleted), this won't work.
Why didn't you simply test it:
int main() {
auto x = fact_t<int>(5);
auto y = x;
}
Result:
copytest.cpp: In function 'int main()':
copytest.cpp:32:14: error: use of deleted function 'fact_t<int>::fact_t(const fact_t<int>&)'
auto y = x;
^
copytest.cpp:21:7: note: 'fact_t<int>::fact_t(const fact_t<int>&)' is implicitly declared as deleted because 'fact_t<int>' declares a move constructor or move assignment operator
class fact_t: public exp_t<val_t> {
^~~~~~
| {
"pile_set_name": "StackExchange"
} |
Q:
Singleton with class in ES6
why we get true here, I understand the concept of the singleton, but anyway myCount1 and myCount2 are assigned to the same object, but two objects cant be equal anyway, so why we get true in the end, here is the code:
class Counter{
constructor(){
if(typeof Counter.instance==="object"){
return Counter.instance;
}
this.count=0;
Counter.instance= this;
return this;
}
getCounter(){
return this.count;
}
increaeCounter(){
return this.count++;
}
}
const myCount1 = new Counter();
const myCount2 = new Counter();
console.log(myCount1===myCount2) //true , why??
A:
Because they refer to the same object in memory (thats what a Singleton is for). If you have
let a = {}
let b = {}
Then they are not ===.
Its like referential equality in java.
String a ="ab";
String b = StringBuilder("ab").toString();
Then a != b
| {
"pile_set_name": "StackExchange"
} |
Q:
Can we improve the current way spoilers are written?
I've noticed that when hovering over a question/answer with spoilers, the text displayed will instantly pop up, and will give no warning of "spoilers" until you hover over it.
Can we implement a feature that requires the user to either click on the box to show spoilers? Or in other ways, show a warning (similar to how Steam shows Spoilerized screenshots) before users click on it?
Based on Robotnik's suggestions, I believe we could setup the spoiler tag this way:
Before clicking on spoilers box:
Possible spoilers, click to read at your own risk
After clicking on spoilers box:
In the end of Generic Game X, Y dies, and you resort to doing Z. Then Θ happens.
A:
I personally believe you should have to click to view spoilers, as using a tiny touch-pad I sometimes accidentally mouse-over spoiler areas. This would be an area where having text as you suggested would be a good idea, saying something like "Click to view this spoiler"
Apart from that, perhaps we could make the spoiler area's colour darker, if it isn't showing up on people's screens? (as the comments on this question would suggest). I don't have a problem with the current colour. (but please comment if you can't see it).
| {
"pile_set_name": "StackExchange"
} |
Q:
Booting from PCIe SSD on Dell T3600
One of our local workstations SSD is severely slow. I can't seem to find much resources on whether or not the latest BIOS supports booting Windows Server from a PCIe SSD. If it doesn't, is there a way to force it to boot -- like grub on a USB drive or something?
A:
Don't waste your SATA or SAS port for boot SSD! Boot from USB stick and keep expansion ports for capacity & performance tiers!
https://www.starwindsoftware.com/blog/how-to-create-bootable-windows-server-2016-usb-thumb-drive-for-installing-os
https://www.starwindsoftware.com/blog/create-an-esxi-6-5-installation-usb-under-two-minutes
P.S. You might want to boot ESXi and Linux from mirrored SD cards if you have such an equipment on-board, but don't do that with Hyper-V or Windows Server: they will burn replacement cells very soon.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python3: change one character in a list of characters
I want to read a string from stdin and append this string to a list. Then I want to change one character at a time and append the new strings to the same list.
pat=sys.argv[1]
dummy1=list(str(pat))
myList=[]
list.append(pat)
c=0
for letter in dummy1:
if dummy1[c]=="A":
dummy1[c]=="C"
depp=''.join(dummy1)
myList.append(depp)
c+=1
print(myList)
but when I try this, I only get a list containing my original string as often as I looped. What did I miss?
A:
Try This ( in line 8 you should replace == with = ):
pat = "SALAM" # Your Input Data
dummy1 = list(str(pat))
my_list = [pat]
c = 0
for letter in dummy1:
if dummy1[c] == "A":
dummy1[c] = "C"
join_list = ''.join(dummy1)
my_list.append(join_list)
c += 1
last_data = my_list[len(my_list)-1]
print(last_data)
| {
"pile_set_name": "StackExchange"
} |
Q:
Latest Post by Date
How can I achieve something similar to this:
http://anidemon.com/latest-episodes/
Latest Posts are organized under header of the day. I don't about the "View" count.
How can I do this?
A:
Virendar,
Using get_posts() should solve your problem as follows...
<ul>
<?php
$myposts = get_posts('orderby=date&order=DESC');
$tempdate = '';
foreach($myposts as $post) {
$postDate = strtotime( $post->post_date );
if ($tempdate == '' || $postDate < $tempdate) {
$tempdate = $postDate;
echo '<h3>Display Date Title here</h3>';
}
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php } ?>
</ul>
Hope this helps! Please note I haven't included any CSS formatting.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does my tunneled IPv6 connectivity drop after a short period of time?
I correctly setup a Hurricane Electric tunnel on a CentOS 6.5 VPS server (KVM). I use CSF (ConfigServer Security & Firewall) which acts as a wrapper for iptables and ip6tables, the default services themselves are disabled.
Tunnel interface: sit1
WAN interface: eth0
I have a IPv6 address set on the WAN, along with several IPV6ADDR_SECONDARIES.
Initially connectivity is great. I can use ping6/traceroute6 to ping and trace IPv6 sites. However after a short period of time IPv6 connectivity goes down, all IPv6 requests timeout and no communication can be made via IPv6 any longer.
If I flush the firewall i.e. disable it, everyting works again, if I restart the firewall, IPv6 connectivity works for a short while before going down again. It seems unless I flush the firewall connectivity is completely blocked until doing so.
What could be the reason for this? Do I need to add specific firewall entries in addition to the configuration provided by CSF, or am I experiencing problems because IPv6 connectivity is coming over a tunnel interface and then being accessed via the WAN (eth0)?
Thanks for any help the community can provide!
A:
It appears I overlooked my iptables firewall, the problem doesn't appear to be with ip6tables but actually proto 41 being blocked which is required for 6in4 to work, I added the following to my csfpre.sh file:
iptables -t filter -I INPUT -p 41 -j ACCEPT
iptables -t filter -I OUTPUT -p 41 -j ACCEPT
Connectivity appears to be maintained now.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java adding ArrayList to ArrayList> replaces all elements of the ArrayList of ArrayLists
I apologize for the long title, please let me know if you can think of a better one!
What I am doing is trying to create an ArrayList of ArrayLists and adding ArrayLists to it one by one. The two AL<AL<I>>s that I have are called triangle and square, and I am adding AL<I>s via the addToList() method- adding the AL<I> called temp to the appropriate AL<AL<I>>. There doesn't seem to be a problem with temp, but after I run the entire method figurateNumbers(), my AL<AL<I>>s only contain [98,70], the last temp to be added. The code is below:
import java.util.ArrayList;
import java.util.Iterator;
public class problem
{
public static ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>();
public static ArrayList<ArrayList<Integer>> square = new ArrayList<ArrayList<Integer>>();
public static ArrayList<Integer> temp = new ArrayList<Integer>();
public static void figurateNumbers()
//Inserts into individual arraylists, numbers, all figurate numbers square : octagonal
{
for (int ii = 1; ii < 141; ii++)
{
if ((ii * ii >= 1000) & (ii * ii < 10000))
addToList(ii * ii , square);
if (((ii * ii + ii) / 2 >= 1000) & ((ii * ii + ii) / 2 < 10000))
addToList((ii * ii + ii) / 2 , triangle);
}
}
public static void addToList(int num, ArrayList<ArrayList<Integer>> list)
//Splits the two parts of the number and inserts the arraylist into the proper arraylist
{
temp.clear();
int numInt_one = Integer.parseInt(String.valueOf(num).substring(0,2));
int numInt_two = Integer.parseInt(String.valueOf(num).substring(2,4));
temp.add(numInt_one);
temp.add(numInt_two);
list.add(temp);
}
public static void main (String [] args)
{
figurateNumbers();
System.out.println(triangle.size());
System.out.println(square.size());
Iterator<ArrayList<Integer>> it = square.iterator();
while(it.hasNext())
{
ArrayList<Integer> obj = it.next();
System.out.println(obj);
}
System.out.println(triangle.get(25));
}
}
Any help would be greatly appreciated, whether it's regarding the issue at hand or my use of these data structures.
A:
You are not creating a new Instance of temp everytime you call below, the same list is added into the list, which you are clearing.Remember it is the reference of the list which is added.
public static void addToList(int num, ArrayList<ArrayList<Integer>> list)
//Splits the two parts of the number and inserts the arraylist into the proper arraylist
{
// temp.clear();// this is the issue do below
ArrayList<Integer> temp = new ArrayList<Integer>();
int numInt_one = Integer.parseInt(String.valueOf(num).substring(0,2));
int numInt_two = Integer.parseInt(String.valueOf(num).substring(2,4));
temp.add(numInt_one);
temp.add(numInt_two);
list.add(temp);
}
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.