text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
wcf - customizing service document
I am new to WCF programming and its syndication classes etc. I am trying to produce a AtomPub service document programmatically when someone tries to access root address of my service. I am able to do that only to some extent using ServiceDocument, ResourceCollectionInfo, Workspace classes -
<service>
<app:workspace>
<a10:title type="text">Sample Repository</a10:title>
<app:collection href="http://some_url">
<a10:title type="text">Root Collection</a10:title>
</app:collection>
</app:workspace>
</service>
However I would like to add some custom attributes and elements as can be seen below. Please notice the xmlns attributes, cmisra elements etc.
<service
xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:app="http://www.w3.org/2007/app"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/">
<workspace>
<atom:title>Sample Repository</atom:title>
<collection href="http://some_url">
<atom:title>Root Collection</atom:title>
<cmisra:collectionType>root</cmisra:collectionType>
</collection>
</workspace>
</service>
There is nothing much available on msdn website or elsewhere. Any inputs on how to achieve this would be appreciated.
Thanks!
Thanks.
A:
The ResourceCollectionInfo class has two properties ElementExtensions and AttributeExtensions which can be used to customize the serialization of a ResourceCollectionInfo. Please note that most of the syndication elements have those extensions, which work with both the RSS and Atom formatters.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set a specific fixed IP address when I create a docker machine or container?
When I create my container, I want to set a specific container's IP address in the same LAN.
Is that possible? If not, after the creation can I edit the DHCP IP address?
A:
Considering the conclusion of the (now old October 2013) article "How to configure Docker to start containers on a specific IP address range", this doesn't seem to be possible (or at least "done automatically for you by Docker") yet.
Update Nov 2015: a similar problem is discussed in docker/machine issue 1709, which include the recent workaround (Nov 2015)proposed by Tobias Munk (schmunk42) for docker machine
(for container see the next section):
A workaround for some use-cases could be to create machines like so:
192.168.98.100
docker-machine create -d virtualbox --virtualbox-hostonly-cidr "192.168.98.1/24" m98
192.168.97.100
docker-machine create -d virtualbox --virtualbox-hostonly-cidr "192.168.97.1/24" m97
192.168.96.100
docker-machine create -d virtualbox --virtualbox-hostonly-cidr "192.168.96.1/24" m96
If there's no other machine with the same cidr (Classless Inter-Domain Routing), the machine should always get the .100 IP upon start.
Another workaround:
(see my script in "How do I create a docker machine with a specific URL using docker-machine and VirtualBox?")
My virtualbox has dhcp range 192.168.99.100 - 255 and I want to set an IP before 100.
I've found a simple trick to set a static IP: after create a machine I run this command and restart the machine:
echo "ifconfig eth1 192.168.99.50 netmask 255.255.255.0 broadcast 192.168.99.255 up" \
| docker-machine ssh prova-discovery sudo tee /var/lib/boot2docker/bootsync.sh > /dev/null
This command create a file bootsync.sh that is searched by boot2docker startup scripts and executed.
Now during machine boot the command is executed and set static IP.
docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM
test-1 - virtualbox Running tcp://192.168.99.50:2376 test-1 (mast
Michele Tedeschi (micheletedeschi) adds
I've updated the commands with:
echo "kill `more /var/run/udhcpc.eth1.pid`\nifconfig eth1 192.168.99.50 netmask 255.255.255.0 broadcast 192.168.99.255 up" | docker-machine ssh prova-discovery sudo tee /var/lib/boot2docker/bootsync.sh > /dev/null
then run command (only the first time)
docker-machine regenerate-certs prova-discovery
now the IP will not be changed by the DHCP
(replace prova-discovery by the name of your docker-machine)
April 2015:
The article mentions the possibility to create your own bridge (but that doesn't assign one of those IP addresses to a container though):
create your own bridge, configure it with a fixed address, tell Docker to use it. Done.
If you do it manually, it will look like this (on Ubuntu):
stop docker
ip link add br0 type bridge
ip addr add 172.30.1.1/20 dev br0
ip link set br0 up
docker -d -b br0
To assign a static IP within the range of an existing bridge IP range, you can try "How can I set a static IP address in a Docker container?", using a static script which creates the bridge and a pair of peer interfaces.
Update July 2015:
The idea mention above is also detailed in "How can I set a static IP address in a Docker container?" using:
Building your own bridge
The result should be that the Docker server starts successfully and is now prepared to bind containers to the new bridge.
After pausing to verify the bridge’s configuration, try creating a container — you will see that its IP address is in your new IP address range, which Docker will have auto-detected.
you can use the brctl show command to see Docker add and remove interfaces from the bridge as you start and stop containers, and can run ip addr and ip route inside a container to see that it has been given an address in the bridge’s IP address range and has been told to use the Docker host’s IP address on the bridge as its default gateway to the rest of the Internet.
Start docker with: -b=br0 (that is also what the echo 'DOCKER_OPTS="-b=bridge0"' >> /etc/default/docker can set for you by default)
Use pipework (192.168.1.1 below being the default gateway ip address):
pipework br0 container-name 192.168.1.10/24@192.168.1.1
| {
"pile_set_name": "StackExchange"
} |
Q:
Change voyager model
I want to add some mutators on Voyager's User class, but I won't change anything inside vendor folder, and Voyages uses a User model inside the package. Is it possible for me to, somehow, change this?
A:
Simple enough. Modify the default Laravel User model to
<?php
namespace App\Models;
use TCG\Voyager\Models\User as VoyagerUser;
class User extends VoyagerUser {
// add custom mutators and other code in here
}
Then you can update app/config/voyager.php as @aimme said and have it as
'user' => [
'add_default_role_on_register' => true,
'default_role' => 'user',
'admin_permission' => 'browse_admin',
'namespace' => App\User::class,
],
This way you bring in the power of Voyager's User model to your own with no hackery involved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do I need a temporary value for the columns in the 2D Fourier Transform (Matlab)
Here is the matlab code for a 2D discrete Fourier Transform. This code was transcribed from:
Scilab Textbook Companion for Digital Image Processing
by S. Jayaraman, S. Esakkirajan And T. Veerakumar.
I am not really certain what is going on during the second for loop, and why we have to use a temporary value for f_2.
What is happening during this stage of the script?
Thank you.
function [ftransformed2d]= dft2d(f)
[rows,cols]=size(f);
for k=1:cols
f_1(:,k)=exp(-2*1j*pi*(0:nROWs-1)'*(0:rows-1)/rows)*f(:,k);
end
for J=1:rows
f_2_a=exp(-2*1j*pi*(0:nCOLs-1)'*(0:nCOLs-1)/cols)*(f_1(J,:)).';
f_2(J,:)=f_2_a.';
end
ftransformed2d = circshift(f_2,floor(size(f_2)/2));
end
A:
The first loop performs an FFT on each column, and the second loop performs an FFT on each row. As concerns the second loop,
f_2_a=exp(-2*1j*pi*(0:cols-1)'*(0:cols-1)/cols)*(f_1(J,:)).';
f_2(J,:)=f_2_a.';
the use of f_2_a is certainly not necessary but may have been included for ease of reading. It could have been written instead as
f_2(J,:) = ( exp(-2*1j*pi*(0:cols-1)'*(0:cols-1)/cols)*(f_1(J,:)).' ).';
| {
"pile_set_name": "StackExchange"
} |
Q:
Запятая перед как
Предложение: Управлением образования, как уполномоченным органом по организации отдыха, оздоровления и занятости детей ()муниципального района, организуется работа по отдыху, оздоровлению и занятости детей и молодежи.
Считаю, что перед как и после "района" нужна запятая, так как оборот с "как"выступает в значении причины. Управление организует отдых, потому что является уполномоченным органом по организации отдыха. Правильно ли я рассуждаю? Спасибо.
A:
Да, верно: Управлением образования, так как оно является уполномоченным органом по организации отдыха, оздоровления и занятости детей (...) муниципального района, ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Iterating having value contains List , that contains another list is not working?
I'm using richFaces 3.3 and JSF 1.2.
In my sample application I need to display List of items in and contains also
i.e( 2 columns having and third one is )
If I try to give List with in another List as value for rich:columns means its not working but direct bean value is working ???
mainClass
having getter , setter of String item1 , String item2, List priceList
mainList
contains item 1
item 2
List<price> priceList like that...
so in <rich:dataTable> if i try to give value like
<rich:dataTable id="positions" value="#{bean.mainList}" var="var">
<rich:column>
<f:facet name="header">
<h:outputText value="item1"/>
</f:facet>
<h:outputText id="contname" value="#{var.item1}">
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value="item2"/>
</f:facet>
<h:outputText id="contname" value="#{var.item2}">
</rich:column>
<rich:columns value="#{var.priceList}" var="partnerPriceItem" columns="2" index="ind">
<f:facet name="header">
<h:outputText id="output#{ind}" value="#{partnerPriceItem.id}" />
</f:facet>
<h:outputText id="price#{ind}" value="#{partnerPriceItem.price}" />
</rich:columns>
</rich:dataTable>
here for first 2 columns working fine. but when I try to give referencing from another List means not working ??
output like
item 1 item 2 price1 price2 price3
1 2 100 200 300
2 2 50 100 75
A:
To resolve your problem, you need to use the rich:dataTable and rich:subTable. There is an example in the exadel live demo site.
Let's have a look in the code (this is not the real code of the site, it's just an example to get the idea):
Java Classes
//POJOs
public class Expenses {
private Date day;
private decimal meals;
private decimal hotels;
private decimal transports;
//getters and setters for the attributes;
}
public class Record {
private String city;
private List<Expenses> items;
private decimal totalMeals;
private decimal totalHotels;
private decimal totalTransport;
private decimal total;
//getters and setters for the attributes;
}
public class ExpReport {
private List<Record> records;
private decimal totalMeals;
private decimal totalHotels;
private decimal totalTransport;
private decimal grandTotal;
//getters and setters for the attributes;
}
//Managed Bean
public class Report {
private ExpReport expReport;
//getter and setter for the attribute;
}
We have the managed bean Report that contains an instance of ExpReport. Inside ExpReport we have a List of Records (the list we want to display in the table), but each record has its own inner List of Expenses (the list we want to display along with the records). Now, we just need to set up our rich:dataTable and the rich:subTable in it to get the magic flowing in our jsp.
Note: You can get more info on the documentation of rich:column.
<!-- Here we set the data list for the dataTable as the list of records of our
object expReport. Also, the name of the iterator will be 'record' -->
<rich:dataTable width="100%" value="#{report.expReport.records}" var="record">
<f:facet name="header">
<!-- This columnGroup tag component will define a group of columns for
the header of the dataTable (the body of the dataTable can has
more columns, for this example there will be the same).-->
<rich:columnGroup>
<rich:column rowspan="2">
<rich:spacer />
</rich:column>
<rich:column colspan="3">
<h:outputText value="Expenses" />
</rich:column>
<rich:column rowspan="2">
<h:outputText value="subtotals" />
</rich:column>
<!-- The 'breakBefore' attribute tells the column to start from the
next row to be rendered in the dataTable. This attribute doesn't
affect the rows generated in rich:extendedDataTable. For more
info, see the documentation (link above the code). -->
<rich:column breakBefore="true">
<h:outputText value="Meals" />
</rich:column>
<rich:column>
<h:outputText value="Hotels" />
</rich:column>
<rich:column>
<h:outputText value="Transport" />
</rich:column>
</rich:columnGroup>
</f:facet>
<!-- Now, let's set the content of the rows of the dataTable -->
<!-- This column will show city from our 'record' iterator. -->
<rich:column colspan="5">
<h:outputText value="#{record.city}" />
</rich:column>
<!-- After printing the city, we want to show the data from the expenses
made in this record. For this, we will use the subTable tag
component, setting the 'record.items' list as the data list for
subTable and naming the inner iterator 'expense'. The syntax for the
subTable is like the dataTable. -->
<rich:subTable value="#{record.items}" var="expense">
<rich:column>
<h:outputText value="#{expense.day}" />
</rich:column>
<rich:column>
<h:outputText value="#{expense.meals}">
<f:convertNumber pattern="$####.00" />
</h:outputText>
</rich:column>
<rich:column>
<h:outputText value="#{expense.hotels}">
<f:convertNumber pattern="$####.00" />
</h:outputText>
</rich:column>
<rich:column>
<h:outputText value="#{expense.transport}">
<f:convertNumber pattern="$####.00" />
</h:outputText>
</rich:column>
<rich:column>
<rich:spacer />
</rich:column>
</rich:subTable>
</rich:dataTable>
Sorry for my bad english, I hope this can be helpful in your application.
| {
"pile_set_name": "StackExchange"
} |
Q:
SASS + COMPASS - image sprite repeat-y
How to make a sprite from a lot of pictures, and one of them use the "repeat-y"
I see that there is an update about that - https://github.com/chriseppstein/compass/commit/a8241e7924410d0e0f63fca0742e3a01897e4e2c
A:
You have to use the development version of Compass (see rubygems).
Install an alpha version of Compass
For install it, you can uses Bundler to not pollute your global environment. In first place, install bundler:
$ [sudo] gem install bundler
Now, put in your Compass project a file named Gemfile with the following content:
source "https://rubygems.org"
gem "compass", "~> 0.13.alpha"
Initialize the Bundler project locally:
$ cd my_project/
$ bundle install --path .vendors/bundler
You can use the command bundle exec compass instead of compass for used that specific version of Compass.
Use the repeat-y option of the sprite engine
Automatic sprites
If you use the basic import, you have to declare the variable $<map>-<sprite>-repeat: repeat-y before the import:
@import "compass/utilities/sprites";
$icons-layout: horizontal;
$icons-foobar-repeat: repeat-y;
@import "icons/*.png";
@include all-icons-sprites;
In this example, the image named icons/foobar.png will be repeated vertically.
Note that this featured only works with a horizontal layout.
Manual sprites
The syntax to declare a repeat-y for a sprite is $<map>-<sprite>-repeat: repeat-y. Again, only the horizontal arrangement will be viable:
@import "compass/utilities/sprites";
$icons: sprite-map("icons/*.png",
$icons-layout: horizontal,
$icons-foobar-repeat: repeat-y);
.icons {
background: transparent $icons no-repeat;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Action variables in canonical transformations
Let's suppose we have a Hamiltonian $H(p_k, q_k)$ and we want to transform it via a canonical transformation to one Hamiltonian which doesn't depend on the new coordinates $w_k$, but only in the momenta, $\bar{H}(J_k)$
Such coordinates are called action-angle variables. One (or the only one?) way to find the new coordinates is define $J_l$ as:
$$J_l = \int^{T_l}_0 p_l dq_l$$
Why are this $J_l$ the momenta that make the Hamiltonian doesn't depend on $\bar{q}_k$?
I think it has something to do with the type 1 generating function (in one dimension, $S(q, \bar{q})$), since:
$$dS = \frac{\partial S}{\partial q}dq + \frac{\partial S}{\partial q}dq =
pdq - Jdw$$
And then integrating in a period of motion:
$$\oint dS = \oint pdq - J\oint dw$$
$\oint dw$ is defined to be 1, and S is basically the action and thus should be 0 in one period, so that we could deduce the $J$ equation from here. Am I right?
A:
I think your derivation is correct.
An alternative approach. Suppose that (in any phase space) we have a tube of phase trajectories. Let $\gamma_1$ and $\gamma_2$ be two curves that encircle the tube. Given any 1-form $\omega^1$, Stokes' lemma is (see page 236 and surrounding of Arnold's Mathematical Methods of Classical Mechanics)
$\oint_{\gamma_1} \omega^1 = \oint_{\gamma_2} \omega^1$.
Now the so-called integral invariant of Poincare-Cartan (couldn't figure out how to do acute accents here) $\mathbf{p}d\mathbf{q} - H dt$ is a 1-form so
$\oint_{\gamma_1} \mathbf{p}d\mathbf{q} - Hdt = \oint_{\gamma_2} \mathbf{p}d\mathbf{q} - Hdt$.
Or, if the phase-space is time-independent (or if we consider trajectories on a single time slice)
$\oint_{\gamma_1} \mathbf{p}d\mathbf{q} = \oint_{\gamma_2} \mathbf{p}d\mathbf{q}$.
If the system has an action-angle representation, all trajectories are confined to some topological torus in phase space. Thus the tori constitute a tube of phase trajectories.
The specific tori are labelled by the action variables $J_i$. But from the above we see that integrating over any loop encircling a given torus must always give the same result, while integrating over a different torus will give a different result. Therefore, the integral $\oint_{\gamma} \mathbf{p}d\mathbf{q}$ must yield the action variables. Integrating over the relevant coordinate period closes the loop in the appropriate way.
| {
"pile_set_name": "StackExchange"
} |
Q:
Quantity of areas within a larger area broken down by percentages.
I have the following problem to solve.
I have a total area of At (Area Total). Example 1000m2
Within that area I want to find out how many 1 bedroom, 2bedroom, and 3bedroom units I can fit. The areas for each unit are A1, A2, A3 respectively. Example 55m2, 80m2, 95m2.
I want the number of units to be calculated using a percentage. P1, P2, P3. respectively. Example 20%, 70%, 10%.
What is the formula for 1bedroom, 2bedroom and 3bedrooms to fit in a total area by certain percentages?
I started out calculating the percentage of the total area. I.e. 20% of 1000m2 and then divide by 55m2 for 1bedrooms. But the percentage is then calculating based on area rather than quantity.
I then started to go down the path of dividing the total area by one of the bedrooms to get a quantity and then working out a percentage of the one bedroom compared to the others but got a bit lost.
This is a formula I want to calculate to work out residential unit potential for a development site.
A:
First work out:
V = (P1/100) * A1 + (P2/100) * A2 + (P3/100) * A3.
That's the average area of an apartment. In your example V=76.5. Then work out:
T = At / V
That's the approximate total number of apartments. In your example T~=13 Next, work out:
U1 = T * (P1/100),
U2 = T * (P2/100), and
U3 = T * (P3/100)
Those are the approximate numbers of apartments. In your example that's ~2.6, ~9.2 and ~1.3. Next, round these numbers down to make sure it all fits, giving 2, 9 and 1. Finally, work out the area this gives and see if you can fit another one in. In your case you get 925 and so can fit another 55 in. The last part is manual because there's no simple way to get whole numbers to fit together.
None of this accounts for corridor space, wall space, gardens and the like. It also doesn't ensure that the apartments will actually fit together.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: I am trying to use a function returned by another function
I am learning Python for scientific computing, and there is an exercise where I create a polynomial using its roots:
Exercise 3.5
from sympy import symbols, expand
def poly(roots): #Pass real and/or complex roots
x = symbols('x')
f = 1
for r in roots:
f *=(x - r)
return expand(f)
Test:
from numpy.lib.scimath import sqrt
poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
Gives:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0
I am trying to return the polynomial and use it by passing a x value:
f = lambda x: poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
f(-1/2)
Gives:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0
The problem is that f(-1/2) is not giving 0, which it should. How can I tell Python to use the expression algebraically? Thank you!
A:
You have to substitute for x and evaluate the polynomial to a float:
poly(...).subs('x', y).evalf()
Try with it:
from sympy import symbols, expand, sqrt
def poly(roots): # Pass real and/or complex roots
x = symbols('x')
f = 1
for r in roots:
f *= (x - r)
return expand(f)
f = lambda y: poly([-1 / 2, 5, (21 / 5), (-7 / 2) + (1 / 2) * sqrt(73), (-7 / 2) - (1 / 2) * sqrt(73)]).subs('x',
y).evalf()
print(f(-1 / 2))
Output:
-1.06581410364015e-14
| {
"pile_set_name": "StackExchange"
} |
Q:
Symfony, log without explicit error at every page
I face a strange problem here with symfony. Indeed, since a few days I struggle with this "bug" : At every page of my application I load, I have no errors on the page, everything is perfect BUT symfony write somes logs in the dev.log file. I read them but there is only thrown and catched events, no errors, I do not know where to search but this is a problem because the dev.log file grow really fast ^^. Maybe someone faced the same problem ? Or can fins something in the dev.log : I also have FOSRestbundle/wsse, but can find nothing in it...
[2014-04-23 21:14:27] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest". [] []
[2014-04-23 21:14:27] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] []
[2014-04-23 21:14:27] event.DEBUG: Notified event "kernel.request" to listener "FOS\RestBundle\EventListener\BodyListener::onKernelRequest". [] []
[2014-04-23 21:14:27] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest". [] []
[2014-04-23 21:14:27] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". [] []
[2014-04-23 21:14:27] request.INFO: Matched route "romain_general_homepage" (parameters: "_controller": "Romain\GeneralBundle\Controller\GeneralController::presentationAction", "_route": "romain_general_homepage") [] []
[2014-04-23 21:14:27] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". [] []
[2014-04-23 21:14:27] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
[2014-04-23 21:14:27] security.DEBUG: Read SecurityContext from the session [] []
[2014-04-23 21:14:27] security.DEBUG: Reloading user from user provider. [] []
[2014-04-23 21:14:28] security.DEBUG: Username "Voyager" was reloaded from user provider. [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest". [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener::injectLogger". [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener::injectLogger". [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.controller" to listener "FOS\RestBundle\EventListener\ParamFetcherListener::onKernelController". [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector::onKernelController". [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.controller" to listener "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelController". [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController". [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController". [] []
[2014-04-23 21:14:28] event.DEBUG: Notified event "kernel.controller" to listener "FOS\RestBundle\EventListener\ViewResponseListener::onKernelController". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse". [] []
[2014-04-23 21:14:29] security.DEBUG: Write SecurityContext in the session [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\FirePHPHandler::onKernelResponse". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\ChromePhpHandler::onKernelResponse". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener::onKernelResponse". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse". [] []
[2014-04-23 21:14:29] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener::onKernelTerminate". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "FOS\RestBundle\EventListener\BodyListener::onKernelRequest". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". [] []
[2014-04-23 21:14:32] request.INFO: Matched route "_wdt" (parameters: "_controller": "web_profiler.controller.profiler:toolbarAction", "token": "6e72f6", "_route": "_wdt") [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener::injectLogger". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener::injectLogger". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.controller" to listener "FOS\RestBundle\EventListener\ParamFetcherListener::onKernelController". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector::onKernelController". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.controller" to listener "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelController". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.controller" to listener "FOS\RestBundle\EventListener\ViewResponseListener::onKernelController". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\FirePHPHandler::onKernelResponse". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\ChromePhpHandler::onKernelResponse". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener::onKernelResponse". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse". [] []
[2014-04-23 21:14:32] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener::onKernelTerminate". [] []
and on doctrine_dev.log (I separated the files...)
[2014-04-23 21:14:27] doctrine.DEBUG: SELECT t0.username AS username1, t0.username_canonical AS username_canonical2, t0.email AS email3, t0.email_canonical AS email_canonical4, t0.enabled AS enabled5, t0.salt AS salt6, t0.password AS password7, t0.last_login AS last_login8, t0.locked AS locked9, t0.expired AS expired10, t0.expires_at AS expires_at11, t0.confirmation_token AS confirmation_token12, t0.password_requested_at AS password_requested_at13, t0.roles AS roles14, t0.credentials_expired AS credentials_expired15, t0.credentials_expire_at AS credentials_expire_at16, t0.id AS id17, t0.nom AS nom18, t0.prenom AS prenom19, t0.termes AS termes20 FROM user t0 WHERE t0.id = ? LIMIT 1 [1] []
[2014-04-23 21:14:29] doctrine.DEBUG: SELECT t0.id AS id1, t0.nom AS nom2, t0.localisation AS localisation3, t0.dateCreation AS dateCreation4, t0.proprietaire_id AS proprietaire_id5 FROM groupe t0 INNER JOIN groupe_user ON t0.id = groupe_user.groupe_id WHERE groupe_user.user_id = ? [1] []
[2014-04-23 21:14:29] doctrine.DEBUG: SELECT t0.id AS id1, t0.dateCreation AS dateCreation2, t0.description AS description3, t0.type AS type4, t0.criticite AS criticite5, t0.vu AS vu6, t0.info AS info7, t0.user_id AS user_id8 FROM notification t0 WHERE t0.user_id = ? [1] []
So am I the only one ? I think there is a bug with no log and not visible on the page.
Anyway thanks for your time.
A:
Log files don't have to contain only errors, but various types of messages. Those you pasted are debug messages. You could change dev environment configuration not to do it but I see no reason why would you.
If you use your application in prod environment (without app_dev.php) debug messages won't be logged.
| {
"pile_set_name": "StackExchange"
} |
Q:
Group and count observations per year from a dataset containing interval data
I have data concerning the activity of a number of different writers, the data includes the start.date and end.date of their writing careers
library("tidyverse")
writing_period_data <- tribble(
~start.date, ~end.date, ~writer, ~topic,
12, 18, "a", sample(letters[10:20],1),
14, 20, "b", sample(letters[10:20],1),
17, 22, "c", sample(letters[10:20],1),
15, 30, "a", sample(letters[10:20],1)
)
I would like to ultimately create a joyplot of this data, which requires me to generate this data structure:
desired_output <- tribble(
~year, ~count, ~writer,
12, 1, "a",
13, 1, "a",
14, 1, "a",
14, 1, "b",
15, 2, "a",
15, 1, "b",
16, 2, "a",
16, 1, "b",
17, 2, "a",
17, 1, "b",
17, 1, "c",
18, 2, "a",
18, 1, "b",
18, 1, "c",
19, 1, "a",
19, 1, "b",
19, 1, "c",
20, 1, "a",
20, 1, "b",
20, 1, "c",
21, 1, "a",
21, 1, "c",
22, 1, "a",
22, 1, "c",
23, 1, "a",
24, 1, "a"
)
Which we can see from this chart demonstrates the distribution of writers across the time period of interest:
desired_output %>%
ggplot(aes(x = year, y = count, fill = writer)) + geom_col()
How can I go about generating desired_output from writing_period_data?
A:
A solution from tidyverse. dt is the final output.
library(tidyverse)
dt <- writing_period_data %>%
mutate(year = map2(start.date, end.date, `:`)) %>%
unnest() %>%
count(year, writer) %>%
select(year, count = n, writer)
| {
"pile_set_name": "StackExchange"
} |
Q:
Negative high frequency intraday volatility - Zhou estimator
To estimate high frequency tick data stock intraday volatility, I have read Robert Almgren's notes7.pdf
http://www.cims.nyu.edu/~almgren/timeseries/notes7.pdf
where he talks about the bias free estimator by Zhou:
$Z = \sum ((y_j - y_{j-1})^2 + 2(y_j - y_{j-1})(y_{j+1} - y_j))$
where $y_j$ is the log return of the price at time $j$.
However, this expression sometimes yields negative volatility. We see that the first term is a square which is always positive, but the second term $2(y_j-y_{j-1})(y_{j+1}-y_j)$ can be negative. So how do I treat this estimator? I want a positive volatility, not a negative! I am thinking of just applying absolute value on the second term, but that does not sound right. Any suggestions?
A:
In any finite sample, it is always possible for the Zhou estimator to return a negative number, even though we know the unobservable parameter being estimated is non-negative. This is a well known issue in the academic literature. There are several approaches to dealing with this problem:
1) Ignore it. (I don't like this one). It is particularly nefarious if you ever move to a multivariate setting and you suddenly end up with a covariance matrix that is not positive semi-definite. (try taking the inverse of it and watch everything go to hell in your code).
2) Set your final estimator equal to $max(v, 0)$, where $v$ is the Zhou estimator. In practice, there is nothing wrong with this ad hoc estimator, although a pure theorist might get cross about the fact that the asymptotic distribution is affected. From a coding perspective, you might even want to use $max(v, \alpha)$ for some small positive constant $\alpha$ so you don't accidentally end up dividing by zero anywhere. NOTE: please do not take the absolute value of the autocovariance portion of the estimator, as you mention in the question. This makes no sense from an estimation perspective and will result in a heavily biased estimator that is inconsistent even under ideal modelling assumptions.
3) Use a different intraday-data based estimator of volatility that doesn't suffer from this problem. I strongly recommend this option. The Zhou estimator was state-of-the-art in 1996 (and that paper itself was astonishingly pre-scient - it took another decade for everyone else to catch on to the problems Zhou tried to solve in that paper), but a lot of work since then has demonstrated that it will be heavily biased for many high-frequency datasets, see e.g. Hansen, Lunde (2006) "Realised Variance and Market Microstructure Noise". Probably the most popular estimator at the present point in time is the realised kernels estimator of Barndorff-Nielsen, Hansen, Lunde, and Shephard. The original 2008 paper is a bit heavy going for a non-theorist, but have a look at Barndorff-Nielsen, Hansen, Lunde, and Shephard (2009) "Realized Kernels in Practice" - it is much more friendly. (I have an implementation of this estimator in the Julia language based off this paper).
This estimator also has the nice property that if you use a Parzen kernel (see the above reference for more detail), then the estimator will always be non-negative. Be warned, for other types of kernel function, especially flat-top kernels, there is no guarantee of non-negativity. See eg footnote 2 of the above-mentioned paper.
If you want something simpler in that you can implement quickly, then just use a low sampling frequency realized variance, e.g. 5-minute realized variance or maybe 10-minute. Since this is just a sum of squared intrady returns, it is guaranteed to always be non-negative and will, in my experience, provide a better estimate than the Zhou estimator anyway.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ballerina function to limit the decimal points in a float
I want to limit the number of decimal points in a float value, I don't want to round off the value rather format it. Is there a specific method like JavaScript toFixed() in Ballerina for this?
I'm using Ballerina 0.990.2.
A:
I think what you are looking for is io:sprintf().
Eg -
float f = 123.4567;
// This will format the floating point number to 2 decimal points.
io:println(io:sprintf("%.2f", f));
More info on sprintf function is available at https://ballerina.io/learn/api-docs/ballerina/io.html#sprintf
| {
"pile_set_name": "StackExchange"
} |
Q:
Get a table data from database using WebApi & Entity Framework 6.XX
i made a Entity Data Model From Database Table Like this.
Then add 4 line of codes in WebApiConfig.cs to get json data from response.
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
Then i created a Controller (Web API 2 controller with read/Write action) named importController.
then i added this codes to add and retrieve data from database. but not working.
CodeXenETSEntities db = new CodeXenETSEntities();
[HttpPost]
[ActionName("pushlocation")]
// POST: api/pushlocation
public HttpResponseMessage pushlocation( int userid,decimal longitude, decimal latitude , TimeSpan time )
{
user_locations ulog = new user_locations();
ulog.user_id = userid;
ulog.lon = longitude;
ulog.lat = latitude;
ulog.time = time;
db.user_locations.Add(ulog);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.Accepted, "Successfully Created");
}
[HttpGet]
[ActionName("pulllocation")]
// GET: api/pulllocation/5
public HttpResponseMessage pulllocation(int userid, decimal longitude, decimal latitude, TimeSpan time)
{
db.user_locations.ToList();
return Request.CreateResponse(HttpStatusCode.Accepted, "Success");
}
this is the output :
Database Data :
A:
3 things:
1) In WebApiConfig.cs use routeTemplate: "api/{controller}/{action}/{id}"
2) In importController change public HttpResponseMessage pulllocation(int userid, decimal longitude, decimal latitude, TimeSpan time) to public HttpResponseMessage pulllocation()
3) In Browser address bar use http://localhost:57715/api/{controller name}/pulllocation. in your case http://localhost:57715/api/import/pulllocation
I hope this will solve
| {
"pile_set_name": "StackExchange"
} |
Q:
Firebase - NodeJS: Domain-Wide Delegation with OAuth2 for Google API
Goal:
This Firebase Cloud Function should use Cloud APIs with domain-wide delegation so any user can update some G Suite Admin Panel user information when the Firebase DB changes.
Question:
Which package's method should I use to gain domian-wide delegation for my app.
firebase: firebase.auth.GoogleAuthProvider()
googleapis: google.auth.OAuth2
google-auth-library: new GoogleAuth()
Details:
I'm not connecting the dots regarding the Google Identity Platform, and I am stuck here at this step. How does a firebase-hosted nodejs app put together a web and access token for Google API requests?
Firebase projects use Google Cloud Platform projects, so
I have...
Added to the project a service account actor via API/Credentials in the
GCP-Console
Checked the Enable G Suite Domain-wide Delegation box
Stored the private_key.JSON.
Authorized API Clients (in the G Suite Admin Panel) with the Service Account Client ID
Should I Use...
Firebase: Maybe look into the whitelisting area of Google OAuth2 settings, and/or work with the services.json I got from firebase.
Google API via googleapis: Even though I'm using firebase.auth.GoogleAuthProvider() to validate the user, maybe use google.auth.OAuth2 to get domain-wide delegation from GCP (like app or compute engine)
Google Auth via google-auth-library: Again, even though I'm using firebase.auth.GoogleAuthProvider() to validate the user, maybe use new GoogleAuth() to get domain-wide delegation from GCP (like app or compute engine)
Updates
I've learned:
Google's npm package googleapis is not for clients (browsers). I'm now trying to using it in Firebase Cloud Functions
A:
The answer is:
Use googleapis for service account authentication with JWT Service Tokens.
Example
The code below is deployed to Firebase Cloud Functions and the logs seem to indicate authentication is successful.
Firebase Functions Logs
3:56:35.101 PM authorize Function execution started
3:56:35.620 PM authorize Successfully connected!
3:56:35.668 PM authorize Function execution took 568 ms, finished with status code: 200
NodeJS Code
// Firebase Admin SDK
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
// Google APIs
const googleapis = require('googleapis')
const drive = googleapis.drive('v3')
const gsuiteAdmin = googleapis.admin('directory_v1')
// Service Account Key - JSON
let privatekey = require("./privatekey.json")
let jwtClient = new googleapis.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
['https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/admin.directory.user'])
// Firebase Cloud Functions - REST
exports.authorize = functions.https.onRequest((request, response) => {
//authenticate request
jwtClient.authorize(function (err, tokens) {
if (err) {
console.log(err)
return
} else {
console.log("Successfully connected!")
}
response.send("Successfully connected!")
})
})
| {
"pile_set_name": "StackExchange"
} |
Q:
interval for a product to infinity
I was wondering - how would I specify the interval (the amount that n increases each time) between terms? Is that possible? What if I want it to increase by, say, 2, each time instead of one.
In Python it would be n += 2 -> I'm looking for an equivalent...
A:
You could do it two different ways. You could use a substack, like this
$$ \prod_{\substack{n=1 \\ 2 \mid n}}^\infty \frac{4n^2}{4n^2 -1} .$$
Or you could also let $n = 2m$ (or $n = 2m - 1$ if you want to start at $1$) and take the product as $m$ goes from $1$ to $\infty$, like this
$$ \prod_{m=1}^\infty \frac{4(2m)^2}{4(2m)^2-1} . $$
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the proper term for printed book sides?
In german we call it »Schnittverzierungen«. There are different kinds of them, the most common one is »Farbschnitt«, where all sides are colored.
Here are some examples:
Source
Source
A:
You could speak of edge painting or fore-edge painting, or gilt-edged for the golden variant.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to check if a Windows.Form is empty(without controls) but not null?
I have a function which returns an instance of Windows Form
public Form getForm(string Node)
{
Form obj = new Form();
obj = (Form)Activator.CreateInstance(Node);
return obj;
}
I am Calling this function as:
Form requestedForm = new Form();
requestedForm = getForm(system);
if ((requestedForm != null) && (requestedForm.Text!=""))
// to check if the Form is not empty.
{
openform(requestedForm);
}
else
{
MessageBox.Show("No form Found");
}
In some cases I get requestedForm.Text="" even if the form is not blank so how do I check this?
A:
public Form getForm(string Node)
{
Form obj = (Form)Activator.CreateInstance(Node);
return obj;
}
Call this as:
Form requestedForm = getForm(system);
if ((requestedForm != null) && (requestedForm.Controls.Count > 0))
{//Form is not empty
openform(requestedForm);
}
else
{
MessageBox.Show("No form Found");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Existence of graph spanners
An (unweighted) $k$-spanner of a graph $G$ is a subset of edges $S$ such that the distance between any two vertices of $G$ when using only edges in $S$ is at most $k$ times the distance in graph $G$. The goal is to find a small set $S$ that satisfies this constraint.
Recently, I've looked at some algorithms for this problem such as A simple and linear time randomized algorithm for computing sparse spanners in weighted graphs. Interestingly, all of them seem to compute a $(2k-1)$-spanner that have at most $O(k n^{1+1/k})$ edges, for integers $k\ge 1$.
This made me wonder about the following:
Is it impossible to construct a $k$-spanner for even $k$, e.g., $k=2,4$, in general graphs?
A:
Strictly speaking it is possible to construct $2k$ spanners but, under some assumptions (see below), their size will never be asymptotically better than the size of the best $2k-1$ spanner.
Indeed, assuming Erdős Girth Conjecture, there are graphs $G=(V,E)$ with girth (length of the shortest cycle) $2k+2$ and $\Omega(n^{1+\frac{1}{k}})$ edges.
A $2k$ spanner $S$ of $G$ cannot exclude any edge $(u,v) \in E$. Indeed, if $(u,v) \in E \setminus S$, either $u$ and $v$ are disconnected in $(V, S)$, or their distance in $(V, S)$ is at least $2k+1$. This is a contradiction.
This means that any $2k$ spanner of $G$ must have at least $\Omega(n^{1+\frac{1}{k}})$ edges. However, $O(n^{1+\frac{1}{k}})$ edges are already enough to guarantee the existence of $2k-1$ spanners in any graph, as you point out.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scala class to implement two Java Interfaces - how?
I have just started learning Scala and I'm now wondering how I could implement two different Java interfaces with one Scala class? Let's say I have the following interfaces written in Java
public interface EventRecorder {
public void abstract record(Event event);
}
public interface TransactionCapable {
public void abstract commit();
}
But a Scala class can extend only one class at a time. How can I have a Scala class that could fulfill both contracts? Do I have to map those interfaces into traits?
Note, my Scala classes would be used from Java as I am trying to inject new functionality written in Scala into an existing Java application. And the existing framework expects that both interface contracts are fulfilled.
A:
The second interface can be implemented with the with keyword
class ImplementingClass extends EventRecorder with TransactionCapable {
def record(event: Event) {}
def commit() {}
}
Further on each subsequent interface is separated with the keyword with.
class Clazz extends InterfaceA
with InterfaceB
with InterfaceC {
//...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are the following varieties symplectomorphic?
I saw a statement somewhere that for the Hirzebruch surfaces $F_n:=\mathbb{P}_{\mathbb{P}^1}(\mathcal{O}\oplus\mathcal{O}(n))$, $F_n$ and $F_m$ are symplectormorphic when $m$ and $n$ have the same parity.
My question is: Why is this true?
I can see that they are diffeomorphic by Freedman's Theorem: computing the intersection pairing on $\text{Pic}(F_n)=H^2(F_n, \mathbb{Z})$, which is an even form when n is even, and an odd form when n is odd.
But this result is deep and abstract, is there any easy way to construct a symplectomorphism? Certainly it is not given by polynomial maps, I'm wondering what it will be.
A:
In order to obtain an explicit description of the diffeomorphism, one can use the following argument.
Take $B=\mathbb{C}^{n-1}$, with coordinates $t_1, \ldots, t_{n-1}$, and consider the complex space
$\mathcal{X}$ obtained glueing $\mathbb{P}^1 \times \mathbb{C} \times B$ with $\mathbb{P}^1 \times \mathbb{C} \times B$ by the identification of
$(y_0, y_1, z, t_1, \ldots, t_{n-1})$ with $(y_0', y_1', z',t_1, \ldots, t_{n-1})$
if
$z'=z^{-1}, \quad y_1'=y_1z^{-n}, \quad y_0'=y_0+y_1 \sum_{i=1}^{n-1}t_iz^{-i}$.
Let us denote by $\pi \colon \mathcal{X} \to B$ the family obtained in this way.
Let now $T_k \subset B$ be the determinantal locus given by rank $M \leq k$, where $M$ is the matrix
\begin{bmatrix}
t_1 & \ldots & t_{k+1} \cr
t_2 & \ldots & t_{k+2} \cr
\cdot & \cdot & \cdot \cr
\cdot & \cdot & \cdot \cr
\cdot & \cdot & \cdot \cr
t_{n-k-1} & \ldots & t_{n-1}
\end{bmatrix}
Then, if $t \in T_k - T_{k-1}$ we have $X_t :=\pi^{-1}(t) \cong \mathbb{F}_{n-2k}$.
By using Ehresmann theorem, one concludes that
$F_n$ is diffeomorphic to $F_{n-2k}$.
Geometrically speaking, we are considering all the rank $2$ vector bundles $V$ which fit into the short exact sequence
$0 \to \mathcal{O}_{\mathbb{P}^1} \to V_n \to \mathcal{O}_{\mathbb{P}^1}(n) \to 0$.
They are classified by $H^1(\mathbb{P}^1, \mathcal{O}(-n)) \cong \mathbb{C}^{n-1}$, and we consider the family of ruled surfaces $\mathbb{P}(V_n)$, thus obtained, as a deformation of $\mathbb{F}_n = \mathbb{P}(\mathcal{O} \oplus \mathcal{O}(n))$.
This argument shows that even Hirzebruch surfaces are diffeomorphic to $S^2 \times S^2$, whereas odd Hirzebruch surfaces are diffeomorphic to $\mathbb{CP}^2 \sharp \overline{\mathbb{CP}^2}$.
The uniqueness of the symplectic structrure in each case is a more difficult story, and was proven by Lalonde and McDuff [J-curves and the classification of rational and
ruled symplectic 4-manifolds, Contact and Symplectic Geometry (Cambridge,
1994)].
A:
Let $n>0$. It is enough to show that the vector bundles $\mathcal{O} \oplus \mathcal{O}(n)$ and $\mathcal{O}(1) \oplus \mathcal{O}(n-1)$ are isomorphic as complex vector bundles with smooth transition maps. (They are NOT isomorphic as complex vector bundles with holomorphic transition maps.) Once we show that, we get that $\mathbb{P}(\mathcal{O} \oplus \mathcal{O}(n))$ is diffeomorphic to $\mathbb{P}(\mathcal{O}(1) \oplus \mathcal{O}(n-1))$, and we have $\mathcal{O}(1) \oplus \mathcal{O}(n-1) \cong \mathcal{O}(1) \otimes ( \mathcal{O} \oplus \mathcal{O}(n-2))$, so $\mathbb{P}(\mathcal{O}(1) \oplus \mathcal{O}(n-1)) \cong \mathbb{P}(\mathcal{O} \oplus \mathcal{O}(n-2))$.
We have a short exact sequence
$$0 \to \mathcal{O} \to \mathcal{O}(1) \oplus \mathcal{O}(n-1) \to \mathcal{O}(n) \to 0$$
where the maps are given by $\left( \begin{smallmatrix} x \\ y^{n-1} \end{smallmatrix} \right)$ and $\left( \begin{smallmatrix} -y^{n-1} & x \end{smallmatrix} \right)$.
Now, in the category of smooth vector bundles, every short exact sequence $0 \to A \to B \to C \to 0$ splits. The proof is as follows: use a partition of unity argument to put a positive definite Hermitian structure on $A$, $B$ and $C$. Then the adjoint of the map $B \to C$ provides a splitting.
So $\mathcal{O}(1) \oplus \mathcal{O}(n-1) \cong \mathcal{O} \oplus \mathcal{O}(n)$ and we are done.
A:
In Hirzebruch's original paper
(F. Hirzebruch, Über eine Klasse von einfachzusammenhängenden komplexen Mannigfaltigkeiten, Math. Ann. 124 (1951), 77–86.)
there are polynomial (or rational) formulas for the diffeomorphisms.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to insert data while looping and inside array as well
This is my table order:
+-------+-------+
| month | count |
+-------+-------+
| 6 | 11 |
| 11 | 27 |
| 12 | 9 |
+-------+-------+
I want to create a graph using fusioncharts. Let's say that the year is 2017. How do I put the missing month into the array of which fusioncharts I'm using? I'm stuck on the condition.
This is my code:
$strQuery2 = "SELECT DATE_FORMAT(order_date, '%c') as month, COUNT(*) AS cnt FROM orders where YEAR(order_date)='2017' GROUP BY month ORDER BY `month` DESC";
$result2 = $dbhandle->query($strQuery2);
// Push the data into the array
while($row2 = $result2->fetch_assoc()) {
$q = $row2["month"];
$w = $row2["cnt"];
$e = 0;
$x = 1;
if ($x != $q){
echo "true";
array_push($arrData2["data"],
array(
"label" => $row2[$x],
"value" => $row2[$e]
)
);
}
else{
echo "false";
array_push($arrData2["data"],
array(
"label" => $row2["month"],
"value" => $row2["cnt"]
)
);
}
$x++;
echo $row2["month"] . "<br />";
echo $row2["cnt"] . "<br />";
}
A:
You never get a month from the database that isn't there. If you push data into an empty array:
array_push($arrData2["data"]
you still end up with an array that only contains the months returned from the database.
What you can do is first create an array with all 12 months:
$arrData2["data"]=range(1,12,false);
You have now an array that contains 12 elements (months) from 1 - 12, all with values of false. (You could use any value, an array or false if you need).
Now inside your resultloop, just replace the array elements you have values for:
$arrData2["data"][$row2["month"]] = array(
'label' => $row2["month"],
'value' => $row2["cnt"]
);
$arrData2 now will look like:
array(
1 => false,
2 => false,
3 => false,
4 => false,
5 => false,
6 => array('label'=> 6,'value'=> 11),
7 => false,
8 => false,
9 => false,
10 => false,
11 => array('label'=> 11,'value'=> 27),
12 => array('label'=> 12,'value'=> 9)
)
Now you can replace all the false values for arrays with value 0
So your whole code could be schortened to:
//set empty array
$arrData2['data'] = range(1, 12, false);
//fill elements we know
while($row2 = $result2->fetch_assoc()) {
$arrData2["data"][$row2["month"]] = array(
'label' => $row2["month"],
'value' => $row2["cnt"]
);
}
//replace the rest with 0
foreach($arrData2["data"] as $key => $value){
// skip what we already know
if($values !== false) continue;
// replace the rest
$arrData2["data"][$key]=array(
'label'=>$key,
'value'=> 0
);
}
echo print_r($arrData2,true);
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you open the event log programatically?
I'm logging errors to the event log using the usual:
System.Diagnostics.Trace.TraceError("<" + purpose + "><time>" + DateTime.Now.ToUniversalTime() + "</time><message>" + message + "</message></" + purpose + ">");
and am wondering if there is a way to call this log file and display it for the user (either in my own format or by opening the event log file directly as does 'Event Viewer').
I've found the file in %SystemRoot%\System32\Winevt\Logs\mylog.evtx but not sure whether I should be approaching it this way or not. Ideally I'd like to emulate what the Event Viewer does but customised for my application.
A:
Try System.Diagnostics.EventLog
For Example, you can view entries in the applications log as follows
var log = EventLog.GetEventLogs().Where(x => x == "Application").First();
foreach (var entry in log.Entries) {
// Do something with the entry
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Create variable from text string with new lines and quotes
I have some contents from a text file. I want to load it into a variable in PHP
I just need to copy/paste the text directly into a variable without escaping all quotes etc
How to do something like this? I'm not looking for a solution with file_get_content, since my use case's environment does not support file reads.
$str = "saldflasdfl
asdklksadlasd "quoted string"
aslkdlsadfkl";
A:
How about this, which allows you to use unescaped quote marks in your text block:
$str = <<<DATA
saldflasdfl
asdklksadlasd "quoted string"
aslkdlsadfkl
DATA;
Note that it does need to be added with no whitespace indentation, since that would be taken to be part of the string.
However, do note that if your text block gets over a certain size, it is probably cleaner to put it in a text file and read it into a string.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sorting arrays with uncertain data
I am crafting a script for a browser game that will generate a random animal for the player to battle with anywhere from 0-5 markings. The markings on that animal are randomly generated and are fed into a custom imagick function, which will add them in order as they appear in the array.
While the markings are randomly decided, there are a lot of rules to how they are supposed to appear on an animal, for instance markings in the "full body" region show above markings in the "belly" region. To better explain, I'll attach an image of the tester so far:
So to break down the 5 markings on this randomly generated animal, the eyeshadow marking belongs to eye region, undertail belongs to tail, streaks belongs to fullbody, appaloosa belongs to back, and okapi belongs to legs. The order right now is just added as the script looped through the database and randomly selected markings, so okapi (the stripes on the legs) is on top since it was the last on in the array, and the last one added. But following the order rules, the last one in the array should have been streaks (the horizontal streaks across the body), since fullbody markings go on top.
Here is the code the selects markings, this is done using the Laravel engine:
// Determine number of markings
$num = mt_rand(1,10);
if ($num == 1) {
$markingNum = 0;
} elseif ($num > 1 && $num < 4) {
$markingNum = 1;
} elseif ($num > 4 && $num < 6) {
$markingNum = 2;
} elseif ($num > 6 && $num < 8) {
$markingNum = 3;
} elseif ($num > 8 && $num < 10) {
$markingNum = 4;
} else {
$markingNum = 5;
}
// Calculate Marking type and color
$markings = array();
if ($markingNum > 0) {
for ($m = 0 ; $m < $markingNum; $m++) {
// Set color values (pulls from the "pallet" selected earlier in the code, which will determine the range of color that marking can be)
if ($m == 1) {
$pal = $pallet->marking1;
} elseif ($m == 2) {
$pal = $pallet->marking2;
} elseif ($m == 3) {
$pal = $pallet->marking3;
} elseif ($m == 4) {
$pal = $pallet->marking4;
} else {
$pal = $pallet->marking5;
}
// Pull previous marking info
if (count($markings) != 0) {
$previous = DataMarking::whereIn('name', array_keys($markings))->get();
// This pulls the regions of the current markings in the array so it won't select a region that already has a marking.
foreach ($previous as $p) {
$regions[$p->region] = $p->name;
}
// Uncommon marking (10% chance)
$r = mt_rand(1, 10);
if ($r == 10) {
$marking = DataMarking::where('rarity', 1)
->where('public', 1)
->whereNotIn('name', array_keys($markings))
->whereNotIn('region', array_keys($regions))
->orderByRaw("RAND()")
->first();
// Common markings
} else {
$marking = DataMarking::where('rarity', 0)
->where('public', 1)
->whereNotIn('name', array_keys($markings))
->whereNotIn('region', array_keys($regions))
->orderByRaw("RAND()")
->first();
}
// Colors marking
if ($pal == 0) {
$markingColor = rand_color();
} else {
$range = ColorRange::where('id', $pal)->firstOrFail();
$markingColor = "#" . mixRange(substr($range->start_hex, 1), substr($range->end_hex, 1));
}
$markings[$marking->name] = $markingColor;
} else {
// Uncommon marking (10% chance)
$r = mt_rand(1, 10);
if ($r == 10) {
$marking = DataMarking::where('rarity', 1)
->where('public', 1)
->orderByRaw("RAND()")->first();
// Common marking
} else {
$marking = DataMarking::where('rarity', 0)
->where('public', 1)
->orderByRaw("RAND()")->first();
}
// Colors marking
if ($pal == 0) {
$markingColor = rand_color();
} else {
$range = ColorRange::where('id', $pal)->firstOrFail();
$markingColor = "#" . mixRange(substr($range->start_hex, 1), substr($range->end_hex, 1));
}
$markings[$marking->name] = $markingColor;
}
}
}
I figure I can accomplish this with a lot of complex if statements but it just doesn't seem like an elegant solution to me. In addition, there is an exception: 'Gradient', a fullbody marking, goes underneath everything even though it is a full body marking. So far it is the only marking with this sort of exception to it, though.
I have tried using various sort functions offered by PHP but I am not having much luck. uksort seems the most promising, but since the value we are sorting by exists in the database and not in the array we are sorting (the imagick function has to be fed a marking => color array format), it's proving difficult to work with.
Tl;dr: I need to reorder an array that an uncertain amount of data based off of values that exist in the DB for the keys (the region for the markings). What's the most elegant way to accomplish this?
A:
Here are some optimizations to your code, there are comments inline to describe what was done. This is obviously not finished as there are some things Marcin pointed out in his answer that would be better.
// Determine number of markings
$num = mt_rand(1,10);
// Removed redundent $num > X as the conditions were already meet that it was > X by the previous if statement
if ($num == 1) {
$markingNum = 0;
} else if ($num < 4) {
$markingNum = 1;
} else if ($num < 6) {
$markingNum = 2;
} else if ($num < 8) {
$markingNum = 3;
} else if ($num < 10) {
$markingNum = 4;
} else {
$markingNum = 5;
}
// Calculate Marking type and color
$markings = array();
if ($markingNum > 0) {
for ($m = 1 ; $m <= $markingNum; $m++) { // incrimented to 1 and <= so we can dynamically select elements
// Set color values (pulls from the "pallet" selected earlier in the code, which will determine the range of color that marking can be)
$pal = $pallet->{'marking' . $m}; // Removed if/else and replaced with a dynamic variable
// Uncommon marking (10% chance)
$r = mt_rand(1, 10);
// removed duplicate database selections for a simple $rarity variable that accomplishes the same task
if ($r == 10) {
$rarity = 1;
} else {
$rarity = 0;
}
$marking = DataMarking::where('rarity', $rarity)
->where('public', 1)
->whereNotIn('name', array_keys($markings))
->whereNotIn('region', $regions)
->orderByRaw("RAND()")
->first();
// Colors marking
if ($pal == 0) {
$markingColor = rand_color();
} else {
$range = ColorRange::where('id', $pal)->firstOrFail();
$markingColor = "#" . mixRange(substr($range->start_hex, 1), substr($range->end_hex, 1));
}
$markings[$marking->name] = $marking; // adds all of the marking data, this is where you could have a z-index in the database
$markings[$marking->name] = $markingColor; // add your color to your marking data
$regions[] = $marking->region;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
gensim.similarities.docsim.Similarity returns empty when queried
I seem to be getting all the correct results until the very last step. My array of results keeps coming back empty.
I'm trying to follow this tutorial to compare 6 sets of notes:
https://www.oreilly.com/learning/how-do-i-compare-document-similarity-using-python
I have this so far:
#tokenize an array of all text
raw_docs = [Notes_0, Notes_1, Notes_2, Notes_3, Notes_4, Notes_5]
gen_docs = [[w.lower() for w in word_tokenize(text)]
for text in raw_docs]
#create dictionary
dictionary_interactions = gensim.corpora.Dictionary(gen_docs)
print("Number of words in dictionary: ", len(dictionary_interactions))
#create a corpus
corpus_interactions = [dictionary_interactions.doc2bow(gen_docs) for gen_docs in gen_docs]
len(corpus_interactions)
#convert to tf-idf model
tf_idf_interactions = gensim.models.TfidfModel(corpus_interactions)
#check for similarities between docs
sims_interactions = gensim.similarities.Similarity('C:/Users/JNproject', tf_idf_interactions[corpus_interactions],
num_features = len(dictionary_interactions))
print(sims_interactions)
print(type(sims_interactions))
with the output:
Number of words in dictionary: 46364
Similarity index with 6 documents in 0 shards (stored under C:/Users/Jeremy Bice/JNprojects/Company/Interactions/sim_interactions)
<class 'gensim.similarities.docsim.Similarity'>
That seems right so I continue with this:
query_doc = [w.lower() for w in word_tokenize("client is")]
print(query_doc)
query_doc_bow = dictionary_interactions.doc2bow(query_doc)
print(query_doc_bow)
query_doc_tf_idf = tf_idf_interactions[query_doc_bow]
print(query_doc_tf_idf)
#check for similarities between docs
sims_interactions[query_doc_tf_idf]
and my output is this:
['client', 'is']
[(335, 1), (757, 1)]
[]
array([ 0., 0., 0., 0., 0., 0.], dtype=float32)
How do I get an output here?
A:
Depending on the content of your raw_docs, this can be the correct behaviour.
Your code returns an empty tf_idf although your query words appear in your original documents and your dictionary. tf_idf is computed by term_frequency * inverse_document_frequency. inverse_document_frequency is computed by log(N/d), where N is your total number of documents and d is the number of documents a specific term occurs in.
My guess is that your query terms ['client', 'is'] occur in each document of yours, resulting in an inverse_document_frequency of 0 and an empty tf_idf list. You can check this behaviour with the documents I took and modified from the tutorial you mentioned:
# original: commented out
# added arbitrary words 'now' and 'the' where missing, so they occur in each document
#raw_documents = ["I'm taking the show on the road.",
raw_documents = ["I'm taking the show on the road now.",
# "My socks are a force multiplier.",
"My socks are the force multiplier now.",
# "I am the barber who cuts everyone's hair who doesn't cut their own.",
"I am the barber who cuts everyone's hair who doesn't cut their own now.",
# "Legend has it that the mind is a mad monkey.",
"Legend has it that the mind is a mad monkey now.",
# "I make my own fun."]
"I make my own the fun now."]
If you query for
query_doc = [w.lower() for w in word_tokenize("the now")]
you get
['the', 'now']
[(3, 1), (8, 1)]
[]
[0. 0. 0. 0. 0.]
| {
"pile_set_name": "StackExchange"
} |
Q:
Can i set git push permissions for local machine?
I know i can set permissions on GIT to deny users push access to the master branch, but I don't have access to set these permissions.
I still want to disable write access to the master branch for my developers machines. Is there something i can configure on their local machines to let them write to only one branch?
A:
The ideal way would be to install gitolite on the central server, because you can then control those ACL from your workstation (by modifying the special admin repo 'gitolite-admin')
If this isn't possible, then you have to deploy a hook, like a pre-push hook (here is an example) in order to check the remote ref: if it is origin/master, then you can exit with 1 (fail), and that will cancel the push.
But that is a hook that need to be deployed for all the users, which is less convenient than having a centralized access control solution like gitolite.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access the rest of a 500 GB hard drive that ubuntu is installed on?
I have installed Ubuntu 16.04 LTS, on a second Hard drive (500 GB), but only 50 GB appears accessible to me. How do I access the remainder of 450 GB?
On the 1st Hard drive, windows 7 shows the other 2 partitions (450 GB), of the 2nd drive in the 'disk manager', that I don't seem to be able to access.
A:
It turns out the rest of the 450 GB is in the /temp directory, that was not shown in the left-hand source directories of the folders tab.
My hard disk has now been resized using gparted so that the Ubuntu partition has ~200 GB. This achieved by booting to a USB stick with Ubuntu 16.04 on it, as the hard drive could not be re-partitioned whilst I was using it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel Homestead - vm:The host path of the shared folder is missing: ~/Code on OSX Yosemite
I have brand new installation of laravel Homestead and my Homestead.yaml looks like this:
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox
authorize: ~/.ssh/id_rsa.pub
keys:
- ~/.ssh/id_rsa
folders:
- map: /srv/my_app
to: /home/vagrant/Code
sites:
- map: homestead.app
to: /home/vagrant/Code/public
databases:
- homestead
When i try vagrant up: I get this error:
There are errors in the configuration of this machine. Please fix
the following errors and try again:
vm:
* The host path of the shared folder is missing: ~/Code
~/Code does not exists but it's specify to be other path in yaml file, seems like vagrant is keeping it somewhere in memory or something, any idea?
In case when I create ~/Code directory it works vagrant is up but code is not there because it sits on other location and mapping doesn't work at all, and I run into "No input file specified" issue which is obvious.
A:
You probably were editing the wrong file.
After running init for homestead a local configuration file is created in your home directory under:
~/.homestead/Homestead.yaml you will need to apply changes there for them to take effect.
| {
"pile_set_name": "StackExchange"
} |
Q:
open: redirecting doesn't work when using an array as an argument?
my $cmd = "$exe build 2>&1 </dev/null";
my $FH = FileHandle->new;
open $FH, '-|', $cmd
or die "cannot open: $!";
close $FH;
Now when I changed $cmd to an array
my @cmd = ($exe, 'fly', '2>&1', '</dev/null');
it seems to ignore '2>&1' and '</dev/null'
How can I preserve redirecting STDIN and STDERR using an array an argument to open?
A:
As already indicated in another answer - 2>&1 and </dev/null aren't arguments in the same sense, which is why they don't work.
However in terms of STDIN and STDERR you may wish to consider IPC::Open2 or IPC::Open3 - that way you don't have to worry about it.
use IPC::Open3;
$pid = open3(my $exe_stdin, my $exe_stdout, my $exec_stderr,
'some cmd and args', 'optarg', ...);
That way you can just close $exe_stdin to get the same result as redirecting /dev/null and you can read the other streams independently.
A:
When there's only one argument, it's treated as a shell command.
When there's more than one, it's treated as a program to execute and arguments to that program.
That means that 2>&1 you used to pass to the shell is now being passed as an argument to the program.
This is easy to demonstrate with system, which uses the same convention.
$ perl -e'system(q{perl -E'\''say for @ARGV'\'' abc 2>&1})'
abc
$ perl -e'system(q{perl}, q{-E}, q{say for @ARGV}, q{abc}, q{2>&1})'
abc
2>&1
Since
my $full_cmd = "$exe build 2>&1 </dev/null";
is equivalent to
my @full_cmd = ('sh', '-c', "$exe build 2>&1 </dev/null");
then we want
my @cmd = ($exe, 'build');
my @full_cmd = ('sh', '-c', '"$@" </dev/null', '-', @cmd);
if we want to start with the non-shell parts.
In context, that means changing
my $cmd = "$exe build 2>&1 </dev/null";
open(my $FH, '-|', $cmd)
or die("Can't launch $exe: $!\n");
to
my @cmd = ($exe, 'build');
open(my $FH, '-|', 'sh', '-c', '"$@" 2>&1 </dev/null', '-', @cmd)
or die("Can't launch $cmd[0]: $!\n");
Note that you could also use the following:
use String::ShellQuote qw( shell_quote );
my @cmd = ($exe, 'build');
open(my $FH, '-|', shell_quote(@cmd).' 2>&1 </dev/null')
or die("Can't launch $cmd[0]: $!\n");
A:
The mode that you're attempting to use, open FILEHANDLE, MODE, EXPR, LIST has the following notes:
In the form of pipe opens taking three or more arguments, if LIST is specified (extra arguments after the command name) then LIST becomes arguments to the command invoked if the platform supports it.
However, redirection with 2>&1 and </dev/null are shell constructs, not arguments.
If you must go the array route, you'll need to use join to reassemble your array elements to fit the standard open FILEHANDLE, MODE, EXPR mode.
open $FH, q{-|}, join(' ', @cmd)
Note: If you're using an array to avoid shell interpolation of $exe, then you should consider using @Sobrique's answer using IPC::Open3 instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
What makes enum in java non instantiable?
I know that an enum
enum Year
{
First, Second, Third, Fourth;
}
gets converted into
final class Year extends Enum<Year>
{
public static final Year First = new Year();
public static final Year Second = new Year();
public static final Year Third = new Year();
public static final Year Fourth = new Year();
}
When I tried to instantiate enum (not class) I got compile time error as:
error: enum types may not be instantiated
Year y = new Year();
As per my knowledge a private constructor makes a class non instantiable. And I thought that compiler is providing a private constructor. But again I got confused when saw we can define a constructor for enum with default modifier and still cannot create an object of type enum.
enum Year
{
First, Second, Third, Fourth;
Year()
{
}
}
class Example
{
public static void main(String[] args)
{
Year y = new Year();
}
}
My doubt is, if it is not about constructors then what makes enum in Java non instantiable?
A:
It is specified in the Java Language Specification:
8.9. Enum Types
...
An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1).
Hence the compiler ensures that this requirement is met. Since the compiler "knows" that the type is an enum, it can distinguish between enum Year and final class Year.
Also, no access modifier is allowed for an enum constructor:
8.9.2. Enum Body Declarations
...
It is a compile-time error if a constructor declaration in an enum declaration is public or protected.
...
In an enum declaration, a constructor declaration with no access modifiers is private.
So, in practice, an enum constructor looks like package-scoped (no access modifier), but it really is private.
Finally, the same section also states
In an enum declaration with no constructor declarations, a default constructor is implicitly declared. The default constructor is private, has no formal parameters, and has no throws clause.
This makes the enum non-instantiable even if no constructor is explicitly declared.
A:
An enum in java has a default constructor when it's is not defined and it's private.
Default access modifier has different meanings in different scopes. For example inside a class default access modifier for methods and fields is package private.
Where as in an interface default access modifier means public. In fact there can be no other modifier on an interface field so it's implicitly public.
On a top level class it's package private (where only 2 access modifiers are allowed public and default package private)
So the answer to your question is it is so because compiler decides so. Compiler writer had to uphold the language specification contract.
You're right in thinking that it's a normal class after everything. Every object blueprint type in java is a class which can be represented by java.lang.Class. These restrictions for interfaces, enums, abstract classes, anonymous classes, method local classes are validated by compiler only.
If you can somehow escape the compiler and generate your own byte code for enums or other way around if you can modify the byte code of generated enum class so that it's private constructor becomes public may be you would be able to call it's constructor outside the enum's private scope. You can also try experimenting with reflection to do the same. In fact by generating byte code manually JVM languages like Groovy, Jython, JRuby, Clojure are able to provide functionalities that are not in Java itself. They're bypassing java compiler.
Purpose for having constructor in enums is to be able to set fields of constants in one call. All constants inside an enum are instances of the enum class, so they also consist the fields declared in it.
enum Test
{
T1(1), // equivalent to public static final Test T1 = new Test(1);
T2(2); // equivalent to public static final Test T2 = new Test(2);
int id;
Test(int id)
{
this.id = id;
}
}
And finally bellow is the output of decompiled code for above enum by using java -p Test.class
final class Test extends java.lang.Enum<Test>
{
public static final Test T1;
public static final Test T2;
int id;
private static final Test[] $VALUES;
public static Test[] values();
public static Test valueOf(java.lang.String);
private Test(int);
static {};
}
It should give a better understanding of what happens when the class compiles.
| {
"pile_set_name": "StackExchange"
} |
Q:
The following C code shows that : format '%d' expects argument of type 'int *', but argument 7 has type float *
The following code shows that : format '%d' expects argument of type 'int *', but argument 7 has type float *. I'm not an expert but I can't distinguish the error. This issue is present at the scanf. Along with this issue there are 3 more related warnings. It's at line 158 in the void edit () section. I keep trying and getting this very same thing. I ask if someone can please kindly assist?
Problem:
if(strcmp(e.name,empname) == 0)
{
printf("\nEnter new name,sex,address,designation,age,salary,employee ID ");
scanf("%s %s %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,&e.age,&e.slry,&e.empID);
fseek(fptr,-recsize,SEEK_CUR);
fwrite(&e,recsize,1,fptr);
break;
}
Struct here:
struct employee
{
char name[50];
char sex;
char adrs[50];
char dsgn[25];
int age,empID;
float slry;
};
Entire code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
#include <stdbool.h>
#include <windows.h>
#include "struct.h"
void insert();
void list();
void edit();
void del();
void ext();
FILE * fptr, *ftemp;
struct employee e;
long int recsize;
char empname[50];
int main()
{
//FILE * fptr, *ft;
int choice;
//fptr = fopen("ems.txt","rb+");
fptr = fopen("ems.txt", "r+");
if (fptr == NULL)
{
printf("Can't find file! Attempting to create file... \n");
fptr = fopen("ems.txt","w+");
if(fptr == NULL)
{
printf("Can't create file. Exiting...");
ext(1);
}
}
//Explain the reason for this?
//recsize = (long int) sizeof(e);//
while(1)
{
printf("*******************************\n");
printf("\nEmployee management system");
printf("\n1. Insert employee information");
printf("\n2. List all employee information");
printf("\n3. Edit employee information");
printf("\n4. Delete employee information");
printf("\n5. Exit");
printf("\n\n*****************************\n");
printf("\n\n Enter your choice: ");
scanf("%d", &choice);
fflush(stdin);
switch(choice)
{
case 1:
puts("Insert was chosen");
insert();
break;
case 2:
puts("List was chosen");
list();
break;
case 3:
puts("Edit was chosen");
edit();
break;
case 4:
puts("Delete was chosen");
del();
break;
case 5:
puts("Exit was chosen");
ext(1);
break;
default:
puts("Choice is incorrect!!");
continue;
}
}
return 0;
}
void insert()
{
char next;
do
{
printf("********************************************************** \n");
printf("\nEnter the name of the employee: ");
fgets(e.name);
printf("\nEnter the sex of the employee (M/m or F/f): ");
fgets(&e.sex);
printf("\nEnter the address of the employee: ");
fgets(e.adrs);
printf("\nEnter designation of the employee: ");
fgets(e.dsgn);
printf("\nEnter age of the employee: ");
scanf("%d", &e.age);
printf("\nEnter basic salary of the employee: ");
scanf("%f", &e.slry);
printf("\nEnter the employee's ID: ");
scanf("%d", &e.empID);
fputs(e.name, fptr);
fputs(&e.sex, fptr);
fputs(e.adrs, fptr);
fputs(e.dsgn, fptr);
fprintf(fptr, "%d \n%f \n%d \n", e.age, e.slry, e.empID);
// fwrite(&e,recsize,1,fptr);
fflush(stdin);
printf("\nDo you want to input more? (y/n): ");
next = getche();
printf("\n");
}
while(next !='n');
fclose(fptr);
}
void list ()
{
/* what is going on here??? */
while(fread(&e,recsize,1,fptr)==1)
{
printf("\n%s %c %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,e.age,e.slry,e.empID);
}
getche();
return ;
}
void edit ()
{
char next;
do
{
printf("Enter the employee name to be edited: ");
scanf("%s", empname);
while(fread(&e,recsize,1,fptr)==1)
{
if(strcmp(e.name,empname) == 0)
{
printf("\nEnter new name,sex,address,designation,age,salary,employee ID ");
scanf("%s %s %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,&e.age,&e.slry,&e.empID);
fseek(fptr,-recsize,SEEK_CUR);
fwrite(&e,recsize,1,fptr);
break;
}
}
printf("\nEdit another record(y/n)");
next = getche();
fflush(stdin);
}
while(next != 'n');
return ;
}
void del()
{
char next;
do
{
printf("\nEnter name of employee to delete: ");
scanf("%s",empname);
ftemp = fopen("Temp.dat","wb");
while(fread(&e,recsize,1,fptr) == 1)
{
if(strcmp(e.name,empname) != 0)
{
fwrite(&e,recsize,1,ftemp);
}
}
fclose(fptr);
fclose(ftemp);
remove("ems.txt");
rename("Temp.dat","ems.txt");
fptr = fopen("ems.txt", "rb+");
printf("Delete another record(y/n)");
fflush(stdin);
next = getche();
}while(next !='n');
}
A:
It would have been good if you showed us all the errors you got on that line:
x1.c: In function ‘edit’:
x1.c:170:17: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
scanf("%s %s %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,&e.age,&e.slry,&e.empID);
^
x1.c:170:17: warning: unknown conversion type character ‘.’ in format [-Wformat=]
x1.c:170:17: warning: format ‘%d’ expects argument of type ‘int *’, but argument 7 has type ‘float *’ [-Wformat=]
x1.c:170:17: warning: too many arguments for format [-Wformat-extra-args]
The first warning goes back to your prior question. e.sex has type char (which gets promoted to int) but you specified %s which expects a char *. To read this field, you want to use the %c format specifier which reads a single character instead of a sequence of characters, and you want to pass the address of the field you want to read into, i.e. &e.sex.
The second warning is due to your use of %.2f as a format specifier. Unlike printf, scanf doesn't take a precision. Change this to %f. Once you do that, the third error goes away.
As a rule, always address compilers errors from top to bottom, as problems earlier in the code can cascade down.
| {
"pile_set_name": "StackExchange"
} |
Q:
Representing time intervals in a chart
I'm trying to design a visual representation of a child's sleep schedule for a given week.
I was thinking of making a chart with the time of day on the y-axis and the days of the week on the x-axis and then blocking in the time intervals much like a calendar app would.
What are some alternate ways of representing this data that might result in a better user experience? Keep in mind that all 24 hours of the day have to be visible unlike most workday calendars because kids sleep at all hours.
EDIT: Another option, I suppose is a bubble chart, with the bubble plotted at the midpoint of the sleep duration and the size of the bubble indicating the length of the sleep.
A:
I agree with Charles; the same chart but with the axes reversed makes more sense to me. I tend to think of time in terms of timelines, which your chart just isn't doing for me right now. I also think you want some way to indicate continuities within broken time chunks, so it's clear that the kid didn't wake up briefly at midnight.
download bmml source – Wireframes created with Balsamiq Mockups
It's also worth thinking about presentation in terms of how your users will find the data most useful. For instance, you might allow your users to set the time at which a 'day' begins so that they can get meaningful stats about how much their child slept on an average day. Ergo, if the child is always awake by 10am, you have the day start at 10am (and adjust the display accordingly) so that the night's sleep is all linked to a single day.
A:
Another alternative - one that gets rid of the discontinuity at midnight (or 10am) - would be a spiral visualization, with one day per circuit.
Here's a picture of a spiral visualisation from an earlier UX answer of mine:
You could use 24 hours per circuit, and show history over 7 or 10 days easily. The same time of day always shows at the same angle, so patterns are immediately visible. I'd probably set things up with noon at the top and midnight at the bottom, giving 6am on the left and 9pm on the right.
Disclosure: I encountered these visualizations while working at a company founded by Andrew Cardno; there may be IP issues if you are working on something commercial.
| {
"pile_set_name": "StackExchange"
} |
Q:
What application can rotate a TIFF without re-encoding it?
This is a followup to a question at Apple.stackexchange.com, Why does rotating a TIFF in Preview increase the file size?
One thing I don't like about Preview.app is that even something as simple as rotating an image 90 degrees requires Preview to re-encode the file, adding an alpha channel in the process. This results in a file that is 10% to 20% larger than the original, with no added benefit. This size difference may not matter much on a 5 MB file, but on a 500 MB file, it is a nuisance.
(Interestingly, Preview.app does not increase the file size if you rotate a PDF.)
I gave GraphicConverter 10 a shot. All I did was rotate the TIFF and save, and the file size increased about 60%—it's even worse than Preview.
I tried IrfanView on Windows and it also increased the file size about 60%.
Are there any applications that can rotate a TIFF image 90 degrees without re-encoding it and altering the image in any other way? The source of the TIFF is a scanner, which does not offer a rotation feature.
I did a search and all I found were JPEG programs.
(2013 rMBP) -- (OS X 10.11.4) -- (I am open to Windows programs, too.)
A:
It is possible and even trivial but I am not aware of any application to do that task specifically.
There reason why the file size changes when rotated is that TIFF files are encoded losslessly as one would compress a stream of pixels components from one corner of the image to the opposite one. If you consider Run-Length-Encoding (RLE) which a common TIFF encoding, it is easy to understand why the same image will not compress to the same size after being rotated. It is equally likely that the file increases in size than it would decrease.
There is an easy way to get around that though and that is simply to change the tag which says which way pixels are ordered in the image. By simply changing the tag from a row-oriented ordering to the equivalent column-oriented one, the image is effectively rotated without any change to pixel data. You can read the details about the TIFF format here, just search for tag 274 (Orientation).
Honestly I thought no one used column oriented storage pixels so when I initially wrote a TIFF codec, I ignored that possibility for simplicity. As it would happen, one day we received such a TIFF image and my code did crash! Hopefully not many other developers took that short-cut either. It turns out that the file in question came from a scanner which did the scanning and encoding always exactly in the same way but set the orientation flag depending if it was fed a film-strip with frames in landscape or portrait orientation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript post of json string: nothing passes in or back
I'm working on a page that gets data from an html table (two columns plus an index of a form) and makes a json string. This is supposed to pass into php, then I do some calculations on the data, then send it back to the page to append the table with new column values.
Here's what I've got so far:
Data Arrays
This is what one of the arrays looks like (LatData):
[1, 1, "43.07104167", "43.07178767", "43.0707977", "43.07115595", "43.06975769", "43.07023291", "43.07269194", "43.07112776", "43.07067623", "43.07285063", "43.07132924", "43.07091389", "43.07218128", "43.07279775", "43.07440354", "43.07560161", "43.07471769", "43.07073611", "43.07067713", "43.070925", "43.07148333", "43.07070833", "43.07046389", "43.07024444", "43.07127778"]
Convert arrays and the int to a JSON string
So I take two arrays like the one above of the same length and the Item which is just a single value integer and I make my json string:
json = JSON.stringify({"Item":Item, "Lat": LatData, "Lon": LongData});
Then I get a nice json string as follows:
{"Item":1,"Lat":[1,1,"43.07104167","43.07178767","43.0707977","43.07115595","43.06975769","43.07023291","43.07269194","43.07112776","43.07067623","43.07285063","43.07132924","43.07091389","43.07218128","43.07279775","43.07440354","43.07560161","43.07471769","43.07073611","43.07067713","43.070925","43.07148333","43.07070833","43.07046389","43.07024444","43.07127778"],"Lon":[1,1,"-99.325375","-99.32837458","-99.32465527","-99.325341","-99.32509187","-99.32417542","-99.32573126","-99.32726626","-99.32830531","-99.32749062","-99.32966364","-99.32493056","-99.33109478","-99.33023795","-99.32853197","-99.32776487","-99.32631851","-99.3253","-99.32540699","-99.32571944","-99.32540278","-99.32453889","-99.32566667","-99.32622222","-99.32622222"]}
Send the JSON string to PHP
Here's how I'm posting the data:
function MakePhpCall()
{
var json =""; //this is the JSON string of all the data
var Item=1; //holding this constant for now
json = JSON.stringify({"Item":Item, "Lat": LatData, "Lon": LongData}); //make JSON string to pass into PHP
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","Conversion_JQ.php?json=" + json, true);
xmlhttp.send();
}
PHP handler
Then on the PHP side I do this:
$positions = json_decode($json);
echo $positions->Item[0];
echo $positions->Lat[2];
echo $positions->Lon[2];
I get no errors but I also don't get any call back to my div in the html page.
Goals
Ultimately I would like to decode the JSON to PHP arrays and that will help me do calculations easier.
Can someone please help me out here?
A:
The string was not able to be passed in using the regular method of
xmlhttp.open("GET","Conversion_JQ.php?json=" + json, true);
However, encoding the variable like this:
var uri = encodeRUIComponent(json);
xmlhttp.open("GET","Conversion_JQ.php?json=" + uri, true);
allowed the variable to pass in. It ends up having slashes in it so I had to use
stripslashes($json);
on the PHP side to clean up the string.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create static horizontal scrolling
I'm trying to develop an horizontal scrolling for a landing page. I'm trying information that I found here. But I want to make something similar, but not exactly that...
In that Web page, we have two elements:
We can see we have a menu, and an horizontal list of boxes. This list works as expected: if you press on a link on the menu, it jumps to the correct box. If you go to a mobile browser, it scrolls right and left using your hand.
But, when you scroll right with the mobile browser, the menu on the top, stays at the left of the layer, disapearing from the visible part of the Web. If you do so with a computer browser, the menu stays always at top left.
I want the menu to always stay at top, even if I'm using a mobile browser, so I can scroll, let's say, some images, without hiding left the content of my Web Page.
How can I do so?
I hope I explained myself correctly.
If you also think there's an easier way to make a scroll horizontal, I'm open to suggestions.
PS: I want a kind of result like this:
A:
Mobile browsers have issues with fixed positioning - see this article which also provides a list of JavaScript Solutions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Логика работы последовательности трансформаций в transform
До конца не понимаю как работают трансформации в SVG.
<svg style="width:400px; height: 400px;" viewBox="-100 -100 400 400" xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink">
<line x1="-200" y1="0" x2="400" y2="0" stroke="lime" stroke-dasharray="5 5"></line>
<line x1="0" y1="-200" x2="0" y2="400" stroke="lime" stroke-dasharray="5 5"></line>
<rect x="20" y="20" width="40" height="40" fill="aqua" ></rect>
<rect x="20" y="20" width="40" height="40" fill="green" transform="scale(2, 2)"></rect>
</svg>
Почему scale сделали не вокруг центра фигуры, а от начала координат, ведь теперь фигура не просто увеличилась но и сдвинулась... Тогда вопрос как её увеличить вокруг центра?
<svg style="width:400px; height: 400px;" viewBox="-100 -100 400 400" xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink">
<line x1="-200" y1="0" x2="400" y2="0" stroke="lime" stroke-dasharray="5 5"></line>
<line x1="0" y1="-200" x2="0" y2="400" stroke="lime" stroke-dasharray="5 5"></line>
<rect x="20" y="20" width="40" height="40" fill="green" transform="translate(-20,-20) scale(2, 2)"></rect>
<rect x="20" y="20" width="40" height="40" fill="aqua" ></rect>
</svg>
В данном случае я фигуру первым действием translate(-20,-20) возвращаю в начало координат, как я думаю, и при масштабирование фигура должна остаться у координат 0,0, но она всё-равно сдвинута остаётся, почему?
<svg style="width:400px; height: 400px;" viewBox="-100 -100 400 400" xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink">
<line x1="-200" y1="0" x2="400" y2="0" stroke="lime" stroke-dasharray="5 5"></line>
<line x1="0" y1="-200" x2="0" y2="400" stroke="lime" stroke-dasharray="5 5"></line>
<rect x="20" y="20" width="40" height="40" fill="green" transform="translate(-20,-20) scale(2, 2)"></rect>
<rect x="20" y="20" width="40" height="40" fill="red" transform="scale(2, 2) translate(-20,-20)"></rect>
</svg>
В чём разница этих двух вариантов? Правильно ли я понимаю что преобразования выполняются с конца?
Как правильно повернуть фигуру на 45 градусов и увеличить в два раза относительно её центра?
<rect x="30" y="30" width="40" height="40" fill="blue"></rect>
A:
Я немного изменил исходный код автора, чтобы не учитывать смещение относительно начала координат, которое задает viewBox="-100 -100 400 400", чтобы в чистом виде посмотреть, как влияет команда scale(2) на позиционирование фигур.
<svg style="width:400px; height: 400px;" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg"
xmlns:x="http://www.w3.org/1999/xlink">
<line x1="0" y1="0" x2="400" y2="0" stroke="blue" stroke-dasharray="5 5"></line>
<line x1="0" y1="0" x2="0" y2="400" stroke="blue" stroke-dasharray="5 5"></line>
<rect x="20" y="20" width="40" height="40" fill="aqua" ></rect>
<rect x="20" y="20" width="40" height="40" fill="green" transform="scale(2, 2)"></rect>
</svg>
Если левый верхний угол прямоугольника не совпадает с началом координат, в вашем случае <rect x="20" y="20" сдвинут по горизонтали и вертикали на 20px. то при применении команды scale(2) все параметры прямоугольника умножаются на X2 и координаты левого верхнего угла становятся - 40,40px ширина, будет равна width="80",высота height="80" на рисунке это зеленый квадрат.
Чтобы вернуть увеличенный, зелёный квадрат в исходную позицию 20x20px нужно применить команду translate(-20 -20).
Если команд трансформации несколько, то они выполняются от последней к первой
transform="translate(-20 -20) scale(2 2) "
<svg width="400px" height="400px" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<line x1="0" y1="0" x2="400" y2="0" stroke="blue" stroke-dasharray="5 5"></line>
<line x1="0" y1="0" x2="0" y2="400" stroke="blue" stroke-dasharray="5 5"></line>
<rect x="20" y="20" width="40" height="40" fill="green" transform="translate(-20 -20) scale(2 2) "></rect>
<rect x="20" y="20" width="40" height="40" fill="aqua" ></rect>
</svg>
Пример масштабирования вокруг точки
Допустим у нас есть точка с координатами 50,50px вокруг которой мы будем масштабировать прямоугольник, таким образом, чтобы он увеличивался, без смешения от этого центра.
Механизм центрирования тот же. Считается насколько увеличилось расстояние от начала координат до центра фигуры и вычитается размер, чтобы вернуть фигуру на прежнюю позицию.
<svg width="100%" height="100%" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMinYMin meet">
<!-- центр масштабирования -->
<circle cx="50" cy="50" r="2" style="fill: black;" />
<!-- первоначальный прямоугольник -->
<g id="box" style="stroke: black; fill: none;">
<rect x="35" y="40" width="30" height="20" />
</g>
<use xlink:href="#box" transform="translate(-50,-50) scale(2)" style="stroke-width: 0.5;" />
<use xlink:href="#box" transform="translate(-75,-75) scale(2.5)" style="stroke-width: 0.4;" />
<use xlink:href="#box" transform="translate(-100,-100) scale(3)" style="stroke-width: 0.33;" />
| {
"pile_set_name": "StackExchange"
} |
Q:
Why Gaussian elimination on the columns changes the column space?
This page on theorem 8.2 states that, Neither of the operations of the gaussian elimination changes the row space of an $m \times n$ matrix after applying the operation. It says later that this is only true about the row space and not the column space.
I can clearly see how multiplying and adding two vectors does not change the row space. Let's assume any pair of two dimensional non parallel non zero vectors. These vectors span $R^2$. Thus it does not matter how we combine them linearly, they will still span $R^2$.
The column space for any two non zero non parallel vectors can be thought of as being two dimensional vectors, spanning another two dimensional space again. Lets call this one $R^2_c$.
Now here is my question, doing gaussian elimination on the columns of a matrix, will firstly, do nothing to the span of the column space, $R^2_c$, because that space still can be spanned with the two new column vectors, and secondly, it will result in two new row vectors in $R^2$ that can still span $R^2$. So it seems to me by doing linear combinations on the column space, neither the row nor the column space change.
What am I doing wrong?
A:
Consider the matrix
$$\begin{pmatrix}1&5\\2&10\end{pmatrix}.$$
Its column space is one-dimensional, spanned by $\binom12$ (or equivalently by $\binom5{10}$ since these vectors are proportional). After a row operation, subtracting twice the first row from the second, the matrix becomes
$$\begin{pmatrix}1&5\\0&0\end{pmatrix}.$$
The column space of this is still one-dimensional, but it's a quite different one-dimensional space from before; the new one is spanned by $\binom10$. (Edit to correct an error in a comment: The column space of the original matrix was a line of slope $2$ (not $5$); the column space of the new matrix has slope $0$.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Chrome doesn't load SWF by flash builder
I am using flash builder 4.7 premium build SWF. But chrome does not load and show. I have to change default browser to internet explorer to view my SWF. I have flash version 15.0.0.239 installed and I use flex 4.6.0 SDK. Chrome:plugins already set to enable flash both pepflashplayer.dll and NPSWF32_15_0_0_239.dll. Any ideas are appreciated. Thank you.
A:
Don't run both Flash player plugins at the same time. Disable one or the other.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lotus Notes: Cleaning up log files from a data base is not affecting the database size and document count.
Cleaning up of log files from a database is still not affecting the document count and database size. Please help.
I am using lotus Notes version 6.5.
A:
Try using "compact" (compacting database) after you clean logs..
http://www-12.lotus.com/ldd/doc/domino_notes/rnext/help6_admin.nsf/b3266a3c17f9bb7085256b870069c0a9/4bc933e0fb0898bd85256c1d0039d413?OpenDocument
"When documents and attachments are deleted from a database, Domino tries to reuse the unused space, rather than immediately reduce the file size. Sometimes Domino won't be able to reuse the space or, because of fragmentation, can't reuse the space effectively until you compact the database."
| {
"pile_set_name": "StackExchange"
} |
Q:
Display the file in page when the type of that is not specified
When I want to show an image I use something like this:
public ActionResult Show(int id) {
var MyFile = GetFromDB(id);
return File(MyFile.Data, MyFile.ContentType);
}
And in View:
<img alt ="" src='@Url.Action("show", new { id = 36 })'/>
So assume we have some other types of file like txt, pdf, ...
And I think to use a general tag to show all kind of files instead of <img>. Does any one have any idea about it?
A:
It is not easy, because some files need initialization or need additional declarations to specify how they should be presented, but you can try with iframe:
<iframe src='@Url.Action("show", new { id = 36 })'></iframe>
It will use browser built-in way of presenting documents.
| {
"pile_set_name": "StackExchange"
} |
Q:
Editing keys in a plist dictionary?
I am writing a word puzzle game. I want to have a plist file where i keep track of the users solutions to my puzzles. In other words, I want to save data whenever the user finishes or pauses a level.
The game consists of 20 levels in each of 5 categories (so 100 levels total). The questions are loaded from a plist when the user starts the game. The objective is basically to unscramble the message and i want them to be able to come back to started levels later. Their solutions must then be stored in some sort of editable (mutable?) array.
I'm fairly new to coding and I've looked online but didn't find any answers. I just dont know how to implement it.
My Question: If I create a .plist file to store the users' solutions (with 5 array keys for each category, each array having a set of 20 blank string values) is it possible to edit entries as the user plays the levels?
A:
It is easy to write an NSDictionary or NSArray to a .plist file using the method
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
So, why not load your state information from the plist into an array, each containing an NSMutableDictionary with the user's answers. Then, when the user sets a new answer, set a new object for that question key. When finished, write the parent NSArray to file using the method above - voila.
EDIT - NSArray would work better in this instance
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysqli update query doesn't work
So I'm trying to build a kind of update email function, and the part that should put it into the db looks like this
<?php $emailfrom = $_POST['emailfrom'];
$emailto = $_POST['emailto'];
$query = sprintf('UPDATE `users` SET `email`="%s" WHERE `email`="%s"`',
mysqli_real_escape_string($db, $emailfrom),
mysqli_real_escape_string($db, $emailto));
mysqli_query($db, $query);
The problem is that the row don't update... And I need help in knowing why, as I'm not so well experienced with mysql, used other dbs mainly earlier
A:
You've got syntax error in your query.
\/
$query = sprintf('UPDATE `users` SET `email`= "%s" WHERE `email`= "%s"`',
mysqli_real_escape_string($db, $emailfrom),
mysqli_real_escape_string($db, $emailto));
mysqli_query($db, $query);
Also, you probably want to change emails from emailFrom to emailTo, now you are doing it the other way around. After edit:
$query = sprintf('UPDATE `users` SET `email`= "%s" WHERE `email`= "%s"`',
mysqli_real_escape_string($db, $emailto),
mysqli_real_escape_string($db, $emailfrom));
mysqli_query($db, $query);
| {
"pile_set_name": "StackExchange"
} |
Q:
Architecture Critique: SQL Server FOR XML into XSLT for Rich HTML Interface
Can I get some constructive feedback about the following architecture?
Simplified Architecture Summary:
Return XML from your SQL Server (using FOR XML) and pass it straight into a XSL transform to produce a rich HTML web site.
What are the pro’s and con’s of such a system when compared with a conventional 3-tier ASP.NET architecture?
A:
We have done something like this. And it works for very simple pages. But as soon as you would like to include some client side javascript and similar, you are doomed.
The generated output is hidden in the XSLT stylesheets and it is very hard to read, maintain and fix bugs.
Testing can be done, but also with much more effort than before.
The MVC pattern and similar is much better suited for such a scenario.
| {
"pile_set_name": "StackExchange"
} |
Q:
Based loop groups as stacks?
I have been stuck for some time, thinking about the following question.
Let $G$ be a Lie group. Its classifying space $BG$ can be seen as the differentiable stack $[pt/G]$, which is of dimension $-dim(G)$.
Can something similar be said for the based loop group $\Omega G$ of pointed maps from $S^1$ to $G$ ?
I mean, is $\Omega G$ a differentiable stack and, if so, what is its dimension?
Best,
O.
A:
$\Omega G$ won't be a differentiable stack unless you are willing to go to infinite dimensions. Provided you are considering $S^1$ as a smooth manifold, Nerses answer above is correct- it gives you a nice sheaf on the site of manifolds (it's even concrete- a so-called diffeological space). It's also representable by an infinite dimensional manifold.
The other thing you could mean, is you might mean $S^1$ (or $B \mathbb{Z}$) as a homotopy type, or the "categorical circle." For this, you will have to go to derived manifolds (otherwise you will just recover $G$ back again), and then, $\Omega X = T[1] X$ is the shifted tangent bundle for any manifold $X,$ in particular, for $X=G$. $T[1] X$ is the graded manifold whose underlying space is $X$ and whose structure sheaf $\mathcal{O}$ is given by $\mathcal{O}^{-n}(U)=\Omega^{n}_{dR}(U).$
Edit: Actually, in the above, I am computing $\mathcal{L} X$ the free loops on $X$:
For $x \in X,$ the based loops at $X$ are the homotopy fibered product $* \times_{X} T[1]X$, but since evaluation at the base point of $S^1$ is just the vector bundle map $T[1]X \to X,$ which is a submersion, the ordinary pullback is a homotopy pullback, so we get simply $\Omega_x X=T_x[1] X=\left(T_x X\right)[1],$- the graded manifold associated to the graded vector space with $T_x X$ sitting in degree $-1.$ It's underlying manifold is just a point, but it's structure sheaf is given by the exterior algebra of the dual this vector space (but placed in non-positive degrees).
A:
The based loop-group $\Omega G$ can be thought of as a sheaf on the category of manifolds. You can simply declare $\Omega G(X)$ to be the subset of $C^\infty(X\times I, G)$ of functions that are constant on $X\times\{0,1\}$ with value at the unit of $G$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Excel produce a random distribution of a fixed size and a fixed sum?
We need an Excel macro or formula or something that can produce a random distribution of integers such that the result set has a fixed size and a fixed sum. More specifically, we want to simulate a month's worth of integer data-points (hence a fixed size) whose total represents demand for that month (hence the fixed sum). Does such a feature already exist in Excel or from a third-party? If not, any tips on writing one?
I am looking for something that looks like this:
GetSetWithSum( count: 5, sum: 36)
The result of such a formula would be something like this:
5
13
9
6
3
A:
The following code works, but it does have the possibility of returning 0 for one or more of the values, depending on how quickly it reaches the required total (using your example, if the first random number is 36 then the other four will be 0). the fine folks on Stack OverFlow may be better at writing code which prevents this than I.
Core Random Generator Code
Sub RandomNumbers(ByVal ReqNum As Integer, ByVal ReqSum As Integer, Output As Collection)
Dim NewNum As Integer, SumNum As Integer
Dim I As Integer
SumNum = 0
Do Until (SumNum = ReqSum) Or (Output.Count = (ReqNum - 1))
Randomize Timer
NewNum = Int((ReqSum - SumNum) * Rnd + 1)
SumNum = SumNum + NewNum
Output.Add NewNum
Loop
If Output.Count < ReqNum Then
If SumNum < ReqSum Then
Output.Add (ReqSum - SumNum)
Else
NewNum = Output.Count
For I = (NewNum + 1) To ReqNum
Output.Add 0
Next I
End If
End If
End Sub
you can call this Sub using code with something along the lines of this. This code simply puts the random values into column A.
Dim Numbers As New Collection, NumNum As Integer, SumofNum As Integer
Range("A:A").ClearContents
NumNum = 5
SumofNum = 36
Call RandomNumbers(NumNum, SumofNum, Numbers)
For SumofNum = 1 To Numbers.Count
NumNum = Numbers(SumofNum)
Cells(SumofNum, 1).Value = NumNum
Next SumofNum
| {
"pile_set_name": "StackExchange"
} |
Q:
How to detect touch location of the bottomView when the topView is tapped
I have four UIViews(topViews) added as subviews to the mainView. I want to create a bezierPath from the topViews to an endposition. For this I need to get the location of the topView with respect to the bottomView.
I want the bottomView not to detect any touches, I only want the topViews to get the touches, but in return give their positions with regards to the bottomView.
How is this possible? I am currently using touchesBegan that is justing giving me location from the whole bottomview.
A:
you can use topView.convert(point, to: bottomView) method to convert point detected from the topView coordinate system to bottomView coordinate system.
| {
"pile_set_name": "StackExchange"
} |
Q:
Автообноление activity
Есть приложение с выводом на экран текущего значения заряда батареи.
Код:
public class MainActivity extends Activity {
BroadcastReceiver batteryLevelReceiver = null;
boolean batteryLevelRegistered = false;
TextView battLevel;
IntentFilter batteryLevelFilter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
batteryStat();
registerReceiver(batteryLevelReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
public void batteryStat() {
battLevel = (TextView) findViewById(R.id.battery);
batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
batteryLevelRegistered = false;
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
if (battLevel != null) {
String add_text = "";
if (plugged == BatteryManager.BATTERY_PLUGGED_AC) {
add_text = " AC";
} else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
add_text = " USB";
}
battLevel.setText(level + "%" + add_text);
}
}
;
};
}
}
Дело в том, что при запуске приложения оно показывает текущий заряд, но вот при длительной роботе, если заряд уменьшился скажем, приложение все равно показывает то значение, которое появилось при его запуске.
То есть для того чтобы обновить значение заряда на экране, нужно закрыть и обратно запустить программу.
Как сделать так, что приложение автоматически обновляло значение на экране, соответственно с зарядом батареи?
Типа как в статусбаре.
A:
Вы явно отписываетесь от обновлений в строчке context.unregisterReceiver(this);. Отписываться надо при завершении активити. В onStop или onDestroy или onPause - в зависимости от того, где подписываетесь на уведомления. Попробуйте перенести эту строку в onDestroy
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem using LIMIT in a MySQL subquery?
I have a SQL query as follows
SELECT * FROM epf_application WHERE
application_id IN
(SELECT
application_id FROM
epf_application_device_type WHERE
device_type_id IN
(SELECT
device_type_id FROM
epf_device_type WHERE
name="someDevice") LIMIT 30) LIMIT
30
When I run it in phpMyAdmin, I get the following error
1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME
subquery'
From the error, I am guessing that there is a problem with placing LIMIT in a subquery. Any suggestions on how I can fix this?
A:
SELECT
ea.*
FROM
epf_application ea JOIN epf_application_device ead
ON ead.application_id = ea.application_id
JOIN epf_device_type edt
ON edt.device_type_id = ead.device_type_id
WHERE
edt.name = 'someDevice'
LIMIT 30
| {
"pile_set_name": "StackExchange"
} |
Q:
Backbone Model custom URL
I am unsure how to call and pass a variable into my model to call a custom url.
The url I am trying to call is:
http://localhost:8080/SIMS/resource/class/teacher/{id}
ID is not class ID its teacher ID.
In the main.js I am unsure how to pass an extra parameter into the model and use it in the model. HOw would I go about doing this ?
Model:
window.Class = Backbone.Model.extend({
urlRoot: "http://localhost:8080/SIMS/resource/class/teacher",
defaults: {
"id": null,
"grade": "",
"year": "",
"Tname": "",
"Sname": ""
},
parse: function(response){
response.id = response.idClass;
} ,
toJSON: function(){
}
});
window.ClassCollection = Backbone.Collection.extend({
model: Class,
url: "http://localhost:8080/SIMS/resource/class/teacher",
parse: function(response){
for (var i=0; i<response.length; i++)
{
response.id = response.idClass;
}
return response ;
}
});
Main.js
routes: {
"sidebar/:id": "sidebar"
},
sidebar: function(){
this.classList = new ClassCollection();
this.classList.fetch({success: function() {
$('#sidebar-collapse').html( new TeachersidebarView({model: app.classList}).render().el );
if (callback) callback();
}});
},
View
window.TeachersidebarView = Backbone.View.extend({
tagName:'ul',
initialize:function () {
this.templateA = _.template(tpl.get(sidebarA));
this.templateB = _.template(tpl.get(sidebarB));
this.model.bind("reset", this.render, this);
var self = this;
this.model.bind("add", function (Class) {
$(self.el).append(new TeachersidebarItemView({model:Class}).render().el);
});
},
render:function (eventName) {
$(this.el).html(this.templateA());
_.each(this.model.models, function (Class) {
$(this.el).append(new TeachersidebarItemView({model:Class}).render().el);
}, this);
$(this.el).append(this.templateB());
return this;
}
});
window.TeachersidebarItemView = Backbone.View.extend({
tagName:"li",
initialize:function () {
this.template = _.template(tpl.get('sidebarC'));
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
render:function (eventName) {
$(this.el).html(this.template(this.model.attributes));
return this;
}
});
A:
The url property of your model can be a function which concatenates and returns the base URL and the dynamic id property. Something like this:
baseURL: "http://localhost:8080/SIMS/resource/class/teacher",
url: function() { return this.baseURL + '/' + this.id; },
| {
"pile_set_name": "StackExchange"
} |
Q:
NameError: name 'unicode' is not defined when I install package - Python 3
I'm trying to install the package. But there is the error. How can I fix it?
C:\WINDOWS\system32>python -m pip install zopyx.convert2
Collecting zopyx.convert2
Using cached zopyx.convert2-2.4.6.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Admin\AppData\Local\Temp\pip-build-e90y11sx\zopyx.convert2\setup.py", line 17, in <module>
desc = unicode(file(os.path.join('docs', 'source', 'README.rst')).read().strip(), 'utf-8')
NameError: name 'unicode' is not defined
A:
It looks to me like this library, which has not been updated since 2012, is not compatible with Python 3 and they haven't properly indicated that in the pypi metadata.
The source code is here, if you can't find an alternative library, you may be able to update it to python3 yourself and either make a pull request or a fork.
| {
"pile_set_name": "StackExchange"
} |
Q:
Phoenix frameworks and validating embeds
Given the following code works fine:
image_1 = %Image{naturalHeight: "100", naturalWidth: 100}
diffbot_objects = [
%DiffbotObject{
availability: true,
images: [
image_1
]
}
]
changeset = Ecto.Changeset.change(product)
changeset = Ecto.Changeset.put_embed(changeset, :diffbot_objects, diffbot_objects)
How can I ensure that fields are validated on the Image model? I can generate a changeset using the the changeset method on the Image model (see below) but I'm unable to insert data using a nested changeset, it has to be e struct it seems.
My image model:
defmodule Shopshare.Product.DiffbotObject.Image do
use Shopshare.Web, :model
embedded_schema do
field :naturalHeight, :integer
field :naturalWidth, :integer
end
@required_fields ~w(naturalHeight, naturalWidth)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
A:
I saw that you are using put_embed but I don't see the schema from product. I don't know if this is the real problem. But I tried some code that works.
I create a new app with Blog and Post model. I used the generate models:
mix phoenix.gen.model Blog blogs name:string
mix phoenix.gen.model Post posts title:string body:text blog_id:references:blogs
I'm using a simple validation for required fields. Let's take a deeper look into Blog model:
defmodule MyApp.Blog do
use MyApp.Web, :model
schema "blogs" do
field :name, :string
has_many :posts, MyApp.Post
timestamps
end
@required_fields ~w(name)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
I create manually the has_many association with posts (it isn't created with my generate model). Now, we have the Post model:
defmodule MyApp.Post do
use MyApp.Web, :model
schema "posts" do
field :title, :string
field :body, :string
belongs_to :blog, MyApp.Blog
timestamps
end
@required_fields ~w(title body)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
Now, we can play in the IEx (iex -S mix):
iex(1)> blog_changeset = MyApp.Blog.changeset(%MyApp.Blog{}, %{name: "blog name"})
%Ecto.Changeset{...}
iex(2)> blog_changeset.valid?
true
iex(3)> invalid_post_changeset = MyApp.Post.changeset(%MyApp.Post{}, %{})
%Ecto.Changeset{...}
iex(4)> blog_changeset = Ecto.Changeset.put_assoc(blog_changeset, :posts, [invalid_post_changeset])
%Ecto.Changeset{action: nil,
changes: %{name: "blog name",
posts: [%Ecto.Changeset{action: :insert,
changes: ..., constraints: [],
errors: [title: "can't be blank", body: "can't be blank"], filters: %{},
...]}, ...,
model: %MyApp.Blog{...}, optional: [], opts: [], params: %{"name" => "blog name"},
prepare: [], repo: nil, required: [:name],
types: %{...},
valid?: false, validations: []}
iex(5)> blog_changeset.valid?
false
I suppressed some output to focus in the the errors. Changeset works like a tree. So, you can have the parent changeset and the children. The difference from your code is that I'm using the put_assoc (https://hexdocs.pm/ecto/Ecto.Changeset.html#put_assoc/4) (maybe the relation too, but I didn't see your schema).
The behaviour expected from put_assoc:
If the association has no changes, it will be skipped. If the association is invalid, the changeset will be marked as invalid. If the given value is not an association, it will raise.
I hope this can help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Buttons in box and text resizeable
Desktop View:
Desktop View
Mobile View:
Mobile View
.event_item {
background: #2b325f;
color: white;
text-align: center;
padding: 30px;
vertical-align: top;
margin:0 0 5px 0;
height: 215px;
}
.event_item h2{margin-bottom:0;}
.event_item h6{margin-bottom:10px;}
.event_summary{display:none;}
.event_item_read p{color:#b00909;text-transform:uppercase;}
.btn-primary{
background:#b00909 !important;
color:white;
border-color: transparent;
}
.btn-align {
text-align: center;
margin-top: -20px;
margin-bottom: 20px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row eventRow">
<div class="col-md-4">
<div class="events">
<div class="event_item">
<div class="col-md-12">
<h6>03/16/2016</h6>
<h2>Just a title testing, why is this long?</h2>
<p>Detroit</p>
<h5 style="font-weight: bold;">7pm - 7am</h5>
</div>
</div>
</div>
<div class="btn-align">
<button type="button" class="btn btn-primary doEdit" editKey="'.$key.'"data-toggle="modal" data-target="#editEvent">
Edit Event
</button>
<button type="button" class="btn btn-primary doDelete" delKey="'.$key.'" data-toggle="modal" data-target="#deleteEvent">
Delete Event
</button>
</div>
</div>
</div>
</div>
How would I fix this issue?
A:
You're missing your row class. The column floats which collapses the container, which made you decide to add a set height, which was too short for that amount of text. Remove the fixed height and add the .row class to .event_item and it should be fixed.
https://jsfiddle.net/19aqx97w/
@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css);
.event_item {
background: #2b325f;
color: white;
text-align: center;
padding: 30px;
vertical-align: top;
margin:0 0 5px 0;
}
.event_item h2{margin-bottom:0;}
.event_item h6{margin-bottom:10px;}
.event_summary{display:none;}
.event_item_read p{color:#b00909;text-transform:uppercase;}
.btn-primary{
background:#b00909 !important;
color:white;
border-color: transparent;
}
.btn-align {
text-align: center;
margin-top: -20px;
margin-bottom: 20px;
}
<div class="container">
<div class="row eventRow">
<div class="col-md-4">
<div class="events">
<div class="event_item row">
<div class="col-md-12">
<h6>03/16/2016</h6>
<h2>Just a title testing, why is this long?</h2>
<p>Detroit</p>
<h5 style="font-weight: bold;">7pm - 7am</h5>
</div>
</div>
</div>
<div class="btn-align">
<button type="button" class="btn btn-primary doEdit" editKey="'.$key.'"data-toggle="modal" data-target="#editEvent">
Edit Event
</button>
<button type="button" class="btn btn-primary doDelete" delKey="'.$key.'" data-toggle="modal" data-target="#deleteEvent">
Delete Event
</button>
</div>
</div>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Upper Triangular Matrix Definition
Is
\begin{bmatrix}
1 & 1 & 2 & 3 \\
0 & 0 & 4 & 4 \\
0 & 0 & 4 & 4 \end{bmatrix}
an upper triangular matrix? My linear algebra teacher says that the main diagonals must have exclusively pivots or zeros, but I thought that the only requirement for upper triangular form is to have zeros below the main diagonal. Online sources like proofwiki seem to agree with me.
Whose definition is correct?
A:
One source that I have has a definition (kind of hidden away in the questions): "An $m\times n$ matrix $A$ is called upper triangular if all entries lying below the diagonal entries are zero, that is, if $A_{ij}=0$ whenever $i>j$." (p.21 Friedberg et al, Linear Algebra 4th edition)
I have yet to find a source that explicitly contradicts this definition (so deliberately states that $m \times n$ matrices cannot be upper triangular), thereby limiting upper triangular matrices to square matrices only. But in all my other sources we have something similar to "...$A \in M_{n \times n}(K)$...upper triangular iff...". The other sources I could consult here was p.37 Cullen (Matrices and linear transformations) and p.149 Golan (The linear algebra a beginning graduate student ought to know).
| {
"pile_set_name": "StackExchange"
} |
Q:
Python unittest mock configuration not proliferating to test method
I have a complex class which I would like to mock in testing. However, I want to be able to set a particular attribute on my mocked class so that my function under test will work. Simple, runnable example with actual and expected output is below.
In my example, why doesn't my mock configuration proliferate to my_module.instantiate_class_do_stuff? It's clear that MyClass is indeed being mocked, but my attempt to configure the mocking of MyClass.a just isn't sticking.
Contents of directory tmp:
tmp
├── __init__.py
├── my_module.py
└── test_my_module.py
Note that __init__.py is empty.
Contents of file my_module.py:
class MyClass:
def __init__(self):
# Do expensive operations that will be mocked in testing.
self.a = 7
def instantiate_class_do_stuff():
"""Create MyClass instance and do stuff with it"""
instance = MyClass()
print('Value of a in instantiate_class_call_method: {}'.format(instance.a))
# Do stuff with instance...
Contents of file test_my_module.py:
import unittest
from unittest.mock import patch
from tmp import my_module
class MyTestCase(unittest.TestCase):
def setUp(self):
print('*' * 79)
def test_create_class_call_method_1(self):
"""Try using the Mock's configure_mock method."""
with patch('tmp.my_module.MyClass') as p:
p.configure_mock(a=10)
print('Value of a in test_create_class_call_method_1: {}'
.format(p.a))
my_module.instantiate_class_do_stuff()
self.assertTrue(True)
def test_create_class_call_method_2(self):
"""Try passing in kwargs to patch, which should make it to
configure_mock, according to the docs.
"""
with patch('tmp.my_module.MyClass', a=10) as p:
print('Value of a in test_create_class_call_method_2: {}'
.format(p.a))
my_module.instantiate_class_do_stuff()
self.assertTrue(True)
def test_create_class_call_method_alternate_2(self):
"""Try using patch.object instead of plain patch."""
with patch.object(my_module, 'MyClass', a=10) as p:
print('Value of a in test_create_class_call_method_3: {}'
.format(p.a))
my_module.instantiate_class_do_stuff()
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
Actual output from running test_my_module.py:
*******************************************************************************
Value of a in test_create_class_call_method_1: 10
Value of a in instantiate_class_call_method: <MagicMock name='MyClass().a' id='140029598201104'>
*******************************************************************************
Value of a in test_create_class_call_method_2: 10
Value of a in instantiate_class_call_method: <MagicMock name='MyClass().a' id='140029598270096'>
*******************************************************************************
Value of a in test_create_class_call_method_3: 10
Value of a in instantiate_class_call_method: <MagicMock name='MyClass().a' id='140029598347088'>
Expected output from running test_my_module.py:
*******************************************************************************
Value of a in test_create_class_call_method_1: 10
Value of a in instantiate_class_call_method: 10
*******************************************************************************
Value of a in test_create_class_call_method_2: 10
Value of a in instantiate_class_call_method: 10
*******************************************************************************
Value of a in test_create_class_call_method_3: 10
Value of a in instantiate_class_call_method: 10
So, how can I make my attribute configuration be effective when my function under test is actually run?
Similar (but different) question I posted but didn't get a particularly satisfactory answer
A:
Well, this certainly wasn't very intuitive to me, but I figured it out.
I noticed that in my testing methods, the value of p (the mocked instance of MyClass) has a __repr__ like <MagicMock name='MyClass' id='140054079807440'>.
However, inside the function under test, instantiate_class_do_stuff, the value of instance has a __repr__ like <MagicMock name='MyClass()' id='140054079941392'>. The difference is in the () after MyClass.
So, it would appear that I wasn't mocking the correct thing - I want to mock the a attribute on the return value of MyClass.
So, here's what a working test looks like:
def test_creat_class_call_method(self):
# Create a mock which will be returned by MyClass.
m = MagicMock()
m.a = 10
with patch('tmp.my_module.MyClass', return_value=m) as p:
my_module.instantiate_class_do_stuff()
And the print statement in my_module.instantiate_class_do_stuff prints the following:
Value of a in instantiate_class_do_stuff: 10
Success!
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem using $var for shortcode attr value
I am trying to pass a variable value to a shortcode attribute. I can't get it to work.
Is the following supposed to work, or must values be literal?
$mycat = 'books';
$myshortcode = '[products category="'.$mycat .'"]';
echo do_shortcode($myshortcode);
The above outputs nothing. If I replace it with
$myshortcode = '[products category="books"]';
echo do_shortcode($myshortcode);
Then it produces the expected result.
I'm placing this code in a 'Custom Code Block' in the HeadWay Theme's Visual editor. I'm trying to find out if the problem I have has to do with the way HeadWay parses the content of the custom code block, or if it is indeed not possible to construct a string for use with do_shortcode() like this.
A:
After more probing I found out, that the problem must be with the way HeadWay is parsing the content of the custom code block.
I still don't understand it exactly, but changing the code from this:
$mycat = 'books';
$myshortcode = '[products category="'.$mycat .'"]';
echo do_shortcode($myshortcode);
to this
$mycat = 'books';
$myshortcode = 'products category="'.$mycat .'"';
$myshortcode = '[' . $myshortcode . ']';
echo do_shortcode($myshortcode);
made it work...
| {
"pile_set_name": "StackExchange"
} |
Q:
$f(z)$ is analytic on unit disk $ \cup \{1\}, f(1)=1$ , then $f'(1)\geq0$
$D= \big\{z\in \Bbb C:|z| \lt 1\big\}$. A function $f(z)$ such that
1) $f(D)\subset D, f(1)=1$
2) $f(z)$ is analytic on $D \cup \{1\}$
show that $f'(1)\geq0$.
If $f'(1)\ne 0$, Could we get that $\arg(f'(1))=0 $?
A:
Let's first prove the following lemma: assume $u,v$ real s.t $\Re{((u+iv)(z-1)+O((z-1))^2}) > 0$ for all $|z| <1$ in a small neighborhood of $1$, then $u \le 0,v=0$.
Proof: picking $z=r<1$ but close enough to $1$, we get $u(r-1)+O((r-1)^2) >0$ hence $u \le 0$. If $v \ne 0$, pick $z=1-\epsilon^2\pm i\epsilon$ and for small enough $\epsilon>0$, $|z|<1$ so $z$ is in the given neighbourhood intersected with the open unit disc, $|z-1|^2=O(\epsilon^2)$ and $\Re{((u+iv)(z-1))+O((z-1))^2}=|u|\epsilon^2 \pm v\epsilon+O(\epsilon^2)=\epsilon (|u|\epsilon \pm v+O(\epsilon))$ which can be clearly made negative if we choose the right sign in $\pm$ and small enough $\epsilon >0$, so contradiction.
With this lemma let's prove the result. Take $g=\frac{1-f}{1+f}$, $g$ is analytic on the unit disc, extends analytically at $1$, and $\Re g >0$ on the unit disc, while $g(1)=0$. Plainly $2g'(1)=-f'(1)$ so we need to prove that $g'(1) \le 0$. We can write the Taylor series on a small disc around $1$ as $g(z)=(u+iv)(z-1)+O((z-1)^2)$ and $\Re g >0$ on the piece of that disc that belongs to the unit disc. Applying the lemma we get $u \le 0, v=0$ and obviously $g'(1)=u \le 0$, so done!
| {
"pile_set_name": "StackExchange"
} |
Q:
Autocomplete extender in Ajax Toolkit and JQuery limiting to "Starts with"
There are many flavours to the AutoComplete implementation, I first did a WPF implementation that was very robust, each entry took keywords, so when searching for an employee, it didn't matter if you typed the first or last name, the results came back similar to Google Suggest.
What I have found limiting in both the JQquery autocomplete and the ASP.Net Autocomplete extender is that there is no keyword search, or contains functionality, it simply uses a "Startswith" type search.
For example, in order to Search for "Mark Adams" as a staff name, you have to type in M,a,r, etc. If you typed in A,d, etc, no result would return.
Does anyone know of plans for this? Is there anything out there right now?
A:
You must have missed jquery autocomplete option like
matchContains:true
It does exactly what you want. It would match for Mark Adams, when you type A,d etc.
Edit
And for ajaxtoolkit AutoCompleteExtender, i fear you don't get any option equivalent of matchContains in jquery. But you can do it easily in service method. Set it as...
ServiceMethod="GetNameList"
where GetNameList contains the whole logic of how to match the data. E.g.
public partial class _Default : System.Web.UI.Page {
[WebMethod]
public static string[] GetNameList(string prefixText, int count) {
string sql = String.Format("select name from customers where name like @given_name");
List<string> nameList = new List<string>();
using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind;Data Source=."))
using (SqlCommand command = new SqlCommand(sql, connection)) {
connection.Open();
command.Parameters.AddWithValue("@given_name", "%"+prefixText"%");
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
nameList.Add(reader.GetString(0));
}
}
}
return nameList.ToArray();
}
}
The below is the code line, which does the matching.
command.Parameters.AddWithValue("@given_name", "%"+prefixText"%");
| {
"pile_set_name": "StackExchange"
} |
Q:
undefined method `model_name' for NilClass:Class when trying to create a record in my database
Ive got a problem with my Rails app.
When I try to create a new client in my clients table im getting this error => undefined method model_name for NilClass:Class
It's telling me the error is in my show view at line #2.
1: <%- model_class = @client.class -%>
2: <h1><%=t '.title', :default => model_class.model_name.human %></h1>
3:
4: <p>
5: <strong><%= model_class.human_attribute_name(:name) %>:</strong><br>
Heres my show view..
<%- model_class = @client.class -%>
<h1><%=t '.title', :default => model_class.model_name.human %></h1>
<p>
<strong><%= model_class.human_attribute_name(:name) %>:</strong><br>
<%= @client.name %>
</p>
<p>
<strong><%= model_class.human_attribute_name(:detail) %>:</strong><br>
<%= @client.detail %>
</p>
<p>
<strong><%= model_class.human_attribute_name(:more_detail) %>:</strong><br>
<%= @client.more_detail %>
</p>
<p>
<strong><%= model_class.human_attribute_name(:more_details) %>:</strong><br>
<%= @client.more_details %>
</p>
<div class="form-actions">
<%= link_to t('.back', :default => t("helpers.links.back")),
clients_path, :class => 'btn' %>
<%= link_to t('.edit', :default => t("helpers.links.edit")),
edit_client_path(@client), :class => 'btn' %>
<%= link_to t('.destroy', :default => t("helpers.links.destroy")),
client_path(@client),
:method => 'delete',
:confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')),
:class => 'btn btn-danger' %>
</div>
Here's my controller =>
class ClientsController < ApplicationController
respond_to :html
def index
@clients = Client.all
respond_with (@clients)
end
def new
@clients = Client.new
respond_with (@clients)
end
def create
@clients = Client.new(params[:name])
if @clients.save
flash[:notice] = "Client successfully created"
end
respond_with(@clients)
end
def destroy
@clients = Client.find(params[:id])
@clients.destroy
flash[:notice] = "Client has been removed."
respond_with(@clients)
end
end
I can't see where the problem is?
Ive recently installed the rails-twitter-bootstrap gem but don't think that would effect it much.
A:
You're setting in your controller the value of @clients (with s at the end) and accessing in your view just the @client variable, i.e. without s. Fix this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Primefaces tab not updating properly
I have a dialogue with a commandButton, and this is what I'm trying to do:
Do some Java work
Update a Primefaces tab
Make my dialogue box disappear
Go to that certain tab.
This is the code I'm using:
<p:commandButton value="Submit"
action="<some java work>"
oncomplete="dialogue.hide(); sideTabs.select(1)"
update="<update side tab">
</p:commandButton>
The problem is, this only works once between refreshes. What I mean is, I click the button, and everything works fine-the tab changes to the requested tab, the tab is updated, and the dialogue disappears. But when I click the button again, the requested tab is indeed selected, but isn't properly refreshed until I hit f5. Once I do that, I can click the dialogue button again and the tab will properly refresh again, but once again, only once - until I hit f5 again. So, something like this:
Click the button -> see 1 item in the tab
Click the button again -> still see only 1 item in the tab
Hit f5 -> see 2 items in the tab
Click the button -> see 3 items in the tab
Click the button again -> still see 3 items in the tab
Hit f5 -> see 4 items in the tab
etc...
Does anyone have an idea why this is happening? Do I need to add some page refresh mechanism to my commandButton? If so, how is this done?
Thanks!!!
A:
I've tried to replicate the problem with no success.
Here is a the attribute from my ViewScoped bean:
private String str1 = "a";
private String str2 = "b";
private String update = ":f:t";
private Integer index = 0;
And here is the view:
<h:form id="f">
<p:tabView id="t" widgetVar="tVar" activeIndex="#{viewMBean.index}" >
<p:tab id="a" title="A" >
#{viewMBean.str1}
</p:tab>
<p:tab id="b" title="B">
#{viewMBean.str2}
</p:tab>
</p:tabView>
</h:form>
<p:dialog id="d" widgetVar="dVar">
<h:form>
<p:inputText value="#{viewMBean.str1}" />
<br />
<p:inputText value="#{viewMBean.str2}" />
<br />
<p:inputText value="#{viewMBean.update}" />
<br />
<p:inputText value="#{viewMBean.index}" />
<br />
<p:commandButton value="Submit" update="#{viewMBean.update}" oncomplete="dVar.hide();" />
</h:form>
</p:dialog>
I believe the problem is somewhere else in your code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can withdrawing asylum be illegal?
Julian Assange, one of the founders of WikiLeaks, and its most visible member, was arrested at the Ecuador embassy in London, after Ecuador withdrew his asylum
Today, I announce that the discourteous and aggressive behavior of Mr. Julian Assange, the hostile and threatening declarations of its allied organization, against Ecuador, and especially, the trangression of international treaties, have led the situation to a point where the asylum of Mr. Assange is unsustainable and no longer viable
Wikileaks then made this tweet
Ecuador has illigally terminated Assange political asylum in violation of international law. He was arrested by the British police inside the Ecuadorian embassy minutes ago.
This is a purely political decision either way, but what international law(s) are at play here? Can the mere act of withdrawing asylum really be illegal?
A:
what international law(s) are at play here?
In the case of Assange being removed from the Ecuadorian embassy with the consent of the ambassador -- only the Vienna Convention on Diplomatic Relations.
Subsequent likely proceedings are not covered in this answer but, for example, the Universal Decaration on Human Rights can apply to extradition proceedings.
Refugee vs Asylum seeker
The parts of international law that I have read (few) mostly seem to cover refugees. I suspect that most of us use these terms to mean more or less the same thing. There may be a subtle distinction in law that I don't know about (unsurprisingly)
However, there is a significant difference between withdrawing asylum in an embassy and expulsion from a country of refuge. Most International law seems to cover the latter.
Definition of refugee
At the beginning of the 1951 Convention Relating to the Status of Refugees it defines refugee. It does so by referring to older documents. Consequently I don't have a good grasp of how exactly one qualifies and what exceptions may exist.
We can all be reasonably certain that someone fleeing war in Syria and crossing into Turkey should be regarded as a refugee in international law. Assange's case is not so clear.
Citizenship and Asylum
Prior to 2017 Assange was an Australian citizen in the United Kingdom seeking Asylum in the embassy of Ecuador against possible extradition to Sweden because he feared extradition to the United States where he expected to be mistreated.
As phoog commented, in 2017 Assange obtained Ecuadorian citizenship. International laws do not provide for people to be an international refugee in their own country -- or at least that is not usually seen as an international matter. If Assange was an Ecuadorian citizen in Ecuadorian territory, the rest of this answer would not apply. I believe when you obtain citizenship in your country of refuge, you are now a citizen, not an international refugee.
Embassies and Territory
As the New York Times reports
As a matter of international law, an embassy is not ''territory'' of the sending state; it is territory of the receiving state that is accorded, through various treaties and customs, some immunities from host-country law.
This is important because someone being expelled from the London embassy of Ecuador is not being expelled from Ecuador.
Can the mere act of withdrawing asylum really be illegal?
International law on asylum applies where someone outside their home country applies for asylum in the country where they are present.
Some international laws do cover the situation where asylum or refugee-status is withdrawn or where someone is expelled from a country.
Generally a country "shall not expel a refugee lawfully in their territory save on grounds of national security or public order".
Note that, with respect to Ecuador, Assange was not in their territory. lawfully or otherwise.
We can look at some International law, along with other reasons why they likely don't apply to Assange.
1928 Convention on Asylum
The 1928 Convention on Asylum was signed by Ecuador. The UK is not a signatory for geographical reasons so it does not apply to the UK nor to UK territory.
It says
Signed in Havana, February 20, 1928, at the Sixth International Conference of
American States
...
Article 1.-
It is not permissible for States to grant asylum in legations, warships, military
camps or military aircraft, to persons accused or condemned for common crimes,
or to deserters from the army or navy.
Persons accused of or condemned for common crimes taking refuge in any of the
places mentioned in the preceding paragraph, shall be surrendered upon request
of the local government.
Which suggests someone who is sheltering in a legation should be surrendered if they were accused of the common crime of failure to appear in court after being granted bail.
It doesn't explicitly say anything about withdrawing asylum though.
1951 Convention Relating to the Status of Refugees
I believe this applies to both UK territory and to Ecuadorian territory.
Crime
Someone who has committed a serious crime is excluded:
F. The provisions of this Convention shall not apply to any person with
respect to whom there are serious reasons for considering that:
...
(b) he has committed a serious non-political crime outside the country of
refuge prior to his admission to that country as a refugee;
A crime punishable by a year in prison may be serious enough.
New citizenship
C. This Convention shall cease to apply to any person falling under the
terms of section A if:
(1) He has voluntarily re-availed himself of the protection of the country
of his nationality; or
(2) Having lost his nationality, he has voluntarily re-acquired it; or
(3) He has acquired a new nationality, and enjoys the protection of the
country of his new nationality; or ...
Assange acquired Ecuadorian citizenship in 2017.
Expulsion
Sections 32 and 33 cover expulsion:
Article 32
expulsion
1. The Contracting States shall not expel a refugee lawfully in their territory save on grounds of national security or public order.
Of course there is another reason this does not apply to Assange -- he was not in the territory of Ecuador.
Being moved from one part of London to another part of London does not constitute expulsion from a country. Certainly not from Ecuador.
1954 Caracas Convention on Diplomatic Asylum
The UK is not a signatory to this since it is not a member of the Organization of American States. So this does not apply to the UK or to actions on UK territory.
The governments of the Member States of the Organization of American
States, desirous of concluding a Convention on Diplomatic Asylum, have agreed
to the following articles:
Article I. Asylum granted in legations, war vessels, and military camps or
aircraft, to persons being sought for political reasons or for political offenses shall be respected by the territorial State in accordance with the provisions of this Convention.
...
Article III. It is not lawful to grant asylum to persons who, at the time of
requesting it, are under indictment or on trial for common offenses or have been
convicted by competent regular courts and have not served the respective
sentence, nor to deserters from land, sea, and air forces, save when the acts giving rise to the request for asylum, whatever the case may be, are clearly of a political nature.
At the time of his Asylum request, I believe Assange was indicted for extradition to Sweden on charges of rape. Assange promised the court he would show up in court at the specified date for this matter to be considered.
By not showing up, Assange became guilty of the crime of failure to appear.
Other useful references
Asylum Law - Encyclopædia Britannica
The right of asylum falls into three basic categories: territorial, extraterritorial, and neutral.
Universal Decaration on Human Rights - UN
Article 14
Everyone has the right to seek and enjoy in other countries asylum from
persecution
This right may not be invoked in the case of prosecutions genuinely arising
from non-political crimes or from acts contrary to the purposes and principles
of the United Nations.
A:
The obvious candidate treaty is the 1951 Refugee Convention, of which Ecuador seems to be a contracting party. This has at least two relevant articles, dealing with expulsion in general, and return specifically.
Article 32: Expulsion
The Contracting States shall not expel a refugee lawfully in their territory save on grounds of national security or public order.
The expulsion of such a refugee shall be only in pursuance of a decision reached in accordance with due process of law. Except where compelling reasons of national security otherwise require, the refugee shall be allowed to submit evidence to clear himself, and to appeal to and be represented for the purpose before competent authority or a person or persons specially designated by the competent authority.
The Contracting States shall allow such a refugee a reasonable period within which to seek legal admission into another country. The Contracting States reserve the right to apply during that period such internal measures as they may deem necessary.
Article 33: Prohibition of expulsion or return
No Contracting State shall expel or return ("refouler") a refugee in any manner whatsoever to the frontiers of territories where his life or freedom would be threatened on account of his race, religion, nationality, membership of a particular social group or political opinion.
The benefit of the present provision may not, however, be claimed by a refugee whom there are reasonable grounds for regarding as a danger to the security of the country in which he is, or who, having been convicted by a final judgement of a particularly serious crime, constitutes a danger to the community of that country.
A:
Assange was a citizen of Ecuador (at least until Ecuador decided to stop protecting him), so the only law that applies to Ecuador's decision to allow the UK to arrest him in Ecuador's embassy is the national law of Ecuador. International law is irrelevant.
Even if the 1951 refugee convention ever applied to him, which is doubtful, it would have ceased to apply when he took Ecuadorian nationality. Article 1(C):
C. This Convention shall cease to apply to any person falling under the
terms of section A if:
(1) ...; or
(2) ...; or
(3) He has acquired a new nationality, and enjoys the protection of the
country of his new nationality; or
...
Ecuador's revocation or "suspension" of his Ecuadorian citizenship could prompt a reassessment of whether Assange meets the definition of refugee under the 1951 convention. To meet the definition, he would have to be "unable or unwilling to avail himself of the protection" of Australia "owing to wellfounded fear of being persecuted for reasons of race, religion, nationality, membership of a particular social group or political opinion."
Refugee protection would enable him to avoid deportation or removal to Australia. None of that would prevent his extradition to the US or Sweden. If he's trying to establish that he is a refugee, he is barking up the wrong tree.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding maximum value of $\arg(z_{1})-\arg(z_{2})$
If $|z|=2$ and $z_{1}$ and $z_{2}$ be two points on that circle.
Then find maximum value of $\arg(z_{1})-\arg(z_{2})$.
where $z,z_{1},z_{2}$ Represents complex number.
$\theta=\arg(z)$ represents principle argument which means $\theta\in (-\pi,\pi]$.
$(a)\; \pi/2\;\;\; (b)\; \pi\;\;(c)\; 2\pi/3\;\;(d)\; 2\pi$
Try: let $z_{1}=x_{1}+iy_{2}$ and $z_{2}=x_{2}+iy_{2}$ be any two complex number.Then $x^2_{1}+y^2_{1}=4,x^2_{2}+y^2_{2}=4$.
So $\displaystyle \arg(z_{1})-\arg(z_{2})=\arctan(\frac{y_{1}}{x_{1}})-\arctan(\frac{y_{2}}{x_{2}})$.
Could some help me to solve it, Thanks
A:
The options $(a)(b)(c)$ can be excluded since for $z_1=-\sqrt 3+i$ and $z_2=-\sqrt 3-i$, we have
$$\arg(z_1)-\arg(z_2)=\frac{5}{6}\pi-\left(-\frac 56\pi\right)=\frac 53\pi$$
which is larger than $\pi$.
We have
$$-\pi\lt\arg(z_1)\le\pi$$
and
$$-\pi\lt\arg(z_2)\le\pi\iff -\pi\le -\arg(z_2)\lt \pi$$
from which
$$-2\pi\lt \arg(z_1)-\arg(z_2)\lt 2\pi$$
follows.
So, the option $(d)$ is not correct.
Hence, there are no correct options.
($\arg(z_1)-\arg(z_2)$ has no maximum value.)
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I insert a new database record in the middle of an existing table?
I want to insert a new highlighted row in my table, but there is already some data present before. What should I do?
please find the picture below;
I would like to have SQL Statements in Rails.
A:
I used the below approach;
User.find(previous id value).update_column(:id, new id value)
For example, id value of 1st row is 1 and id value of third row is 2 and to place the highlighted row whose id value is 3 in between.
At first we will change the id value = 2 to 4 and consequently change the id value = 3 to 2 hence the result.Hope everything is clear.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible that I can use React Routes without a server running
Currently I am using BrowserHistory for my Routing in React which I need to run a nodejs server for it and I dont want to.
Are there any alternative from using BrowserHistory, I have heard of HashHistory, could anyone give me some example of hashHIstory and what is the difference between.
For me I dont care if the url looks ugly, I just dont wanna run a server only for routing.
My current code looks like this:
import React from "react";
import {BrowserRouter, Route, Switch, Redirect} from 'react-router-dom';
import Main from './components/main/main.component';
import SecondView from './components/secondview/secondview.component';
import ThirdView from './components/thirdview/thirdview.component';
import Traineeship from './components/traineeship/traineeships.component';
import InformationFilter from "./components/information/information-filter.component";
const AppRoutes = () => (
<BrowserRouter>
<Switch>
<Route exact path='/' component={Main}/>
<Route path='/secondview' component={SecondView}/>
<Route path='/traineeships' component={Traineeship}/>
<Route path='/information-filter' component={InformationFilter}/>
<Route path='/thirdview/:number?' component={ThirdView}/>
<Redirect from='*' to='/' />
</Switch>
</BrowserRouter>
);
export default AppRoutes;
A:
you can use the Hash-bang mode, by utilising HashRouter
so, in your case, I think you just need to replace BrowserRouter with HashRouter
import React from "react";
import {HashRouter, Route, Switch, Redirect} from 'react-router-dom';
import Main from './components/main/main.component';
import SecondView from './components/secondview/secondview.component';
import ThirdView from './components/thirdview/thirdview.component';
import Traineeship from './components/traineeship/traineeships.component';
import InformationFilter from "./components/information/information-filter.component";
const AppRoutes = () => (
<HashRouter>
<Switch>
<Route exact path='/' component={Main}/>
<Route path='/secondview' component={SecondView}/>
<Route path='/traineeships' component={Traineeship}/>
<Route path='/information-filter' component={InformationFilter}/>
<Route path='/thirdview/:number?' component={ThirdView}/>
<Redirect from='*' to='/' />
</Switch>
</HashRouter>
);
export default AppRoutes;
| {
"pile_set_name": "StackExchange"
} |
Q:
Sorting parallel lists in python - first item descending, second item ascending
I have two lists - one for a team name and the second for points
I wanted to sort them based on the points without losing track of the corresponding team. I found something on SO that works great for doing this - and it sorts teams by points in descending order (most to least).
There doesn't appear to be a sort on the second list.
EDIT - Original Data
Teams Pts
D Clark 0
D Dupuis 2
T Leach 2
J Schutz 0
C Hearder 2
R Pagani 0
M Cameron 2
B Hunter 0
This is what I'm using:
pts, teams = zip(*sorted(zip(pts, teams), reverse=True))
i = 1
for team, num_pts in zip(teams, pts):
standings = str(i) + '. ' + team + " (" + num_pts + ")"
print standings
i += 1
And it results in this:
1. T Leach (2)
2. M Cameron (2)
3. D Dupuis (2)
4. C Hearder (2)
5. R Pagani (0)
6. J Schutz (0)
7. D Clark (0)
8. B Hunter (0)
What I'm trying to do is to add an additional sort on team name - so if there's a tie, then it will sort by names in ascending order,
Like This:
1. C Hearder (2)
2. D Dupuis (2)
3. M Cameron (2)
4. T Leach (2)
5. B Hunter (0)
6. D Clark (0)
7. J Schutz (0)
8. R Pagani (0)
A:
You have two options here. You could use cmp or key as a parameter to sorted.
With a cmp you're defining a function which takes two arguments, the two values being compared. If the first argument is smaller than the second, return a negative number. If it is larger than the second, return a positive number. If they are equal, return 0.
First example using cmp:
pts = ['2', '2', '2', '2', '2', '0', '0', '0', '0']
teams = ['T Leach', 'M Cameron', 'D Dupuis', 'C Hearder', 'R Pagani',
'J Schutz', 'D Clark', 'B Hunter']
def custom_cmp(x,y):
return cmp(x[0], y[0]) or cmp(y[1], x[1])
pts, teams = zip(*sorted(zip(pts, teams), cmp=custom_cmp, reverse=True))
The python or operator will return the left hand side if it evaluates to True (not 0 as described above), otherwise it will return the right hand side. Therefore this custom_cmp returns the comparison of the points from x to y if the points are not equivalent. Otherwise it compares the teams from y to x (the opposite order).
With key on the other hand you are just considering how to view an element individually in order that python will naturally understand how to sort it how you want. We know the first item is being compared properly, so now we just need to flip the second. Numbers would be easy, we could just take the negative. But how do you flip a string?
One approach is to take the ord (which should be an ascii value integer for your strings) of each character in the string. Then you can take the negative of these values and package them into a tuple. This is what one of these would look like:
>>> tuple(-ord(c) for c in 'C Hearder')
(-67, -32, -72, -101, -97, -114, -100, -101, -114)
Second example using key:
def custom_key(pair):
pts, team = pair
return (pts, tuple(-ord(c) for c in team))
pts, teams = zip(*sorted(zip(pts, teams), key=custom_key, reverse=True))
Restrospective edit:
If we're defining a custom key we may as well invert the key itself and remove the reverse argument:
def custom_key(pair):
pts, team = pair
return (-int(pts), team)
pts, teams = zip(*sorted(zip(pts, teams), key=custom_key))
| {
"pile_set_name": "StackExchange"
} |
Q:
Erlang: "extending" an existing module with new functions
I'm currently writing some functions that are related to lists that I could possibly be reused.
My question is:
Are there any conventions or best practices for organizing such functions?
To frame this question, I would ideally like to "extend" the existing lists module such that I'm calling my new function the following way: lists:my_funcion(). At the moment I have lists_extensions:my_function(). Is there anyway to do this?
I read about erlang packages and that they are essentially namespaces in Erlang. Is it possible to define a new namespace for Lists with new Lists functions?
Note that I'm not looking to fork and change the standard lists module, but to find a way to define new functions in a new module also called Lists, but avoid the consequent naming collisions by using some kind namespacing scheme.
Any advice or references would be appreciated.
Cheers.
A:
To frame this question, I would ideally like to "extend" the existing lists module such that I'm calling my new function the following way: lists:my_funcion(). At the moment I have lists_extensions:my_function(). Is there anyway to do this?
No, so far as I know.
I read about erlang packages and that they are essentially namespaces in Erlang. Is it possible to define a new namespace for Lists with new Lists functions?
They are experimental and not generally used. You could have a module called lists in a different namespace, but you would have trouble calling functions from the standard module in this namespace.
| {
"pile_set_name": "StackExchange"
} |
Q:
Writing a Linux int 80h system-call wrapper in GNU C inline assembly
I'm trying to use inline assembly...
I read this page http://www.codeproject.com/KB/cpp/edujini_inline_asm.aspx but I can't understand the parameters passing to my function.
I'm writing a C write example.. this is my function header:
write2(char *str, int len){
}
And this is my assembly code:
global write2
write2:
push ebp
mov ebp, esp
mov eax, 4 ;sys_write
mov ebx, 1 ;stdout
mov ecx, [ebp+8] ;string pointer
mov edx, [ebp+12] ;string size
int 0x80 ;syscall
leave
ret
What do I have to do pass that code to the C function... I'm doing something like this:
write2(char *str, int len){
asm ( "movl 4, %%eax;"
"movl 1, %%ebx;"
"mov %1, %%ecx;"
//"mov %2, %%edx;"
"int 0x80;"
:
: "a" (str), "b" (len)
);
}
That's because I don't have an output variable, so how do I handle that?
Also, with this code:
global main
main:
mov ebx, 5866 ;PID
mov ecx, 9 ;SIGKILL
mov eax, 37 ;sys_kill
int 0x80 ;interruption
ret
How can I put that code inline in my code.. so I can ask for the pid to the user.. like this..
This is my precode
void killp(int pid){
asm ( "mov %1, %%ebx;"
"mov 9, %%ecx;"
"mov 37, %%eax;"
:
: "a" (pid) /* optional */
);
}
A:
Well, you don't say specifically, but by your post, it appears like you're using gcc and its inline asm with constraints syntax (other C compilers have very different inline syntax). That said, you probably need to use AT&T assembler syntax rather than Intel, as that's what gets used with gcc.
So with the above said, lets look at your write2 function. First, you don't want to create a stack frame, as gcc will create one, so if you create one in the asm code, you'll end up with two frames, and things will probably get very confused. Second, since gcc is laying out the stack frame, you can't access vars with "[ebp + offset]" as you don't know how it's being laid out.
That's what the constraints are for -- you say what kind of place you want gcc to put the value (any register, memory, specific register) and the use "%X" in the asm code. Finally, if you use explicit registers in the asm code, you need to list them in the 3rd section (after the input constraints) so gcc knows you are using them. Otherwise it might put some important value in one of those registers, and you'd clobber that value.
You also need to tell the compiler that inline asm will or might read from or write to memory pointed-to by the input operands; that is not implied.
So with all that, your write2 function looks like:
void write2(char *str, int len) {
__asm__ volatile (
"movl $4, %%eax;" // SYS_write
"movl $1, %%ebx;" // file descriptor = stdout_fd
"movl %0, %%ecx;"
"movl %1, %%edx;"
"int $0x80"
:: "g" (str), "g" (len) // input values we MOV from
: "eax", "ebx", "ecx", "edx", // registers we destroy
"memory" // memory has to be in sync so we can read it
);
}
Note the AT&T syntax -- src, dest rather than dest, src and % before the register name.
Now this will work, but its inefficient as it will contain lots of extra movs. In general, you should NEVER use mov instructions or explicit registers in asm code, as you're much better off using constraints to say where you want things and let the compiler ensure that they're there. That way, the optimizer can probably get rid of most of the movs, particularly if it inlines the function (which it will do if you specify -O3). Conveniently, the i386 machine model has constraints for specific registers, so you can instead do:
void write2(char *str, int len) {
__asm__ volatile (
"movl $4, %%eax;"
"movl $1, %%ebx;"
"int $0x80"
:: "c" (str), /* c constraint tells the compiler to put str in ecx */
"d" (len) /* d constraint tells the compiler to put len in edx */
: "eax", "ebx", "memory");
}
or even better
// UNSAFE: destroys EAX (with return value) without telling the compiler
void write2(char *str, int len) {
__asm__ volatile ("int $0x80"
:: "a" (4), "b" (1), "c" (str), "d" (len)
: "memory");
}
Note also the use of volatile which is needed to tell the compiler that this can't be eliminated as dead even though its outputs (of which there are none) are not used. (asm with no output operands is already implicitly volatile, but making it explicit doesn't hurt when the real purpose isn't to calculate something; it's for a side effect like a system call.)
edit
One final note -- this function is doing a write system call, which does return a value in eax -- either the number of bytes written or an error code. So you can get that with an output constraint:
int write2(const char *str, int len) {
__asm__ volatile ("int $0x80"
: "=a" (len)
: "a" (4), "b" (1), "c" (str), "d" (len),
"m"( *(const char (*)[])str ) // "dummy" input instead of memory clobber
);
return len;
}
All system calls return in EAX. Values from -4095 to -1 (inclusive) are negative errno codes, other values are non-errors. (This applies globally to all Linux system calls).
If you're writing a generic system-call wrapper, you probably need a "memory" clobber because different system calls have different pointer operands, and might be inputs or outputs. See https://godbolt.org/z/GOXBue for an example that breaks if you leave it out, and this answer for more details about dummy memory inputs/outputs.
With this output operand, you need the explicit volatile -- exactly one write system call per time the asm statement "runs" in the source. Otherwise the compiler is allowed to assume that it exists only to compute its return value, and can eliminate repeated calls with the same input instead of writing multiple lines. (Or remove it entirely if you didn't check the return value.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Settings variables through a method
I have variables that I want to set through a method.
string size
double sizeprice
This is the code
public static void PizzaSizeUI(int choice, string size, double sizeprice, bool Quit){
Console.WriteLine("Size");
Console.WriteLine("1.Small");
Console.WriteLine("2.Medium");
Console.WriteLine("3.Large");
//To Check if Int is entered, If a character / string is entered, program doesn't crash.
while (!int.TryParse(Console.ReadLine(), out choice))
{
break;
}
if (choice == 1)
{
size = "Small";
sizeprice = 5.00;
Quit = true;
}
else if (choice == 2)
{
size = "Medium";
sizeprice = 7.00;
Quit = true;
}
else if (choice == 3)
{
size = "Large";
sizeprice = 10.00;
Quit = true;
}
}
This is where the method is called
PizzaSizeUI(choice, size, sizeprice, Quit);
I've printed the values that came from the method itself, and they have been set, but the outside values are still set as they were, "Not Chosen" and 0.
How do I set the variables through the method?
A:
You are just changing the values inside the method. You are not giving a 'pointer' to the variables, instead it copies them (or their references are copied, depending on the type).
In order to make this work, you should pass the variables in using ref, or if there are only for output, you should mark them out:
public static void PizzaSizeUI(out int choice, out string size, out double sizeprice, out bool Quit){
And call them with out too:
int choice;
string size;
double sizeprice;
bool Quit;
PizzaSizeUI(out choice, out size, out sizeprice, out Quit);
| {
"pile_set_name": "StackExchange"
} |
Q:
query 2 wordpress database tables at once
I have the following query which i am running:
$query = "SELECT post_title, ID, post_date_gmt, post_author
FROM wp_posts
WHERE post_type='course-manager'
AND post_status='publish'
AND SUBSTRING(post_date_gmt,1,4) = '$this->yearGet'
AND SUBSTRING(post_date_gmt,6,2) = '$this->monthGet'
AND post_author = '$userid'
ORDER BY post_title";
$query_result = mysql_query ($query);
while ($info = mysql_fetch_array($query_result))
{
currently this is querying just the wordpress posts table. i would like to also query data from the wordpress postmeta table, an example would be like this where i have added the "AND course_date which is within the postmeta table:
$query = "SELECT post_title, ID, post_date_gmt, post_author
FROM wp_posts
WHERE post_type='course-manager'
AND post_status='publish'
AND SUBSTRING(post_date_gmt,1,4) = '$this->yearGet'
AND SUBSTRING(post_date_gmt,6,2) = '$this->monthGet'
AND post_author = '$userid'
AND course_date = '$this->yearGet'
ORDER BY post_title";
$query_result = mysql_query ($query);
while ($info = mysql_fetch_array($query_result))
{
any help would be greatly appreciated
A:
If you need to query a combined set of data whose source is from more than one table, you need to do a join. Basically, you need to make the connection between the 2 tables, in the post and postmeta case, that connection would be the post id. So the query should look like this:
SELECT a.something, b.anotherthing
FROM wp_posts AS a JOIN wp_postmeta AS b
ON a.ID = b.post_id
//followed by all of your where clause...
| {
"pile_set_name": "StackExchange"
} |
Q:
Name mangling problems when using GNU linker to link to VC++ compiled library
In asking this question, I'm looking for either better understanding of the situation or preferably a solution.
I'm created C++ code and I would like to be able to use the Eclipse CDT IDE rather than Visual Studios, (my workplace is more Eclipse friendly). This implies that, practically speaking, I must use the GNU tool chain to compile my code. For the project at hand, I must link to a library called HyDE.lib that was compiled with the Visual Studios compiler. Of course, the problem that I run into is that the GNU linker can't find the appropriate symbols in HyDE because (I presume) both compilers use different name mangling schemes.
So how do I get around this?
Current thoughts:
The most obvious thing would be to recompile HyDE.lib with the GNU tool chain. This is proving to be more complicated than perhaps it's worth. However there is one avenue that I haven't investigated here. We have a cmake file that supposedly can build to unix... is there some way to have cmake instead use Cygwin GNU? I really know nothing about cmake (and very little about make), so a reference to good information would be nice.
I could connect Eclipse CDT to the Window compiler tools. Yes, but best I can tell this is not easy, and I would potentially lose debugging and maybe even code completion. Then there is Eclipse Wascana, but I read a recent blog that indicated that the Wascana community is waining.
Is there any sort of library demangler-remangler? I imagine a program that I would give a Windows compiled library too, and the program would pick out the symbols, demangle them, and then create a library that had the same symbols, but mangled in the GNU way. At this point I'm making stuff up, so maybe someone could help me better understand name mangling here.
Any ideas?
A:
Unless you place most of the code in HyDE.lib with extern "C" blocks, then your best bet is to recompile it with G++. Even if you do place it in extern "C" blocks, I would still reccomend compiling it with G++ as it usually (but not always) has better support for standards than MSVC.
| {
"pile_set_name": "StackExchange"
} |
Q:
Codeigniter and RestServer. How to upload images?
I am coding an API using Phils RestServer (see link) in Codeigniter.
I need a way to upload images via the API. How can I do that?
Is it just as simple as making a POST request with the correct headers (what headers to use)?
https://github.com/philsturgeon/codeigniter-restserver
Thankful for all input!
A:
Ok,
There is another solution here: FIle upload from a rest client to a rest server
But neither of these solutions worked for me.
However, this is what worked; actually worked.
First, I wasn't sure if my file was reaching the method, so I changed the response line to:
function enter_post()
{
$this->response($_FILES);
}
Note, this is a great way to test your REST methods.
You can also output:
$this->response($_SERVER);
and
$this->response($_POST);
etc.
I got the following JSON output:
{"file":{"name":"camel.jpg","type":"application/octet-stream","tmp_name":"/tmp/phpVy8ple","error":0,"size":102838}}
So I knew my file was there.
I then changed the method to find and move the file. I used common file access script to get the file from its temp location and move it to a new location:
$uploaddir = '/home/me/public_html/uploads/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
$data['status'] = 'uploaded';
} else {
$data['status'] = 'failed';
}
A:
You can actually use CodeIgniter's native File Upload Class to facilitate uploads with Phil's Rest-Server like this:
/**
* REST API Upload using native CI Upload class.
* @param userfile - multipart/form-data file
* @param submit - must be non-null value.
* @return upload data array || error string
*/
function upload_post(){
if( ! $this->post('submit')) {
$this->response(NULL, 400);
}
$this->load->library('upload');
if ( ! $this->upload->do_upload() ) {
$this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
} else {
$upload = $this->upload->data();
$this->response($upload, 200);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Corebluetooth, How to get a unique UUID?
my question is the UUID of CBPeripheral seems not to be unique.
I have two iPad2, and a bluetooth4.0 device.
The UUID of the bluetooth device differs from the two iPad.
As shown in following images.
Is there any way to find a unique UUID of bluetooth device on iOS device?
I need to find a UUID or mac address that would not change between different devices.
Thank you very much, please help me!!
A:
I was looking for a way to deploy platform-independent, static configurations of BLE devices. I was getting discouraged (Apple's UUIDs are +/- meaningless, and the MAC/BDADDR which can be obtained on most/all other platforms is not accessible from CoreBluetooth). Fortunately, I noticed that the "Device Information Service" profile (0x180A) contains a "System ID" attribute (0x2A23) which encodes the device's unique MAC/BDADDR address. I don't know if it is mandatory for a BLE device to expose this service, however.
A:
The peripheral uses a random resolvable address that changes at least every 15 minutes, at which point the peripheral will appear to be new. To change this behavior you need to pair with the peripheral, then you will see the UUID and it will be persistent.
| {
"pile_set_name": "StackExchange"
} |
Q:
Translate PostgreSQL conditions to mongoDB
I have these WHERE conditions in a PostgreSQL query that I need to translate to mongoDB:
(starts_at BETWEEN :starts AND :ends) OR (starts_at <= :starts AND ends_at >= :starts)
Note :starts and :ends are UTC times. Specifically, I'm moving this from ActiveRecord to MongoMapper. So bonus if you can help me with that!
A:
In mongodb, you'd use the $or operator like this (along with $gte and $lte):
db.collection.find({
$or: [
{ starts_at: { $gte: starts }, starts_at: { $lte: ends } },
{ starts_at: { $lte: starts }, ends_at: { $gte: starts } }
]
});
In MongoMapper that would translate to:
Model.where(
:$or => [
{ :starts_at => { :$gte => starts, :$lte => ends } },
{ :starts_at => { :$lte => starts }, :ends_at => { :$gte => starts } }
]
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Enable CORS for tomcat applications with credentials support
I have a simple GWT application running from IIS on my server. I am trying to test HTTP requests to tomcat running on the same server. However, since both the application servers are running on different ports, my browser (chrome and firefox) treats the requests as a CORS request.
To enable tomcat to accept CORS request, I updated it to Tomcat 7.0.52 and enabled the CORS filter in the global web.xml configuration. I tested this simple setup and it seems to work. Here is the code in GWT:
String url = "http://bavarians:8080/";
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
box.setText(url);
try
{
rb.sendRequest("", new RequestCallback(){
@Override
public void onResponseReceived(Request request, Response response)
{
Window.alert(response.getStatusCode() + response.getStatusText());
}
@Override
public void onError(Request request, Throwable exception)
{
Window.alert("Request failed");
}});
}
catch (RequestException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is the CORS filter associated with it:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://bavarians</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Authorization</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials, Authorization</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
With this setup, I get a 200 OK response from tomcat. So its safe to assume that CORS filter is working. To back this up, I took a fiddler trace and all looked good.
Now, since I want to access one of the apps of tomcat(solr), I need basic authentication with my CORS request. This brings a preflight request into picture. Since I setup my CORS filter to enable credential use, I didn't need any changes to it. So, I made the following change to my code
String url = "http://bavarians:8080/solr/select?wt=xml&q=tag_name:abcd&username=domain\\userid";
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
box.setText(url);
rb.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
rb.setIncludeCredentials(true);
Now, when I try to use this code, it gets inside the onResponseReceived code block and gives an alert box with "0" value. When I took a fiddler trace, I get this:
It makes sense for the browser to send a preflight request since I am adding the custom header to the request. But I don't understand why tomcat responds with a 401 code despite adding the authorization header to its CORS filter configuration.
I'd appreciate any help or response
EDIT: One more thing that I have noticed- if my URL is just "bavarians:8080/solr/";, tomcat successfully authorizes the preflighted request and the immediate next request is processed as a normal GET request with a 200 OK response. But if I enter the function name and query with the URL, I get 401 again. Accessing the above URL from browser requires Basic Authentication. So CORSFilter does work until some point
A:
Credentials won't be sent in the preflight request, so you have to configure Tomcat to let the request reach the CorsFilter even when unauthenticated. That is, you have to declare a <security-constraint> with <http-method>OPTIONS</http-method> and no <auth-constraint>.
| {
"pile_set_name": "StackExchange"
} |
Q:
ActionBar logo not showing
i have declared the logo in the manifest file like this :
android:allowBackup="true"
android:logo="@drawable/ic_launcher"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/CustomActionBarTheme"
and the custom theme is like this :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<!-- Support library compatibility -->
<item name="actionBarStyle">@style/MyActionBar</item>
</style>
<!-- ActionBar styles -->
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="android:background">@drawable/actionbar_background</item>
<item name="android:icon">@drawable/ic_launcher</item>
<!-- Support library compatibility -->
<item name="background">@drawable/actionbar_background</item>
<item name="icon">@drawable/ic_launcher</item>
</style>
</resources>
but the logo is not showing in the actionbar, i have tried many ways but not working, can anybody pls help me ?
A:
With the new appcompat 21, the pattern is changed.
The Action Bar follows the material design guidelines and uses a Toolbar.
As you can read here:
The use of application icon plus title as a standard layout is
discouraged on API 21 devices and newer.
If you would like an application icon, you can use the method setLogo().
You should read this official post.
| {
"pile_set_name": "StackExchange"
} |
Q:
Migrating django admin auth.groups and users to a new database using fixtures
Here's the scenario:
I'm using django's admin interface and I would like to be able to load users and groups via fixtures (if this is possible.) I'm able to dump users/groups like so:
manage.py dumpdata auth auth.group > usersandgroups.json
But upon loading the data in a brand new database...
manage.py loaddata <appname>/fixtures/usersandgroups.json
I get all sorts of errors having to do with foreign keys and such. Here's an example of one:
django.db.utils.IntegrityError: insert or update on table "auth_permission" violates foreign key constraint "content_type_id_refs_id_728de91f"
DETAIL: Key (content_type_id)=(37) is not present in table "django_content_type".
I'd really appreciate it if anyone could point me in the right direction. Thanks in advance!
A:
You're including more than just user and groups in your dump -- namely, permissions as well. You're getting a conflict because of the permissions. Since you don't need those, just get rid of them from your fixture.
manage.py dumpdata auth.User auth.Group > usersandgroups.json
| {
"pile_set_name": "StackExchange"
} |
Q:
Drag and drop image files to LyX
Is it possible somehow to drag and drop image files from a browser or files directly to LyX when creating a latex document? If not, is there any other editor for OS X that can do this? I find it really slow to add images to a latex document, or if you can tell me an easy approach. Thanks
A:
No. It is not possible to drag and drop image files directly into LyX. If you keep all of the graphics that you are going to be using in the document in a single subfolder, it is fairly quick to go through the insert graphics dialog since you don't need to search through multiple directories.
I do not use emacs, but apparently somebody has hacked together a way to automate the process of inserting images into LaTeX documents. This is discussed here: http://lists.gnu.org/archive/html/auctex/2010-12/msg00010.html.
A:
Not by drag & drop, but it is possible with copy & paste. Just put the image in the clipboard and select Edit->Paste Special. LyX will then immediately open a "Save as" dialog, where you can specify where and under which name the image will be saved. However, you can also just press Enter to choose the selected name and path.
Specifically for MacOS there is also the option to Paste as LinkBack PDF, which is enabled if the source application of the image supports the LinkBack technology. Basically, this is what OLE once was for Windows: You can later right-click the pasted image to edit it in the original application. LinkBack is supported by many OS X applications, among them EazyDraw, OmniGraffle, and LaTeXIt.
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle 11g: SQLDeveloper |status: failure-test failed: IO error. connection reset|
part 1
new / select database connection
info
connection name: ziv
username:oracle
password: xxxxxxx
connection type: basic role: sysdba
host name : localhost.localdomain
port: 1158
sid: orcl
quest is to make new connection what to do?
i trying to connect a database from sqldeveloper
but im get the follow error
error:
status: failure-test failed: IO error. connection reset
part 2
i change the port to 1521 and im get other error
status failure test failed IO error the nestwork adapter could not
establish the connection
[oracle@localhost Desktop]$ lsnrctl status
LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 08-DEC-2015 09:16:27
Copyright (c) 1991, 2009, Oracle. All rights reserved.
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
TNS-12541: TNS:no listener
TNS-12560: TNS:protocol adapter error
TNS-00511: No listener
Linux Error: 111: Connection refused
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=localhost.localdomain)(PORT=1521)))
TNS-12541: TNS:no listener
TNS-12560: TNS:protocol adapter error
TNS-00511: No listener
Linux Error: 111: Connection refused
part 3
[oracle@localhost Desktop]$ lsnrctl start
LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 08-DEC-2015 09:39:16
Copyright (c) 1991, 2009, Oracle. All rights reserved.
Starting /u01/app/oracle/product/11.2.0/db_1/bin/tnslsnr: please wait...
TNSLSNR for Linux: Version 11.2.0.1.0 - Production
System parameter file is
/u01/app/oracle/product/11.2.0/db_1/network/admin/listener.ora
Log messages written to
/u01/app/oracle/diag/tnslsnr/localhost/listener/alert/log.xml
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)
(PORT=1521)))
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.1.0 -
Production
Start Date 08-DEC-2015 09:39:18
Uptime 0 days 0 hr. 0 min. 0 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
/u01/app/oracle/product/11.2.0/db_1/network/admin/listener.ora
Listener Log File
/u01/app/oracle/diag/tnslsnr/localhost/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521)))
The listener supports no services
The command completed successfully
[oracle@localhost Desktop]$ lsnrctl status
LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 08-DEC-2015 09:39:40
Copyright (c) 1991, 2009, Oracle. All rights reserved.
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.1.0 -
Production
Start Date 08-DEC-2015 09:39:18
Uptime 0 days 0 hr. 0 min. 22 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
/u01/app/oracle/product/11.2.0/db_1/network/admin/listener.ora
Listener Log File
/u01/app/oracle/diag/tnslsnr/localhost/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521)))
Services Summary...
Service "orcl.localdomain" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this service...
Service "orclXDB.localdomain" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this service...
The command completed successfully
PART 4
okey so im try again and other error ^^ this time
status: failure- test failed : ora-01031 insufficient privileges
okey so now it work after the last step
**before**
connection name: ziv
username: sys
password: xxxxxxx
connection type: basic
role: sysdba
host name : localhost.localdomain
port: 1521
sid: orcl
change the username from oracle to sys and it worked...
**after**
connection name: ziv
username: oracle
password: xxxxxxx
connection type: basic
role: sysdba
host name : localhost.localdomain
port: 1521
sid: orcl
tnx for all for the help
A:
1158 is the default port for Enterprise Manager Database Console, not the database listener, and you can not log in there using SQL*Net or JDBC.
The default port for the database listener is 1521, try connecting using that port. You can check the listener port by:
lsnrctl status
| {
"pile_set_name": "StackExchange"
} |
Q:
Maven+Selenium 2: How to run tests with one single browser open
I'm trying to run some tests, seven to be specific, I've created my xml file and all and it works correctly, my test file has a package which has the seven tests in it, so the thing is, when the xml file is executed it opens a new browser window for each test (in case you were wondering, I do have the driver quit and close functions, they are at the @afterTest annotation) and I don't want that, what I need is just to get one browser open at all times, e.g. after finishing test one, close that browser because for the second test a second browser is open, what I'll like to get is to close each browser after each test is finished, is it a way to achieve that?
Here is my pom file:
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.enterprise.automation</groupId>
<artifactId>enterpriseAutomation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>barcoAutomation</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- added -->
<suiteFile>src/test/resources/barcoColor.xml</suiteFile>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<!-- <classifier>jdk17</classifier> -->
</dependency>
<dependency>
<groupId>org.uncommons</groupId>
<artifactId>reportng</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.42.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/myTestsFile.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/test/resources/</directory>
</resource>
</resources>
</build>
EDIT: the reason i don't want the seven browsers opened is because we are testing a SPA which has a lot of javascript and it consumes a bit too much pc resources, so if more than one browser are opened the computer performance drops
I also saw the "-1", if you could tell how to improve the question details I'll appreciate it
Thanks
A:
Instead of @AfterTest and @BeforeTest use @BeforeSuite and @AfterSuite
Create a BaseTest class containing @BeforeSuite and @AfterSuite.
public class BaseTest{
static WebDriver driver;
@BeforeSuite
public void start() {
driver = new FFDriver();
driver.get(url);
}
@AfterSuite
public void end() {
driver.close();
driver.quit();
}
}
Create Test classes.
public class Test1{
static WebDriver driver;
@Test
public void test1() {
driver = BaseTest.driver;
//code goes here
}
}
public class Test2{
static WebDriver driver;
@Test
public void test2() {
driver = BaseTest.driver;
//code goes here
}
}
Modify testNG xml file as follows.
<suite name="Regression Testing" parallel="classes">
<test verbose="2" name="Test1">
<classes>
<class name="BaseTest"/>
<class name="Test1"/>
</classes>
</test>
<test verbose="2" name="Test2">
<classes>
<class name="Test2"/>
</classes>
</test>
</suite>
The @BeforeSuite is run first followed by Test1, Test2 and @AfterSuite. Driver instance is obtained in each Test class by setting driver as static in BaseTest.
Let me know if this helps you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Entity Framework Code First (New Database) Producing Error - "CREATE DATABASE permission denied in database 'master'."
I have created a new project (ASP.NET MVC) that will use Entity Framework Code First to create a new Database and add records to the database one time only and populate a drop down.
I am trying to figure out how to generate the database automatically. So far, when I run the code I get "CREATE DATABASE permission denied in database 'master'.". Master is not the correct database. What would I need to modify in my code or connection string to create the database automatically from scratch?
Controller:
namespace TDReport.Controllers
{
public class ReportController : Controller
{
//
// GET: /Report/
public ActionResult Index()
{
var db = new StageContext();
if (!db.Database.Exists())
{
db.Database.Create();
db.Stages.Add(new Stage { PCR = 201 });
db.Stages.Add(new Stage { PCR = 202 });
db.Stages.Add(new Stage { PCR = 203 });
db.Stages.Add(new Stage { PCR = 501 });
db.SaveChanges();
}
return View();
}
Context Class:
namespace TDReport.Models
{
public class StageContext : DbContext
{
public DbSet<Stage> Stages { get; set; }
public DbSet<Report> Reports {get; set;}
}
}
Model:
namespace TDReport.Models
{
public class Stage
{
public int ID { get; set; }
public int PCR { get; set; }
}
}
Connection String Tags:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-TDReport-20140825134744;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-TDReport-20140825134744.mdf" />
<add name="StageProductionEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\StageProduction.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
A:
You need to have a connection string that matches the name of db context if you have parameterless constructor in the db context.
<add name="StageContext" providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial
Catalog=TheDatabaseName;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\TheDatabaseName.mdf" />
| {
"pile_set_name": "StackExchange"
} |
Q:
JPA Query for toggling a boolean in a UPDATE
SQL version works okay and I can toggle the boolean called bar ...
mysql> update Foo set bar = ! bar WHERE id IN (1, 7, 13);
Query OK, 3 rows affected (0.02 sec)
Is there a easy JPA Query equivalent, I tried
final Set<Integer> ids;
final Query query = em.createQuery("UPDATE " + Foo.class.getName()
+ " a set bar= !bar"
+ " where a.id in :ids");
query.setParameter("ids", ids);
query.executeUpdate();
The above gives a org.hibernate.QueryException.
In my entity :
@Column(columnDefinition = "INTEGER", nullable = false)
private boolean bar;
Any ideas on the JPA syntax ?
A:
That can be done with the case expression:
UPDATE FOO a
SET a.bar =
CASE a.bar
WHEN TRUE THEN FALSE
ELSE TRUE END
WHERE a.id in :ids
For nullable Boolean bit more is needed:
UPDATE FOO a
SET a.bar =
CASE a.bar
WHEN TRUE THEN FALSE
WHEN FALSE THEN TRUE
ELSE a.bar END
WHERE a.id in :ids
| {
"pile_set_name": "StackExchange"
} |
Q:
What is a good algorithm for getting the minimum vertex cover of a tree?
What is a good algorithm for getting the minimum vertex cover of a tree?
INPUT:
The node's neighbours.
OUTPUT:
The minimum number of vertices.
A:
I didn't fully understand after reading the answers here, so I thought I'd post one from here
The general idea is that you root the tree at an arbitrary node, and ask whether that root is in the cover or not. If it is, then you calculate the min vertex cover of the subtrees rooted at its children by recursing. If it isn't, then every child of the root must be in the vertex cover so that every edge between the root and its children is covered. In this case, you recurse on the root's grandchildren.
So for example, if you had the following tree:
A
/ \
B C
/ \ / \
D E F G
Note that by inspection, you know the min vertex cover is {B, C}. We will find this min cover.
Here we start with A.
A is in the cover
We move down to the two subtrees of B and C, and recurse on this algorithm. We can't simply state that B and C are not in the cover, because even if AB and AC are covered, we can't say anything about whether we will need B and C to be in the cover or not.
(Think about the following tree, where both the root and one of its children are in the min cover ({A, D})
A
/|\___
B C D
/|\
E F G
)
A is not in the cover
But we know that AB and AC must be covered, so we have to add B and C to the cover. Since B and C are in the cover, we can recurse on their children instead of recursing on B and C (even if we did, it wouldn't give us any more information).
"Formally"
Let C(x) be the size of the min cover rooted at x.
Then,
C(x) = min (
1 + sum ( C(i) for i in x's children ), // root in cover
len(x's children) + sum( C(i) for i in x's grandchildren) // root not in cover
)
A:
T(V,E) is a tree, which implies that for any leaf, any minimal vertex cover has to include either the leaf or the vertex adjacent to the leaf. This gives us the following algorithm to finding S, the vertex cover:
Find all leaves of the tree (BFS or DFS), O(|V|) in a tree.
If (u,v) is an edge such that v is a leaf, add u to the vertex cover, and prune (u,v). This will leave you with a forest T_1(V_1,E_1),...,T_n(U_n,V_n).
Now, if V_i={v}, meaning |V_i|=1, then that tree can be dropped since all edges incident on v are covered. This means that we have a termination condition for a recursion, where we have either one or no vertices, and we can compute S_i as the cover for each T_i, and define S as all the vertices from step 2 union the cover of each T_i.
Now, all that remains is to verify that if the original tree has only one vertex, we return 1 and never start the recursion, and the minimal vertex cover can be computed.
Edit:
Actually, after thinking about it for a bit, it can be accomplished with a simple DFS variant.
A:
I hope here you can find more related answer to your question.
I was thinking about my solution, probably you will need to polish it but as long as dynamic programing is in one of your tags you probably need to:
For each u vertex define S+(u) is
cover size with vertex u and S-(u)
cover without vertex u.
S+(u)= 1 + Sum(S-(v)) for each child v of u.
S-(u)=Sum(max{S-(v),S+(v)}) for each child v of u.
Answer is max(S+(r), S-(r)) where r is root of your tree.
After reading this. Changed the above algorithm to find maximum independent set, since in wiki article stated
A set is independent if and only if its complement is a vertex cover.
So by changing min to max we can find the maximum independent set and by compliment the minimum vertex cover, since both problem are equivalent.
| {
"pile_set_name": "StackExchange"
} |
Q:
redirect/listen to port 8080 if 80 is unreachable, apache to lighttpd
i am running apache and lighty on different ports and want to redirect if apache is down. Do i have to use iptables ?
mod proxy_http is enabled, anything to enable something in lighty?
Are there any suggestions?
edit:
FORWARD chain ?
A:
You should use something like haproxy or lighttpd or nginx in front of Apache, and configure any of them to send the request to other backend hosts/server instances if Apache is down. (Apache has modules for this, too, so you could run Apache in front of Apache.)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set the output size in GraphViz for the dot format?
I want to make sure, that all nodes are within some range (say [0,0,W,H]) after layout.
I figured bounding box would be the solution by using the bb attribute, but both dot and neato simply overwrite it.
For example my graph:
strict digraph {
1,2,3;
1 -> 3;
3 -> 2;
}
Output of neato -Gbb="0,0,50,50" -T dot file.txt:
strict digraph {
graph [bb="0,0,120.49,162.36"];
node [label="\N"];
1 [height=0.5,
pos="27,18",
width=0.75];
3 [height=0.5,
pos="70.233,75.918",
width=0.75];
1 -> 3 [pos="e,57.954,59.469 39.043,34.133 43.004,39.441 47.504,45.468 51.827,51.261"];
2 [height=0.5,
pos="93.485,144.36",
width=0.75];
3 -> 2 [pos="e,87.436,126.56 76.221,93.545 78.643,100.67 81.496,109.07 84.177,116.97"];
}
I get the same positions for any value of bb or any combination of size and dpi.
What I need, is to have all nodes within a given box.
Any suggestions how to do this?
Full story:
I'm using *graphviz_layout* from networkx to layout my graph. I draw the graph with pyprocessing. I want to avoid re-scaling the results from *graphviz_layout*, if there is a way to tell neato my bounds instead.
A:
Here's the TL;DR version:
To generate a 900 by 1500 pixel PNG image from the graph in foo.gv you can run:
dot -Tpng -Gsize=9,15\! -Gdpi=100 -ofoo.png foo.gv
to yield an image that is exactly 900 pixels wide or 1500 tall, but not necessarily both; and then:
convert foo.png -gravity center -background white -extent 900x1500 final.png
to pad the image with whitespace so that it is exactly 900 by 1500 pixels; where convert is part of the ImageMagick suite.
Here's the detailed explanation:
To clarify:
The bb attribute is marked as "write-only", so none of the Graphviz layout engines are likely to respect whatever values you submit before processing.
In the general case, Graphviz can generate both vector (scalable) and bitmap graphics, so DPI isn't always a meaningful metric.
In particular, the dpi attribute is only valid for bitmap and SVG output formats.
What you're trying to do is a little bit complicated as the pixel size of an image generated by Graphviz is driven by a couple of interacting attributes.
Let's take an arbitrary graph as an example.
The command gvgen -dh3 will generate a directed hypercube of degree three. (If you'd like more detail on that, a PDF rendition of of gvgen's man page is here, but it doesn't matter, it's just an arbitrary graph for demonstration purposes.)
A default dot-generated PNG rendering of that graph can be created by running the command:
gvgen -dh3 | dot -Tpng -oexample.png
When I do that, I get a 275 x 347 pixel PNG-format (bitmap) image. (As reported by file example.png.)
The size attribute lets you recommend a maximum or desired height and width for the output image in inches. I.e., the attribute size=3,5 tells Graphviz to generate a 3 by 5 inch image at most. If the image is smaller than 3 by 5 to begin with, Graphviz will leave it alone. If the image is larger than 3 inches by 5 inches to begin with, Graphviz will scale it down until it fits within a 3 by 5 inch canvas (preserving the aspect ratio of the original image).
Adding an exclamation point changes the size attribute from a maximum size to a desired size. Now if both dimensions are smaller than the specified size, the drawing is scaled up until at least one dimension equals the specified size.
For example, running:
gvgen -dh3 | dot -Tpng -Gsize=3,5\! -oexample.png
(Note that \! escapes the exclamation point for bash. In a DOT file you would just write size=3,5!.)
generates a 288 x 363 pixel image, slightly larger in both dimensions that the default.
How did dot come up with those numbers? Well, Graphviz's default DPI value is 96 pixels per inch. At that resolution a 3 by 5 inch image is a 288 by 480 pixel image. The layout engine has simply scaled up the image until at least one of the dimensions matched the desired size.
You can override the default DPI value using the dpi attribute, like so:
gvgen -dh3 | dot -Tpng -Gsize=3,5\! -Gdpi=200 -oexample.png
Now the generated image measures 600 by 757 pixels. Again, Graphviz simply scaled the image up until one of the dimensions matched the desired size (but at this resolution, a 3 by 5 inch image is a 600 by 1000 pixel image).
Hence if you want to generate an image that contains an arbitrary number of pixels you need to set both size and dpi appropriately.
I.e., suppose you want to create a 900 by 1500 pixel image. You could use:
gvgen -dh3 | dot -Tpng -Gsize=9,15\! -Gdpi=100 -oexample.png
or
gvgen -dh3 | dot -Tpng -Gsize=3,5\! -Gdpi=300 -oexample.png
or even:
gvgen -dh3 | dot -Tpng -Gsize=900,1500\! -Gdpi=1 -oexample.png
(But while that last one seemed to work for me in quick test, I'd recommend sticking with a more conventional DPI value just in case.)
That solves most of your problem, but note that Graphviz is only scaling the image until one of the dimensions matches the specified size. Depending upon the aspect ratio of your original image you may or may not get the exact size you are looking for.
This is where the ratio attribute comes into play.
The command:
gvgen -dh3 | dot -Tpng -Gsize=3,5\! -Gdpi=300 -Gratio=fill -oexample.png
should give you an image with the precise dimension you are looking for, but with a couple of caveats:
In practice, it seems to sometimes yield a slightly different size than desired. E.g., when I run the command above I get a 900 by 1472 pixel image (rather than 900 by 1500). I don't know if this is due to rounding error or what.
To achieve this, Graphviz must scale the layout independently in each dimension. It's smart enough to scale the layout and not the image, so the image isn't distorted per se, but depending upon how different your requested aspect ratio is from the layout's "natural" aspect ratio the horizontal vs. vertical spacing may look a little weird.
ratio also accepts a few different values. See the documentation and/or experiment a little to see what they do.
For what it's worth, if you literally want an image of the precise pixel dimensions you're requesting, my suggestion would be to let Graphviz scale the image such that one of the two dimensions matches and then use something like ImageMagick to pad the image to get to the precise aspect ratio you're looking for. E.g., the command:
convert in.png -gravity center -background white -extent 900x1500 out.png
will center the image (from in.png) on a 900 by 1500 pixel canvas (saving it into out.png) by padding the horizontal or vertical dimension as necessary
| {
"pile_set_name": "StackExchange"
} |
Q:
Closed-form solution for a second order ODE
I have a series of second order ODE's that are in the form:
$$
Ay''+By'+Cy=\frac{1}{1+e^{-t}}
$$
($y'' = \frac{d^2}{dt^2}y(t)$, $y' = \frac{d}{dt}y(t)$ )
The initial conditions are known: $y(0)=y_0$, $y'(0)=y'_0$
Clearly, the general solution for the homogeneous form $Ay''+By'+Cy=0$ is trivial; I'm stuck in finding the particular solution.
Is there a hope that I can come up with a closed-form solution parametrized by $A$, $B$, $C$ and the initial conditions (All in $\mathbb{R}$)?
Background: Initially I was trying to solve the ODE with the step function (the heavy-side function: $u(t)=1~if~t>0; ~0~ow$) on the right-hand side and a different set of coefficients on the left-hand side:
$$
(A_1t+A2)y''+(B_1+B2)y'+(C_1t+C2)y=\frac{1}{1+e^{-t}}
$$
But, I thought maybe I could find the solution with a smooth function on the RHS, and a simpler ODE in the first place.
Therefore, a solution to the original (either with affine or with constant coefficients) problem will be helpful too.
Thanks for any help!
A:
As hinted, variation of parameters is one way to go. The homogeneous solution is given by
$$y_h(t)=\underbrace{c_1 e^{\lambda_1 t}}_{=:y_1(t)}+\underbrace{c_2 e^{\lambda_2 t}}_{=:y_2(t)}$$
where
$$\lambda_1=\frac{-B-\sqrt{B^2-4AC}}{2A}, ~\lambda_2=\frac{-B+\sqrt{B^2-4AC}}{2A}$$
Now compute the Wronskian
$$\mathcal{W}(t)=\begin{vmatrix} y_1 & y_2 \\ \tfrac{d}{dt}y_1 & \tfrac{d}{dt}y_2 \end{vmatrix}=...=\frac{e^{-\frac{Bt}{A}}\sqrt{B^2-4AC}}{A} $$
Now the particular solution is given by
$$y_p(t)=-y_1(t) \int \frac{y_2(t)}{A(e^{-t}+1)\mathcal{W}(t)} ~\text{d}t +y_2(t) \int \frac{y_1(t)}{A(e^{-t}+1)\mathcal{W}(t)} ~\text{d}t$$
and the solution to the ODE is
$$y(t)=y_h(t)+y_p(t).$$
You asked for a closed form solution but this is quite strenuous since it involves hypergeometric functions. WolframAlpha and Mathematica tell me the following
UPDATE: I checked the system
$$(a_1t+a_2)y''(t)+(b_1t+b_2)y'(t)+(c_1t+c_2)y(t)=0$$
and according to WolframAlpha the solution is everything but nice; it involves the Laguerre polynomial and the confluent hypergeometric function of second kind. See yourself:
Maybe some numerical methods would be more appropriate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento Layered navigation filters for grouped products
In few words - problem is same as in this question Magento - Layered navigation, configurable products, multiple filters active issue
We have products (configutable / grouped / bundle), that have there linked simple products.
That linked products have own attributes, and configurable have its own.
Layered Navigation gets all availiable options for linked products and add them into parent product, so when we getting different combinations of filters, we can set options for non existing simple products
Example:
SKU | Type | Country | City | Linked Skus
--------------------------------------------------------
SP1 | Simple | USA | NY | -
SP2 | Simple | USA | LA | -
SP3 | Simple | Russia | Moscow | -
SP4 | Simple | Russia | St. Pitersburg | -
GP1 | Grouped | - | - | SP1, SP2
GP2 | Grouped | - | - | SP1, SP3, SP4
In that way we can check in filters Country = USA AND City = Moscow and magento will show us product GP2 as availiable for this combination of filters.
The reason of that is that in index table catalog_product_index_eav it would have something like:
SKU | Attribute | Value
--------------------------------
GP1 | Country | USA
GP1 | City | NY
GP1 | City | LA
GP2 | Country | USA
GP2 | Country | Russia
GP2 | City | NY
GP2 | City | Moscow
GP2 | City | St. Pitersburg
So for this selection USA + Moscow it would show result product GP2 because it have linked simples, that have values in attributes for USA and Moscow, but really not one simple have selected USA + Moscow at same time, so showing GP2 for such filters is mistake
Is there any extentions / ideas how to solve this?
Only one idea that comes to me is to add into catalog_product_index_eav additional column linked_id and for simples put into it zero value or simple entity_id value, but for grouped / configurable etc. generate index based for every linked simple + parent attribute values.
On this example it would look like:
SKU | Attribute | Linked Sku | Value
----------------------------------------
GP1 | Country | SP1 | USA
GP1 | Country | SP2 | USA
GP1 | City | SP1 | NY
GP1 | City | SP2 | LA
GP2 | Country | SP1 | USA
GP2 | Country | SP3 | Russia
GP2 | Country | SP4 | Russia
GP2 | City | SP1 | NY
GP2 | City | SP3 | Moscow
GP2 | City | SP4 | St. Pitersburg
So here we can add additional condition that all attributes in row must have same Linked Sku
May be someone knows ready solutions for this or have any additional ideas? Maybe wanna to discuss this?
Every ideas / solutions / opinions are welcome :)
A:
Looks like it works in such way I discribed
Just developed extention that doing this.. Now we testing it, but we will test only on grouped products, because we not using other types. Really it looks like it must work not only with grouped...
| {
"pile_set_name": "StackExchange"
} |
Q:
menupopup with vbox closed after hover (Firefox extension)
<menu id="list-menu" class="icon-list menu-iconic" label="Menu list">
<menupopup>
<vbox flex="1" class="help">
<html:div class="help-text">
<label>Here is help text</label>
</html:div>
</vbox>
<vbox flex="1" class="list" id="list-box">
Here is box with default height 300px;
</vbox>
<vbox flex="1">
<button class="button" value="Here is button" />
<button class="button" value="Here is button 2" />
</vbox>
</menupopup>
</menu>
If I sharply bring the mouse cursor to elements in menupopup it closes. How to fix it?
Thanks in advance.
A:
Oh I see now, it wasn't seen in the video but this is a submenu that opens when your mouse is over the menuitem.
.
So when you hover your mouse over the "Proxy List >" menuitem, which opens the sub-menuitem, and now want to move your mouse from this menuitem over the submenu that opened, you MUST move your mouse carefully keeping it hovered over the "Proxy List >" menuitem. If your mouse goes off of the this "Proxy List >" menuitem before it reaches the sub-menuitem than it will make your sub-menuitem disapper EVEN IF your mouse is now over the sub-menuitem. To work around this you have to prevent the popup from hiding IF the mouse is over your sub-menuitem. I'll write a thing for you here I'll go work on it. My solution will do a stopPropogation on popuphiding if the users mouse is over this panel. But posting this here so @nmaier can see what your issue is, maybe he has better ideas while I'm working.
Ok here's the solution:
In overlay.xul added the onmousenter onmouseleave, and onmousedown attributes like this:
<menupopup onmouseenter="Components.utils.reportError('entered');this.addEventListener('popuphiding', ProxyAddonBar.preventHide, false)" onmousedown="Components.utils.reportError('downed');this.removeEventListener('popuphiding', ProxyAddonBar.preventHide, false)" onmouseleave="Components.utils.reportError('left');this.removeEventListener('popuphiding', ProxyAddonBar.preventHide, false)">
Then in overlay.js and this function:
preventHide: function(e) {
e.preventDefault();
Components.utils.reportError('PREVENTED HIDE'); //you can remove this, this is just a debug message to tell you when it hides
}
So now this does what you want, you can try by installing the addon from my fork: https://github.com/Noitidart/firex/
Edit:
Ok I figured out your second problem where it was hiding even after we implemented the above. What happend was now the opposite. If you carefully moved from "Proxy List >" to the submenu, and now from here you quickly moved from submenu to to "Proxy List >" but on the way you moused over "Disable Proxy", it will hide it, this is normal expected behavior, but if you want to prevent that, I understand. Forget that stopPropogation thing I'll edit the code above. So solution to this is to add to the <menu> tag these attributes: onmouseenter="this.childNodes[0].addEventListener('popuphiding', ProxyAddonBar.preventHide, false)" onmouseleave="this.childNodes[0].removeEventListener('popuphiding', ProxyAddonBar.preventHide, false)"
It was also triggering false enter and left events, while moving mouse within the sub-menuitem. So I fixed that by checking for event.relatedTarget.
So combining both solutions above, in overlay.xul we have this now:
<menu id="proxy-list-menu" class="icon-list menu-iconic" label="&proxy-list;" onmouseenter="this.childNodes[0].addEventListener('popuphiding', ProxyAddonBar.preventHide, false)" onmouseleave="this.childNodes[0].removeEventListener('popuphiding', ProxyAddonBar.preventHide, false)">
<menupopup onmouseenter="if (!event.relatedTarget) { Components.utils.reportError('entered');this.addEventListener('popuphiding', ProxyAddonBar.preventHide, false) }" onmousedown="Components.utils.reportError('downed');this.removeEventListener('popuphiding', ProxyAddonBar.preventHide, false)" onmouseleave="if (!event.relatedTarget) { Components.utils.reportError('left');this.removeEventListener('popuphiding', ProxyAddonBar.preventHide, false) }">
Question for @nmaier. After making my change, if you move the mouse from the "Proxy List >" submenu item and accidentally hover off, but end up with your cursor on the sub-menuitem it prevents the hide. If you then move your mouse off and onto "Disalbe Proxy" menuitem or "Check connection speed" it will NOT hide the sub-menuitem even though I already removed the preventHide function. It will only close if you hover over "Proxy List >" again.
IF you open the submenu by hovering over "Proxy List >" and carefully take your mouse to the submenu that opened without accidentally leaving the "Proxy List >" item, then once you reach the submenuitem then leave it by hovering on to "Disable Proxy" or "Check connection speed", it will close after like a second. So this is the normal hide behavior, how come when I preven the hide, it doesnt hide like normal once I hover over these other labels?
| {
"pile_set_name": "StackExchange"
} |
Q:
Detect which USB device generated input
I have 2 keyboards and I want to know if it's possible to know which keyboard generated an input event in Windows (using WINAPI)?
A:
Windows has a RAW Input API that can be used to monitor events from keyboards, mice, and HIDs (joysticks, etc) without using low-level hooks.
Use GetRawInputDeviceList() and GetRawInputDeviceInfo() to discover which keyboard devices are connected to the system.
Use RegisterRawInputDevices() to register for events from the desired keyboard devices.
You will receive a WM_INPUT message whenever an input event occurs on a registered device. It will tell you which device sent it.
There is also a WM_INPUT_DEVICE_CHANGE message to notify you when devices are added and removed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sort two dimensional list python
I have a two dimensional list like this
a = [[42, 206], [45, 40], [45, 205], [46, 41], [46, 205], [47, 40], [47, 202], [48, 40], [48, 202], [49, 38]]
Actually these are coordinates in 2D-Euclidean space. I want to sort it like in a way that close points come in a sequence. So, the list looks like the following
sorted_a = [[45,205],[42,206],[46,205],[47,202],[48,202],[45,40],[46,41],[47,40],[48,40],[49,38]]
I have also used the method
sorted_a = sorted(a, key=lambda x: (x[0],x[1]))
but it is not returning me required results. Your help is appreciated. Thanks
A:
I'm not sure this is a sorting problem; it's more of a grouping one (or optimization?)
Sorting requires some criteria for putting the [45,205] list before [42,206]. key works if you can come up with one number that represents the desired order.
For example calculate the distance from the origin
A = np.array(a) creates a numpy array:
In [346]: A
Out[346]:
array([[ 42, 206],
[ 45, 40],
[ 45, 205],
[ 46, 41],
[ 46, 205],
[ 47, 40],
[ 47, 202],
[ 48, 40],
[ 48, 202],
[ 49, 38]])
distance or radius in polar coordinates is sum of squares (sqrt isn't needed for this purpose). Applying argsort to this ranks the points by distance from origin.
In [347]: np.sum(A**2,axis=1)
Out[347]: array([44200, 3625, 44050, 3797, 44141, 3809, 43013, 3904, 43108, 3845])
In [348]: r = np.sum(A**2,axis=1)
In [349]: idx = np.argsort(r)
In [350]: idx
Out[350]: array([1, 3, 5, 9, 7, 6, 8, 2, 4, 0], dtype=int32)
In [351]: A[idx,:]
Out[351]:
array([[ 45, 40],
[ 46, 41],
[ 47, 40],
[ 49, 38],
[ 48, 40],
[ 47, 202],
[ 48, 202],
[ 45, 205],
[ 46, 205],
[ 42, 206]])
The list equivalent operation uses a key function like
def foo(xy):
x,y=xy
return x**2+y**2
In [356]: sorted(a, key=foo)
Out[356]:
[[45, 40],
[46, 41],
[47, 40],
[49, 38],
[48, 40],
[47, 202],
[48, 202],
[45, 205],
[46, 205],
[42, 206]]
Pairwise distances
In numpy it's fairly easy to come up with pairwise distance (even easier with one of the scipy tools). But what would you do with those? What defines order based on such distances?
For example to use the kind of iteration that we are often asked to 'vectorize':
In [369]: D = np.zeros((10,10))
In [370]: for i in range(10):
...: for j in range(i,10):
...: D[i,j] = np.sqrt(sum((A[i,:]-A[j,:])**2))
# D[i,j] = np.linalg.norm(A[i,:]-A[j,:])
In [372]: D.astype(int)
Out[372]:
array([[ 0, 166, 3, 165, 4, 166, 6, 166, 7, 168],
[ 0, 0, 165, 1, 165, 2, 162, 3, 162, 4],
[ 0, 0, 0, 164, 1, 165, 3, 165, 4, 167],
[ 0, 0, 0, 0, 164, 1, 161, 2, 161, 4],
[ 0, 0, 0, 0, 0, 165, 3, 165, 3, 167],
[ 0, 0, 0, 0, 0, 0, 162, 1, 162, 2],
[ 0, 0, 0, 0, 0, 0, 0, 162, 1, 164],
[ 0, 0, 0, 0, 0, 0, 0, 0, 162, 2],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 164],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
is a matrix of distances, rounded for ease of display.
numpy has a lexical sort. We could use that to sort on the 2nd coordinate first, and then the 1st coor. That would group all those 200's together:
In [375]: np.lexsort(A.T)
Out[375]: array([9, 1, 5, 7, 3, 6, 8, 2, 4, 0], dtype=int32)
In [376]: A[_,:]
Out[376]:
array([[ 49, 38],
[ 45, 40],
[ 47, 40],
[ 48, 40],
[ 46, 41],
[ 47, 202],
[ 48, 202],
[ 45, 205],
[ 46, 205],
[ 42, 206]])
pairwise distances with that sorted array look like:
array([[ 0, 4, 2, 2, 4, 164, 164, 167, 167, 168],
[ 0, 0, 2, 3, 1, 162, 162, 165, 165, 166],
[ 0, 0, 0, 1, 1, 162, 162, 165, 165, 166],
[ 0, 0, 0, 0, 2, 162, 162, 165, 165, 166],
[ 0, 0, 0, 0, 0, 161, 161, 164, 164, 165],
[ 0, 0, 0, 0, 0, 0, 1, 3, 3, 6],
[ 0, 0, 0, 0, 0, 0, 0, 4, 3, 7],
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 3],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
Search over permutations
Another way of thinking of this problem is as a search problem, for example seeking to find the order of points that minimizes the 'travel' distance, i.e. the sum of distances between successive points.
With the original a (A), the distance (with default np.linalg.norm method) between successive points is
In [407]: np.linalg.norm(A[1:]-A[:-1],axis=1)
Out[407]:
array([ 166.02710622, 165. , 164.00304875, 164. ,
165.00303028, 162. , 162.00308639, 162. ,
164.00304875])
and their sum:
In [408]: _.sum()
Out[408]: 1474.0393203904973
With the lexsort order
In [410]: np.linalg.norm(A1[1:]-A1[:-1],axis=1)
Out[410]:
array([ 4.47213595, 2. , 1. , 2.23606798,
161.00310556, 1. , 4.24264069, 1. ,
4.12310563])
In [411]: _.sum()
Out[411]: 181.07705580534656
Clearly this has better clustering, mainly based on the 2nd column values.
Your sorted_a improves this sum a bit:
In [414]: sortedA = np.array(sorted_a)
In [415]: np.linalg.norm(sortedA[1:]-sortedA[:-1],axis=1)
Out[415]:
array([ 3.16227766, 4.12310563, 3.16227766, 1. ,
162.0277754 , 1.41421356, 1.41421356, 1. ,
2.23606798])
In [416]: _.sum()
Out[416]: 179.53993144488973
A brute force solution is to try all the permutations, and pick the one that minimizes this sum.
| {
"pile_set_name": "StackExchange"
} |
Q:
Git: currently in merge/conflict with private remote repo. How to tell Git to just use my local files?
Trying to use/learn git with a personal project. There's only me and a remote git repo, a few commits, and I'm stuck in a failed merge. A lot of my files have Git merge conflict markup now too.
How do I tell git to just throw everything out, just use mine?
A specific example of how I got into the state I'm in:
echo A new file > myFile.txt # example file
git add myFile.txt # add file
git commit # commit changes
git push # push changes to remote repo
echo A conflicting edit > myFile.txt # oh, no, forgot some changes
git add myFile.txt # add again
git commit --amend # amend previous commit
git push # fails. Git suggests to do a pull first
git pull origin HEAD # "Automatic merge failed" Now what?
# Just use what I have locally!
A:
git checkout --ours . # checkout our local version of all files
git add -u # mark all conflicted files as merged/resolved
git commit # commit the merge
There is a messy alternative that can break the repo for everyone else using the same remote origin. Only consider it if you're the only one using it:
git reset --hard HEAD # undo that failed merge
git push --force # replace everything remote with local
Explanation (now that I understand git better)
The reason this happened is because amending commits changes 'history'. Doing this locally is safe because it doesn't affect anyone else. However, amending commits that have already been pushed does affect other repos, and is not safe.
A:
Your GUI is probably just setting --strategy=ours (git merge -s ours <branch>). This will perform the merge, citing both commits as parents, but keep your entire directory state.
Your other option is to use git merge -s recursive -X ours <branch>, which will try to bring in files from both branches but will prefer your version whenever there is a conflict.
Docs
You can see the two different styles at work using the following demonstration shell script:
#!/bin/sh
mkdir gittest
cd gittest
git init
git checkout master
echo "Line one" > bar
git add bar
git commit -m "Original commit"
git checkout -b fork1
echo "Line one and something" > bar
echo "Line two" > bam
git add bar bam
git commit -m "Fork1 commit."
git checkout master
git checkout -b fork2
echo "Line one and other stuff" > bar
echo "Line three" > baz
git add bar baz
git commit -m "Fork2 commit."
git checkout fork1
if [ "$1" = "ours" ]; then
# `ls gittest` => bam bar
# `cat gittest/bar` => Line one and something
git merge -s ours fork2
else
# `ls gittest` => bam bar baz
# `cat gittest/bar` => Line one and something
git merge -X ours fork2
fi
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a Firefox Add-on for automatic redirection based on XPath?
I would like to have Firefox add-on which recognizes a website page and automatically redirects to link in the page identified its XPath.
One example for this is on the news aggregator sites like DZone. Whenever I click a DZone RSS feed's link it goes the DZone website and only after clicking the link it jumps to the actual blog/news page. I want to automatically jump to the actual content/blog/news page when I land the DZone site.
A:
Sounds it would be easy to create Greasemonkey userscript to do so.
Greasemonkey scripts are launched only on URLs matching the expreession you provide (so you can write sth like "http://dzone.com/*), and they are executed once page is loaded (top be more more detailed: when DOMContentLoaded event fires).
Writing a script should be easy with just plain JavaScript and XPath.
You need to read some value by XPath like you say, and then to do the redirect, set window.location = ....
If I understood you correctly, you can use the following code - works for me in Firefox 7.0.1 / Greasemonkey 0.9.11
// ==UserScript==
// @name Dzone Automatic Redirect
// @namespace userscript_dzone
// @include http://www.dzone.com/links/rss/*
// ==/UserScript==
var XPathTools =
{
getElementByXpath : function(xpath, referenceNode)
{
var xPathResult = document.evaluate (xpath, referenceNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return xPathResult.singleNodeValue;
}
};
var xpath = "//div[@id='linkDetails']//div[@class='ldTitle']/a";
var url = XPathTools.getElementByXpath(xpath,document);
window.location = url;
| {
"pile_set_name": "StackExchange"
} |
Q:
How does spring-boot @ConditionalOnClass work?
How exactly does the @ConditionalOnClass annotation work?
My goal is to load a specific bean only if the jar providing this class is included in the classpath.
I thought the I could annotate a @Bean with @ConditionalOnClass(MyService.class) and declaring the dependency in maven as optional:
<dependency>
<groupId>de.my</groupId>
<artifactId>my-framework<artifactId>
<optional>true</optional>
</dependency>
@Bean
@ConditionalOnClass(MyService.class)
public MyConditionalBean statistics() {
return new MyConditionalBean();
}
Now, anyone having my-framework as dependency should get that bean automatically wired. But anyone not having the dependency should skip it.
But when I start the app, I get the following error:
Caused by: java.lang.ClassNotFoundException: de.MyService.class
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702) ~[catalina.jar:7.0.50]
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547) ~[catalina.jar:7.0.50]
So I'm probably doing something wrong. How can I then create the bean conditional on the dependency jars and the classes contained in the classpath?
From the spring docs:
The classes that must be present. Since this annotation parsed by
loading class bytecode it is safe to specify classes here that may
ultimately not be on the classpath.
But the error states different...
A:
Good catch!
You can use on @Bean method level, but in that case you have to specify your class as a String literal:
@Bean
@ConditionalOnClass(name ="de.MyService")
public MyConditionalBean statistics() {
return new MyConditionalBean();
}
I don't remeber already "why", but it is from an existing code of Spring Boot sources.
| {
"pile_set_name": "StackExchange"
} |
Q:
Метод map для копии массива
Каким образом метод map примененный к копии массива меняет оригинал массива clients ?
const clients = [
{ name: 'Alex',town: 'Sitka',debt: false },
{ name: 'Bob',town: 'Phoenix',debt: false },
{ name: 'Pol',town: 'LosAngeles',debt: true },
{ name: 'Roy',town: 'Buckeye',debt: false },
{ name: 'Brad',town: 'Dallas',debt: false },
{ name: 'Leny',town: 'Charlotte',debt: true },
{ name: 'Peny',town: 'Hibbing',debt: false },
]
const clientsCopy1 = clients.slice();// делаем копию массива clients;
const clientsCopy2 = [...clientsCopy1]; // делаем копию массива clientsCopy1
const clientsCopy3 = clientsCopy2.map(i => { // перебираем вторую копию методом map
i.name = i.name.toUpperCase()
return i;
})
console.log(clients); // исходный массив тоже изменился!
Использование других способов копирования дает тот-же результат.
Такое поведение только с методом map.
При модификации копий массивов другими способами, исходный массив остается
без изменений.
A:
.slice не копирует объекты внутри массива. Он копирует размер массива и ссылки на объекты которые лежат в массиве.
Чтобы сделать полную копию надо превратить в JSON и распарсить обратно. Это самый быстрый способ, но он не позволяет сохранить информацию о классах (однако, вам тут это и не надо).
const clientsCopy1 = JSON.parse(JSON.stringify(clients));
| {
"pile_set_name": "StackExchange"
} |
Q:
Repository pattern aggregate and aggregate root with Entity Framework 4.0
I have a question on implementing the repository pattern with my data model. I have searched online and looked into a lot of posts but I do not find any answer which clears my doubts. Basically our domain model goes like below
we have a client object which has a lot of child objects and some child objects in turn will have a child objects and at any point of time these child objects without their parent objects are not needed and does not make any sense in the application.
client
--> client zip codes
--> client phone history
--> client medical history
--> client direct services
--> client direct service assessments
--> client direct service risk reductions
--> client housing
--> client housing landlord
and it goes like this.
So from the above representation I have some aggregates and the root is the client object so I was thinking of creating a repository at the aggregate root level which is the client. My question is how do I handle the other aggregates. Can anyone please provide me some ideas on this.
Thanks,
Ajay.
A:
In general, it is the repository's responsibility to prepare the aggregate root for use by the rest of the program. So you should query the repository for a client, and it should return a full client object complete with zip codes, phone history, medical history, etc. The idea of an aggregate root is that no outside code should have to worry about getting clients without those other aggregates available.
Looking at it another way, since you are creating a client repository and client is the aggregate root, it is the client repository's job to compose all subobjects, even if they are themselves aggregates.
| {
"pile_set_name": "StackExchange"
} |
Q:
Want to upload a file to directory in google appengine using python
I am new to google appengine.
I want to upload a file to a directory instead of storing as blob.
main.py
import cgi
import webapp2
from google.appengine.api import users
from google.appengine.ext.webapp.template \
import render
from os import path
class MainHandler(webapp2.RequestHandler):
def get(self):
context={}
tmpl = path.join(path.dirname(__file__), 'static/html/index.html')
self.response.out.write(render(tmpl, context))
def post(self):
form_data = self.request.get('file')
file_data = form_data
f=open('static/html/'+form_data,'w')
f.write(file_data)
f.close
routes=[
(r'/', MainHandler),
]
app = webapp2.WSGIApplication(routes=routes,debug=True)
index.html
> <html>
> <head><title>test</title></head>
> <body>hello
> <form id="addmovieform" action="/" method="post" ENCTYPE="multipart/form-data">
> <input type="file" name="file" >
> <input type="submit" name="submit">
> </form>
> </body>
> </html>
Error
Traceback (most recent call last): File
"/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py",
line 1536, in call
rv = self.handle_exception(request, response, e) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py",
line 1530, in call
rv = self.router.dispatch(request, response) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py",
line 1278, in default_dispatcher
return route.handler_adapter(request, response) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py",
line 1102, in call
return handler.dispatch() File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py",
line 572, in dispatch
return self.handle_exception(e, self.app.debug) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py",
line 570, in dispatch
return method(*args, **kwargs) File "/Users/saravase/test/main.py", line 33, in post
f=open('static/html/'+form_data,'w') File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py",
line 589, in init
raise IOError('invalid mode: %s' % mode) IOError: invalid mode: w
please guide me ...
A:
From "What is Google App Engine?"
Applications cannot write to the file system in any of the runtime
environments. An application can read files, but only files uploaded
with the application code. The app must use the App Engine datastore,
memcache or other services for all data that persists between
requests. The Python 2.7 environment allows bytecode to be read,
written, and modified.
You'll need to return to using the blobstore, or try the Google Cloud Storage API, depending on the needs of your application.
| {
"pile_set_name": "StackExchange"
} |
Q:
SwiperJS : Horizontal carousel with one slide expanded
I want to create a Swiper slider in which one slide should be expanded like image below:
I'm doing it like this:
https://codepen.io/amiut/pen/poyyqye
But the problem is that when you want to open the slides that are placed on the right and left edges of the screen, a part of them will go under the screen and they are not visible.
I also tried with translateTo according to swiper documentation to move the whole slider a little bit but that also won't work.
The CodePen I created is very simple with no animations and stuff.
A:
Working example:
click on image will scroll to that image (centering it)
drag the image line will change current active image
Same example on codepen.
Some notes:
id='test' and all CSS prefixes #test - this is just to be able to run example here on this site in code snippet
opacity in CSS is just for fun
.swiper-slide:after - this is just to display "real" slide index in the left top corner of every slide (I used it for testing)
pointer-events: none; in CSS was used for testing, you can remove them if you need to interact with slide inner contents
var featured_games = new Swiper('.swiper-container', {
slidesPerView: 'auto',
spaceBetween: 30,
centeredSlides: true,
freeMode: true,
freeModeSticky: false,
watchSlidesProgress: true,
watchSlidesVisibility: true,
loop: true,
on: {
click: function (swiper, e) {
if (typeof this.clickedIndex !== 'undefined') {
this.slideTo(this.clickedIndex);
}
},
}
});
#test .featured-game {
overflow: hidden;
height: 100%;
width: 100%;
background-repeat: no-repeat;
background-position: top left;
background-size: cover;
pointer-events: none;
background-image: url("https://images.unsplash.com/photo-1593642702909-dec73df255d7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80");
}
#test .featured-game .summary,
#test .featured-game .content {
padding: 0 25px;
display: flex;
align-items: center;
justify-content: center;
min-width: 0;
pointer-events: none;
width: 128px;
height: 150px;
box-sizing: border-box;
position: absolute;
}
#test .featured-game {
width: 128px;
transition: width 0.4s;
}
#test .featured-game .content {
right: 0;
width: 0;
overflow: hidden;
padding: 0;
transition: width 0.4s, padding: 0.2s;
}
#test .swiper-slide {
display: flex;
height: 150px;
flex: 1;
width: auto;
cursor: pointer;
opacity: 0.5;
}
#test .swiper-slide-active {
opacity: 1;
}
#test .swiper-slide-active .featured-game {
width: 256px;
}
#test .swiper-slide-active .featured-game .content {
width: 128px;
}
#test .swiper-slide:after {
display: block;
position: absolute;
content: attr(data-swiper-slide-index);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/5.4.5/css/swiper.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/5.4.5/js/swiper.min.js"></script>
<div class="swiper-container" id="test">
<div class="swiper-wrapper">
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
<div class="swiper-slide">
<div class="featured-game">
<div class="summary">SUMMARY</div>
<div class="content">CONTENT</div>
</div><!-- .featured-game -->
</div><!-- .swiper-slide -->
</div><!-- .swiper-wrapper -->
</div><!-- .swiper-container -->
| {
"pile_set_name": "StackExchange"
} |
Q:
How to load images dynamically (or lazily) when users scrolls them into view
I've noticed this in numerous "modern" websites (e.g. facebook and google image search) where the images below the fold load only when user scrolls down the page enough to bring them inside the visible viewport region (upon view source, the page shows X number of <img> tags but they are not fetched from the server straight away). What is this technique called, how does it work and in how many browsers does it work. And is there a jQuery plugin that can achieve this behavior with minimum coding.
Edit
Bonus: can someone explain if there is a "onScrolledIntoView" or similar event for HTML elements. If not, how do these plugins work?
A:
Some of the answers here are for infinite page. What Salman is asking is lazy loading of images.
Plugin
Demo
EDIT: How do these plugins work?
This is a simplified explanation:
Find window size and find the position of all images and their sizes
If the image is not within the window size, replace it with a placeholder of same size
When user scrolls down, and position of image < scroll + window height, the image is loaded
A:
Dave Artz of AOL gave a great talk on optimization at jQuery Conference Boston last year. AOL uses a tool called Sonar for on-demand loading based on scroll position. Check the code for the particulars of how it compares scrollTop (and others) to the element offset to detect if part or all of the element is visible.
jQuery Sonar
Dave talks about Sonar in these slides. Sonar starts on slide 46, while the overall "load on demand" discussion starts on slide 33.
A:
I came up with my own basic method which seems to work fine (so far). There's probably a dozen things some of the popular scripts address that I haven't thought of.
Note - This solution is fast and easy to implement but of course not great for performance. Definitely look into the new Intersection Observer as mentioned by Apoorv and explained by developers.google if performance is an issue.
The JQuery
$(window).scroll(function() {
$.each($('img'), function() {
if ( $(this).attr('data-src') && $(this).offset().top < ($(window).scrollTop() + $(window).height() + 100) ) {
var source = $(this).data('src');
$(this).attr('src', source);
$(this).removeAttr('data-src');
}
})
})
Sample html code
<div>
<img src="" data-src="pathtoyour/image1.jpg">
<img src="" data-src="pathtoyour/image2.jpg">
<img src="" data-src="pathtoyour/image3.jpg">
</div>
Explained
When the page is scrolled each image on the page is checked..
$(this).attr('data-src') - if the image has the attribute data-src
and how far those images are from the bottom of the window..
$(this).offset().top < ($(window).scrollTop() + $(window).height() + 100)
adjust the + 100 to whatever you like (- 100 for example)
var source = $(this).data('src'); - gets the value of data-src= aka the image url
$(this).attr('src', source); - puts that value into the src=
$(this).removeAttr('data-src'); - removes the data-src attribute (so your browser doesn't waste resources messing with the images that have already loaded)
Adding To Existing Code
To convert your html, in an editor just search and replace src=" with src="" data-src="
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio 2015 - Class Wizard in C++
When I right click my project and go to Class Wizard I'm met with the following error:
"The solution's source code database may not have been opened. Please make sure the solution is not open in another copy of Visual Studio, and that its database file is not read only."
What I've tried so far:
Creating a new project
Restarting Visual Studio
Restarting PC
Repairing Visual Studio
Reinstalling Visual Studio
Installing MS SQL Server Compact 3.5
Deleting the folder: C:\Users\Jacob\AppData\Roaming\Microsoft\VisualStudio\14.0
None of these have had any effect, and I'm finding very few pages online where others have had this issue. I am totally at a loss on what to do next.
If anyone has any ideas, I would really appreciate them.
A:
It turns out the problem here was actually caused by JetBrains Resharper C++, which I didn't consider could be the problem.
There seems to be no solution, however the program provides an alternative Class Wizard in the same menu.
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Contacts API get phone number (PHP)
I'm using the Google Contacts API and I'm able to extract names and email addresses but I'd like to also get profile pictures and phone numbers.
I'm using PHP and here's my code while authenticating:
//if authenticated successfully...
$req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
$doc = new DOMDocument;
$doc->recover = true;
$doc->loadXML($val->getResponseBody());
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('gd', 'http://schemas.google.com/g/2005');
$emails = $xpath->query('//gd:email');
foreach ( $emails as $email ){
echo $email->getAttribute('address'); //successfully gets person's email address
echo $email->parentNode->getElementsByTagName('title')->item(0)->textContent; //successfully gets person's name
}
PHONE NUMBER
This part getting the phone number doesn't work.
$phone = $xpath->query('//gd:phoneNumber');
foreach ( $phone as $row ){
print_r($row); // THIS PART DOESNT WORK
}
PROFILE PICTURE
Judging from the API link above, it looks like I can also grab the profile picture from the URL: https://www.google.com/m8/feeds/contacts/default/full but I'm not sure how to find it within the DOMXPath $xpath object I generated.
Thoughts?
A:
The Google Contacts API uses an Atom feed. The contacts are provided as entry elements. So it makes more sense the iterate them. To do that you have to register a prefix for the atom namespace as well.
$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
$xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
$xpath->registerNamespace('gd', 'http://schemas.google.com/g/2005');
If you use DOMXpath::evaluate() you can use expressions that return scalars. The second argument is a context node for the expression.
foreach ($xpath->evaluate('/atom:feed/atom:entry') as $entry) {
$contact = [
'name' => $xpath->evaluate('string(atom:title)', $entry),
'image' => $xpath->evaluate('string(atom:link[@rel="http://schemas.google.com/contacts/2008/rel#photo"]/@href)', $entry),
'emails' => [],
'numbers' => []
];
foreach ($xpath->evaluate('gd:email', $entry) as $email) {
$contact['emails'][] = $email->getAttribute('address');
}
foreach ($xpath->evaluate('gd:phoneNumber', $entry) as $number) {
$contact['numbers'][] = trim($number->textContent);
}
var_dump($contact);
}
With the first example response from the Google Contacts API documentation this returns:
array(3) {
["name"]=>
string(17) "Fitzwilliam Darcy"
["image"]=>
string(64) "https://www.google.com/m8/feeds/photos/media/userEmail/contactId"
["email"]=>
string(0) ""
["numbers"]=>
array(1) {
[0]=>
string(3) "456"
}
}
The example does not include an email element, so it is empty. A contact can have multiple email addresses and/or phone numbers or none at all. The rel attribute is provided to classify them as home, work, ...
Fetching the image:
The image is provided as an Atom link element with a specific rel attribute.
atom:link[@rel="http://schemas.google.com/contacts/2008/rel#photo"]
This would return the link node, but it is possible to fetch the href attribute directly:
atom:link[@rel="http://schemas.google.com/contacts/2008/rel#photo"]/@href
Cast the attribute node list into a string:
string(atom:link[@rel="http://schemas.google.com/contacts/2008/rel#photo"]/@href)
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits