source
list | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0015255224.txt"
] |
Q:
Cucumber / Savon omit or remove logging output
While running a cucumber test I am getting (in addition to the test results) a lot of debug/log related output in the form:
D, [2013-03-06T12:21:38.911829 #49031] DEBUG -- : SOAP request:
D, [2013-03-06T12:21:38.911919 #49031] DEBUG -- : Pragma: no-cache, SOAPAction: "", Content-Type: text/xml;charset=UTF-8, Content-Length: 1592
W, [2013-03-06T12:21:38.912360 #49031] WARN -- : HTTPI executes HTTP POST using the httpclient adapter
D, [2013-03-06T12:21:39.410335 #49031] DEBUG -- : <?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
...
Is there a way to turn this output off? I have tried following the instructions in this post, and my config_spec.rb file is:
require "spec_helper"
describe Savon::Config do
let(:config) {
config = Savon::Config.new
config._logger = Savon::Logger.new
config.log_level = :error # changing the log level
HTTPI.log = false # to total silent the logging.
config
}
describe "#clone" do
it "clones the logger" do
logger = config.logger
clone = config.clone
logger.should_not equal(clone.logger)
end
end
it "allows to change the logger" do
logger = Logger.new("/dev/null")
config.logger = logger
config._logger.subject.should equal(logger)
end
it "allows to change the log level" do
Savon::Request.log_level = :info
config.log_level = :error
config._logger.level.should == :error
end
it "allows to enable/disable logging" do
config.log = false
config._logger.should be_a(Savon::NullLogger)
config.log = false
config._logger.should be_a(Savon::Logger)
end
end
But the logging still showing when I run the cucumber tests.
A:
By looking at the documentation for the Savon API you seem to be able to silence the logging by doing:
Savon.configure do |config|
config.log = false
end
The snippet above could be put in your Cucumber World or in features/support/env.rb in order to silence the logging in Cucumber as well.
|
[
"stackoverflow",
"0022152830.txt"
] |
Q:
Setting up Amazon Cloudfront without S3
I want to use Cloudfront to serve images and CSS from my static website. I have read countless articles showing how to set it up with Amazon S3 but I would like to just host the files on my host and use cloud front to speed up delivery of said files, I'm just unsure on how to go about it.
So far I have created a distribution on CloudFront with my Origin Domain and CName and deployed it.
Origin Domain: example.me CName media.example.me
I added the CNAME for my domain:
media.mydomain.com with destination xxxxxx.cloudfront.net
Now this is where I'm stuck? Do I need to update the links in my HTML to that cname so if the stylesheet was http://example.me/stylesheets/screen.css do I change that to http://media.example.me/stylesheets/screen.css
and images within the stylesheet that were ../images/image1.jpg to http://media.example.me/images/image1.jpg?
Just finding it a little confusing how to link everything it's the first time I have really dabbled in using a CDN.
Thanks
A:
Yes, you will have to update the paths in your HTML to point to CDN. Typically if you have a deployment/build process this link changing can be done at that time (so that development time can use the local files).
Another important thing to also handle here is the versioning the CSS/JS etc. You might make frequent changes to your CSS/JS. When you make any change typically CDNs take 24 hrs to reflect. (Another option is invalidating files on CDN, this is but charged explicitly and is discouraged). The suggested method is to generate a path like "media.example.me/XYZ/stylesheets/screen.css", and change this XYZ to a different number for each deployment (time stamp /epoch will do). This way with each deployment, you need to invalidate only the HTML and other files are any way a new path and will load fresh. This technique is generally called finger-printing the URLs.
|
[
"stackoverflow",
"0025316816.txt"
] |
Q:
Format date to include day of week
I have a SQL Server 2012 query that converts date to VARCHAR
SELECT
CONVERT(VARCHAR(12), dbo.Download.Date_of_Download, 107) as Date_to_Display,
dbo.Download.Number_of_Computers
FROM dbo.Download
ORDER BY dbo.Download.Date_of_Download DESC
Below are results
Date_to_Display Number_of_Computers
-----------------------------------
Aug 14, 2014 240
Aug 13, 2014 519
Aug 12, 2014 622
Aug 11, 2014 2132
Aug 10, 2014 1255
Aug 09, 2014 3240
How do I include day of week, i.e. Saturday, Aug 09, 2014 ?
A:
try this:
select datename(dw,getdate())
output:
------------------------------
Thursday
(1 row(s) affected)
using your query:
SELECT
Datename(dw, dbo.Download.Date_of_Download)+', '+CONVERT(VARCHAR(12), dbo.Download.Date_of_Download, 107) as Date_to_Display,
dbo.Download.Number_of_Computers
FROM dbo.Download
ORDER BY dbo.Download.Date_of_Download DESC
|
[
"math.stackexchange",
"0000909819.txt"
] |
Q:
Calculate forward direction vector using 2 vectors
I have 2 vectors:
a(1,2,5) and b(-5,8,1)
I need to calculate the forward direction vector from vector A to vector B.
How do I do this? Is there a formula?
A:
The direction vector from vector a to vector b can be calculated as followed:
$$\overrightarrow{AB}=\overrightarrow{OB}-\overrightarrow{OA}$$
In this case:
$\overrightarrow{AB}=\begin{pmatrix}-5\\8\\1\end{pmatrix}-\begin{pmatrix}1\\2\\5\end{pmatrix}=\begin{pmatrix}-6\\6\\-4\end{pmatrix}$
So the direction vector from $a$ to $b$ is $\overrightarrow{AB}=\begin{pmatrix}-6\\6\\-4\end{pmatrix}$.
|
[
"stackoverflow",
"0009257826.txt"
] |
Q:
Physical Boost.Units User Defined Literals
Now that we soon have user defined literals (UDL), in GCC 4.7 for example, I'm eagerly waiting for (physical) unit libraries (such as Boost.Units) using them to ease expression of literals such as 1+3i, 3m, 3meter or 13_meter. Has anybody written an extension to Boost.Units using UDL supporting this behaviour?
A:
No one has come out with such an extension. Only gcc (and possibly IBM?) has UDL so it might be a while. I'm hoping some kind of units makes it into tr2 which is starting about now. If that happens I'm sure UDL for units will come up.
This works:
// ./bin/bin/g++ -std=c++0x -o units4 units4.cpp
#include <boost/units/unit.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si.hpp>
using namespace boost::units;
using namespace boost::units::si;
quantity<length, long double>
operator"" _m(long double x)
{ return x * meters; }
quantity<si::time, long double>
operator"" _s(long double x)
{ return x * seconds; }
int
main()
{
auto l = 66.6_m;
auto v = 2.5_m / 6.6_s;
std::cout << "l = " << l << std::endl;
std::cout << "v = " << v << std::endl;
}
I think it wouldn't be too hard to go through you favorite units and do this.
Concerning putting these in a library:
The literal operators are namespace scope functions. The competition for suffixes is going to get ugly. I would (if I were boost) have
namespace literals
{
...
}
Then Boost users can do
using boost::units::literals;
along with all the other using decls you typically use. Then you won't get clobbered by std::tr2::units for example. Similarly if you roll your own.
A:
In my opinion there is not much gain in using literals for Boost.Units, because a more powerful syntax can still be achieved with existing capabilities.
In simple cases, looks like literals is the way to go, but soon you see that it is not very powerful.
For example, you still have to define literals for combined units, for example, how do you express 1 m/s (one meter per second)?
Currently:
auto v = 1*si::meter/si::second; // yes, it is long
but with literals?
// fake code
using namespace boost::units::literals;
auto v = 1._m_over_s; // or 1._m/si::second; or 1._m/1_s // even worst
A better solution can be achieved with existing features. And this is what I do:
namespace boost{namespace units{namespace si{ //excuse me!
namespace abbreviations{
static const length m = si::meter;
static const time s = si::second;
// ...
}
}}} // thank you!
using namespace si::abbreviations;
auto v = 1.*m/s;
In the same way you can do: auto a = 1.*m/pow<2>(s); or extend the abbreviations more if you want (e.g. static const area m2 = pow<2>(si::meter);)
What else beyond this do you want?
Maybe a combined solution could be the way
auto v = 1._m/s; // _m is literal, /s is from si::abbreviation combined with operator/
but there will be so much redundant code and the gain is minimal (replace * by _ after the number.)
One drawback of my solution is that it polutes the namespace with common one letter names. But I don't see a way around that except to add an underscore (to the beginning or the end of the abbreviation), as in 1.*m_/s_ but at least I can build real units expressions.
|
[
"stackoverflow",
"0011134539.txt"
] |
Q:
onupdate based on another field with sqlalchemy declarative base
I use sqlalchemy with the pyramid framework, and i want to link a person to his geographical department using his postcode.
So i try to use the onupdate argument when defining the department_id column define the department_id.
see fallowing code:
from datetime import date
from emailing.models import Base, DBSession
from sqlalchemy import Column, Integer, Unicode, Text, DateTime, Sequence, Boolean, Date, UnicodeText, UniqueConstraint, Table, ForeignKey
from sqlalchemy.orm import scoped_session, sessionmaker, column_property, relationship, backref
from sqlalchemy.sql import func
class Person(Base):
__tablename__ = u'person'
id = Column(Integer, primary_key=True)
firstName = Column(Unicode(255))
lastName = Column(Unicode(255))
created_at = Column(Date, default=func.now())
updated_at = Column(Date, onupdate=func.now())
department_id = Column(Integer(), ForeignKey('department.id'), onupdate=dep_id_from_postcode)
department = relationship("Department", backref='persons')
__table_args__ = (UniqueConstraint('firstName', 'lastName'), {})
def dep_id_from_postcode(self):
return int(self.postcode[:2])
on update for the updated_at field works fine, but for the deparment_id field it tell my:
NameError: name 'dep_id_from_postcode' is not defined
i've found documentation about python executed function here: http://docs.sqlalchemy.org/en/latest/core/schema.html?highlight=trigger#python-executed-functions
but nothing that uses another field to use in onupdate argument.
i hope i'm clear enought as i'm not a "natural english speaker"
Thank you all
A:
Move the function definition before its usage:
class Person(Base):
# ...
def dep_id_from_postcode(self):
return int(self.postcode[:2])
# ...
department_id = Column(Integer(), ForeignKey('department.id'), onupdate=dep_id_from_postcode)
# ...
Is the postcode really a field directly in Person? Because if it is not, you might need to handle this completely differently. For example, if the postcode is derived from the primary_address relationship, you need to check add/remove of the primary_address relationships and the changes in the related Address object for proper hooking.
A:
SQLAlchemy has special mechanism for using other column value in default (i.e. onupdate) function called: Context-Sensitive Default Functions
http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#context-sensitive-default-functions:
The typical use case for this context with regards to default
generation is to have access to the other values being inserted or
updated on the row.
As Van pointed out you need to make sure that postcode is a field defined for Person or you'll need to add functionality that will take care about getting postcode associated with Person instance.
What worked for me - regular function, not bound to any object.
SQLAlchemy will call it at the time of insert and/or update and pass special argument with "context" - which is not actual object you are updating.
So for your example I would do something like this.
def dep_id_from_postcode(context):
postcode = context.current_parameters['postcode']
return int(postcode[:2])
class Person(Base):
postcode = Column(String)
# ...
# ...
department_id = Column(Integer(), ForeignKey('department.id'), onupdate=dep_id_from_postcode)
# ...
Be careful with this context argument - I end up with problem when context had None field's value in some cases if I not updating 'postcode' value with the same operation.
Eclipse with pydev with debugger helped me to see what information is passed as context.
|
[
"math.stackexchange",
"0002366557.txt"
] |
Q:
Limit with a summation and sine: how to calculate $\lim_{n\to \infty} n^2\sum_{k=0}^{n-1} \sin\left(\frac{2\pi k}n\right)$?
This is the limit:
$$\lim_{n\to \infty} n^2\sum_{k=0}^{n-1} \sin\left(\frac{2\pi k}n\right)$$
I found that
$k/n <1$
if $n=2k$ the term of the summation is $0$
until $n=4$ the summation is $0$
$ \sin\left(\frac{2\pi k}n\right)= 2\sin\left(\frac{\pi k}n\right)\cos\left(\frac{\pi k}n\right)$
I also tried to increase or decrease the summation with an integral but I think I can do it only if the term in the summation is monotonous.
I totally don't know how to deal with this kind of exercise, I'm looking for a general approach
Thanks! Sorry for english.
A:
If $\zeta_n=e^{\frac{2\pi i}{n}}$, then for every integer $n>1$ we have
$$ \sum_{k=0}^{n-1}\zeta_n^k=\frac{\zeta_n^n-1}{\zeta_n-1}=0$$
And since
$$\zeta_n^k=e^{\frac{2\pi ik}{n}}=\cos\Big(\frac{2\pi k}{n}\Big)+i\sin\Big(\frac{2\pi k}{n}\Big)$$
taking imaginary parts shows that your limit is zero.
A:
$\sum_{k=0}^{n-1}\sin(2\pi k/n)$ is the imaginary part of $\sum_{k=0}^{n-1}e^{i2\pi k/n}$. We can evaluate the latter sum directly since it's a truncated power series:
$$\sum_{k=0}^{n-1}z^k = \frac{z^n - 1}{z-1}$$
provided that $z \neq 1$, so
$$\sum_{k=0}^{n-1}e^{i2\pi k/n} = \frac{e^{i 2\pi} - 1}{e^{i 2\pi / n} - 1} = \frac{1 - 1}{e^{i 2\pi / n} - 1} = 0$$
Hence also
$$\sum_{k=0}^{n-1}\sin(2\pi k/n) = 0$$
for every positive integer $n$. So your limit is
$$\lim_{n \to \infty}n^2 \sum_{k=0}^{n-1}\sin(2\pi k/n) = \lim_{n \to \infty} (n^2 \cdot 0) = \lim_{n \to \infty} 0 = 0$$
|
[
"stackoverflow",
"0028310739.txt"
] |
Q:
Add optgroup to existing select using jquery
I have an existing select:
var $selectStatus = jQuery("<select id='Status' name='status'></select>");
var enabledHtml = "<option value='ENABLED'>"ON"</option>";
var disabledHtml = "<option value='DISABLED'>"OFF"</option>";
var $statusEnabled = jQuery(enabledHtml);
var $statusDisabled = jQuery(disabledHtml);
//some code to add "selected" properties
...
//finally add to select
$selectStatus.append($statusEnabled, $statusDisabled);
This produces a select with ON/OFF as the options. Now I want to add an optgroup along with some values I've got stored in an array.
So what you should get is a select something like:
<select>
<option value="ENABLED">ON</option>
<option value="DISABLED">OFF</option>
<optgroup label="Info">
<option value="some value">some value</option>
<option value="some value">some value</option>
...
</optgroup>
</select>
It could be an empty optgroup with no option values or any number of option values.
I tried this:
var status_optgroup_open = "<optgroup label='Info'>"
for(i=0;i<info.length;i++)
{
$foobar = jQuery('#Status').append(jQuery('<option/>').val(info[i].info_name).html(info[i].info_name));
}
var status_optgroup_close = "</optgroup>"
var $statusOpen = jQuery(status_optgroup_open);
var $statusClose = jQuery(status_optgroup_close);
$selectStatus.append($statusEnabled, $statusDisabled, $statusOpen, $foobar, $statusClose);
The output of info[i].info_name is what I expect but I'm just not sure how do I append them in this context. Right now this just yields an empty optgroup.
A:
The .append() function does not merely concatenate all of the strings passed into it.
So this: $("body").append("<p>","hi","</p>") will not yield <p>hi</p>
Instead, it will take each element in the array, add them to the DOM if necessary, and add those elements to the parent. So the actual output would look like this:
<p></p>
"hi"
<p></p>
Instead, what you want to do, is create the optgroup and append all of the individual options to that. And then add that entire object (children and all) to the select element like this:
var info = [
{info_name: 'Some Value 1'},
{info_name: 'Some Value 2'}
];
// create select
var $selectStatus = $("<select id='Status' name='status'>");
// create options
var enabled = "<option value='ENABLED'>ON</option>";
var disabled = "<option value='DISABLED'>OFF</option>";
// create opt group
var $optgroup = $("<optgroup label='Info'>");
for (i=0; i<info.length; i++) {
var op = "<option value='" + info[i].info_name + "'>" + info[i].info_name + "</option>";
$optgroup.append(op);
}
// create select
$selectStatus.append(enabled, disabled, $optgroup);
// add select to page
$("body").append($selectStatus);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
Note: jQuery will automatically create DOM elements from strings provided in the jQuery constructor $(<html>). Meaning it isn't necessary to close elements tags that pass into the $() function.
|
[
"stackoverflow",
"0047229540.txt"
] |
Q:
In Android Studio 3.0 i want to see layout preview design on device but unfortunately it is not showing.Please help me
Here is the screenshot of that screen,after installing Android Studio 3.0 i face this problem.
A:
Click on the theme selector in the preview window ("MaterialTheme") and select an AppCompat one (or make your theme have that as parent).
The support components won't get rendered unless you select an AppCompat theme. I guess the MaterialTheme is your custom one, so just make sure it uses the appropriate theme as parent.
|
[
"stackoverflow",
"0020290602.txt"
] |
Q:
Store li order in Mysql DB with Jquery sortable
I have a sortable list in my site which saves the order of the list items with an ajax request to a php page.
The problem is when the id of the LI (which is generated by the database) gets above 999 or so it begins to error as the array I'm sending to the PHP page becomes too long.
Is there a better way of doing this?
Currently my Jquery/ ajax is:
$(function() {
$('#sortable').sortable({
update: function(event, ui) {
var order = [];
$('#sortable li').each( function(e) {
order[ $(this).attr('id') ] = $(this).index() + 1;
});
var request = $.ajax({
url: "ajax/save_order.php",
type: "POST",
data: {positions : order},
dataType: "json"
});
}
});
});
My PHP page is:
$positions = $_POST['positions'];
foreach ($positions as $id_section => $order)
{
$sql = sprintf("
UPDATE section_order
SET id_order = %d
WHERE id_section = %d
",
$order,
$id_section
);
$result = mysql_query($sql);
}
I've been trying to work out how to get the data from the sortable into a multidimensional array in jquery, but currently am drawing a blank.
A:
OK I see. Seems a bit unwieldy for a user to manually drag and drop items in a list of over 1000 items. But I don't know how/why you are doing this so will assume it works for your application.
The below solution is actually from this SO question jQuery UI Sortable, then write order into a database
jQuery Sortable has a serialize function that takes care getting the order for you. Use it like below:
$('#sortable').sortable({
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'save_order.php'
});
}
});
And in the save_order.php file, just check what the posted data looks like and loop though it, should be able to do something like:
<?php
foreach ($_POST['each_item_whatever...'] as $value) {
// Database stuff
}
?>
|
[
"workplace.stackexchange",
"0000083957.txt"
] |
Q:
What degree of specificity should recruiters receive when dealing with an exigent family matter?
I'm currently looking for a job, but due to extensive and exigent family matters, I've not really had the time or focus on requests by hiring managers, or really follow up on leads. Worse, I don't know when it will be resolved enough to allow me to focus again on the job hunt.
I've talked to the recruiters that have been working with me in what I'd describe as cryptic terms - analogous to, "I'm going through an exigent family matter, and haven't managed to look at this yet," or "I'm going through an exigent family matter, and unfortunately have to withdraw from the interviewing process at this time," and for the most part it seems like they're amicable to the situation.
However, I really don't want to make this seem like I'm slacking off; I'm genuinely dealing with family matters which require my near-constant attention.
I don't want to burn bridges or miss out, as these recruiters have opportunities I have a genuine interest in. To that effect, I'd like to inform them of what's going on so that they have in their minds when I'd be reasonably available. However, I'm not sure how much sharing would be necessary or professional.
What degree of specificity should I be stating when I say, "I have an exigent family matter"? Is simply mentioning it enough, or should I look to go deeper?
A:
"Hi, I just want to let you know that I have family matters I will need to be attending to. I will be out of touch for a couple weeks. Thank you for all the work you've done so far and I hope to keep working with you when things are settled."
That is about right -- honestly, you could go terser but I am kind of a believer in thanking people more than is strictly necessary -- and it is totally fine professional currency in my experience (U.S., software, New York -- but I'm pretty sure this is just common business culture).
have to withdraw from the interviewing process at this time,
No, do not say that. It is their choice whether they want to be patient.
However, I really don't want to make this seem like I'm slacking off; I'm genuinely dealing with family matters which require my near-constant attention.
Everyone above the age of 33 knows exactly what you are going through and you will have to say no more.
Likely your recruiter will offer condolences and say something like, they will manage things with your prospective employers. A good business contact of any kind tries to help out in these situations.
|
[
"stackoverflow",
"0050855441.txt"
] |
Q:
Hero animation start delayed
I am trying to implement a transition between two controllers with Hero inside a navigation controller.
I have this method to handle a pan gesture:
@objc func pannedCell(gesture: UIPanGestureRecognizer) {
guard let animatedView = gesture.view as? HotelListingCollectionViewCell else {
return
}
let translation = gesture.translation(in: nil)
let screenHeight = self.rootView.bounds.height
let progress = ((-1 * translation.y) / screenHeight) * 2
print(progress)
switch gesture.state {
case .began:
self.initialViewPostion = animatedView.center
Hero.shared.defaultAnimation = .fade
let vc = ListingSearchViewController()
vc.viewModel.hotels.value = self.viewModel.hotels.value
self.navigationController?.pushViewController(vc, animated: true)
case .changed:
Hero.shared.update(progress)
let pos = CGPoint(
x: animatedView.center.x + translation.x,
y: self.rootView.hotelResultsCollectionView.center.y + translation.y
)
Hero.shared.apply(modifiers: [
.position(pos),
.useGlobalCoordinateSpace,
.useOptimizedSnapshot
], to: animatedView)
default:
if progress > 0.8 {
Hero.shared.finish()
} else {
Hero.shared.cancel()
}
}
}
The problem here is the pushViewController method takes ~ 1 second to execute so when I start dragging my view, it moves under my finger approx. 1 second after I started moving the finger on the screen.
I am doing it wrong ?
Thanks
A:
Ok, I think I found something !
The issue seems to be related to operation I did in .began case of the gesture handler.
I moved the instantiation of the new view controller out of this call back to avoid overloading the UI thread during the animation and everything seems to work as expected.
|
[
"french.stackexchange",
"0000016093.txt"
] |
Q:
Existe-t-il un nom en référence au participe passé "échu" ?
Je me demande s'il est possible de reformuler une phrase de ce type :
À terme échu, vous pourrez …
en quelque chose de comme ça :
À ???? du terme, vous pourrez …
Ou ???? serait un nom, par exemple (je sais que ce mot n'existe pas, mais j'illustre mon propos), échoiement.
Existe-t-il un tel mot ?
A:
Je dirais simplement :
À l'échéance , ...
|
[
"math.stackexchange",
"0001724396.txt"
] |
Q:
Finding the maximum of $f(x,y,z)=x^ay^bz^c$ where $x,y,z\in [0,\infty)$ and $x^k+y^k+z^k=1$
Given $a,b,c,k > 0$, find the maximum of $f(x,y,z)=x^ay^bz^c$ where $x,y,z\in [0,\infty)$ and $x^k+y^k+z^k=1$
The subject is Lagrange multipliers, thus that is what I tried to use, where the gradients are
$$\triangledown f=\begin{pmatrix}ax^{a-1}y^{b}z^{c}\\
bx^{a}y^{b-1}z^{c}\\
cx^{a}y^{b}z^{c-1}
\end{pmatrix}
$$
and if $g$ is the function of the constraint, then
$$\triangledown g=\begin{pmatrix}kx^{k-1}\\
ky^{k-1}\\
kz^{k-1}
\end{pmatrix}$$
but then I'm having troubles finding the actual maximum, as I'm interested in $x,y,z,\lambda$ satisfying
$$
\begin{pmatrix}ax^{a-1}y^{b}z^{c}\\
bx^{a}y^{b-1}z^{c}\\
cx^{a}y^{b}z^{c-1}
\end{pmatrix}=\lambda\begin{pmatrix}kx^{k-1}\\
ky^{k-1}\\
kz^{k-1}
\end{pmatrix}
$$
and ignoring for a second the possibilities of one of the constants being $1$, this gives some equations which really don't seem all that right, as extracting $x$ from the first equality for example gives
$$x=\left(\frac{ay^{b}z^{c}}{\lambda k}\right)^{\frac{a-1}{k-1}}$$
which then setting into the second equality to extract $y$ gives
$$b\left(\frac{ay^{b}z^{c}}{\lambda k}\right)^{\frac{a-1}{k-1}}y^{b-1}z^{c}=\lambda ky^{k-1}$$
where I'm not sure how to even approach extracting $y$, and even if I will be able to seems to convoluted to be able to help me in the future..
Any better approaches to the question?
A:
Just played with it a little and got:
$$
\left(\begin{matrix}x^{a}y^{b}z^{c}\\
x^{a}y^{b}z^{c}\\
x^{a}y^{b}z^{c}
\end{matrix}\right)=\lambda k\left(\begin{matrix}x^{k}/a\\
y^{k}/b\\
z^{k}/c
\end{matrix}\right)
$$
Therefore $x^k/a=y^k/b=z^k/c$. By putting it in the constraint, we get
$$
1=x^k+y^k+z^k=(1+b/a+c/a)x^k \\
x=\sqrt[k]{\frac{a}{a+b+c}}
$$
and similarly $y=\sqrt[k]{\frac{b}{a+b+c}}$ and $z=\sqrt[k]{\frac{c}{a+b+c}}$.
|
[
"stackoverflow",
"0032912568.txt"
] |
Q:
Bootstrap col-md-3 arranging
I'm trying to design this footer on a web page, and I've set that my containers for text and social buttons to be col-md-3. So far so good, but I'd like them to arrange themselves in 3 to 2 lines, when I'm resizing the window, it snaps from 4 columns, to 3 columns, and then directly to 1 column
<footer class="container-fluid container-footer">
FOOTER</span>-->
<div class="col-md-2 col-md-offset-1">
<span> DARKWOOD </span>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
</div>
<div class="col-md-2 col-md-offset-1">
<span> PRODUCTS </span>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
</div>
<div class="col-md-2">
<span> ABOUT</span>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
</div>
<div class="col-md-2 social-hub">
<span> SOCIAL</span>
<div class="row-fluid for-social">
<a href="#"><div class="col-xs-3 social" id="facebook"></div></a>
<a href="#"><div class="col-xs-3 social" id="google-plus"></div></a>
<a href="#"><div class="col-xs-3 social" id="twitter"></div></a>
<a href="#"><div class="col-xs-3 social" id="tumblr"></div></a>
</div>
</div>
</div>
<div class="col-md-12" id="copyright"></div>
All the code is over here:
Fiddle
Also, pics:
Initally:
Intermediate:
Last:
So, as you can see, there's enough space for at least 2 of the categories is the final image.
//EDIT//
Can you guys think about anything to solve this stuff?
A:
I believe you need to add additional 'col' classes to describe the behaviour you want. For example, if you want 2x2 on small screens, you need to do something like this:
<footer class="container-fluid container-footer">
<div class="row-fluid ">
<div class="col-md-2 col-md-offset-1 col-sm-4 col-sm-offset-2">
<span> DARKWOOD </span>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
</div>
<div class="col-md-2 col-md-offset-1 col-sm-4 col-sm-offset-2">
<span> PRODUCTS </span>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
</div>
<div class="col-md-2 col-sm-4 col-sm-offset-2">
<span> ABOUT</span>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
<p><span class="glyphicon glyphicon-chevron-right"></span> Lorem Ipsum</p>
</div>
<div class="col-md-2 social-hub col-sm-4 col-sm-offset-2">
<span> SOCIAL</span>
<div class="row-fluid for-social">
<a href="#"><div class="col-xs-3 social" id="facebook"></div></a>
<a href="#"><div class="col-xs-3 social" id="google-plus"></div></a>
<a href="#"><div class="col-xs-3 social" id="twitter"></div></a>
<a href="#"><div class="col-xs-3 social" id="tumblr"></div></a>
</div>
</div>
</div>
<div class="col-md-12" id="copyright"></div>
</footer>
Bear in mind that a 'row' is 12 'units' wide and that anything at the 'size' (eg. md, sm etc) that is over 12 will be wrapped. So above, by setting the div widths to 6 (col-sm-4 + col-sm-offset-2), they will wrap in pairs until the extra small size takes over.
So, col-md-3 means 3/12s the width of the container at medium size.
Also keep in mind that these classes apply upwards only (eg. col-md-3 will work at medium and large, but not small or extra small).
|
[
"electronics.stackexchange",
"0000061491.txt"
] |
Q:
Circuits newb needs someone to help with a diagram
I'm trying to build an OBDII circuit for a STN1110 chip from OBD Solutions. My problem is I don't understand some of the values needed. For instance, the datasheet has most of the information I need, but in the ISO transceiver I cannot understand what the Q's are or what their values need to be. Also how do I tell what the right LM339 chip is? There are like 6 different versions on mouser.
Also, if anyone can tell me the difference between DLC_RAW and just DLC I would appreciate it...
A:
The Q are NPN bipolar junction transistors, they do not have an specific value, you have to find the right transistor for the application. Regarding the LM339 most likely you are looking at different packages in which they come in I recommend you go with a DIP(dual in line package)Like this one. The diffence between DLC_RAW and DLC is that a DLC_RAW is a signal comming from the outside and is unprotected, while the DLC is protected againg reversed polarity by the diode, current limited by the PTC fuse, and over voltage protected by the ESD protected by the TVS diode, and filtered out the high frequencies by the capacitors
|
[
"math.stackexchange",
"0002995972.txt"
] |
Q:
Compact operators on $\ell^1$
Let $T\in \ell^1$, $Tx = (\lambda_1x_1,\dots,\lambda_nx_n,\dots)$. Want to show that if $T$ is compact, then $\lambda_n\to0$.
I know for $p\in(1,\infty]$, canonical basis $e_n \rightharpoonup 0$ (so $T(e_n)\rightharpoonup 0$), and $T(e_n)\in \overline{T(B(0,1))}$, which is compact, so we can get $T(e_n)\to 0$, and $\lambda_n\to 0$.
But what should I do with this problem when $p=1$, there is no weak convergence to $0$. Can someone help me with this? Thanks
A:
Suppose that $T\colon\ell^1 \to \ell^1$ is compact. Then the sequence $\left(Te_n\right)_{n\geqslant 1}$ admits a subsequence $\left(Te_{n_k}\right)_{k\geqslant 1}$ which converges to some $v$ (strongly) in $\ell^1$. Look at $\left\lVert Te_{n_{k+1}}-Te_{n_k}\right\rVert_1$ to conclude that $\lambda_{n_k}\to 0$.
Now apply the previous result to $\left(Te_{N_j}\right)_{j\geqslant 1}$ for a fixed sequence $N_j\uparrow \infty$ instead of $\left(Te_n\right)_{n\geqslant 1}$ to see that each subsequence of $\left(\lambda_n\right)_{n\geqslant 1}$ admit a further subsequence with converges to $0$.
|
[
"stackoverflow",
"0044798719.txt"
] |
Q:
Substitute in vim, with special characters
I am trying to use substitute command in vim to enclose all occurences of a particular pattern
\cite{author1}
\cite{author2}
with
(\cite{author1})
(\cite{author2})
Based on other answers in stack exchangeI used the following vim command
%s/\\cite{(\w\+)}/(\\cite{\1})/g
But, no luck. It says "no matches found". I put two back slashes, one of which is supposed to be the escape character. Kindly help.
I know I could use some other editor and finish the job, but I want to know my mistake. Thank you.
A:
please escape ()
%s/\\cite{\(\w\+\)}/(\\cite{\1})/g
A:
You do not need a capture group to get the entire match. You can use \0 or & for the whole match in the replacement portion of your substitution.
:%s/\\cite{\w\+}/(&)/g
If you do want to use a capture group, then you need to escape the capture group/parenthesis.
:%s/\(foo\)/(\1)/g
For more help see:
:h :s%
:h /magic
A:
As mentioned, normally you need escape the parentheses.
You can use very magic mode (\v) to make the regex simpler; removing the need to escape lots of the regex parts, including the parentheses for capturing:
%s/\v(\\cite\{\w+\})/(\1)/g
|
[
"stackoverflow",
"0009866654.txt"
] |
Q:
Table column is squashed with scollbars
I know this has been asked much the same before but no answers seem to apply to me.
I have a table inside a DIV container. When 5 rows are inside the table, scrollbars on the the x-axis are shown, however, you can see that the content in column 1 is squashed.
The width of both columns 2 & 3 are fixed, but 1 is allowed to adjust itself to the correct width. When I try to measure the width of the text (by copying it to a span) it is not the correct size, otherwise I would just tally up the width of the 3 columns and adjust the table width.
How would I prvent the squashing or get the table width? jQuery tells me the width and outer width are zero...
A:
Try adding a css rule to the elements in the column white-space: nowrap;
otherwise can you js fiddle it or provide a link?
|
[
"stackoverflow",
"0056657660.txt"
] |
Q:
Increment specific value of element in a 2d array JS
How can I create the starting positon on a coordinate plot and update (increment) the x value? Initially, position was given values of 2 and 5, but for testing purposes, I'd just like to update the x value by 1, but am getting the same values returned?
function boardCreate(rows, columns) {
for (let x = 0; x < rows; x++) {
for (let y = 0; y < columns; y++) {
boardCell(x, y);
}
}
}
function boardCell(x, y) {
board[x] = board[x] || [];
board[x][y] = x + " " + y;
}
var board = [];
boardCreate(10, 10);
let position = board[2][5];
function incrementX(position) {
position[1] = position[1] + 1;
return position;
}
incrementX(position);
console.log(position);
A:
If I understand correctly, you need to increment the board coordinates based on the x and y values of the current position - this can be achieved by:
extracting the x and y values at the specified position
const [x, y] = position.split(' ');
incrementing x by one:
const nextX = Number.parseInt(x) + 1;
reading the new position value from new x value and exisiting y
return board[nextX][y]
Hope this helps!
function boardCreate(rows, columns) {
for (let x = 0; x < rows; x++) {
for (let y = 0; y < columns; y++) {
boardCell(x, y);
}
}
}
function boardCell(x, y) {
board[x] = board[x] || [];
board[x][y] = x + " " + y;
}
var board = [];
boardCreate(10, 10);
let position = board[2][5];
function incrementX(position) {
/* Ensure valid position specified before attempting increment */
if (!position) {
return;
}
/* Read x,y coordinates from array value */
const [x, y] = position.split(' ');
/* Parse x to number and increment it */
const nextX = Number.parseInt(x) + 1;
if (nextX >= board.length) {
console.error(`next x: ${ nextX } out of bounds`);
return;
}
/* Look up board value at next x, and same y coordinate */
return board[nextX][y]
}
console.log(position);
/* Testing */
let p = incrementX(position);
for (let i = 0; i < 10; i++) {
p = incrementX(p);
console.log(p);
}
|
[
"mathoverflow",
"0000144246.txt"
] |
Q:
Seeking conceptual explanation of these nice bijections on roots of unity
I proved the following facts by unenlightening calculations. Since the statements are quite clean, I think there should be a conceptual explanation for them, which my proof certainly is not.
Let $q$ be a prime power, and let $\mu_{q+1}$ be the set of $(q+1)$-th roots of unity in the finite field $\mathbf{F}_{q^2}$. If $b\in\mu_{q+1}$ and $c\in\mathbf{F}_{q^2}\setminus\mathbf{F}_q$ then
$$
x\mapsto \frac{cx-bc^q}{x-b}
$$
maps $\mu_{q+1}$ to $\mathbf{F}_q\cup\{\infty\}$. If $b\in\mu_{q+1}$ and $d\in\mathbf{F}_{q^2}\setminus\mu_{q+1}$ then
$$
x\mapsto \frac{x-bd^q}{dx-b}
$$
maps $\mu_{q+1}$ to itself. (It is also true that these are the only degree-one rational functions which map $\mu_{q+1}$ to either $\mathbf{F}_q\cup\{\infty\}$ or $\mu_{q+1}$, but I'm mainly interested in understanding the existence.)
I tagged this "group theory" because the first fact vaguely feels like a connection between orbits of a nonsplit torus and a split torus in $\textrm{PGL}_2(q)$. It's tempting to identify $\mathbf{F}_{q^2}$ with $\mathbf{F}_q\times\mathbf{F}_q$, and consider the resulting action of $\textrm{GL}_2(q)$ on $\mathbf{F}_{q^2}$, but I don't see how to go further in this way.
Any suggestions?
A:
Let $E$ be a curve defined by a singular Weierstrass equation over $\mathbb{F}_q$, where the singularity is a node, say at the origin. Then, Silverman says (Arithmetic of Elliptic Curves, page 46) that $E$ may be written as
$$
E: y^2 + A_1 xy - A_2 x^2 - x^3 = 0,
$$
where $A_1^2 + 4 A_2$ is not zero.
If the two tangent lines at the node are given by $y = a_i x$ for $i=1,2$, then by comparing coefficients we see that the slopes are roots of $t^2 + A_1 t - A_2$.
Suppose this quadratic is irreducible over $\mathbb{F}_q$. Then it splits in $L = \mathbb{F}_{q^2}$. According to Silverman's Prop. 2.5 on page 56 (properly adjusted to not assume algebraic closure, see Exercise 3.5 on page 105), the map $(x,y) \rightarrow (y - a_1 x)/(y - a_2 x)$ gives us an isomorphism of algebraic groups $E_{ns}(L)\cong L^\times$. Part (ii) of the exercise referenced above shows that under this isomorphism, $E_{ns}(K)$ corresponds precisely to those elements of $L^\times$ whose norm to $K$ is $1$. Now $N(x) = x\cdot x^q = x^{q+1}$, so elements of norm $1$ are precisely the $(q+1)th$ roots of unity in $\mathbb{F}_{q^2}$. Since $E$ is singular with a point defined over $\mathbb{F}_q$, its non-singular part is isomorphic to $\mathbb{P}^1(\mathbb{F}_q)$.
So, we have a bijection between the $(q+1)th$ roots of unity in $\mathbb{F}_{q^2}$ and $\mathbb{P}^1(\mathbb{F}_q)$ given by a linear fractional transformation.
A:
The question and the analog to the Cayley map in complex numbers pointed out in the comment by Jyrki Lahtonen is not only an analog, but in fact both are special cases of this more general observation: Let $z\mapsto\bar z$ be an involutory automorphism of a field $F$, and let $E$ be the subfield fixed by $\bar{\phantom{a}}$. Furthermore, set $S=\{z\in F\;|\;z\bar z=1\}$. Then, for $b\in S$, $c\in F\setminus E$, and $d\in F\setminus S$,
\begin{equation*}
z\mapsto \frac{cz-b\bar c}{z-b}
\end{equation*}
maps $S$ to $E\cup\{\infty\}$ and
\begin{equation*}
z\mapsto \frac{z-b\bar d}{dz-b}
\end{equation*}
maps $S$ to $S$.
|
[
"stackoverflow",
"0027437957.txt"
] |
Q:
Cakephp 3.0 Class 'App\Controller\App' not found error
I got this error when I tried to integrate Plugins for charts. The plugins I found online are all for cake version 2.*. I try to did the same for 3.0 and got this error.Here's my code.I also tried high charts and got the same thing.
use App\Controller\AppController;
App::uses('AppController', 'Controller');
App::uses('GoogleCharts', 'GoogleCharts.Lib');
class ChartsController extends AppController {
public $helpers = array('GoogleCharts.GoogleCharts');
//Setup data for chart
public function index() {
$chart = new GoogleCharts();
$chart->type("LineChart");
//Options array holds all options for Chart API
$chart->options(array('title' => "Recent Scores"));
$chart->columns(array(
//Each column key should correspond to a field in your data array
'event_date' => array(
//Tells the chart what type of data this is
'type' => 'string',
//The chart label for this column
'label' => 'Date'
),
'score' => array(
'type' => 'number',
'label' => 'Score',
//Optional NumberFormat pattern
'format' => '#,###'
)
));
//You can also manually add rows:
$chart->addRow(array('event_date' => '1/1/2012', 'score' => 55));
//Set the chart for your view
$this->set(compact('chart'));
}
}
A:
You cannot just throw Cake 2x and Cake 3x stuff together and expect it to work, in case the plugin is not made for 3.x, you simply cannot use it as such.
You are receiving the error because there is no App class in the current namespace, Cake 3x uses real namespaces and autoloading, so if you'd wanted to use the App class, you would have to import it using the use statement
use Cake\Core\App;
However there is no App::uses() anymore anyways, you either use autoloading, or simply include/require the files manually.
Suggested readings:
http://php.net/namespace
http://book.cakephp.org/3.0/en/appendices/3-0-migration-guide.html
http://book.cakephp.org/3.0/en/plugins.html
https://getcomposer.org/doc/
|
[
"stackoverflow",
"0028973203.txt"
] |
Q:
Function error: Uncaught TypeError: undefined is not a function
Made a script that checks if: $("#password") has 9 symbols and if $("#password") = $("#confirm_password").
The problem is when I try to enable the "submit" button... What is wrong with "function submitButton()"?
$("form span").hide();
$('input[type="submit"]').attr("disabled", "true");
var samePass = false;
var eight = false;
var $password01 = $("#password");
var $password02 = $("#confirm_password")
//Why this function doesn't work?
function submitButton() {
if (samePass && eight){
$('input[type="submit"]').removeAttr('disabled');
};
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide().submitButton();
} else {
$password01.next().show();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if($password02.val() !== $password01.val()) {
$password02.next().show();
} else {
samePass = true;
$password02.next().hide().submitButton();
};
};
$password01.focus(passwordEvent).keyup(passwordEvent).focus(passwordCheck).keyup(passwordCheck);
$password02.focus(passwordCheck).keyup(passwordCheck);
$("form span").hide();
$('input[type="submit"]').attr("disabled", "true");
var samePass = false;
var eight = false;
var $password01 = $("#password");
var $password02 = $("#confirm_password")
//Why this function doesn't work?
function submitButton() {
if (samePass && eight){
$('input[type="submit"]').removeAttr('disabled');
};
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide().submitButton();
} else {
$password01.next().show();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if($password02.val() !== $password01.val()) {
$password02.next().show();
} else {
samePass = true;
$password02.next().hide().submitButton();
};
};
$password01.focus(passwordEvent).keyup(passwordEvent).focus(passwordCheck).keyup(passwordCheck);
$password02.focus(passwordCheck).keyup(passwordCheck);
body {
background: #384047;
font-family: sans-serif;
font-size: 10px
}
form {
background: #fff;
border-radius: 10px;
padding: 4em 4em 2em;
box-shadow: 0 0 1em #222;
max-width: 400px;
margin: 100px auto;
}
p {
margin: 0 0 3em 0;
position: relative;
}
label {
font-size: 1.6em;
font-weight:600;
color: #333;
display: block;
margin: 0 0 .5em;
}
input {
display: block;
height: 40px;
width: 100%;
box-sizing: border-box;
outline: none
}
input[type="text"],
input[type="password"] {
background: #f5f5f5;
border: 1px solid #F0F0F0;
border-radius: 5px;
font-size: 1.6em;
padding: 1em 0.5em;
}
input[type="text"]:focus,
input[type="password"]:focus {
background: #fff
}
span {
border-radius: 5px;
padding: 7px 10px;
background: #2F558E;
color: #fff;
width: 160px;
display: block; /* Needed for the width to work */
text-align: center; /* For the inner text */
position: absolute;
left: 105%;
top: 25px;
}
span:after {
content: " ";
position: absolute;
/* pointer-events: none;*/
right: 100%;
top: 50%;
/*
height: 0;
width: 0;
*/
border: solid transparent;
/* border-color: rgba(136, 183, 213, 0);*/
border-right-color: #2F558E;
border-width: 8px;
margin-top: -8px;
}
.enableSub {
background: #0099FF;
border: none;
border-radius: 5px;
color: white;
height: 50px;
box-shadow: 0 3px 0 0 #005C99;
}
.disableSub {
background: #AEAEAE;
border: none;
border-radius: 5px;
color: white;
height: 50px;
}
<!DOCTYPE html>
<html>
<head>
<title>Sign Up Form</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<form action="#" method="post">
<p>
<label for="username">Username</label>
<input id="username" name="username" type="text">
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" type="password">
<span>Enter a password longer than 8 characters</span>
</p>
<p>
<label for="confirm_password">Confirm Password</label>
<input id="confirm_password" name="confirm_password" type="password">
<span>Please confirm your password</span>
</p>
<p>
<input type="submit" class="disableSub" value="SUBMIT">
</p>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
A:
$password01.next().hide().submitButton();
et al. won't work. You instead need to do;
$password01.next().hide();
submitButton();
You've declared submitButton as a function, not a method on a jQuery object, hence you need to call it as such.
The "undefined is not a function" error appears cryptic at first, but becomes clear once understood.
Since the jQuery object returned from hide() doesn't have a submitButton property (or method), hide().submitButton returns undefined. You're then trying to call that as a function (with the ()), hence JavaScript is telling you that undefined is not a function.
As well as the above, your logic is also flawed. Namely samePass is being set to true the second you click into the password1 field (since, on focus, when they're both blank, $password02.val() === $password01.val()). That means that as soon as password is > 8 chars, both conditions will match, and your submit will be enabled.
To fix this, you should probably be setting samePass and eight to false when they don't match their criteria, and calling submitButton() in all cases to update the state
//Why this function doesn't work?
function submitButton() {
if (samePass && eight) {
$('input[type="submit"]').removeAttr('disabled');
} else {
$('input[type="submit"]').attr('disabled', "true");
}
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide();
submitButton();
} else {
eight = false;
$password01.next().show();
submitButton();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if ($password02.val() !== $password01.val()) {
samePass = false;
$password02.next().show();
submitButton();
} else {
samePass = true;
$password02.next().hide();
submitButton();
};
};
... which then works; http://jsfiddle.net/9qqnqLxm/
|
[
"stackoverflow",
"0008251618.txt"
] |
Q:
Google Maps API Key
Do I need a new API key for each of my projects or do you just need one that you can use multiple times in any project?
A:
Each Google Maps API key is associated with the keystore you use to sign your app. So, if you use the same keystore for signing your all apps, you can use the same Maps API key.
But I not recommend you use the same Maps API key. Because now Google Maps API is no longer total free. Each Maps API key is limited query per day. Creating different Maps API key for each app is a good way to prevent limit Google Maps query.
|
[
"stackoverflow",
"0015861659.txt"
] |
Q:
is it possible to add components to UIDatepicker?
I have a uidatepicker in Time Mode I want to add a component with string value into it
I think I have 2 approaches:
1.using a custom pickerview
2.adding component to uidatepicker of my Mode Time(I don't know the possibility)
if it is possible to add a component to a ready built in uidatepicker of TimeMode I think it is awesome because it is more easy than building a customepickerview
Here is the TimeMode:
TimePicker.datePickerMode=UIDatePickerModeTime;
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"HH:mm"];
is it possible to add a component here?or I should build a picker view from scratch?
I know how to build from scratch I just want to know if it is possible to add a component to datepicker
A:
No, you can't to that, the UIDatePickerView doesn't allow access to its underlying UIPickerView, in order to do that you must create you custom version on to of UIPickerView.
|
[
"math.stackexchange",
"0000197671.txt"
] |
Q:
Recapturing + on Natural numbers.
Consider the (multiplically written) free commutative monoid $M$ on a countably infinite set $\mathcal P$ of generators (it is isomorphic to $(\mathbb N,\cdot)$ with the primes as generators, $\mathcal P:=\{2,3,5,7,11,13,\ldots\}$).
Q1: Are all those commutative, associative $+$ operations described on $M$ somewhere in the literature which satisfy the distributive law ($(a+b)m = am+bm$)? We can restrict first to the cancellative $+$ operations.
Q2: Is it true that each of these can be obtained by some automorphism $M\to M$ (i.e. using a permutation $\mathcal P\to\mathcal P$)
A:
Some examples that are quite different from $a+b$ on $\mathbb N$ are $\min(a,b)$ and $\max(a,b)$, using a partial order on $M$ such that $a \le b$ implies $am \le bm$.
|
[
"stackoverflow",
"0061822074.txt"
] |
Q:
How to add custom icon badge for qualified products in WordPress
I found the following code allows you to add custom image badge for sale
<php
add_filter( 'woocommerce_sale_flash', 'my_custom_sales_badge' );
function my_custom_sales_badge() {
$img = '<span class="onsale"><img src="http://yourwebsite.com/wp-content/uploads/2014/11/custom-
sales-badge.png" /></span>';
return $img;
}
CSS
span.onsale {
background: none;
box-shadow: none;
}
This code is not related to sale flash products.
What I would like to do is to add a customize icon as a badge for qualified products.
I assumed that I just find the right argument for add_filter but I didn't find anything.
A:
add_filter( 'woocommerce_product_thumbnails', 'my_custom_sales_badge' );
function my_custom_sales_badge() {
$img = '<span class="onsale"><img src="https://via.placeholder.com/50" /></span>';
echo $img;
}
add_filter('wp_footer', 'add_style_to_badge');
function add_style_to_badge(){
?>
<style>
span.onsale {
background: none;
box-shadow: none;
float:right;
}
</style>
<?php
}
Add this into your active theme functions.php
|
[
"stackoverflow",
"0056155169.txt"
] |
Q:
df with a columns of dates add a duration column between current and next row's date
suppose I have a df of dates:
date quantity
2015-01-01 100
2016-01-01 500
2016-01-05 100
and I want to add another new column about the time between current row's date and next row's date. If last row, refer to today's date.
date quantity days
2015-01-01 100 365
2016-01-01 500 4
2016-01-05 100 1227
Note that: 1227 is the number of days from 2016-01-05 to 2019-05-16 (today).
I can do it with loops, just wonder if I can make use of pandas to do it cleanly.
A:
If we push it into one-line
df['New']=df.date.append(pd.Series(pd.datetime.now())).diff().dropna().dt.days.values
df
Out[102]:
date quantity New
0 2015-01-01 100 365
1 2016-01-01 500 4
2 2016-01-05 100 1226
|
[
"stackoverflow",
"0025443692.txt"
] |
Q:
xcode beta 6 sprite kit?
I just update to xCode beta 6. In beta5 everything works but in beta 6 got to change somethings. I add a lot of "!" in my codes. Anyway, My project is little game. And after complete the level(won or lose) I want to call skscene.
The code is where in mainviewController:
if(flag==true){// IF we WON
/* That below lines should call "Won.swift" file But it doesn't */
var scene = Won(fileNamed: "GameScene")
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
scene.scaleMode = SKSceneScaleMode.AspectFill
scene.position = CGPointMake(0, 568)
skView.presentScene(scene)
}
Won.swift file is:
class Won: SKScene {
var audioPlayer = AVAudioPlayer()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Fireworks", ofType: "mp3")!)
// Removed deprecated use of AVAudioSessionDelegate protocol
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound2, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "You Win";
myLabel.fontSize = 65;
myLabel.fontColor = UIColor.redColor()
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
this code does work in beta 5 but doesn't in beta6.
Additionally I re-add uikit, avfoundation, spritekit foundations to project. And also check media files "mp3" or images are exist in bundle resources... The project runs perfectly without any eroor or warnings. But Skscene section doesn't work. I also tried to put breakpoint to trace how it does goes. the process goes on these lines but never goes "Won.swift" file.
Any suggestion?
Thank you.
A:
It sounds like your variable "flag" isn't being properly set to true. Have you tried putting some println()'s in that code to see whether that code is actually being called?
Also, why are you putting it in the mainViewController? Put it in the play scene, so that the scene is controlling when you move to a different scene. Your main view controller should (probably) only fire up the very first scene, and let the scene logic handle transitioning to other scenes.
In fact, that could be your problem - if that "flag" is set to true, and that function is called repeatedly, say, every frame, then that file is getting called up repeatedly. Or, if you're setting flag back to false in there, and that code gets executed, somewhere else, it might be calling your other scene file, and immediately switching back to it so that you never see the "Won" scene.
Could be a lot of things. Start sprinkling some println() and set breakpoints to figure out what exactly is going on.
|
[
"stackoverflow",
"0008635219.txt"
] |
Q:
How to prevent Visual Studio 2010 adding large SQL file to my project in C++?
I am developing a project in Visual studio 2010 in c++ and c# .till when I added c++ project in solution I always see a SQL Server Compact Edition Database (.sdb) File.It always annoying me
Please anyone help me how to stop creation of this file ?
A:
Well, if my guess that you mean sdf and not sdb file is right, you can disable it in "Tools" -> "Options" -> "Text Editor" -> "C/C++" -> "Advanced" -> "Disable Database"
However you will most likely lose the IntelliSense functionality (I can't test it right now). If you don't want this file to be created in the project structure but you wouldn't mind it being somewhere else, you can set the fallback location in the advanced settings mentioned above and set "Always Use Fallback Location" to True.
|
[
"math.stackexchange",
"0000083543.txt"
] |
Q:
Are all subspaces of the rationals order topologies (with respect to some linear order)? All closed subspaces?
This is a follow-up to this question. Let $Y \subset \mathbb{Q}$, and give $Y$ the subspace topology. Is there necessarily a linear ordering $<$ of $Y$ (possibly different from the order inherited from $\\mathbb{Q}$) which induces the topology on $Y$? What if $Y$ is assumed to be closed in $\mathbb{Q}$?
Some discussion: let $L$ be the set of limit points of $Y$. Let $I$ be the set of isolated points of $Y$. Note that $I$ must have some limit points (in $L$). Otherwise, $L$ is perfect so $L \cong \mathbb{Q} \cong \mathbb{Q} \cap [0,1]$ by a theorem of Sierpiński. Also we have $Y$ homeomorphic to the disjoint union of $L$ and $I$ in this case. It is easy to see that the disjoint union of $\mathbb{Q} \cap [0,1]$ with a discrete space can be realized as an order topology. So, $I$ needs to have some limit points, eg. something like $Y = \{0,1,1/2,1/3,1/4,\ldots\}$ (but the latter is an order topology).
A:
Yes, there is. Proposition 3.2 of Bennett & Lutzer, A shorter proof of a theorem on hereditarily orderable spaces, says (among other things) that a metrizable space is hereditarily orderable iff it is orderable and totally disconnected. $\mathbb{Q}$ is certainly metrizable, orderable, and totally disconnected, so it must be hereditarily orderable.
|
[
"stackoverflow",
"0028344007.txt"
] |
Q:
Fizzbuzz game with for loop
I'm trying to do a function that'll print the numbers between 1-27 in my console.log.
When a number can be divided by 3, it should replace the number with "Fizz"
When a number can be divided by 5, replace it with "Buzz".
If the number can be divided by both 3 and 5, replace it with "Fizzbuzz"
Reference: http://en.wikipedia.org/wiki/Fizz_buzz)
This is my code:
var fizzbuzz = function(start,stop) {
for (var x=1;x <= stop; x++)
var string =',';
if (x%3 == 0) {
string += 'Fizz';
}
if (x%5 == 0){
string += 'Buzz';
}
if (x%5 && x%3){
string += 'Fizzbuzz';
}
return string;
};
Console.log is giving me "," and I'm not sure what I've done wrong.
Just to clarify.
I want my answer to print out 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,Fizz Buzz,16,17,Fizz,19,Buzz,Fizz,22,23,Fizz,Buzz,26,Fizz and so on depending on 'stop' in the If-statement.
A:
Valentins comment is correct, you do need to add brackets around your loop.
You are however also redefining the string var in every iteration of the loop.
The last if also makes the output a bit wrong as for example 15 would hit all 3 statements and print FizzBuzzFizzBuzz
so go with something like
var fizzbuzz = function(start,stop) {
var string = '';
var addComma = false;
for (var x=1;x <= stop; x++){
addComma = false;
if (x%3 == 0) {
string += 'Fizz';
addComma = true;
}
if (x%5 == 0){
string += 'Buzz';
addComma = true;
}
if(addComma && x!== stop){
string+=','
}
}
return string;
};
This is not the best way to keep track of where to add a comma, but it does the job.
|
[
"stackoverflow",
"0036301525.txt"
] |
Q:
How can I capitalize every letter after the > character and stop it when the < character is met?
I want to essentially implement the functionality given in Devexpress Simple masked mode in Javascript. For this I have chosen to use the jQuery-Mask-Plugin. The only issue is I am not sure how to implement functionalities using the special characters('>' and '<'). I tried reading about using regex and the replace function but they seem a bit confusing for me. :(
A:
I would use regex,
var s = 'foo>bar ++ buzz<blah';
alert(s.replace(/>[^<]*</g, function(x){return x.toUpperCase()}))
or
alert(s.replace(/>[\s\S]*?</g, function(x){return x.toUpperCase()}))
>[^<]*< matches all the characters that are present inbetween > and <.
this match is passed as first parameter x to the anonymous function which returns all Uppercase form of the matched chars.
|
[
"homebrew.stackexchange",
"0000003661.txt"
] |
Q:
What is Fermcap-S and what does it do?
Lately I've been doing some very large boils -- 7 gallons in a 7.5 gallon kettle. To prevent boilovers, I've been using Fermcap-s. It's great, and I've had no boilover problems, but I have no idea how Fermcap works or what's in it. What is this stuff? Other than preventing boilover and excessive kreusen, does it have any effect on my beer?
A:
Fermcap-S is a silicone (Dimethylpolysiloxane) based emulsion that works by breaking surface tension. It has no effect on the finished product if used in the boil at designated dosage. If used in the fermenter, I have read that it will increase residual bitterness by ~10%. This is likely due to the compound binding to the yeast cells before the dissolved bittering compounds do, thereby leaving more bitterness in the beer. I have not verified this myself.
Stick to recommended dosage, or you will exceed FDA guidelines for silicone content in your beer.
This thread at BeerAdvocate covers the topic: Fermcap-S (login required)
A:
The FDA has recently decided that Fermcap S should be filtered before you drink your beer. Fortunately, there's Fermcap AT which is fine to use without filtering.
Here's some info from Birko, which makes a product very much like Fermcap..
"Brewers should not use silicone-containing antifoam for unfiltered
beers. The FDA allows active silicone to be used up to 10
parts-per-million (ppm) but stipulates that the silicone must be
removed prior to packaging by either filtration or centrifugation. In
the case of unfiltered beers, use a food grade, non-silicone antifoam.
We sell a food grade, canola oil based antifoam that works well for
this purpose and has an added benefit of being yeast-friendly at the
same time. Look for my article on antifoams in the brewery in the
July/August issue of The New Brewer. Please contact me directly if you
would like to discuss this or any other matter further.
Cheers!
Dana Johnson Brewery Technical Representative BIRKO Corporation
Henderson, Colorado www.birkocorp.com:
|
[
"security.stackexchange",
"0000003861.txt"
] |
Q:
Does sandboxie "grab" all the system calls?
Sandboxie: http://www.sandboxie.com
Does sandboxie "grab" all the system calls, e.g.: filesystem calls? Or it "grabs" all the low level calls from a process?
A:
As a quick starter for 10, see this page:
The driver component of Sandboxie could not complete initialization. This message indicates that Sandboxie asked the system to provide notifications when processes (applications) start and stop, but the system was not able to accomodate this request.
In technical terms, Sandboxie is asking to register a process notification routine, and this request has failed.
The call in question is PsSetCreateProcessNotifyRoutine
Then this page
The driver component of Sandboxie could not complete initialization. This message indicates that Sandboxie could not intercept and extend some system service.
So the answer is this package is installing a kernel level driver to hook system calls, or rather respond to kernel events and alter the outcome. My knowledge of kernel-mode programming is limited, but I suspect functions such as IoRegisterContainerNotification can be used to create hooks into IO activity and determine what to allow and what to block.
I should advise you - this level of operation is different from a rootkit only in terms of intent and install method, i.e. that you are consensually letting this driver be installed and that you trust it. This software appears entirely innocent but you should be careful when deciding whether or not to install software that does this sort of thing, so evaluate solutions like this carefully.
Edit Just for interests' sake I ran dumpbin /IMPORTS SbieDrv.sys. This driver imports functions from FLTMGR.SYS, the Microsoft File Filter Manager. It also imports amongst many other things PsSetCreateProcessNotifyRoutine from ntoskrnl.exe, the Windows kernel. Just to confirm the above.
|
[
"cs.stackexchange",
"0000044679.txt"
] |
Q:
Merge two series of sorted number, one much longer than the other
This is the problem:
Merge two sorted series of numbers. Their lengths are $n$ and $m$, respectively, but $n \gg m$. Your algoritm should take $O(m \log(n/m))$
comparisons.
I have come up with this algorithm:
1. Choose n/m "special" elements among n elements.
2. for i = 1 to m do
2.1 Using binary search find block (between two special elements)
where m_i should be inserted - time O(log(n/m))
2.2 Using binary search in found block, find exact position for $m_i$. -
O(log m)
Step 2.1 takes time $O(\log(n/m)$ and step 2.2 time $O(\log m)$, so I get in total a runtime in $O(m (\log n/m + \log m))$. How do I get rid of the $O(\log m)$ term?
Here's a sketch of the algorithm:
As you can see I have a problem - O(log m). How to eleminate it ?
A:
What exactly does $n \gg m$ mean for your professor?
If it means $m \in o(n)$, then you are allowed $O(\log m)$ time for step 2.2. Note that $\log(n/m) = \log n - \log m$. If $m \in o(n)$, the target runtime bound simplifies to $O(m \log n)$; a summand $m \log m$ is dominated by this.
If $m \in \Theta(n)$ is allowed -- arguably, $m = n \cdot 10^{-10}$ would fulfill "a lot smaller" -- you can have that $\log n/m \in O(1)$ and the runtime bound is $O(m)$. It's quite clearly impossible to perform this task in time $O(m)$, so I think we can safely ignore this case for the purpose of this exercise.
But here is something more for you to think about.
In step 1, you need to specify "special"; if you don't pick the elements according to your sketch, the rest won't work out. So we have to select the elements $i(n/m)$. In order to do this in $o(n)$ time and perform binary search efficiently, we need the series to be stored as arrays.
We can not copy all values to a new array in the required time. We can not insert values into an array, either. So how is this to work at all?
|
[
"ru.stackoverflow",
"0001161386.txt"
] |
Q:
Как исправить комментарий наставника?
Получил от наставника такие замечания по коду. Но если я пытаюсь ввести переменные , то скрипт перестает работать. Как тут правильно объявить их
const makeImage = (text, imageLink) => {
const cardElement = cardElementTemplate.cloneNode(true);
cardElement.querySelector('.element-grid__photo').src = imageLink;
cardElement.querySelector('.element-grid__text').textContent = text;
cardElement.querySelector('.element-grid__photo').setAttribute('alt', text);
/*Каждый html элемент ищется один раз (используйте переменные).
- Повторный поиск .element-grid__photo*/
cardElement.querySelector('.element-grid__like-button').addEventListener('click', toggleLikeButton);
cardElement.querySelector('.element-grid__delete-button').addEventListener('click', deleteImage);
cardElement.querySelector('.element-grid__photo').addEventListener('click', showCard);
/*Каждый html элемент ищется один раз (используйте переменные).
- Повторный поиск .element-grid__photo*/
return cardElement;
}
A:
Так не работает?
const makeImage = (text, imageLink) => {
const cardElement = cardElementTemplate.cloneNode(true);
const cardElementPhoto = cardElement.querySelector('.element-grid__photo');
const cardElementText = cardElement.querySelector('.element-grid__text');
const cardElementLikeBtn = cardElement.querySelector('.element-grid__like-button');
const cardElementDeleteBtn = cardElement.querySelector('.element-grid__delete-button');
cardElementPhoto.src = imageLink;
cardElementText.textContent = text;
cardElementPhoto.setAttribute('alt', text);
cardElementLikeBtn.addEventListener('click', toggleLikeButton);
cardElementDeleteBtn.addEventListener('click', deleteImage);
cardElementPhoto.addEventListener('click', showCard);
return cardElement;
}
|
[
"codereview.stackexchange",
"0000040488.txt"
] |
Q:
Is my use of CSS inheritance clean enough for these sprites?
I have a set of links with background images on this CodePen.
I am seeking feedback to see if I did this the most optimal way. For example, I made a sprite so that I can just load one image. And I leveraged inheritance so that I did not have to assign every containing div a class. Just used a child selector and for the individual buttons, I used :nth-of-type to pass the background image.
Tell me your thoughts if this could use improvement.
HTML
<div class="introSelect">
<div>
<a href="#"> <!-- Link Pending -->
<span>Dentist</span>
</a>
</div>
<div>
<a href="#"> <!-- Link Pending -->
<span>Patient</span>
</a>
</div>
<div>
<a href="#"> <!-- Link Pending -->
<span>Lab</span>
</a>
</div>
</div>
CSS
.introSelect { text-align:center; }
.introSelect div {
display:inline-block;
position: relative;
text-align: center;
background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/bruxzir-user-sprites_1.png') no-repeat;
width: 90px;
height: 90px;
}
.introSelect div:nth-of-type(1) {
background-position: 0 -180px ;
}
.introSelect div:nth-of-type(2) {
background-position: -90px -180px;
}
.introSelect div:nth-of-type(3) {
background-position: -180px -180px;
}
.introSelect a {
display:block;
text-decoration: none;
}
.introSelect span {
background-color: rgba(152, 216, 242, 0.7);
color: #444;
font-weight: bold;
letter-spacing: 1px;
position: absolute; bottom: 0; left: 0; right: 0;
}
A:
There hasn't been a good reason to use extra elements such as spans for purposes of hiding text in the last 10 years. If you need to support very old browsers, negative indentation is the simplest method. Otherwise, there's plenty of clean, modern techniques to choose from.
.foo {
text-indent: -100em;
}
http://nicolasgallagher.com/css-image-replacement-with-pseudo-elements/
http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/
There's not really a good reason to use nth-child here. You'd be better off using self-documenting class names. If the order of the images need to be adjusted, then you don't have to make modifications in multiple places (markup and CSS).
.introSelect .dentist {
background-position: 0 -180px ;
}
.introSelect .patient {
background-position: -90px -180px;
}
.introSelect .lab {
background-position: -180px -180px;
}
A:
if you don't want to mess with all the headache of the HTML and CSS you could just create an Image map
in other words you create the image
and then you map out the separate squares using the HTML syntax and link them to the right pages. this minimizes the amount of HTML and CSS, and makes sure that your font is always displayed.
if you want to see how to do it check with this link about Creating HTML Image Maps
it would look something like
<img src="MenuMap.gif" usemap="#MenuMap" />
<map name="MenuMap">
<!-- these are only examples. use a picture editor to get the coords. -->
<area shape="polygon" coords="19,44,45,11,87,37,82,76,49,98" href="http://www.trees.com/save.html">
<area shape="rect" coords="128,132,241,179" href="http://www.trees.com/furniture.html">
<area shape="circle" coords="68,211,35" href="http://www.trees.com/plantations.html">
</map>
the only time that I ever did this I was using Dream Weaver and it gave me the coords.
I think this would be the perfect use for it though. if you want to make it look the way you want.
if the person zooms in or whatever the picture stays the same and so does the map, so they would always hit the links. No Divs, no Spans, just nice and neat.
Updates from Research
Responsive Image Maps jQuery Plugin by Matt Stow
a little link that I stole from an answer, probably can't be used as OP said that they wanted to use pure CSS, not sure how this translates for jQuery though.
also, found this out about SEO on image maps,
sounds like there are some Google Search Bots that don't crawls these "links" and some that do, but the final decision that every blog that I have seen so far is that the image map is SEO Friendly and will still show up for SEO.
Joe Hall Post
Image Map Crawlability
What you should know about Image Maps
When it comes down to it, Google is all about content, and alt content is something that SEO is driven on, but you can't just spam it with keywords, because we all know that Google is savvy to this abuse and will shut you down.
One person mentioned the href saying
an href is an href is an href
I am going to have to agree with this. I think that Google watches the traffic in and out of the site as well as the content on the page to determine what is relevant and what isn't.
I Tried to make sure that all the links I looked for were the newest ones that I could find
|
[
"stackoverflow",
"0033536123.txt"
] |
Q:
Why is the "::" operator used in std::cout rather than the "." operator?
A pretty basic question, but I've been stumped on this for a while.
Why exactly do we write
int main(){
std::cout << "HelloWorld!";
}
Instead of
int main(){
std.cout("HelloWorld!");
}
I understand that the :: operator is used to edit functions in classes, but why is it used in this context to call a function in the std class rather than the . operator?
A:
The :: operator is the scope resolution operator. The prefix can be either a namespace or a class.
The . operator is used to select a member of an object. The prefix is an expression of structure, union, or class type (and is most commonly the name of an object of that type).
std is a namespace, not a class. Even if it were a class, std::cout would still be correct if cout were a static member of that class. std.cout would be correct only if std were an object of a type that has a member named cout.
C++ could have been defined to use . for all these cases, but the use of :: as the scope resolution operator and . as the member selection operator can make code easier to read because it's more explicit. (There are other languages that use . for both.)
|
[
"stackoverflow",
"0061700228.txt"
] |
Q:
Is it possible to create one index for both primary and foreign key?
Let's suppose we have two tables A and B and between them one-to-one relation.
CREATE TABLE IF NOT EXISTS A
(
ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS B
(
ID INT UNSIGNED NOT NULL,
PRIMARY KEY (ID),
FOREIGN KEY (ID) REFERENCES A(ID)
ON UPDATE CASCADE ON DELETE CASCADE
);
B.ID key will be used as foreign key in tables about which A doesn't know. When row is deleted from A there also will be deletion from other tables that are linked to B. As we see in B one column is at the same time primary and foreign key. As I know keys use indexes. So, is it possible to make these two keys use the same index? Does it depend on RDBMS? Or there is something wrong in my understanding?
A:
As I know [foreign] keys use indexes
This is false. I am guessing that your experience with databases is limited to MySQL/MariaDB. These are two databases where a foreign key definition does created an index on the referencing table.
In most databases, a foreign key definition does NOT create an index on the referencing table. Another difference is that most databases (and I'm pretty sure the standard as well) requires that the referenced key be either a primary key or unique key. That doesn't affect you in this case, but it is another deviation from the standard in MySQL in this area.
|
[
"stackoverflow",
"0021536806.txt"
] |
Q:
After creating a signed release build with Eclipse how do I run the release APK?
I'd like to run the release APK to make sure it runs ok with Proguard.
A:
You install it using adb:
adb install your.signed.apk
|
[
"english.stackexchange",
"0000128055.txt"
] |
Q:
What do you call a freelancer working predominantly at home?
According to Farlex Financial Dictionary, an e-lancer is an independent contractor who performs their duties predominantly or exclusively online, at home, communicating with clients and colleagues via phone and e-mail.
So, since in others terms an e-lancer is a kind of freelancer working at home, I would like to call a character participating in my next novel a 'homepreneur', which seems a word in current usage ("Three's the magic number for Kristy Sturgess, a homepreneur from Vineyard.").
But, alas, I didn't find that word in dictionaries, so I wonder:
Is 'homepreneur' a valid word, a word that I can use in a novel?
If not, what do you call a freelancer working at home?
A:
@Stan and @jwpat have dealt with your first question in their comments. I will attempt to answer your second question:
what do you call a freelancer working at home?
People who work at home are usually referred to as homeworkers or teleworkers or telecommuters. These words describe a working arrangement and not the employment or contractual status of the worker.
There is no word to distinguish between a freelancer who works at home and other people who work at home (for example, permanent employees, part-time employees, and temporary employees).
I think you may have misinterpreted the definition. According to The Free Dictionary by Farlex, an e-lancer is
An independent contractor who performs his/her duties predominantly or exclusively online.
The reference to "at home" is given as an example.
I agree with the other comments that homepreneur is ugly and hokey, but in any case I don't think it is a good description of someone who does freelance work. A freelancer does well-defined assignments at a fixed hourly rate. The revenue potential is limited by the number of hours the freelancer can work, but the risk is also limited. An entrepreneur has greater revenue potential but also takes on a bigger risk. A freelancer could become an entrepreneur by taking on more work and hiring more people to deliver it. In all of this, whether the work is done from somebody's home or somewhere else is irrelevant.
|
[
"stackoverflow",
"0041790118.txt"
] |
Q:
Protractor+Typescript => Getting "Failed: Cannot read property 'sendKeys' of undefined"
I am trying create protractor js spec files using type script and facing below error while running the converted spec files.
Failed: clculator_1.calculator.prototype.getResult is not a function
Below are the type script files.
calculator.ts
import { element, browser, by, ExpectedConditions as EC, ElementFinder, ElementArrayFinder } from 'protractor';
export class calculator {
firstElement = element(by.model('first'));
secondElement = element(by.model('second'));
submit = element(by.id('gobutton'));
operator = element.all(by.options('value for (key, value) in operators'));
getResult=(val1: string, val2: string, operator: string):any=>{
this.firstElement.sendKeys(val1);
this.secondElement.sendKeys(val2);
// this.operator.$$("option:contains('" + operator + "')").click();
}
}
SampleSpec.ts
import { browser, by, until, ExpectedConditions as EC, Key, element, ElementFinder } from "protractor";
import { helperUtility as util } from '../utility/helperUtility';
import { calculator as calc } from '../pages/clculator';
beforeEach(() => {
util.prototype.isAngular(false);
browser.get('https://juliemr.github.io/protractor-demo/');
});
describe('Test login functionality', () => {
xit('should login the user and allow to logout ', () => {
var resultCountBefore = element(by.repeater('result in memory'));
element(by.model('first')).sendKeys('3');
element(by.model('second')).sendKeys('5');
element(by.id('gobutton')).click();
browser.wait(EC.or(isResultUpdated), 5000);
browser.sleep(500);
let result = element(by.xpath("//button[@id='gobutton']/../h2")).getText();
expect(result).toEqual('8');
});
it('test mathemetical operation', () => {
browser.waitForAngular();
calc.prototype.getResult('1','2','+');
});
});
export let isResultUpdated = function () {
return element(by.xpath("//button[@id='gobutton']/../h2")).getText().then(function (result) {
console.info(result + ' is the result')
return result == '. . . . . .';
});
};
config.ts
import { ProtractorBrowser, Config,browser } from 'protractor';
export let config: Config = {
allScriptsTimeout: 60000,
baseUrl: 'https://www.google.com',
seleniumAddress: 'http://localhost:4444/wd/hub',
framework: 'jasmine2',
capabilities:{
browserName:'chrome'
},
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
},
onPrepare: () => {
browser.manage().window().maximize();
browser.manage().timeouts().implicitlyWait(5000);
},specs:['../specs/First.spec.js'],
};
Error
Failures:
1) Test login functionality test mathemetical operation
Message:
Failed: clculator_1.calculator.prototype.getResult is not a function
Stack:
TypeError: clculator_1.calculator.prototype.getResult is not a function
at Object.<anonymous> (F:\Selenium2\Protractor\TypeScriptProject\ConvertedJSFiles\specs\First.spec.js:22:42)
at C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:102:25
at new ManagedPromise (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\
promise.js:1067:7)
at controlFlowExecute (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:87:
18)
at TaskQueue.execute_ (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\
promise.js:2970:14)
at TaskQueue.executeNext_ (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\
lib\promise.js:2953:27)
at asyncRun (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js
:2860:25)
at C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:676:7
at process._tickCallback (internal/process/next_tick.js:103:7)
From: Task: Run it("test mathemetical operation") in control flow
at Object.<anonymous> (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:86:
14)
at C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:61:7
at ControlFlow.emit (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\ev
ents.js:62:21)
at ControlFlow.shutdown_ (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\l
ib\promise.js:2565:10)
at shutdownTask_.MicroTask (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver
\lib\promise.js:2490:53)
at MicroTask.asyncRun (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\
promise.js:2619:9)
From asynchronous test:
Error
at Suite.<anonymous> (F:\Selenium2\Protractor\TypeScriptProject\ConvertedJSFiles\specs\First.spec.js:20:5)
at Object.<anonymous> (F:\Selenium2\Protractor\TypeScriptProject\ConvertedJSFiles\specs\First.spec.js:9:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
Pending:
1) Test login functionality should login the user and allow to logout
Temporarily disabled with xit
2 specs, 1 failure, 1 pending spec
Finished in 4.931 seconds
[22:52:57] I/launcher - 0 instance(s) of WebDriver still running
[22:52:57] I/launcher - chrome #01 failed 1 test(s)
[22:52:57] I/launcher - overall: 1 failed spec(s)
[22:52:57] E/launcher - Process exited with error code 1
A:
There are a few issues:
You should wrap your beforeEach method at the top of your sample spec.
I would suggest capitalizing your class. So instead of export class calculator, maybe export Calculator. This suggestion is more for style guide adherence. I like the angular.io style guide (biased opinion)
After importing a class, you need to call the constructor.
In your configuration file, you have the baseUrl set to google.com. This is weird. Please read the docs on baseUrl
For a very similar example to typescript / jasmine / protractor, see the cookbook.
So back to your code:
calculator.ts
import { element, browser, by, ExpectedConditions as EC, ElementFinder, ElementArrayFinder } from 'protractor';
// style nit
export class Calculator {
constructor() { /* initialize calculator variables */ }
SampleSpec.ts
import { browser, by, until, ExpectedConditions as EC, Key, element, ElementFinder } from "protractor";
// don't know what util is doing, but leaving it alone.
import { helperUtility as util } from '../utility/helperUtility';
import { Calculator } from '../pages/calculator';
// remove beforeEach, this should happen in the describe block
describe('Test login functionality', () => {
// create a local calculator object to be used by tests within
// this describe block
let calculator: Calculator;
beforeEach(() => {
calculator = new Calculator(); // initialize the calculator
util.prototype.isAngular(false);
browser.get('https://juliemr.github.io/protractor-demo/');
});
it('test mathemetical operation', () => {
// remove browser.waitForAngular();
// wait for angular is not needed. Please read the api docs (link below).
calculator.getResult'1','2','+');
});
Read the browser.waitForAngular API docs (noted above in the it block)
|
[
"stackoverflow",
"0032127831.txt"
] |
Q:
DDD: Quering child objects of aggregate root
If I have understood right, in domain driven design there are repositories for only aggregate root objects. So what is the right way to implement, for example, paging (or access control filtering) for those objects which are child objects of roots.
Example:
@Entity
public class Person extends AbstractPersistable<Long> {
@OneToMany
private List<Competence> competences = new ArrayList<>();
public void addCompetence( Competence competence ) {
this.competences.add( competence );
}
public List<Competences> competences() {
return this.competences;
}
}
So if I first get person object from repository and then I'd like to send subset (page) of competences to my front end? It not make sense to create CompetenceRepository to find competences by person because it brokes the whole idea of aggregate roots... For now I have used Spring Data JPA.
A:
A popular approach is to avoid using the domain model (which is a transactional model optimized for processing commands) for queries. You can read about that a little more by searching for CQRS.
|
[
"stackoverflow",
"0008519905.txt"
] |
Q:
XCode iOS operator new custom implementation
XCode issues warning for my implementation of global operator new:
void *operator new(size_t blocksize);
It says: 'operator new' is missing exception specification 'throw(std::bad_alloc)'
But my implementation does not intend to throw any exception, and I'd rather declare it as
void *operator new(size_t blocksize) throw();
However, the latter implementation leads to an error:
Exception specification in declaration does not match previous declaration
So, the question is: am I really forced (to calm down XCode compiler) to declare a custom 'operator new' as throw(std::bad_alloc) even if it wont throw any exception?
A:
So, the question is: am I really forced (to calm down XCode compiler)
to declare a custom 'operator new' as throw(std::bad_alloc) even if it
wont throw any exception?
Yes you do:
http://developer.apple.com/library/mac/#technotes/tn2185/_index.html
For complete control and portability, if you replace any of these signatures, you should replace all of them. However the default implementation of the array forms simply forward to the non-array forms. If you only replace the four non-array forms, expect the default array forms to forward to your replacements.
|
[
"math.stackexchange",
"0000091516.txt"
] |
Q:
Coefficients of $(1+x+\dots+x^n)^3$?
Consider the following polynomial:
$$ (1+x+\dots+x^n)^3 $$
The coefficients of the expansion for few values of $n$ ($n=1$ to $5$) are:
$$ 1, 3, 3, 1 $$
$$ 1, 3, 6, 7, 6, 3, 1 $$
$$ 1, 3, 6, 10, 12, 12, 10, 6, 3, 1 $$
$$ 1, 3, 6, 10, 15, 18, 19, 18, 15, 10, 6, 3, 1 $$
$$ 1, 3, 6, 10, 15, 21, 25, 27, 27, 25, 21, 15, 10, 6, 3, 1 $$
Is there a closed-form formula for the $i$th element of this sequence (for different values of $n$)?
Edit This looks similar to the sequence A109439 on OEIS corresponding to the coefficients of the expansion of: $ \left( \frac{1 - x^n}{1 - x} \right)^3 .$
A:
An alternative approach:
Just as the $x^i$ term in $(1+\dots+x^n+\dots)^3$ counts the number of ways of picking three numbers to add to $i$, the $x^i$ term in your expansion counts the number of non-negative integer solutions to the system
$$y_1+y_2+y_3 = i$$
$$y_1, y_2, y_3 \leq n$$
If it wasn't for that pesky second condition we'd have a classic problem that can be solved by the Stars and Bars method (or whatever other name you wish to call it). There's a total of $\binom{i+2}{2}$ solutions. In fact, that second condition disappears once $n \geq i$, which explains why each term in your sequence eventually stabilizes (and matches the OEIS sequence you found).
We now need to subtract off solutions where some of the $y_i$ are too large. To avoid overcounting, we use Inclusion-Exclusion, which tells us that the number we want is equal to
$$\binom{i+2}{2}-3S_1+3S_2-S_3,$$
where $S_1$ is the number of solutions with $y_1>n$ (the $3$ comes from the fact that we also count $y_2>n$ and $y_3>n$), $S_2$ is the number of solutions with $y_1>n$ and $y_2>n$, and $S_3$ counts the number of solutions with all three variables too large.
Now we use one final trick. The number of solutions to $y_1+y_2+y_3=n$ with $y_1>n$ is the same as the number of solutions to
$$(y_1-(n+1))+y_2+y_3=i-(n+1)$$
$$y_1-(n+1), y_2, y_3 \geq 0$$
which is just $\binom{i-(n+1)+2}{2}=\binom{i+1-n}{2}$. Doing an identical trick with $S_2$ and $S_3$ gives a final answer of
$$\binom{i+2}{2}-3\binom{i+1-n}{2}+3\binom{i-2n}{2}-\binom{i-1-3n}{2}.$$
(correspondence fixed thanks to Thomas's helpful correction from his comment)
|
[
"windowsphone.stackexchange",
"0000008890.txt"
] |
Q:
Can I download, re-sign, and distribute a Windows Store app across an organisation?
We have a situation where we're like to distribute a free-to-download Windows Store app to ~1,000 users across an organisation.
Currently the approach is for each user to log in to the store individually and download the app.
Would it be possible to download the xap file once, re-sign it, and distribute it using intune?
A similar method is described here, but it may just be for in house developed apps:
Channel 9 - Deploying Windows Phone apps for the Enterprise
A:
You can create an application in Windows Intune pointing to the actual app in the store, and deploy that to your devices:
In the Configuration Manager console, click Software Library.
In the Software Library workspace, expand Application Management, and then click Applications.
In the Home tab, in the Create group, click Create Application.
On the General page of the Create Application Wizard, select Automatically detect information about this application from installation files.
In the Type drop-down, select the app package for your device type.
Click Browse to open the store, select the app you want to include, and then click Next.
On the General Information page, enter the descriptive text and category information that you want users to see in the company portal.
Complete the wizard.
For more information, visit this technet page and checkout the section To create an application containing a link to a store.
|
[
"cs.stackexchange",
"0000062759.txt"
] |
Q:
Check if a given polynomial is primitive
I try to estimate error detection capabilities of arbitrary CRC polynomials. One important criteria is if a given polynomial is primitive. So I need an algorithm to check that. My goal is to write a C or C++ routine.
Unfortunately I only found analytical solutions for the problem on the web.
Is there some numerical algorithm for testing a given polynomial for primitivity?
Please consider that my mathematical knowledge wasted away during the last two decades. Any algorithm descriptions, pseudo code or code in a common programming language would be very helpful.
A:
In order to check that a degree $n$ polynomial $P$ over $GF(2)$ is primitive, you first need to know the factorization of $2^n-1$ (you can look it up in tables, or use a CAS). Then, you test that $x^{2^n-1} \equiv 1 \pmod{P(x)}$ (using repeated squaring to do this efficiently), and that for every prime factor $p$ of $2^n-1$, $x^{(2^n-1)/p} \not\equiv 1 \pmod{P(x)}$.
You can also just use a CAS (computer algebra software). For example, using the free software Sage you can do
F.<x> = GF(2)[]
(x^8+x^6+x^5+x+1).is_primitive()
For more on the relevant mathematics, see the Wikipedia article.
|
[
"tex.stackexchange",
"0000284338.txt"
] |
Q:
Italic small caps not working
I use small caps with \textsc{} a lot, but cannot find a way to get it set in italics. This is primarily a problem inside environments such as theorems, where the theorem text is set in italics, so that \textsc{} gives upright small caps. I always load the fixltx2e (no longer necessary?) package after reading it enables italic small caps, but that does not seem to be the case. I get slanted small caps with slantsc, but since slanted looks rather unappealing for normal text, that does not solve much. Loading different combinations of the packages fixlte2e, fontenc with T1, and lmodern produces different results, none of which are what I want. I have the same problem with Palatino (using \usepackage[sc]{mathpazo}), except Palatino prints upright lowercase for slanted small caps. I get the warning "Font shape 'T1/lmr/m/scit' undefined(Font) using 'T1/lmr/m/n' instead", which I guess means small-caps-italic font is not available. Is there an easy fix, or is this where one needs other Latex flavors? (I use pdflatex in TeXLive on a Mac.)
Sorry if this is a duplicate -- I could not find the answer anywhere.
MWE:
\documentclass{article}
\usepackage{fixltx2e}
\usepackage[T1]{fontenc}
\usepackage{slantsc}
\usepackage{lmodern}
%\usepackage[sc]{mathpazo}
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}
\begin{document}
\textsl{\textsc{gnu}'s not Unix} (\verb|\textsl{}|) \par
{\slshape gnu}'s not Unix (\verb|{\slshape }|) \par
\textit{\textsc{gnu}'s not Unix} (\verb|\textit{}|) \par
\emph{\textsc{gnu}'s not Unix} (\verb|\emph{}|)
\verb|\textsc{}| inside \verb|amsthm| theorem:
\begin{theorem}
\textsc{gnu}'s not Unix.
\end{theorem}
\end{document}
A:
The font definition file for Latin Modern doesn't define a scit shape, but you can add it, telling LaTeX to substitute scsl for it.
You may want to use fontaxes instead of slantsc.
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{slantsc}
\usepackage{lmodern}
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}
\AtBeginDocument{%
\DeclareFontShape{T1}{lmr}{m}{scit}{<->ssub*lmr/m/scsl}{}%
}
\begin{document}
\textsl{\textsc{gnu}'s not Unix} (\verb|\textsl{}|) \par
{\slshape gnu}'s not Unix (\verb|{\slshape }|) \par
\textit{\textsc{gnu}'s not Unix} (\verb|\textit{}|) \par
\emph{\textsc{gnu}'s not Unix} (\verb|\emph{}|)
\verb|\textsc{}| inside \verb|amsthm| theorem:
\begin{theorem}
\textsc{gnu}'s not Unix.
\end{theorem}
\end{document}
In order to have Palatino, load mathpazo for math and tgpagella for text:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{amsthm}
\usepackage{fontaxes}
\usepackage{mathpazo}
\usepackage{tgpagella}
\newtheorem{theorem}{Theorem}
\begin{document}
\textsl{\textsc{gnu}'s not Unix} (\verb|\textsl{}|) \par
\textit{\textsc{gnu}'s not Unix} (\verb|\textit{}|) \par
\emph{\textsc{gnu}'s not Unix} (\verb|\emph{}|)
\verb|\textsc{}| inside \verb|amsthm| theorem:
\begin{theorem}
\textsc{gnu}'s not Unix and math is right
\[
\int_{-\infty}^{\infty} \exp(-x^{2})\,dx=\sqrt{\pi}
\]
\end{theorem}
\end{document}
You get very much alike output with
\usepackage{newpxtext,newpxmath}
Take your pick.
|
[
"mechanics.stackexchange",
"0000057186.txt"
] |
Q:
windshield condensation when running air conditioning
My air conditioning is sufficiently cold but occasionally I've noticed a little thin film of condensation on the lower surface of the windshield. The area is across most of the width of the windshield in the bottom eighth. This would be on hot days, about 30 Celsius or 86 Fahrenheit.
What is the cause and solution for this problem?
Details:
2002 Acura RSX, The air conditioning compressor was replaced one year ago.
A:
From your description, this is normal. If you check it out, you'll probably find the condensation is on the outside. You've made the windshield sufficiently cold enough that the moisture is dewing on the outside of it. With how moisture condensates, it doesn't take much on a hot humid day to cause this to happen.
|
[
"stackoverflow",
"0031451021.txt"
] |
Q:
Meta tag viewport makes the entire page disappear on mobile
On this WordPress site my client is using a paid WP theme (Fortis7). I had to make several fixes and changes to the default CSS and JS code by adding my separate CSS and JS files to the theme's flow. After noticing that pages turned blank when the meta tag viewport is present (default), I removed all my custom code, thus switching back to the original, which is responsive by design. Nada. Zippo. When the meta tag is on, pages are blank. Any ideas/suggestions/hints?
ps: the HTTP errors you will see in the console don't cause the problem. I've already tested this.
Thanks in advance :-)
A:
In your style.css, Find this line and change width to 100% :
@media (max-width: 600px){body { width: "??";}}
|
[
"stackoverflow",
"0012241021.txt"
] |
Q:
EF generic repository Query method, how to select one column?
I am usign EF 4 with repository patren which have a generic query method which is coded as below:
public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
{
return objectSet.Where(filter);
}
I know how to query for selecting a complete object which was like below:
context.PeriodRepository.Query(a => a.EntityId == selectedEntityId);
Can you please guide me how to query not compelte object rather how to get just a property, I want to put property directly into textbox.
thanks
Edit
I have decided to get full object from query as:
MyType obj = context .Signatories1Repository.Query(a=>a.Id==signatory1Id);
but it shows an error:
Cannot convert from IEnumarable to type. An explicit conversion exisit. Are you missing a cast ?
Can you please advice how I can make it workign correctly ?
A:
In order to retrieve just a property (or some properties), you need to call the Select() linq extension method for doing a transformation that will retrieve just what you want:
context.PeriodRepository.Query(a => a.EntityId == selectedEntityId)
.Select(x => x.TheProperty);
I also suggest returning IQueryable<T> instead of IEnumerable<T> in your Query method. In fact, I would avoid the query method and just make your repository implement IQueryable<T> so you can just use the out-of-the-box linq extension methods like Where() instead.
|
[
"stackoverflow",
"0033715497.txt"
] |
Q:
Android can send udp but not receive
I've written a basic udp client server where one android sends message to the server and server relays it to the rest of the clients.
The issue is, the incoming udp messages get to the server and server relays them back but they never reach the rest of the devices.
Whats really amazing is that if I use the server as echo server (i.e relaying only to sender) then everything works. All client and server sockets use same port 2706
Server code
while (true) {
DatagramPacket packetToReceive = new DatagramPacket(new byte[2048], 2048);
try {
listenerSocket.receive(packetToReceive);
InetAddress senderAddress = packetToReceive.getAddress();
relayedBytes += packetToReceive.getLength();
if (!connectedClients.contains(senderAddress)) {
connectedClients.add(senderAddress);
}
for (InetAddress addr : connectedClients) {
// commenting this line will make it an echo server
if (!addr.equals(senderAddress))
{
//The following actually prints the ips of the android
//devices so it knows where to send
System.out.println(senderAddress.getHostAddress().toString() +
" to " + addr.getHostAddress().toString());
byte[] data = packetToReceive.getData();
packetToReceive.setData(data, 0, packetToReceive.getLength());
packetToReceive.setAddress(addr);
listenerSocket.send(packetToReceive);
}
}
} catch (IOException) {
e.printStackTrace();
}
}
android sender logic:
mainSocket=new DatagramSocket(homePort);
//targetAddressString is the public IP of server
target = InetAddress.getByName(targetAddressString);
while (true) {
byte[] data = getdata();
if (data == null)
continue;
DatagramPacket packet = new DatagramPacket(data, data.length, target, targetPort);
mainSocket.send(packet);
}
meanwhile on other thread the reciever just waits with the same udp socket:
while (true) {
Log.d("Player", "Waiting for data");
DatagramPacket packet = new DatagramPacket(new byte[2048], 2048);
try {
mainSocket.receive(packet);
Log.d("Player", "packet received");
//do something with the packet
} catch (IOException e) {
e.printStackTrace();
}
}
It never moves further than waiting for data since it'll block until it receives a packet
Moreover I can also see it in the wifi and Mobile data icons that no data is ever received but data sending is always on and is seen received on the server
**EDIT:- Echo server **
while (true) {
DatagramPacket receivedPacket = new DatagramPacket(new byte[2048], 2048);
try {
listenerSocket.receive(receivedPacket);
InetAddress senderAddress = receivedPacket.getAddress();
if (!connectedClients.contains(senderAddress)) {
connectedClients.add(senderAddress);
}
for (InetAddress addr : connectedClients) {
byte[] data = receivedPacket.getData();
DatagramPacket sendPacket= new DatagramPacket(data, 0, receivedPacket.getLength(), addr, receivedPacket.getPort());
listenerSocket.send(sendPacket);
}
} catch (IOException e) {
// ...
}
}
Basically it should relay the message to every single client who've ever sent any data but somehow it only sends its to its original sender the rest of clients miss it. the code is trolling with me
A:
This is the NAT traversal problem as you have figured out.
Here's a few hints:
The server can be hardcoded to listen on port 2706. But it shouldn't make any assumptions about what source port of received packets are. From your code, it doesn't look like you ever attempt to call setPort. So even if the NAT wasn't mapping your port number differently, I'm not sure how your original code was even getting the any destination port set. But I think you figured this out based on your own answer and your updated code.
Don't hardcode a client port on the client's socket. Choose port "0" (or don't set one) on your socket to let the OS choose the first available port for you. If you have multiple clients behind the same NAT, this behavior will allow for quicker client restarts, multiple devices behind the same NAT, and other nice things.
|
[
"stackoverflow",
"0045471077.txt"
] |
Q:
PHP - Redirect PHP after process done
I was wondering if it's possible to redirect a specific session after a background PHP script was done.
header("location: index.php");
$myboxes = $_POST['myCheckbox'];
error_log("location:index.php");
if(empty($myboxes))
{
error_log("You didn't select any boxes.");
}
else
{
$i = count($myboxes);
error_log("You selected $i box(es): ");
for($j = 0; $j < $i; $j++)
{
error_log($myboxes[$j] . " ");
}
header("location: sucess.php");
}
Is it possible to redirect/refresh someone after i already redirect him (and waiting for the background process to finish running).
Many Thanks
A:
My advice would be to run the script on index.php and then you can either display text or do a single redirect from there.
To answer your question directly, no it is not possible to send the headers twice.
If you do no explicitly tell php to send the initial header it will wait till execution has finished and send the latest header, for example:
header("Location: initialPage.php");
sleep(2);
header("Location: secondPage.php");
Will wait 2 seconds and then redirect the user to 'secondPage.php'
Alternatively you could force php to send the headers by flushing the output like so:
header("Location: initialPage.php");
flush();
ob_flush();
sleep(2);
header("Location: secondPage.php");
Then the user will be redirected to initialPage.php straight away and it will ignore the second redirect
Conclusion: No you cannot get the effect you desire by sending 2 headers.
|
[
"ru.stackoverflow",
"0000059014.txt"
] |
Q:
Ошибка в коде: задача на нахождение max и min
Здравствуйте!
Я только начала изучать Pascal. Дело очень интересное. Но вот моя задача: Мне нужно составить простую программу на нахождение максимального и минимального значения из N введенных чисел.
Вроде бы все сделала правильно. И ошибок компилятор не выдает. Но работает программа не совсем верно.
{Программа для определения максимального и минимального значения из N введенных чисел}
program max_i_min_iz_N;
uses crt;
var N,min,max,a,i,m:integer;
BEGIN
clrscr;
repeat
repeat
write('Введите любое положительное число: '); readln(N); writeln();
until(N>0);
write('Введите ',N,' чисел(-а) через пробел: ');
i:=2;
read(a);
max:=a;
min:=a;
repeat
read(a);
if(a>max)then max:=a else max:=max;
if(a<min)then min:=a else min:=min;
i:=i+1;
until(i>N);
writeln();
writeln('max=',max);
writeln('min=',min);
writeln();
writeln('Для продолжения программы нажмите цифру 1');
writeln('Для завершения программы нажмите цифру 2'); writeln();
readln(m);
writeln();
until(m=2);
END.
Вообще программа работает правильно во всех случаях, кроме одного...
Если здесь
write('Введите ',N,' чисел(-а) через пробел: ');
пользователь вводит значение переменной N = 1, то программа все равно ждет ввода следующей переменной для сравнения.
Я понимаю, что так происходит потому, что у меня в коде прописано дважды считывание переменной a, но по-другому сделать у меня не получилось.
Если сделать так:
i:=1;
max:=a;
min:=a;
repeat
read(a);
if(a>max)then max:=a else max:=max;
if(a<min)then min:=a else min:=min;
i:=i+1;
until(i>N);
Тогда переменной i присваиваю 1 и дополнительного значения вводить не надо, в этом плане цикл работает правильно. Но находит из введенных значений правильно только максимальное число. Минимальному присваивает 0. Интересно то, что, если программу не закрыть, а продолжить дальше, то тогда программа начинает находить минимальное и максимальное число правильно. Но не из только что введенных значений, а из всех значений, которые были введены.
Если сделать так:
i:=1;
read(a);
max:=a;
min:=a;
repeat
if(a>max)then max:=a else max:=max;
if(a<min)then min:=a else min:=min;
i:=i+1;
until(i>N);
То здесь программа присваивает первое значение и max, и min, и следующие значения не сравнивает. При этом цикл на повторение программы не срабатывает. Программа просто закрывается и все. В приниципе, понятно, почему не сравнивает значения, ведь в следующем цикле учавствует только одно и то же значение переменной а, которое было введено первым. А вот почему тогда программа закрывается сама, не считывая переменную m?
В общем, я отказалась от идеи использовать только одно считывание переменной N. Но только тогда как можно сделать так, чтобы программа в случае ввода цифры 1 для переменной N все работало правильно? Может быть просто добавить для 1 конструкцию case?
Еще мне не очень нравиться i:=2; Не красиво как-то что ли. Привычнее видеть i:=1; Но если я присваиваю переменной i значение 1, то программа запрашивает для сравнения введенных значений на одно больше.
Но вообще стукаюсь глазами и не вижу, что делаю не так.
Не сочтите за труд, подскажите, пожалуйста, где я ошибаюсь.
A:
Первое, что бросается в глаза - это такие строки:
if(a>max)then max:=a else max:=max;
if(a<min)then min:=a else min:=min;
Их точно можно записать короче:
if(a>max)then max:=a;
if(a<min)then min:=a;
Функционал тот же, а глазу приятнее.
Теперь перейдем к самому главному. К этому циклу
repeat
read(a);
if(a>max)then max:=a else max:=max;
if(a<min)then min:=a else min:=min;
i:=i+1;
until(i>N);
Его можно записать красивее:
while(i <= N) do begin
read(a);
if(a>max)then max:=a;
if(a<min)then min:=a;
i:=i+1;
end;
И все должно работать.
Если не нравится i := 2; то можно заменить на i := 1;, но нужно ещё одно изменение - while(i <= N) заменить на while(i < N).
A:
Чтобы прога не мотала цикл, нужно вложенный Repeat заменить на While так:
i:=1;
Write('a = ');
read(a);
max:=a;
min:=a;
While (i<N) Do // если ввести 1, цикл работать не будет
Begin
Write('a = ');
read(a);
if(a>max)then max:=a;
if(a<min)then min:=a;
i:=i+1;
End;
Или написать такое условие после первого вложенного цикла Repeat:
If (N=1) Then Break;
Но, я бы сделал так: изменил бы условие на цикле:
repeat
write('Введите любое положительное число: '); readln(N); writeln;
until(N>1);
Сразу от пользователя ввод положительного числа требовать.
Тогда и счётчику i:=1 единичку присвоить можно.
|
[
"stackoverflow",
"0043365967.txt"
] |
Q:
couldn't find with id= when passing parameter in url
I'm very new to rails and this is my first application. I'm trying to display all the questions that belong to a batch_set. batch_set has many questions and question belongs to a batch_set. Also, batch has many batch_sets and batch_set belongs to a batch.
In the batch show page, I've linked a new page called batch_questions (which will contain all the questions related to that batch) and passed the batch id to it.
<%= link_to b.title, batches_batch_questions_path(:batches => @batch.id) %>
My url for the batch_questions page looks like this
http://localhost:3000/batches/batch_questions?batches=1
So, in the batch_question action which is in the batch controller, I'm trying to get the batch id. How do I do that? I tried this.
@batch = Batch.find(params[:batch])
I'm getting an error saying
"Couldn't find Batch with 'id'= "
So how do I assign @batch the parameter that is passed in the URL?
A:
Try following code in your controller:
@batch = Batch.find(params[:batches])
|
[
"superuser",
"0001328283.txt"
] |
Q:
How to draw boxes and tables in plain text
In many plain text documents, box drawing characters are used to draw these boxes in figures and tables. Such examples (from RFC 5766) are shown below. Is there a better way to draw this (for instance, a Unix command line tool), other than using the trial-and-error method?
Examples from RFC 5766:
+----------------------------+---------------------+
| TURN client to TURN server | TURN server to peer |
+----------------------------+---------------------+
| UDP | UDP |
| TCP | UDP |
| TLS over TCP | UDP |
+----------------------------+---------------------+
And this one, also from RFC 5766:
Peer A
Server-Reflexive +---------+
Transport Address | |
192.0.2.150:32102 | |
| /| |
TURN | / ^| Peer A |
Client's Server | / || |
Host Transport Transport | // || |
Address Address | // |+---------+
10.1.1.2:49721 192.0.2.15:3478 |+-+ // Peer A
| | ||N| / Host Transport
| +-+ | ||A|/ Address
| | | | v|T| 192.168.100.2:49582
| | | | /+-+
+---------+| | | |+---------+ / +---------+
| || |N| || | // | |
| TURN |v | | v| TURN |/ | |
| Client |----|A|----------| Server |------------------| Peer B |
| | | |^ | |^ ^| |
| | |T|| | || || |
+---------+ | || +---------+| |+---------+
| || | |
| || | |
+-+| | |
| | |
| | |
Client's | Peer B
Server-Reflexive Relayed Transport
Transport Address Transport Address Address
192.0.2.1:7000 192.0.2.15:50000 192.0.2.210:49191
Figure 1
A:
The free ASCIIflow website will let you draw text boxes, text, lines, arrows, freeform lines, erase, import, export, and even undo/redo. What else would one need?
Here is my wonderful creation using this tool:
+-------------------------------+
| |
| My first ASCII box |
| |
+---------+---------------------+
|
|
|
| My first ever ASCII arrow
|
|
|
+---------v----------------------+
| |
| My second ASCII box |
+--------------------------------+
A:
It is possible to draw such pictures using tools dating back 30 years, namely pic which is part of the troff command suite. These days gnu's groff package will contain the pic command. The link shows a picture of some typical PostScript output, but using nroff or the appropriate options you will get an ascii-art version. See the user manual (pdf) from 1991 for examples.
The tables in your example are probably produced by this same command suite, using just tbl which produces tables from simple lists.
For a gui version, you can use artist-mode in emacs to draw boxes and arrowed lines etc, using the mouse or keyboard. See youtube video demo.
A:
Drawing boxes or other shapes with characters is known as ASCII art (also ANSI or ISO art). There are numerous tools to aid in creating ASCII art, such as online ASCIIFlow, image rendering in ASCII, applications such as figlet, etc. Some have been implemented in JavaScript and can be run in a browser on any OS.
There is nothing new under the sun - micrography is a subset of calligraphy with a long pedigree, used for hundreds of years, using letters to form pictures, such as the calendar below, with much of the image formed from letters.
|
[
"stackoverflow",
"0014582306.txt"
] |
Q:
implementation of .cfi_remember_state
I was wondering how exactly .cfi_remember_state is implemented. I know it is a pseudo-op, so I suppose it is converted into a couple of instructions when assembling. I am interested what exact instructions are used to implement it. I tried many ways to figure it out. Namely:
Read GAS source code. But failed to find anything useful enough.
Read GAS documentation. But the .cfi_remember_state entry is just a simple joke (literally).
Tried to find a gcc switch that would make gcc generate asm from C code with pseudo-ops "expanded". Failed to find such a switch for x86 / x86-64. (Would be nice if someone could point me to such a switch, assuming it exists, BTW.)
Google-fu && searching on SO did not yield anything useful.
The only other solution in my mind would be to read the binary of an assembled executable file and try to deduce the instructions. Yet I would like to avoid such a daunting task.
Could any of You, who knows, enlighten me, how exactly it is implemented on x86 and/or x86-64? Maybe along with sharing how / where that information was acquired, so I could check other pseudo-ops, if I ever have the need to?
A:
This directive is a part of DWARF information (really all it does is emit DW_CFA_remember_state directive). Excerpt from DWARF3 standard:
The DW_CFA_remember_state instruction takes no operands. The required
action is to push the set of rules for every register onto an implicit
stack.
You may play with DWARF information using objdump. Lets begin with simple void assembler file:
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
#.cfi_remember_state
.cfi_endproc
.LFE0:
.size main, .-main
Compile it with gcc cfirem.s -c -o cfirem.o
Now disassemble generated DWARF section with objdump --dwarf cfirem.o
You will get:
00000018 00000014 0000001c FDE cie=00000000 pc=00000000..00000000
DW_CFA_nop
DW_CFA_nop
...
If you will uncomment .cfi_remember_state, you will see instead:
00000018 00000014 0000001c FDE cie=00000000 pc=00000000..00000000
DW_CFA_remember_state
DW_CFA_nop
DW_CFA_nop
...
So it is not really converting in assembler instructions (try objdump -d to see that there are no assembler instructions in our sample at all). It is converted in DWARF pseudo-instructions, that are used when debugger like GDB processes your variable locations, stack information and so on.
|
[
"stackoverflow",
"0063353855.txt"
] |
Q:
While rule evaluation Db Connection null exception
I stuck in a scenario while evaluating the rule it initializes the class B and calls the default constructor, but I am injecting the Db Connection through parameter constructor. Please see the below code and advice.
public class A
{
[ExternalMethod(typeof(B), "IsSpecialWord")]
[Field(DisplayName = "English Word", Description = "English Word", Max = 200)]
public string EngWord { get; set; }
}
public class B
{
public IDbCoonection dbCon { get; set; }
public B(IDbConnection db)
{
dbCon = db;
}
[Method("Is Special Word", "Indicates to test abbreviated word")]
public IsSpecialWord(sting word)
{
db.CheckSpecialWord(word);
}
public insert SpecialWord(T t)
{
db.Insert();
}
public update SpecialWord(T t)
{
db.Update();
}
}
public class TestController
{
A aObj = new A();
aObj.EngWord ="test";
IDbConnection db = null;
if(1)
db = new SQLDBConnection(connString);
else
db = new OracleDBConnection(connectionString);
B b = new B(db);
Evaluator<A> evaluator = new Evaluator<A>(editor.Rule.GetRuleXml());
bool success = evaluator.Evaluate(aObj);
}
A:
If you use an instance external method, the declaring class has to have an empty constructor in order for the engine to be able to instantiate the class and invoke the method successfully.
In your case, you can declare a Connection property in your source, set its value before the evaluation starts, and pass that source as a parameter in order to use that connection in your external method. Params of the source type are not visible to the rule authors, they are passed automatically to methods by the engine during evaluation. In Rule XML they are declared as <self/> param nodes.
Here is how this might look like:
public class A
{
public IDbCoonection Connection { get; set; }
// The rest of the source type goes here...
}
public class B
{
public B( ) { } // Empty constructor
[Method("Is Special Word", "Indicates to test abbreviated word")]
public bool IsSpecialWord( A source, string word )
{
source.Connection.CheckSpecialWord(word);
}
}
The rule would look like this:
If Is Special Word ( test ) then Do Something
Note that rule authors don't have to pass the source as param to the method, it happens automatically.
|
[
"stackoverflow",
"0053654728.txt"
] |
Q:
Matplotlib -Close window without explicit mouseclick
The following code displays the following window:
import numpy as np
import matplotlib.pylab as pl
import matplotlib.gridspec as gridspec
from matplotlib import pyplot as plt
def plot_stuff(x,y,z):
gs = gridspec.GridSpec(3, 1)
plt.style.use('dark_background')
pl.figure("1D Analysis")
ax = pl.subplot(gs[0, 0])
ax.set_ylabel('X VALUE')
pl.plot(x, color="red")
ax = pl.subplot(gs[1, 0])
ax.set_ylabel('Y VALUE')
pl.plot(y, color="green")
ax = pl.subplot(gs[2, :])
ax.set_ylabel('Z VALUE')
pl.plot(z, color="blue")
plt.show()
How do I close the window without an explicit mouse click?
I need to visualize a LOT of data so I'm searching a way to automating the process of opening and closing windows.
I know that plt.show() is a blocking operation and I've tried using the plt.close("all") method as mentioned in the related questions but the window remains there, does not close and I have to close it manually.
I need a simple code for automating the process of opening a window, visualize the data, closing the window after a certain interval of time; and then repeat the procedure in a for loop fashion.
A:
Here is another solution, using an explicit close statement to close then recreate the figure at each iteration
from matplotlib import gridspec
import matplotlib.pyplot as plt
import numpy as np
def plot_stuff(x, y, z):
gs = gridspec.GridSpec(3, 1)
plt.style.use('dark_background')
fig = plt.figure("1D Analysis")
ax = plt.subplot(gs[0, 0])
ax.set_ylabel('X VALUE')
plt.plot(x, color="red")
ax = plt.subplot(gs[1, 0])
ax.set_ylabel('Y VALUE')
plt.plot(y, color="green")
ax = plt.subplot(gs[2, :])
ax.set_ylabel('Z VALUE')
plt.plot(z, color="blue")
return fig
things_to_plot = [np.random.random(size=(100, 3)),
np.ones((100, 3)),
np.random.random(size=(100, 3))]
delay = 5
if __name__ == "__main__":
plt.ion()
for things in things_to_plot:
fig = plot_stuff(x=things[:, 0], y=things[:, 1], z=things[:, 2])
plt.show()
plt.pause(delay)
plt.close()
|
[
"stackoverflow",
"0050442965.txt"
] |
Q:
Shared Preference Swift 4- iOS- Unique Alamofire user id
In my classifieds project there is a user registration page and user id generated in php so in that particular user id all other data of particular user need to save. I would share my swift codes for registration and swift data form to save in that particular user id. But registration user id is getting saved successfully but the datas entering in data form is not saving in unique user id. Please help me in fix that...
Registration page swift
let parameters: Parameters=[
"user_name":nameTextField.text!,
"user_email":emailTextField.text!,
"user_mobile":mobileNumb.text!,
"password":passwordTextField.text!
]
//Sending http post request
Alamofire.request("https://alot.ae/api/user_reg.php", method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
//getting the json value from the server
if let result = response.result.value {
//converting it as NSDictionary
let jsonData = result as! NSDictionary
let defaults: UserDefaults = UserDefaults.standard
//This class variable needs to be defined every class where you set or fetch values from NSUserDefaults
defaults.setValue("password", forKey: "user_id")
defaults.synchronize()
//Call this when you're done editing the defaults. It saves you
}}
And my swift code for other form which have to save data in that particular user id
//creating parameters for the post request
let parameters: Parameters=[
"full_name":profN.text!,
"position":position.text!,
"email":emailCompa.text!,
"phone_number":numComP.text!
]
//Sending http post request
Alamofire.request(URL_USER_EMPLOYER_PROFILE, method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
//getting the json value from the server
if let result = response.result.value {
//converting it as NSDictionary
let jsonData = result as! NSDictionary
let defaults = UserDefaults.standard
defaults.set("URL_USER_EMPLOYER_PROFILE", forKey: "user")
}
}
A:
I found the answer with iPhone developer @ Muhammed Azharuddin, by creating a class for user defaults to store datas in user_id
extension UserDefaults{
static let isLoggedIn = "com.xyz.AlotTest1isLoggedIn"
static let userId = "com.xyz.AlotTest1userId"
}
And call this extension in parameters after @IBAction
//creating parameters for the post request
let parameters: Parameters=[
"full_name":profN.text!,
"position":position.text!,
"email":emailCompa.text!,
"phone_number":numComP.text!,
"user_id" : AuthService.instance.userId ?? ""
]
// Sending http post request
Alamofire.request(URL_USER_EMPLOYER_PROFILE, method: .post, parameters: parameters).responseJSON
{
response in
// printing response
print(response)
// getting the json value from the server
if let result = response.result.value {
UserDefaults.standard.value(forKey: "user_id")
// converting it as NSDictionary
let jsonData = result as! NSDictionary
let defaults: UserDefaults = UserDefaults.standard
//This class variable needs to be defined every class where you set or fetch values from NSUserDefaults
}
}
let employer = self.storyboard?.instantiateViewController(withIdentifier: "employer") as! EmployerViewController
self.present(employer, animated: true)
}
|
[
"stackoverflow",
"0062841115.txt"
] |
Q:
Sort two text files with its indented text aligned to it
I would like to compare two of my log files generated before and after an implementation to see if it has impacted anything. However, the order of the logs I get is not the same all the time. Since, the log file also has multiple indented lines, when I tried to sort, everything is sorted. But, I would like to keep the child intact with the parent. Indented lines are spaces and not tab.
Any help would be greatly appreciated. I am fine with any windows solution or Linux one.
Eg of the file:
#This is a sample code
Parent1 to be verified
Child1 to be verified
Child2 to be verified
Child21 to be verified
Child23 to be verified
Child22 to be verified
Child221 to be verified
Child4 to be verified
Child5 to be verified
Child53 to be verified
Child52 to be verified
Child522 to be verified
Child521 to be verified
Child3 to be verified
A:
I am posting another answer here to sort it hierarchically, using python.
The idea is to attach the parents to the children to make sure that the children under the same parent are sorted together.
See the python script below:
"""Attach parent to children in an indentation-structured text"""
from typing import Tuple, List
import sys
# A unique separator to separate the parent and child in each line
SEPARATOR = '@'
# The indentation
INDENT = ' '
def parse_line(line: str) -> Tuple[int, str]:
"""Parse a line into indentation level and its content
with indentation stripped
Args:
line (str): One of the lines from the input file, with newline ending
Returns:
Tuple[int, str]: The indentation level and the content with
indentation stripped.
Raises:
ValueError: If the line is incorrectly indented.
"""
# strip the leading white spaces
lstripped_line = line.lstrip()
# get the indentation
indent = line[:-len(lstripped_line)]
# Let's check if the indentation is correct
# meaning it should be N * INDENT
n = len(indent) // len(INDENT)
if INDENT * n != indent:
raise ValueError(f"Wrong indentation of line: {line}")
return n, lstripped_line.rstrip('\r\n')
def format_text(txtfile: str) -> List[str]:
"""Format the text file by attaching the parent to it children
Args:
txtfile (str): The text file
Returns:
List[str]: A list of formatted lines
"""
formatted = []
par_indent = par_line = None
with open(txtfile) as ftxt:
for line in ftxt:
# get the indentation level and line without indentation
indent, line_noindent = parse_line(line)
# level 1 parents
if indent == 0:
par_indent = indent
par_line = line_noindent
formatted.append(line_noindent)
# children
elif indent > par_indent:
formatted.append(par_line +
SEPARATOR * (indent - par_indent) +
line_noindent)
par_indent = indent
par_line = par_line + SEPARATOR + line_noindent
# siblings or dedentation
else:
# We just need first `indent` parts of parent line as our prefix
prefix = SEPARATOR.join(par_line.split(SEPARATOR)[:indent])
formatted.append(prefix + SEPARATOR + line_noindent)
par_indent = indent
par_line = prefix + SEPARATOR + line_noindent
return formatted
def sort_and_revert(lines: List[str]):
"""Sort the formatted lines and revert the leading parents
into indentations
Args:
lines (List[str]): list of formatted lines
Prints:
The sorted and reverted lines
"""
sorted_lines = sorted(lines)
for line in sorted_lines:
if SEPARATOR not in line:
print(line)
else:
leading, _, orig_line = line.rpartition(SEPARATOR)
print(INDENT * (leading.count(SEPARATOR) + 1) + orig_line)
def main():
"""Main entry"""
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <file>")
sys.exit(1)
formatted = format_text(sys.argv[1])
sort_and_revert(formatted)
if __name__ == "__main__":
main()
Let's save it as format.py, and we have a test file, say test.txt:
parent2
child2-1
child2-1-1
child2-2
parent1
child1-2
child1-2-2
child1-2-1
child1-1
Let's test it:
$ python format.py test.txt
parent1
child1-1
child1-2
child1-2-1
child1-2-2
parent2
child2-1
child2-1-1
child2-2
If you wonder how the format_text function formats the text, here is the intermediate results, which also explains why we could make file sorted as we wanted:
parent2
parent2@child2-1
parent2@child2-1@child2-1-1
parent2@child2-2
parent1
parent1@child1-2
parent1@child1-2@child1-2-2
parent1@child1-2@child1-2-1
parent1@child1-1
You may see that each child has its parents attached, all the way along to the root. So that the children under the same parent are sorted together.
|
[
"skeptics.stackexchange",
"0000004709.txt"
] |
Q:
Doctors and Handwriting: is it so bad that it inadvertently kills patients?
According to a lot of people, doctors have awful handwriting. First, is this true - is there a statistically significant proportion of doctors who have handwriting which control groups would find hard to read? Secondly, this article claims that because it is so bad, it can kill patients due to mistakes involving drug dosages, or incorrect surgery, or by other means. Really?
A:
The source behind the Time article is a July 2006 report from the Institute of Medicine entitled Preventing Medication Errors: Quality Chasm Series. A brief (PDF) is available online and the information here is from that.
The topic revolves around adverse drug events (ADEs) which includes errors caused by faulty prescriptions:
Some of these “adverse drug events [ADEs],” as injuries due to medication are generally called, are inevitable—the more powerful a drug is, the more likely it is to have harmful side effects, for instance—but sometimes the harm is caused by an error in prescribing or taking the medication, and these damages are not inevitable. They can be prevented.
The number of preventable ADEs is extremely large. The report suggests that a typical hospital patient is subjected to at least one medication error a day. Different studies have claimed 380,000 and 450,000 preventable ADEs per year. The committee behind the report considers these low estimates.
One study calculates, for example, that 800,000 preventable ADEs occur each year in long-term care facilities. Another finds that among outpatient Medicare patients there occur 530,000 preventable ADEs each year.
It again considers those numbers low estimates and then notes that none of these studies involve prescriptions that should have happened but never did — errors of omission. The committee concludes with the number 1.5 million preventable ADEs occurring
in the United States each year as their lowball estimate which one of the numbers used in the Time article. So far so good.
Unfortunately, the brief does not break down these numbers further. The only mention of handwriting is in a section about how using new technologies can help:
Even more promising is the use of electronic prescriptions, or e-prescriptions. By
writing prescriptions electronically, doctors and other providers can avoid many of
the mistakes that accompany handwritten prescriptions, as the software ensures that
all the necessary information is filled out—and legible.
The note on legibility here is not hardly the focus of the section. While it does admit that poor handwriting plays a part in preventable ADEs, the brief alone does not provide enough reason for the Time article's comments that "Doctors' sloppy handwriting kills more than 7,000 people annually." Digging into the full report, I did find a few more notes on handwriting issues:
Poorly handwritten prescription orders are the chief culprit in miscommunications among prescribing clinicians, nurses, and pharmacists, and have often resulted in serious injury or death due to incorrect understanding of the drug or its dosage, route, or frequency (Cohen, 2000).
There was also a note about transcription errors which could be seen as a container for handwriting errors. One study labeled 29 of the 334 errors found as transcription errors. But nowhere in the report did I find an estimated death count for anything specifically targeting handwriting.
Looking closer at the Time article, I realized it may have just been tricky writing:
Doctors' sloppy handwriting kills more than 7,000 people annually. It's a shocking statistic, and, according to a July 2006 report from the National Academies of Science's Institute of Medicine (IOM), preventable medication mistakes also injure more than 1.5 million Americans annually.
The 1.5 million statistic does come from the IOM report but the 7,000 people killed is entirely unsourced. The Straight Dope comments:
The actual stat alluded to - apparently from a 1998 Lancet paper via subsequent reports by the Institute of Medicine - is that each year 7,000 U.S. deaths result from all medication-related errors of any sort, inside and outside hospitals, and not just those tied to poor penmanship.
The Time article was way off the mark with regards to their statistic and juxtaposing that statistic with an unrelated source. But the direct answer to the question, "Does bad handwriting kill people?" is that yes, it can, if it is the underlying cause for an ADE that results in patient death. Is it a rampant problem? Not when compared to the other preventable ADEs.
A:
Here's an example case: https://web.archive.org/web/20141127155506/http://www.medmal-law.com/illegibl.htm
On June 23, 1995, Ramon Vasquez received the following prescription from his cardiologist. He began taking the medication given to him by the pharmacist on a Saturday morning. By Sunday night, the medication had affected his heart so much that he had a heart attack. He died several days later.
[...]
What is the name of the first drug prescribed? Is it Plendil??? Isordil???
The pharmacist who filled this prescription read it as Plendil. The cardiologist who wrote the Rx states that he wrote Isordil.
[...]
This case marks the first time that a physician has been found negligent for illegible handwriting.
|
[
"stackoverflow",
"0005117992.txt"
] |
Q:
.Net Listbox will not compile with javascript event handler?
This should be the simplest thing ever but it will not work. I have a simple asp.net Listbox and for the event OnSelectedIndexChanged I want to launch a javascript function. This works for when i set links to launch the same function but not when set for this particular control. The line of code is as follows:
<tr><td>
<asp:ListBox ID="ListBox1" runat="server" Width="250"
Height="600" OnSelectedIndexChanged="javascript:selectedIndexChanged()">
</asp:ListBox>
</td></tr>
Here are the compilation errors i am getting:
c:\..\ManufInfo.aspx(171,84): error
CS1026: ) expected
c:\..\ManufInfo.aspx(171,84): error
CS1002: ; expected
c:\..\ManufInfo.aspx(171,84): error
CS1525: Invalid expression term ':'
c:\..\ManufInfo.aspx(171,84): error
CS1026: ) expected
c:\..\ManufInfo.aspx(171,84): error
CS1002: ; expected
c:\..\ManufInfo.aspx(171,84): error
CS1525: Invalid expression term ':'
c:\..\ManufInfo.aspx(171,85): error
CS1002: ; expected
c:\..\ManufInfo.aspx(171,85): error
CS1002: ; expected
c:\..\ManufInfo.aspx(171,107): error
CS1002: ; expected
c:\..\ManufInfo.aspx(171,107): error
CS1525: Invalid expression term ')'
c:\..\ManufInfo.aspx(171,107): error
CS1002: ; expected
c:\..\ManufInfo.aspx(171,107): error
CS1525: Invalid expression term ')'
What the heck is going? ;) Probably a n00b mistake but I thought I was picking up jscript enough to understand that should work...
Thanks to anyone who can point me in the right direction!
A:
OnSelectedIndexChanged is not meant for javascript handlers. Try this on page_load
ListBox1.Attributes.Add("onclick", "selectedIndexChanged()");
|
[
"tex.stackexchange",
"0000443146.txt"
] |
Q:
Nomenclature list not getting updated
I am using \usepackage{nomencl} to define a list of symbols...
For example
\nomenclature[B]{$\varepsilon$}{Permittivity \nomunit{$Farads/cm$}}
\nomenclature[B]{$a$}{Lattice constant\nomunit{$\AA$}}
Now I want to add new symbols, but I do not understand why my pre-existing list is not getting updated in the output file..
Can you please help?
I already tried deleting auxillary file, but it does not help
Here is a working example: (please note the package adsphd can be downloaded here: https://people.cs.kuleuven.be/~wannes.meert/adsphd/)
\documentclass[showinstructions,faculty=firw,department=mtk,phddegree=mtk]{adsphd}
\title{\textsc{Title of the thesis}}
\author{Author}{Name}
\supervisor{Prof. XX}{}
\president{Prof. XX}
\jury{Dr XX }
\externaljurymember{Prof. XX}{far away place}
\researchgroup{XXXXX}
\website{} % Leave empty to hide
\email{} % Leave empty to hide
\address{xx}
\date{Nov 2017}
\copyyear{2017}
\setlength{\adsphdspinewidth}{9mm}
\usepackage{etoolbox}
\usepackage{nomencl} % For nomenclature
\renewcommand{\nomname}{List of Symbols}
\setlength{\nomlabelwidth}{3cm}
\newcommand{\myprintnomenclature}{%
\cleardoublepage%
\printnomenclature%
\chaptermark{\nomname}
\addcontentsline{toc}{chapter}{\nomname} %% comment to exclude from TOC
}
\newcommand{\nomunit}[1]{%
\renewcommand{\nomentryend}{\hspace*{\fill}#1}}
\renewcommand\nomgroup[1]{%
\item[\bfseries
\ifstrequal{#1}{A}{Physics Constants}{%
\ifstrequal{#1}{B}{Other Symbols}{}}%
]}
\makenomenclature%
\usepackage{glossaries} % For list of abbreviations
\newcommand{\glossname}{List of Abbreviations}
\newcommand{\myprintglossary}{%
\renewcommand{\glossaryname}{\glossname}
\renewcommand*{\glossaryentrynumbers}[1]{}
\cleardoublepage%
\printglossary[title=\glossname]
\chaptermark{\glossname}
\addcontentsline{toc}{chapter}{\glossname} %% comment to exclude from TOC
}
\makeglossaries%
\usepackage[utf8]{inputenc} %Uncommented for BibLatex
\usepackage{csquotes} %Uncommented for BibLatex
\usepackage[
hyperref=auto,
mincrossrefs=999,
backend=bibtex,
sorting = none, % to have references appear as they are cited
style=numeric-comp,
firstinits=true, %added new
clearlang=true, %added new
refsegment=chapter,
defernumbers=true
]{biblatex} %Uncommented for BibLatex
\addbibresource{allpapers.bib} %Uncommented for BibLatex
\renewcommand*{\labelalphaothers}{}
\usepackage{float}
\usepackage{textcomp} % nice greek alphabet
\usepackage{pifont} % Dingbats
\usepackage{booktabs}
\usepackage{amssymb,amsthm}
\usepackage{amsmath}
\usepackage{mathtools} % for short intertext; somya
\usepackage[font=small,labelfont=bf]{caption}
\usepackage[labelformat=parens,labelfont=md, font=small]{subcaption}
\usepackage{arydshln}
\usepackage[normalem]{ulem}
\usepackage{chemformula}
\usepackage{siunitx}
\usepackage{gensymb} % for degree symbol
\usepackage{hyperref}
\hypersetup{
colorlinks=true,
linkcolor=blue,
citecolor=blue,
filecolor=magenta,
urlcolor=blue,
}
\usepackage[hang]{footmisc}
\setlength\footnotemargin{0.2em}
\usepackage{cancel}
\usepackage{enumitem}
\usepackage{color,soul} % for text highlight
\setcounter{secnumdepth}{5}
\setlength{\belowcaptionskip}{-5pt} %to remove space below caption
%\usepackage[showframe]{geometry}
\usepackage{array, makecell, booktabs}
%\usepackage{siunitx}
\DeclareSIUnit \uF { \micro \farad }
%\usepackage{chemformula}
\renewcommand{\cellalign}{tc}
\usepackage{siunitx}
\newcommand*{\citen}[1]{%
\begingroup
\romannumeral-`\x % remove space at the beginning of \setcitestyle
\setcitestyle{numbers}%
\cite{#1}%
\endgroup
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newglossaryentry{md}{name={MD},description={molecular dynamics}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\makeindex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\maketitle
%\frontmatter % to get \pagenumbering{roman}
\glsaddall
\myprintglossary
\makenomenclature
\myprintnomenclature
\tableofcontents
\mainmatter % to get \pagenumbering{arabic}
\cleardoublepage
\nomenclature[A]{$k$}{Boltzmann Constant \nomunit{$8.617\times10^5 \, eV.K^{-1}$}}
An example text can be typed here !
%\makebackcoverXII
\end{document}
A:
I finally find the solution.
I am using TeXstudio.
Go to Option--> Configure Texstudio --> Commands
In the field of Makeindex write the following:
makeindex.exe %.nlo -s nomencl.ist -o %.nls
I have no clue what it means. But it works!
|
[
"stackoverflow",
"0042960000.txt"
] |
Q:
Java deserializing part of the JSON into object and the rest into JsonObject
I was looking everywhere how to deserialize part of the JSON into an object and the rest into JsonObject.
for example:
{
"id" : "123",
"message" : {"subject" : "test sub" , "body" : "test body"}
}
I want to deserialize this JSON into this class:
public class className {
private String id;
private transient JsonObject message;
// getters and setters
}
The problem is that after the deserialization I get empty object {}inside "message".
Does anyone have any idea about it?
======================================================
EDIT:
A little more info, I am using Spring MVC, the JSON is being sent by POST message into my controller.
The controller function looks like this:
public @ResponseBody String publish(@RequestBody final className input, final HttpServletRequest request,
final HttpServletResponse response) {
//input.message = {}
}
A:
That is because Spring tries to parse your object with Jackson library while your object holds Gson objects (which can't be parsed with Jackson).
Please refer Configure Gson in Spring.
@Configuration
@EnableWebMvc
public class Application extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter < ? >> converters) {
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
converters.add(gsonHttpMessageConverter);
}
}
|
[
"stackoverflow",
"0014526652.txt"
] |
Q:
dynamically adding callable to class as instance "method"
I implemented a metaclass that tears down the class attributes for classes created with it and builds methods from the data from those arguments, then attaches those dynamically created methods directly to the class object (the class in question allows for easy definition of web form objects for use in a web testing framework). It has been working just fine, but now I have a need to add a more complex type of method, which, to try to keep things clean, I implemented as a callable class. Unfortunately, when I try to call the callable class on an instance, it is treated as a class attribute instead of an instance method, and when called, only receives its own self. I can see why this happens, but I was hoping someone might have a better solution than the ones I've come up with. Simplified illustration of the problem:
class Foo(object):
def __init__(self, name, val):
self.name = name
self.val = val
self.__name__ = name + '_foo'
self.name = name
# This doesn't work as I'd wish
def __call__(self, instance):
return self.name + str(self.val + instance.val)
def get_methods(name, foo_val):
foo = Foo(name, foo_val)
def bar(self):
return name + str(self.val + 2)
bar.__name__ = name + '_bar'
return foo, bar
class Baz(object):
def __init__(self, val):
self.val = val
for method in get_methods('biff', 1):
setattr(Baz, method.__name__, method)
baz = Baz(10)
# baz.val == 10
# baz.biff_foo() == 'biff11'
# baz.biff_bar() == 'biff12'
I've thought of:
Using a descriptor, but that seems way more complex than is necessary here
Using a closure inside of a factory for foo, but nested closures are ugly and messy replacements for objects most of the time, imo
Wrapping the Foo instance in a method that passes its self down to the Foo instance as instance, basically a decorator, that is what I actually add to Baz, but that seems superfluous and basically just a more complicated way of doing the same thing as (2)
Is there a better way then any of these to try to accomplish what I want, or should I just bite the bullet and use some closure factory type pattern?
A:
One way to do this is to attach the callable objects to the class as unbound methods. The method constructor will work with arbitrary callables (i.e. instances of classes with a __call__() method)—not just functions.
from types import MethodType
class Foo(object):
def __init__(self, name, val):
self.name = name
self.val = val
self.__name__ = name + '_foo'
self.name = name
def __call__(self, instance):
return self.name + str(self.val + instance.val)
class Baz(object):
def __init__(self, val):
self.val = val
Baz.biff = MethodType(Foo("biff", 42), None, Baz)
b = Baz(13)
print b.biff()
>>> biff55
In Python 3, there's no such thing as an unbound instance (classes just have regular functions attached) so you might instead make your Foo class a descriptor that returns a bound instance method by giving it a __get__() method. (Actually, that approach will work in Python 2.x as well, but the above will perform a little better.)
from types import MethodType
class Foo(object):
def __init__(self, name, val):
self.name = name
self.val = val
self.__name__ = name + '_foo'
self.name = name
def __call__(self, instance):
return self.name + str(self.val + instance.val)
def __get__(self, instance, owner):
return MethodType(self, instance) if instance else self
# Python 2: MethodType(self, instance, owner)
class Baz(object):
def __init__(self, val):
self.val = val
Baz.biff = Foo("biff", 42)
b = Baz(13)
print b.biff()
>>> biff55
|
[
"math.stackexchange",
"0001295033.txt"
] |
Q:
The angle between $u$ and $v$ is $30º$, and the vector $w$ of norm $4$ is ortogonal to both $u,v$. Calculate $[u,v,w]$.
The angle between the unit vectors $u$ and $v$ is $30º$, and the vector $w$ of norm $4$ is ortogonal to both $u,v$. The basis $(u,v,w)$ is positive, calculate $[u,v,w]$.
I did the following:
Take an arbitrary vector of norm $1$, for simplicity I took $u=(1,0,0)$.
Now I need another vector $v$ with norm $1$ and $30$ degrees from $u$. To do it, I solved the following pait of equations:
$$\frac{(1,0,0)\cdot(x,y,z)}{\sqrt{x^2+y^2+z^2}}=\frac{\pi}{6} \quad \quad \quad \quad \quad \quad \quad \quad \sqrt{x^2+y^2+z^2}=1$$
For simplicity, I took this vector from the $xy$ plane, that means that $z=0$. Then:
$$\frac{(1,0,0)\cdot(x,y,0)}{\sqrt{x^2+y^2}}=\frac{\pi}{6} \quad \quad \quad \quad \quad \quad \quad \quad \sqrt{x^2+y^2}=1$$
The solutions are:
$$\begin{array}{cc}
x_1: \frac{\pi }{6} & y_1: -\frac{1}{6} \sqrt{36-\pi ^2} \\
x_2: \frac{\pi }{6} & y_2: \frac{\sqrt{36-\pi ^2}}{6} \\
\end{array}$$
Now to get a vector that is perpendicular to $u,v$, I could use the cross product, but for these two vector, it's pretty easy to figure out I can use $w=(0,0,4)$.
Now to calculate $[u,v,w]$, I used the following determinants:
$$\
\begin{vmatrix}
0 & 0 & 4 \\
1 & 0 & 0 \\
\frac{\pi }{6} & -\frac{1}{6} \sqrt{36-\pi ^2} & 0 \\
\end{vmatrix}=-\frac{2}{3} \sqrt{36-\pi ^2} \quad \quad \quad \begin{vmatrix}
0 & 0 & 4 \\
1 & 0 & 0 \\
\frac{\pi }{6} & \frac{\sqrt{36-\pi ^2}}{6} & 0 \\
\end{vmatrix}=\frac{2 \sqrt{36-\pi ^2}}{3}$$
The problem is that the answer of the book is $2$. I assume it's not some sort of computation mistake because I did it entirely via Mathematica.
A:
The error is here:
$$
\frac{(1,0,0)\cdot(x,y,z)}{\sqrt{x^2+y^2+z^2}}=\frac{\pi}{6}
$$
which should be
$$
\frac{(1,0,0)\cdot(x,y,z)}{\sqrt{x^2+y^2+z^2}}=\color{red}\cos\frac{\pi}{6} = \frac 12 \sqrt 3 \, ,
$$
and one solution would be
$$
(x,y,z) = (\cos\frac{\pi}{6}, \sin\frac{\pi}{6}, 0)
$$
(But note that the given conditions still hold if $u$ or $v$ are multiplied
by any positive real number, so without any restriction on the norm
of $u$ and $v$ the solution is not unique.)
|
[
"stackoverflow",
"0038157632.txt"
] |
Q:
c# WinForm DataGridView bind List in List
I want to bind list (ProductList) to DataGridView, but one column is collection (Categories), but the DataGridView show "(Collection)" and not the content of List. I can't rewrite or change this ProductList class. How can i bind this Categories List column?
Here is the Binding:
dataGridView1.AutoGenerateColumns = false;
dataGridView1.ColumnCount = model.ColumnsNames.Length;
for (int i = 0; i < model.ColumnsNames.Length; i++)
{
string columnName = model.ColumnsNames[i];
dataGridView1.Columns[i].Name = columnName;
dataGridView1.Columns[i].DataPropertyName = columnName;
}
dataGridView1.DataSource = model.Products;
Here is ProductModel and the data source of grid is List<Product>:
public class Product
{
//...
/// <summary>
/// List of product categories names (string).
/// In write-mode need to pass a array of categories IDs (integer)
/// (uses wp_set_object_terms())
/// </summary>
public List<object> categories { get; set; }
// ...
}
I don't want to use sub-grid, i just want to show the property as a string in a TextBoxColumn something like this: CollectionElement1, CollectionElement2, etc.
It's not my class, actually just a reference. So I cant change it anywhere.
A:
You can use CellFormatting event of DataGridView to provide a friendly representation of categories property:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//Use zero based index of the cell that contains categories
var cell= 3;
if (e.ColumnIndex == cell && e.RowIndex >= 0)
{
var categories = (List<object>)dataGridView1.Rows[e.RowIndex].Cells[cell].Value;
e.Value = string.Join(", ", categories.Select(x => x.ToString()));
}
}
In this case, categories contains List of product categories names (string). So selecting ToString() is OK. But for a case of List<SomeClass>, you either should override ToString of SomeClass or select one of it's properties.
As another option you can shape the result of query using a new ViewModel or using anonymous type, but in the current situation which Product model doesn't belong to you and it has lot's of properties, previous solution is the most simple option.
|
[
"stackoverflow",
"0042780315.txt"
] |
Q:
Jquery,AJAX not posting data
I am facing problem while sendingsome arrays and data to a page but it is not getting posted i tried print_r($_POST); but its showing Array() as output and other data is also not being posted
The script is as follows:
<script type="text/javascript">
$(document).on('click', "#submitr", function(){
var favorite = [];
var tag = [];
var type = [];
var scheme = [];
$.each($("input[name='pcheck']:checked"), function(){
favorite.push($(this).val());
});
$.each($("input[name='tag[]']"), function(){
tag.push($(this).val());
});
$.each($("input[name='type[]']"), function(){
type.push($(this).val());
});
$.each($("input[name='scheme[]']"), function(){
scheme.push($(this).val());
});
var count=$("#count").val();
$.ajax({
type: "POST",
url: 'reportr.php',
data: {
count:count,
pcheck:favorite,
tag : tag ,
type : type,
scheme : scheme
},
success: function() {
window.location.href = "reportr.php"; }
});
});
</script>
On alert the values are being displayed
A:
Are you sure about that? Note that you are making 2 requests to reportr.php, first a POST request and when that is successful, a GET request - the redirect. You only show the results of the second requests and $_POST will be empty there.
To see the actual output of your POST request, you need to change the success function:
success: function(data) {
console.log(data);
// window.location.href = "reportr.php";
}
Now you will see the output of reportr.php in the browser's developer tools console.
|
[
"stackoverflow",
"0045423323.txt"
] |
Q:
How to merge variables from parallel flows in Activiti?
Currently I have a sub-process which uses fork/join mechanism to create parallel flows. Lest assume that there are two flows: A, B. Each of that flows takes as input variables complex object CONTEXT. Also each of that flows make some calculation and updates CONTEXT inside. As a output each of flows return updated CONTEXT. The problem here is that in Join point, last result of CONTEXT overrides previous one. Lets assume that flow A fill be finished first with result CONTEXT_1 and flow B will return CONTEXT_2. So final result will be CONTEXT_2 and all changes from flow A will be lost.
The question here is - how to merge results from two flows?
UPDATE:
From my observations passed variable (CONTEXT) from SuperProcess to SubProcess are copied(CONTEXT') and after subProcess is finished, new value of passed variable(CONTEXT') will take place of original (CONTEXT).
In the example below I mean that all passed variables have the same name.
Example:
SuperProcess P1 (Variable: CONTEXT) calls SubProcess P2(variables are passed by copy);
SubProcess P2 (Variable: CONTEXT') creates two parallel flows(Tasks) A, B(variables are passed by copy);
A Task (Variable: CONTEXT_1) updates value of variable, finishes execution and returns variable;
3.1. CONTEXT_1 takes place of variable CONTEXT' so P2 can see only this new value as names of this variables the same;
Meanwhile B Task (Variable: CONTEXT_2) is still working and after some time updates variable, finishes execution and returns variable;
4.1. CONTEXT_2 takes place of variable CONTEXT_1 so P2 can see only this new value as names of this variables the same;
SubProcess P2 (Variable: CONTEXT_2) finish the execution and returns new veriable to SuperProcess.
Result -> CONTEXT_1 is lossed.
My aim scenario:
SuperProcess P1 (Variable: CONTEXT) calls SubProcess P2(variables are passed by copy);
SubProcess P2 (Variable: CONTEXT') creates two parallel flows(Tasks) A, B(variables are passed by copy);
A Task (Variable: CONTEXT_1) updates value of variable, finishes execution and returns variable;
3.1. CONTEXT_1 and CONTEXT are merged into CONTEXT_M1, in other words, only new changes of CONTEXT_1 will be applied to CONTEXT.
Meanwhile B Task (Variable: CONTEXT_2) is still working and after some time updates variable, finishes execution and returns variable;
4.1. CONTEXT_2 and CONTEXT_M1 are merged into CONTEXT_M2, in other words, only new changes of CONTEXT_2 will be applied to CONTEXT_M1 so previous update will be not lost;
SubProcess P2 (Variable: CONTEXT_M2) finish the execution and returns new veriable to SuperProcess.
Result -> CONTEXT_M2. All changes are saved.
A:
After couple days of investigation we figured out that copying variables from SuperProcess to SubProcess is default behavior (link):
"You can pass process variables to the sub process and vice versa. The
data is copied into the subprocess when it is started and copied back
into the main process when it ends."
As the decision we pass variables into SubProcess under different name and merge with source variable after SubProcess finish:
|
[
"stackoverflow",
"0033454834.txt"
] |
Q:
Uncaught Reference Error: $ is not defined get method
function s()
{
alert("hello");
$email = document.getElementById("inp_subscribe").value;
alert($email);
$.get("subscribe.php",{inp_subscribe: $email },"");
alert($email);
}
Please help me to learn how to get this $.get() function to work.
A:
Try this code...
function s() {
alert("hello");
var $email = document.getElementById("inp_subscribe").value;
alert($email);
$.get("subscribe.php",{inp_subscribe: $email },"");
alert($email);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="inp_subscribe">Email:</label>
<input name="inp_subscribe" id="inp_subscribe" type="email"/>
<button onclick="s();">Submit</button>
|
[
"stackoverflow",
"0009334097.txt"
] |
Q:
How to create a cross-compilation sysroot for Linux?
I'm trying to build a GCC cross-compiler with --host=x86_64-apple-darwin10 and --target=ppc64-linux.
I need to have a sysroot for my target. What I have available to me is an .iso that's designed to boot and setup that target. On it are a giant pile of rpms.
I'd like to know the Linux guru incantations that will unpack the proper rpms into an empty directory on OS X successfully and make that sysroot.
A:
You should be able to build rpm2cpio on OSX, and then unpack thus:
mkdir /desired/sysroot && cd /desired/sysroot
for j in /path/to/iso/*.rpm; do
rpm2cpio $j | cpio -idmB
done
But it might be easier to just unpack on a Linux host (perhaps inside a VM).
|
[
"stackoverflow",
"0053344202.txt"
] |
Q:
Individual binding for unpacked array elements in SystemVerilog
In synthesizable SystemC I can bind each element of vector of ports individually:
SC_MODULE(submodule)
{
sc_vector<sc_in<int> > SC_NAMED(in_vec, 3);
};
SC_MODULE(top) {
submodule SC_NAMED(submod_inst);
sc_signal<int> SC_NAMED(a);
sc_signal<int> SC_NAMED(b);
sc_signal<int> SC_NAMED(c);
SC_CTOR(top) {
submod_inst.in_vec[0].bind(a);
submod_inst.in_vec[1].bind(b);
submod_inst.in_vec[2].bind(c);
}
};
Is there a way to do the same in synthesizable SystemVerilog?
module submodule (
input logic[31:0] in_vec[3];
);
endmodule
module top ();
logic [31:0] a;
logic [31:0] b;
logic [31:0] c;
submodule submod_inst (
// What should I put here?
// .in_vec[0] (a), /// ERROR!!
// .in_vec[1] (b),
// .in_vec[2] (c)
);
endmodule
A:
Have you tried
.in_vec('{a, b, c})
Or you can create a array and assign individual value to it. Then bind the array signal to sub module.
|
[
"stackoverflow",
"0025777145.txt"
] |
Q:
Spring Config file to have different bean data populated based on input
I am new to Java spring framwork. I am using the spring framework do the the functional test. As a part of testing, I have file that need to pass to API and validate from the DB, that the file data is goes into DB. I have using spring to store the test file with associated data data. . My test has to call API with multiple files . How can from the spring file properties
DifferentValuesInBeanForFile1 ( see spring file ) = Some bean that has data associated with file 1.
DifferentValuesInBeanForFile2 = Some bean that has data associated with file 2.
So test can validate API correctly processed input file 1 by validatitng data
<bean id="TestHappyPathPostDeal1Hotel1Deal" class="com.abc.FunctionalTests">
<property name="InDate" value="12/20/2014 00:00:00" />
<property name="OutDate" value="12/24/2014 00:00:00" />
<property name="HotelDeals">
<util:map>
<entry InputFile="fileWithDeal123.avro" value="DifferentValuesInBeanForFile1" />
<entry InputFile="fileWithDeal999.avro" value="DifferentValuesInBeanForFile1" />
</util:map>
</property>
</bean>
A:
I'm not sure I understand your question properly. However if I do, then you need to look at using properties. You can add this at the top of your spring file:
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:///opt/somelocation/general.properties</value>
</list>
</property>
</bean>
Then you can reference stuff from in there inside your spring file:
<bean id="config" class="com.something.SomeClassConfiguration">
<property name="hosts" value="${main.hosts}" />
<property name="clusterName" value="${main.clusterName}" />
</bean>
Where your general.properties file contains something like:
main.hosts=127.0.0.1:9160
main.clusterName=test
If you then what to change that depending on your compile, you need to look at your build system. I use maven, and have profiles setup. Depending on what I'm doing I get maven to replace general.properties file with the correct file for the system I'm building.
Hope that helps.
|
[
"stackoverflow",
"0000343711.txt"
] |
Q:
Transferring files over SSH
I'm SSHing into a remote server on the command line, and trying to copy a directory onto my local machine with the scp command. However, the remote server returns this "usage" message:
[Stewart:console/ebooks/discostat] jmm% scp -p ./styles/
usage: scp [-1246BCEpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
[-l limit] [-o ssh_option] [-P port] [-S program]
[[user@]host1:]file1 [...] [[user@]host2:]file2
[Stewart:console/ebooks/discostat] jmm%
I'd like to be able to transfer files in both directions. From what I read, I thought the above command would work for downloading, and scp -p [localpath] [remotepath] for uploading?
A:
You need to scp something somewhere. You have scp ./styles/, so you're saying secure copy ./styles/, but not where to copy it to.
Generally, if you want to download, it will go:
# download: remote -> local
scp user@remote_host:remote_file local_file
where local_file might actually be a directory to put the file you're copying in. To upload, it's the opposite:
# upload: local -> remote
scp local_file user@remote_host:remote_file
If you want to copy a whole directory, you will need -r. Think of scp as like cp, except you can specify a file with user@remote_host:file as well as just local files.
Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.
A:
If copying to/from your desktop machine, use WinSCP, or if on Linux, Nautilus supports SCP via the Connect To Server option.
scp can only copy files to a machine running sshd, hence you need to run the client software on the remote machine from the one you are running scp on.
If copying on the command line, use:
# copy from local machine to remote machine
scp localfile user@host:/path/to/whereyouwant/thefile
or
# copy from remote machine to local machine
scp user@host:/path/to/remotefile localfile
A:
You need to specify both source and destination, and if you want to copy directories you should look at the -r option.
So to recursively copy /home/user/whatever from remote server to your current directory:
scp -pr user@remoteserver:whatever .
|
[
"superuser",
"0001491800.txt"
] |
Q:
Redirect from http to https not working
I installed certbot on my debian to install lets encrypt certificate to apache2.
Everything worked like a charm, and I selected the software option to redirect http traffic to https.
The software changed my apache2 conf file in this way:
<VirtualHost *:80>
ServerName myweburl.com
ServerAlias www.myweburl.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/myweburl/public
<Directory /var/www/html/myweburl>
Options FollowSymLinks MultiViews
Order Allow,Deny
Allow from all
AllowOverride All
ReWriteEngine On
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
/////////
// The software added these lines
/////////
RewriteCond %{SERVER_NAME} =myweburl.com [OR]
RewriteCond %{SERVER_NAME} =www.myweburl.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
These lines don't work.
If I visit myweburl.com it does not redirect.
If I visit https:// www.myweburl.com I can see the correct installed certificate.
A:
For current versions of Apache, there are potentially several ways to approach this:
Try using %{HTTP_HOST} rather than %{SERVER_NAME}
ex. Using %HTTP_HOST
<VirtualHost *:80>
ServerName myweburl.com
ServerAlias www.myweburl.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/myweburl/public
<Directory /var/www/html/myweburl>
Options FollowSymLinks MultiViews
Order Allow,Deny
Allow from all
AllowOverride All
RewriteEngine on
RewriteCond %{HTTP_HOST} myweburl.com [OR]
RewriteCond %{HTTP_HOST} www.myweburl.com
# RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [END,NE,R=permanent]
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Using Redirect. This requires that mod_alias be enabled.
ex. Using Redirect
<VirtualHost *:80>
ServerName myweburl.com
ServerAlias www.myweburl.com
ServerAdmin webmaster@localhost
# DocumentRoot /var/www/html/myweburl/public
Redirect permanent / https://myweburl.com/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Use alternative Rewrite rules. You can read more about mod_rewrite remapping here.
ex. Alternate mod_rewrite rules
<VirtualHost *:80>
ServerName myweburl.com
ServerAlias www.myweburl.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/myweburl/public
<Directory /var/www/html/myweburl>
Options FollowSymLinks MultiViews
Order Allow,Deny
Allow from all
AllowOverride All
RewriteEngine on
RewriteCond %{HTTPS} off
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=permanent]
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
|
[
"ru.stackoverflow",
"0001015930.txt"
] |
Q:
Не правильно работает слайдер на JQ
Есть вот такой код двух слайдеров
$('.button').click(function(){
var currentSlide = $('.item.current');
var currentSlideIndex = $('.item.current').index();
var nextSliderIndex = currentSlideIndex + 1;
var nextSlide = $('.item').eq(nextSliderIndex);
currentSlide.removeClass('current');
if(nextSliderIndex == ($('.item:last').index()+1)) {
$('.item').eq(0).addClass('current');
} else {
nextSlide.addClass('current');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.item {
padding: 10px;
background: royalblue;
margin: 10px;
font-weight: 900;
color: #fff;
display: none;
}
.item.current {
display: block;
}
.button {
background: #2d990d;
width: 140px;
padding:10px;
cursor: pointer;
text-align: center;
color: #fff;
}
</style>
<div class="slider">
<div class="button"> next slide 1</div>
<div class="item current">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
<div class="slider">
<div class="button"> next slide 2</div>
<div class="item current">11</div>
<div class="item">22</div>
<div class="item">33</div>
<div class="item">44</div>
<div class="item">55</div>
</div>
Не могу понять почему показывает слайд 1, 3 и 5. И как сделать чтоб второй слайдер тоже работал ?
A:
И не должен был работать. У вас же $('.item') собирает все такие элементы на странице, а должен собрать только в рамках текущего блока. Значит, код должен строиться на $(this).siblings(). В данном случае, $(this) указывает на элемент, который запустил функцию - кликнутая кнопка. А siblings() - все его соседние элементы.
$('.button').on('click', function() {
var currSlide = $(this).siblings('.current');
var items = $(this).siblings('.item');
var index = items.index(currSlide); // Индекс текущего среди всех item
currSlide.removeClass('current');
index = (index == items.length - 1) ? 0 : index + 1;
items.eq(index).addClass('current');
})
.item {
padding: 10px;
background: royalblue;
margin: 10px;
font-weight: 900;
color: #fff;
display: none;
}
.item.current {
display: block;
}
.button {
background: #2d990d;
width: 140px;
padding: 10px;
cursor: pointer;
text-align: center;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider">
<div class="button"> next slide 1</div>
<div class="item current">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
<div class="slider">
<div class="button"> next slide 2</div>
<div class="item current">11</div>
<div class="item">22</div>
<div class="item">33</div>
<div class="item">44</div>
<div class="item">55</div>
</div>
P.s. длинные и детальные названия переменных - не обязательны для трех строчек кода)
|
[
"stackoverflow",
"0020183519.txt"
] |
Q:
How do I pin the LiveCard using GDK?
I'm using the GDK and can't find in the documentation how to pin the LiveCard to the timeline. Can somebody help pls? Thanks.
A:
In the examples given in the GDK, the LiveCard.publish() method places the card to the left of the ok glass prompt. Is that what you mean? Isn't that the same as pinning? (making the card appear to the left of the clock).
|
[
"stackoverflow",
"0001621766.txt"
] |
Q:
Repository pattern in c#
How to implement repository pattern in C#.net 2.0?
Just show me the basic structure. Coz we don't have DataContext in .net 2.0.
A:
DataContext is not a repository pattern, it's the active record pattern.
Once you understand the difference between the two, you'll understand the response to your question.
Active Record is an object oriented view on of your data in the database.
A Repository is an object which live in your domain model, if you have one, this means that it's public interface is completely decoupled from your data access technology.
You use LINQ or SQL to query your database with the DataContext, and it makes sense since LINQ and SQL are very good to query data.
But when you query your Repository, since we talk more about Domain object than data, we use the Specification Pattern which is in reality a mini query language more suited to your domain.
In a nutshell, Active Record = Database and Data access, Repository = Domain model. Ideally, your customer must be able to understand the design of your Domain Model (so among other, your repository and specification classes), but he doesn't understand what a DataContext is, since it's the developer plumbing.
So to be clear, "An example of the repository pattern in C# 2.0", is not really what you should search for, "An example of the repository pattern" is, but the inner implementation will use classic ADO instead of DataContext.
|
[
"stackoverflow",
"0010508945.txt"
] |
Q:
How to turn Android text-to-Speech inside GPS LocationListener?
Is it possible to turn the text to speech feature on inside the LocatioListener class??
I'm trying to make an android application detect how far you have moved. I am able to turn on the GPS, and monitor for location movement. I would like to make it say "You have moved 300meters". It would be very convenient to put it inside the OnLocation method, but it complains when i try to instantiate the texttospeech??
This is what I was trying:
public class Location implements LocationListener {
static TextToSpeech talk;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//This yells at me on next line, won't let me use 'this' as context?? (Also tried Location.this)
talk = new TextToSpeech(this, new extToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
talk.setLanguage(Locale.UK);
Location aloc = new Location("aloc");
Location bloc = new Location("bloc");
aloc.setLatitude(alat);
aloc.setLongitude(alon);
bloc.setLatitude(blat);
bloc.setLongitude(blon);
float distance = aloc.distanceTo(bloc);
talk.speak("You Moved..", TextToSpeech.QUEUE_FLUSH, null);
}
});
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
A:
You will need a reference to a Context in order to initialise the TTS engine. Hence it will not work with this or Location.this, since both refer to the running instance of your Location class, which obviously is not a Context (or subclass of it).
That being said, there are multiple options.
If you use your Location class as anonymous innerclass or non-static innerclass in e.g. an Activity (or any other class where you can get a reference to a Context object), you can use a reference to the outer class to initialise the TTS engine.
In stead of trying to initialise the TTS engine directly inside the Location class, initialize it somewhere where you do have a Context reference; e.g. the same place where you request the LocationManager (for which you already need a Context reference).
Create a centralized instance of the TTS engine. You could set it up as singleton, but can also subclass Application and keep it around there. After it has been initialized, you can get and use it more or less anywhere you like.
|
[
"stackoverflow",
"0046287695.txt"
] |
Q:
Laravel: Check if Models have same relation
I have models: Partido and Coalicion related in a many to many relationship.
I need to know when two or more Coalicion has the same Partido related.
Hope I have explained myself.
Edit 1:
Model:
class Coalicion extends Model
{
public function partidos()
{
return $this->belongsToMany(Partido::class);
}
}
Let's say users selected some elements from a select input and I grabbed them in an array and send them to the controller.
...
public function example(Request $request)
{
$coaliciones = $request->coaliciones;
foreach ($coaliciones as $c) {
$coalicion = Coalicion::find($c);
# Here we have a list of Coalicion model in a loop
# Let's say the first iteration I can see the relationship
dump($c->partidos);
}
}
This for example give me the following answer at the browser:
Collection {#1 ▼
#items: array:2 [▼
0 => Partido {#271 ▶} #This is Partido with id 1
1 => Partido {#268 ▶}
]
}
Collection {#2 ▼
#items: array:3 [▼
0 => Partido {#279 ▶}
1 => Partido {#280 ▶}
2 => Partido {#283 ▶} #This is Partido with id 1
]
}
I need to know when the item 0 of the first Collection and the item 2 of the second Collection are the same.
A:
I kinda found a way but I don't know if it's the correct or best approach.
In Coalicion model I add the following function:
public function partidosId()
{
return $this->partidos->pluck('id');
}
With this I can get only the id's from the relations, then in the controller I created an empty array() and fill it with all my ids with a foreach loop, then, finishing up I evaluated if the id's in the now filled array are unique, if the unique values are less than the length of the array then some models have the same relation (I don't know which but It's a start), e.g.:
public function example(Request $request)
{
$coaliciones = $request->coaliciones;
$allItems = [];
foreach ($coaliciones as $c) {
$coalicion = Coalicion::find($c);
$allItems = array_merge($allItems, $coalicion->partidosId()->toArray());
}
if (count(array_unique($allItems))<count($allItems)) {
dd("Duplicates");
}else{
dd("Uniques");
}
}
If anyone find a better way or a way to know which are the ones with the duplicate relation please let me know
|
[
"stackoverflow",
"0023577515.txt"
] |
Q:
Spring login returns to error after successful login at server side
I am hosting my html pages at one server (wamp) and the login authentication and other APIs at another server (jetty). When I call the below code to login to the server it always goes to error even though it successfully authenticated at jetty server.
The same API is giving me a success with RestClient.
I inspected after adding a custom filter in Jetty server and I could see that the response code is 200OK.
function login() {
$.ajax({
url : "http://localhost:8080/testapp/j_spring_security_check",
type : "POST",
data : 'j_username=' + $('#userName').val() + '&j_password='
+ $('#loginPassword').val(),
success : function(data, textStatus, jqXHR) {
closeLoginModal();
alert("Login success");
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Login failed");
}
});
}
Any Help is appreciated.
A:
I added a filter in my login provider server web.xml and changed the header to accept request from all origin and it worked. I am not sure if this is the right way. But now login is success
response.setHeader("Access-Control-Allow-Origin", "*");
|
[
"stackoverflow",
"0015164721.txt"
] |
Q:
Android - How crop jpeg using view layout dimensions
Newbie user question:
I have searched and experimented for several days and need some help. I have probably read every SO posting on this topic but I still cannot figure it out.
I am trying to crop a specific area of a camera preview image. The issue is that the blue box is defined by a layout with top = 150 and left = 38, and height = 292 and width = 600. The image has height = 2448 and width = 3264.
Big box is the camera preview screen, small box is the portion I want to crop (apparently I don't yet have the ability to post pictures).
-----------------------------
| |
| |
| |
| --------- |
| | | |
| --------- |
| |
-----------------------------
How do I crop the image so I am only left with the portion in the box? I'll be displaying it on another activity so I am not worried about that part.
Just to complicate things, the box size and image size changes depending on the phone, and I need to work with API 8 (version 2.2, Froyo).
I would also prefer not to save the image to a file because then I would have to encrypt it (the picture would be an image of a check for deposit).
I am using Camera.takePicture() and the jpegCallback as in the following code snippet (initialBitmap would be the "big box" above, and rl would be the "small box"):
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
if ( data != null && data.length > 0 ) {
Bitmap initialBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
int bitmapHeight = initialBitmap.getHeight();
int bitmapWidth = initialBitmap.getWidth();
// get the "picture" frame
RelativeLayout rl = (RelativeLayout) findViewById( R.id.clear_layout );
int frameX = rl.getLeft();
int frameY = rl.getTop();
int frameHeight = rl.getHeight();
Hopefully there is a simple mathematical relationship between the view coordinates/dimensions and the bitmap.
I am also open to any better way to go about things but have tried to use the Preview data itself (too small) and manipulating the bitmap (out of memory errors).
Thanks in advance.
A:
In case anyone cares, I never found an answer to this question. I ended up solving the problem a different way. I used the full preview area and just making my "take picture" button transparent enough to not be in the way. I also never cropped but the image size is close to what it would have cropped to.
From all that I learned over the last year I don't think there is a relationship between the preview size and the resulting jpg file size. The relationship seems to be different for different phone cameras.
If anyone has found a relationship I'd still be happy to learn about it.
|
[
"stackoverflow",
"0022323330.txt"
] |
Q:
data$column returning null in a user-defined function
I'm new at R (and stackoverflow , too), so please forgive any possible stupidity!
I wrote a function
getvariance <-function(data, column)
that returns the variance of values in column in data
In the function I wrote
mydata = read.csv(data)
for i=1:datasize {
x=(mydata$column)[i]
//compute variance of x
}
When I call
getvariance("randomnumbers.csv", X1)
x is returned as a column of null values.
However, when I simply write
x=(mydata$X1[i])
it prints the full column with numerical values.
Can anyone help me understand why mydata$column[i] doesn't work when column's a parameter of a function?
Thanks in advance.
A:
You are trying to access data$column instead of data$X1.
data <- data.frame(X1=1:3)
data$X1
## [1] 1 2 3
data$column
## NULL
Instead try to actually access the column with the name X1 as follows:
fct <- function(data, column){
data[,column]
}
fct(data, "X1")
## [1] 1 2 3
|
[
"stackoverflow",
"0051683756.txt"
] |
Q:
React ag grid - event to find if user reached end of grid while scrolling
In ag-grid, we have 'bodySroll' event to listen scrolling.
But I want to know when user reaches last record of grid while scrolling.
Is there any way I can acheive this?
Thanks
A:
You can add onScroll listener for the Div which holds your ag-grid and then you can use gridApi.getLastDisplayedRow() this gives you last row index in the current viewport you can use this index to compare with your total number of records present on the current grid
if((gridApi.getLastDisplayRow()+1) == totalRecords). In order to update gridApi.getLastDisplayRow()+1 value you need to write it inside onScroll listener function.
|
[
"gaming.meta.stackexchange",
"0000001650.txt"
] |
Q:
Avoid tags that mean different things in different games
Well this is actually a continuation of a rant I had back in July, but the content here is a little different and more specific, so please disregard the previous thread :)
Many tags currently have different meaning in different games. I really think we should try and avoid using tags like these.
There are tons of them. For example (and I've only used tags with more than one appearance):
Profession names, such as shaman or scout or engineer etc. are used in gazillion games and can refer to completely different things in each one.
Likewise, names of buildings or places such as bunker or mines.
Other concepts that mean different things in different games like mutation or energy or trading.
So what's my rationale? I'm going to basically copy-paste from my previous post:
Some users assert that tags are helpful for searching, and I believe this is just not their intended purpose: tags are helpful for filtering (and for gathering statistics). There are some discussions about tagging in meta that seem to agree. I really liked one particular sentence:
Tags connect experts with questions they will be able to answer
In Stack Overflow, one can be an expert in Java or experienced with strings. But there's no way to be an expert on "priest" (since they appear in so many games) and I doubt anyone would consider herself an expert on "energy", let alone filter on it.
On the other hand, of course, it could be asked what's the big deal, what harm is there in a few excess tags? Well I confess it isn't a big deal, but it's a fact SO has over time increased its tag-creation threshold. The more tags there are the more noise and needless complexity we add, in my opinion.
A:
There's two different classes of these tags that we deal with. I believe we should pay heed to this, because I don't think it is remotely wise to avoid a tag just because its meaning varies between games. Take nothing of this to address fully game-specific tags where the tag represents something that's undeniably tied to a single game or franchise.
Semi-dependents, or good generics. A good example we have is achievements, and one that I'd like to become a similarly useful example would be weapons. You bring up the "Death of Meta tags" article. Semi-dependent tags will have different meanings when associated with different games, but will still have a mostly universal meaning to gamers when it is alone - even if it will never get a question that it is the only tag for. I use [strings] on Stack Overflow as an example all the time because it's the same principle. The implementation differs between languages, but the core essence of what it means will always be understood by the target audience - no one is going to confuse these for quartet musicians. I address a lot of this in a different Meta question. This is a little different, though, so you can disregard that thread and just bother with the following quote. ♪
The plague of duplicate questions that differ simply by choice of words is testament to this foul shortcoming of text search: you simply cannot find what isn't there. This same shortcoming applies to tags, but the thing here is that tags can represent the specific as well as the general. So you can ask a question about weapons without ever saying "weapons". In a multi-question theoretical example, suppose we got questions about the game Sora, one question about the Pilebunker, one about the Flamethrower, and one about the Bullet. They really don't need to share any words besides the name of the game and maybe "damage" in their question bodies, but the presence of a unifying tag lets me group these together in a way that they should since they're all about the same content: weapons. You can accomplish this categorization without needing to alter the word choice of the individual questions, because tags are independent of the author's expression of the problem.
Dependents, or bad generics. bunker is actually a pretty good example. In StarCraft and its successor, a Bunker is a building that Terran Infantry can utilize to stay safe from damage. In Resonance of Fate, a bunker is a wall that will block projectiles from a long range but can be fired through when adjacent to it. Though they share the term because of a matching dictionary definition, this knowledge will not help identify what the term means if you are unfamiliar with the game. This is because these don't exist as independent video game constructs, and fully depend on the context of the game to define it within the scope of what we care about.
A good acid test is to think of the tag and consequently how likely it is that you can pinpoint very closely what it'll be in any given applicable game whether you know it or not with its universal meaning. Or, if you can write a tag wiki description that isn't just "This means things so completely different between so many games", that helps.
scout would fail because Team Fortress 2, Disgaea, and StarCraft all have very divergent meanings that extend well past the universal meaning, just to name a few.
minimap would succeed as the difference in implementation between the oh-so-many games with minimaps doesn't change its universal meaning to gamers as a small and dynamic map of the current area.
We shouldn't even begin to describe how bad energy would fail.
There are many different implementations of quests in games, but they all surround a core concept that is well understood by gamers as some sort of objective that must be cleared for some manner of reward. Terribly vague when it's alone, but successful semi-dependent tags tend to be like that.
Using this, you can help sift out the junk dependents while keeping the useful semi-dependents. I'm still one of the advocates of actually using tags in searches (as highlighted in the Meta thread I told you disregard), but my advice here is actually geared towards the utility of tagging for categorization and filtering.
A:
I don't see a big problem with those tags, as the only use for them I can think of is searching within a game-tag. So if I'm searching for WoW rogues, I'll use world-of-warcraft and rogue.
I don't much like the fact that the tags have different meanings in different games, but I'm pretty sure noone uses those tags (on their own) for browsing or favorites anyway.
If we argue that the tags are not for assisting searches and that real tags would have to be useful for filtering/favoriting on their own, I think we would have to remove 90% of the non-game tags here. I don't think that makes much sense.
I'm only using the game tags, I could see a use for genre tags if we applied them consistently, but personally I find no use for any other tag. I think they might be more useful when we have a bigger volume of questions, but we really have to get some kind of order in our tags for that.
I think there is really not a substantial difference between game-specific tags like zerg, semi-general tags (same name but different implementations) like rogue and general tags like achievement or [talk:tips] in how they are used. I can't imagine a case where I would filter only on on of those tags, I would only use them to search within a game, not across multiple games.
For that reason I think it is perfectly acceptable that some tags have different meanings in different games. They might not be useful on their own, but nobody will use them like that anyway, and if you use them together with a game tag they are again useful.
But there is some need for cleanup in our tags for sure, but I don't think this is an important criteria for deciding about the usefulness of a tag.
|
[
"stackoverflow",
"0024912978.txt"
] |
Q:
Spawning a child window in JavaFX
I need to create a popup window for a desktop application. I am communications from a client to a server via TCP and I want the window to cover the main interface while waiting for a response from the server. Basically a "Please wait for response" kind of item.
I have been able to spawn a window and have it end when the response is of a validated nature, but I am unable to show any items on the stage itself.
Label lblSecondWindow = new Label("This is the second window");
lblSecondWindow.setAlignment(Pos.TOP_LEFT);
lblSecondWindow.autosize();
lblSecondWindow.setVisible(true);
StackPane secondLayout = new StackPane();
secondLayout.getChildren().add(lblSecondWindow);
Scene secondScene = new Scene(secondLayout, 300, 200);
Stage secondStage = new Stage();
secondStage.setTitle("Please Wait");
secondStage.setScene(secondScene);
secondStage.show();
A window appears, but the label is nowhere to be found. I am willing to attack this from another way if possible as I have lost more hair on this issue than I am willing to admit.
A:
The code you use doesn't contain the error. However I'm sure I know your error: You block the UI thread by making the server communication on the UI thread. You have to move it to a different thread to make it work.
I could reproduce your error with this code:
Label lblSecondWindow = new Label("This is the second window");
lblSecondWindow.setAlignment(Pos.TOP_LEFT);
lblSecondWindow.autosize();
lblSecondWindow.setVisible(true);
StackPane secondLayout = new StackPane();
secondLayout.getChildren().add(lblSecondWindow);
Scene secondScene = new Scene(secondLayout, 300, 200);
Stage secondStage = new Stage();
secondStage.setTitle("Please Wait");
secondStage.setScene(secondScene);
secondStage.show();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
} // Stands for expensive operation (the whole try catch)
secondStage.close();
but not if I comment out the try-catch block, that stands for your server communication, and secondStage.close();.
The code can be rewritten like this to make it work:
Label lblSecondWindow = new Label("This is the second window");
lblSecondWindow.setAlignment(Pos.TOP_LEFT);
lblSecondWindow.autosize();
lblSecondWindow.setVisible(true);
StackPane secondLayout = new StackPane();
secondLayout.getChildren().add(lblSecondWindow);
Scene secondScene = new Scene(secondLayout, 300, 200);
final Stage secondStage = new Stage();
secondStage.setTitle("Please Wait");
secondStage.setScene(secondScene);
secondStage.show();
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
} // Stands for expensive operation (the whole try catch)
Platform.runLater(new Runnable() {
@Override
public void run() {
// UI changes have to be done from the UI thread
secondStage.close();
}
});
}
}.start();
|
[
"stackoverflow",
"0046402818.txt"
] |
Q:
Verify if a user typed a word from a ReactiveList with Reactive Extension
I have a ReactiveList with keywords. The user can add or remove keyword from that list. The app needs to verify if the user typed one of the keywords.
There was already a similar post but it doesn't take in account a flexible list:
Using Reactive Extension for certain KeyPress sequences?
var keyElements = new ReactiveList<KeyElement>();
IObservable<IObservable<int>> rangeToMax = Observable.Merge(keyElements.ItemsAdded, keyElements.ItemsRemoved).Select(obs => Observable.Range(2, keyElements.Select(ke => ke.KeyTrigger.Length).Max()));
IObservable<IObservable<string>> detectedKeyTrigger = rangeToMax
.Select(n => _keyPressed.Buffer(n, 1))
.Merge().Where(m => keyElements.Where(ke => ke.KeyTrigger == m).Any());
//Here I want to end up with IObservable<string> instead of IObservable<IObservable<string>>
I can get rid of the outer IObservable by reassigning the detectedKeyTrigger each time an element in the reactive list changes, but then I lose all my subscriptions.
So, how can I end up with just an Observable of strings?
A:
First off, both Max and Any have overloads which takes a selector and a predicate respectively. This negates the need of the Select.
Next, I changed the Observable.Merge to use the Changed property of ReactiveList which is the Rx version of INotifyCollectionChanged. I also changed the Select to produce an IEnumerable of ints instead; it just felt more Right™.
var keyElements = new ReactiveList<KeyElement>();
IObservable<IEnumerable<int>> rangeToMax = keyElements.Changed
.Select(_ => Enumerable.Range(2, keyElements.Max(keyElement => keyElement.KeyTrigger.Length));
IObservable<IObservable<string>> detectedKeyTrigger = rangeToMax.
.Select(range => range
.Select(length => _keyPressed.Buffer(length, 1).Select(chars => new string(chars.ToArray()))) // 1
.Merge() // 2
.Where(m => keyElements.Any(ke => ke.KeyTrigger == m)) // 3
.Switch(); // 4
Create an IObservable<string> which emits the last n characters typed by the user. Create such an observable for each of the possible lengths of an combo
Merge the observables in the IEnumerable<IObservable<string>> into one Observable<string>
Only let strings which mach one of the KeyTriggers through
As rangeToMax.Select produces an IObservable<IObservable<string>> we use Switch to only subscribe to the most recent IObservable<string> the IObservable<IObservable<string>> produces.
|
[
"stackoverflow",
"0062484208.txt"
] |
Q:
Why using char type as index for looping gives unexpected results?
Bear in mind this is an old version of the C compiler: CP/M for Z80.
#include<stdio.h>
main()
{
char i = 0;
do
{
printf("0x%04x | ", i);
} while (++ i);
}
Expected:
0x0000 | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 | 0x0009 | 0x000A | 0x000B | 0x000C | 0x000D | 0x000E | 0x000F | 0x0010 | 0x0011 | 0x0012 | 0x0013 | 0x0014 | 0x0015 | 0x0016 | 0x0017 | 0x0018 | 0x0019 | 0x001A | 0x001B | 0x001C | 0x001D | 0x001E | 0x001F | 0x0020 | 0x0021 | 0x0022 | 0x0023 | 0x0024 | 0x0025 | 0x0026 | 0x0027 | 0x0028 | 0x0029 | 0x002A | 0x002B | 0x002C | 0x002D | 0x002E | 0x002F | 0x0030 | 0x0031 | 0x0032 | 0x0033 | 0x0034 | 0x0035 | 0x0036 | 0x0037 | 0x0038 | 0x0039 | 0x003A | 0x003B | 0x003C | 0x003D | 0x003E | 0x003F | 0x0040 | 0x0041 | 0x0042 | 0x0043 | 0x0044 | 0x0045 | 0x0046 | 0x0047 | 0x0048 | 0x0049 | 0x004A | 0x004B | 0x004C | 0x004D | 0x004E | 0x004F | 0x0050 | 0x0051 | 0x0052 | 0x0053 | 0x0054 | 0x0055 | 0x0056 | 0x0057 | 0x0058 | 0x0059 | 0x005A | 0x005B | 0x005C | 0x005D | 0x005E | 0x005F | 0x0060 | 0x0061 | 0x0062 | 0x0063 | 0x0064 | 0x0065 | 0x0066 | 0x0067 | 0x0068 | 0x0069 | 0x006A | 0x006B | 0x006C | 0x006D | 0x006E | 0x006F | 0x0070 | 0x0071 | 0x0072 | 0x0073 | 0x0074 | 0x0075 | 0x0076 | 0x0077 | 0x0078 | 0x0079 | 0x007A | 0x007B | 0x007C | 0x007D | 0x007E | 0x007F | 0x0080 | 0x0081 | 0x0082 | 0x0083 | 0x0084 | 0x0085 | 0x0086 | 0x0087 | 0x0088 | 0x0089 | 0x008A | 0x008B | 0x008C | 0x008D | 0x008E | 0x008F | 0x0090 | 0x0091 | 0x0092 | 0x0093 | 0x0094 | 0x0095 | 0x0096 | 0x0097 | 0x0098 | 0x0099 | 0x009A | 0x009B | 0x009C | 0x009D | 0x009E | 0x009F | 0x00A0 | 0x00A1 | 0x00A2 | 0x00A3 | 0x00A4 | 0x00A5 | 0x00A6 | 0x00A7 | 0x00A8 | 0x00A9 | 0x00AA | 0x00AB | 0x00AC | 0x00AD | 0x00AE | 0x00AF | 0x00B0 | 0x00B1 | 0x00B2 | 0x00B3 | 0x00B4 | 0x00B5 | 0x00B6 | 0x00B7 | 0x00B8 | 0x00B9 | 0x00BA | 0x00BB | 0x00BC | 0x00BD | 0x00BE | 0x00BF | 0x00C0 | 0x00C1 | 0x00C2 | 0x00C3 | 0x00C4 | 0x00C5 | 0x00C6 | 0x00C7 | 0x00C8 | 0x00C9 | 0x00CA | 0x00CB | 0x00CC | 0x00CD | 0x00CE | 0x00CF | 0x00D0 | 0x00D1 | 0x00D2 | 0x00D3 | 0x00D4 | 0x00D5 | 0x00D6 | 0x00D7 | 0x00D8 | 0x00D9 | 0x00DA | 0x00DB | 0x00DC | 0x00DD | 0x00DE | 0x00DF | 0x00E0 | 0x00E1 | 0x00E2 | 0x00E3 | 0x00E4 | 0x00E5 | 0x00E6 | 0x00E7 | 0x00E8 | 0x00E9 | 0x00EA | 0x00EB | 0x00EC | 0x00ED | 0x00EE | 0x00EF | 0x00F0 | 0x00F1 | 0x00F2 | 0x00F3 | 0x00F4 | 0x00F5 | 0x00F6 | 0x00F7 | 0x00F8 | 0x00F9 | 0x00FA | 0x00FB | 0x00FC | 0x00FD | 0x00FE | 0x00FF |
Actual:
0x0A00 | 0x0A01 | 0x0A02 | 0x0A03 | 0x0A04 | 0x0A05 | 0x0A06 | 0x0A07 | 0x0A08 | 0x0A09 | 0x0A0A | 0x0A0B | 0x0A0C | 0x0A0D | 0x0A0E | 0x0A0F | 0x0A10 | 0x0A11 | 0x0A12 | 0x0A13 | 0x0A14 | 0x0A15 | 0x0A16 | 0x0A17 | 0x0A18 | 0x0A19 | 0x0A1A | 0x0A1B | 0x0A1C | 0x0A1D | 0x0A1E | 0x0A1F | 0x0A20 | 0x0A21 | 0x0A22 | 0x0A23 | 0x0A24 | 0x0A25 | 0x0A26 | 0x0A27 | 0x0A28 | 0x0A29 | 0x0A2A | 0x0A2B | 0x0A2C | 0x0A2D | 0x0A2E | 0x0A2F | 0x0A30 | 0x0A31 | 0x0A32 | 0x0A33 | 0x0A34 | 0x0A35 | 0x0A36 | 0x0A37 | 0x0A38 | 0x0A39 | 0x0A3A | 0x0A3B | 0x0A3C | 0x0A3D | 0x0A3E | 0x0A3F | 0x0A40 | 0x0A41 | 0x0A42 | 0x0A43 | 0x0A44 | 0x0A45 | 0x0A46 | 0x0A47 | 0x0A48 | 0x0A49 | 0x0A4A | 0x0A4B | 0x0A4C | 0x0A4D | 0x0A4E | 0x0A4F | 0x0A50 | 0x0A51 | 0x0A52 | 0x0A53 | 0x0A54 | 0x0A55 | 0x0A56 | 0x0A57 | 0x0A58 | 0x0A59 | 0x0A5A | 0x0A5B | 0x0A5C | 0x0A5D | 0x0A5E | 0x0A5F | 0x0A60 | 0x0A61 | 0x0A62 | 0x0A63 | 0x0A64 | 0x0A65 | 0x0A66 | 0x0A67 | 0x0A68 | 0x0A69 | 0x0A6A | 0x0A6B | 0x0A6C | 0x0A6D | 0x0A6E | 0x0A6F | 0x0A70 | 0x0A71 | 0x0A72 | 0x0A73 | 0x0A74 | 0x0A75 | 0x0A76 | 0x0A77 | 0x0A78 | 0x0A79 | 0x0A7A | 0x0A7B | 0x0A7C | 0x0A7D | 0x0A7E | 0x0A7F | 0x0A80 | 0x0A81 | 0x0A82 | 0x0A83 | 0x0A84 | 0x0A85 | 0x0A86 | 0x0A87 | 0x0A88 | 0x0A89 | 0x0A8A | 0x0A8B | 0x0A8C | 0x0A8D | 0x0A8E | 0x0A8F | 0x0A90 | 0x0A91 | 0x0A92 | 0x0A93 | 0x0A94 | 0x0A95 | 0x0A96 | 0x0A97 | 0x0A98 | 0x0A99 | 0x0A9A | 0x0A9B | 0x0A9C | 0x0A9D | 0x0A9E | 0x0A9F | 0x0AA0 | 0x0AA1 | 0x0AA2 | 0x0AA3 | 0x0AA4 | 0x0AA5 | 0x0AA6 | 0x0AA7 | 0x0AA8 | 0x0AA9 | 0x0AAA | 0x0AAB | 0x0AAC | 0x0AAD | 0x0AAE | 0x0AAF | 0x0AB0 | 0x0AB1 | 0x0AB2 | 0x0AB3 | 0x0AB4 | 0x0AB5 | 0x0AB6 | 0x0AB7 | 0x0AB8 | 0x0AB9 | 0x0ABA | 0x0ABB | 0x0ABC | 0x0ABD | 0x0ABE | 0x0ABF | 0x0AC0 | 0x0AC1 | 0x0AC2 | 0x0AC3 | 0x0AC4 | 0x0AC5 | 0x0AC6 | 0x0AC7 | 0x0AC8 | 0x0AC9 | 0x0ACA | 0x0ACB | 0x0ACC | 0x0ACD | 0x0ACE | 0x0ACF | 0x0AD0 | 0x0AD1 | 0x0AD2 | 0x0AD3 | 0x0AD4 | 0x0AD5 | 0x0AD6 | 0x0AD7 | 0x0AD8 | 0x0AD9 | 0x0ADA | 0x0ADB | 0x0ADC | 0x0ADD | 0x0ADE | 0x0ADF | 0x0AE0 | 0x0AE1 | 0x0AE2 | 0x0AE3 | 0x0AE4 | 0x0AE5 | 0x0AE6 | 0x0AE7 | 0x0AE8 | 0x0AE9 | 0x0AEA | 0x0AEB | 0x0AEC | 0x0AED | 0x0AEE | 0x0AEF | 0x0AF0 | 0x0AF1 | 0x0AF2 | 0x0AF3 | 0x0AF4 | 0x0AF5 | 0x0AF6 | 0x0AF7 | 0x0AF8 | 0x0AF9 | 0x0AFA | 0x0AFB | 0x0AFC | 0x0AFD | 0x0AFE | 0x0AFF |
What am I doing wrong?
Assembly:
cseg
?59999:
defb 48,120,37,48,52,120,32,124,32,0
main@:
ld c,0
@0:
push bc
push bc
ld bc,?59999
push bc
ld hl,2
call printf
pop bc
pop bc
pop bc
inc c
jp nz,@0
ret
public main@
extrn printf
end
A:
Golly. LONG time since I used a z80 C compiler, and most were buggy as [unprintable] back then.
I would suggest that you dump the assembler if the compiler allows. My GUESS is that internally the char is being promoted to a 16 bit INT with indeterminate upper bits set.
The problem is that %04X expects an integer - not a char.
You might try forcing the compiler to play nice by explicitly casting the char to an int - i.e.
printf("0x%04x | ", (int) i);
|
[
"stackoverflow",
"0012895922.txt"
] |
Q:
No symbols/source for external library in Xcode 4
My application is not seeing source code for a library:
If I "Jump to definition" on a library method, XCode takes me to the .h file but says there is no .cpp counterpart
When debugging, I see no source code and most of the call-stack is missing for the library:
I have made sure "Show disassembly when debugging" is UNchecked
I built the library as DEBUG and then packaged up the headers+.a file into a SDK dir. So I guess I need to either copy the debug files into that SDK dir as well, or tell my application where to look. I'm not sure how to do either.
To clarify, my application project doesn't maintain a reference to the library project, only to the .a files and the header dirs. This is because the library project is created by CMake and I don't want to modify it.
A:
First of all, you should check the .debug_str section of your static library to verify it contains the appropriate debug information.
Try running this command on the terminal:
xcrun dwarfdump /path/to/library.a | grep "\.m"
You should see a bunch of your source (.m) file paths printed out. Theoretically, this is where Xcode is going to look when you stop in the debugger, so make sure the paths here are correct. If you don't see any paths, you will need to pass an appropriate debug flag (e.g. -g to the compiler when building your library.
If the paths are somehow incorrect, or you want to point them to some other location, you may be able to modify them as part of the build process in CMake, for example to make them relative to your project directory. Try looking at "Make gcc put relative filenames in debug information", which uses CMake to adjust these debug paths.
|
[
"music.stackexchange",
"0000006344.txt"
] |
Q:
Removing human voice from songs
I have been trying so much to do this but to no avail. Some softwares like cooledit remove it to an extent but ruin other things in the music. Please suggest some good method for this.
A:
As a friend of mine once explained, "It's like paint. If you mix together several colors of paint, you can't un-mix it and get the original separate colors of paint back."
Vocal removal software, as mentioned in other answers here, is only of limited usefulness due to laws of physics that cannot be circumvented. All such products use the principle of applying phase cancellation to a 2-channel stereo recording.
It is only possible to totally remove the lead vocal from a mixed recording using vocal removal software if the original recording is mixed under a precise combination of conditions: if the recording is 2-channel stereo, mixed with a wide stereo field, but the lead vocal is positioned exactly in the center, and there is no reverberation or echo applied to the lead vocal. Furthermore the process will always also remove any other instruments or musical elements that are also positioned in the exact center of the stereo field (where the bass instrument is usually positioned) so it is usually the case that removing the lead vocal also removes most of the bass instrument, the kick drum, and a great deal of bass frequencies at any point in the recording where the vocal removal effect is applied.
If the recording from which you wish to remove the lead vocal was not mixed according to these exact conditions, then you will encounter only a partial reduction in the volume of the lead vocal. If the lead vocal was processed with a stereo reverb effect, you might be able to remove the lead vocal but you will still hear the stereo reflections (echoes) of the lead vocal through the reverb effect. Regardless, you will probably notice undesirable artifacts and changes in the frequency spectrum.
Furthermore, the process of vocal removal won't work at all with mono recordings or, to the best of my knowledge, 5.1 or other configurations of multi-channel surround sound.
A:
I basically asked this question on the Audio site: How can I cut out a particular instrument in the same pitch range as other instruments I don't want to cut?
As you can see there, the answer is no. There's no good way for software to tell what is voice and what is not for any arbitrary voice and song combined into a single waveform. As you note it can be done to an extent with varying effects on the song, but there is nothing that can do it very well yet.
A:
The future is here. You can use a neuronal network called "spleeter" to separate voice and the arrangement of any song you like.
It is open source and can be freely downloaded from its official git repository:
https://github.com/deezer/spleeter
I used it a lot and totally love it. The separation isn't 100% clean but it is still very good for hobby usage. For example for singing to original arrangement.
Maybe it is not that easy to install and run the programm for not programmers, since Spleeter do not have any graphical interface. But it is possible! Just follow the instructions on the git page and google or whatch youtube videos to clarify the single installation steps.
Have fun with it!
|
[
"stackoverflow",
"0058674376.txt"
] |
Q:
How does `() -> delegate` wrap a Stream?
Not sure how to write the question, but I saw the following construct in https://stackoverflow.com/a/45971597/242042
public interface MyStream<T> {
Stream<T> stream();
static <T> MyStream<T> of(Stream<T> stream) {
return () -> stream;
}
}
Which I used in my answer https://softwareengineering.stackexchange.com/a/400492/42195
The of method returns a Callable that returns the delegate stream. But how did that even translate to <T> MyStream <T> ?
A:
It might be easier to understand if you separate the code a little more:
public interface MyStream<T> {
Stream<T> stream();
}
class Util {
static <T> MyStream<T> of(Stream<T> stream) {
return () -> stream;
}
}
It is still doing the same thing, but it is a little easier to follow.
Then in a second step, let's write this without a lamda expression in the "classic" way:
public interface MyStream<T> {
Stream<T> stream();
}
class Util {
static <T> MyStream<T> of(Stream<T> stream) {
return new MyStream<>() {
Stream<T> stream() {
return stream;
}
};
}
}
What you are doing here is create an anonymous class, that implements the interaface MyStream. It has a method stream which returns the stream you passed as method argument.
Now with Java 8 there is this fancy new format to write things. This is possible if the interface has only a single method. In this case the new Stream is not necessary, because the compiler knows the type from the return type of your method. Also the Stream<T> stream() definition is not necessary, because the compiler knows it from the interface definition. And in case of a single statement, you can even omit the return, because the compile will assume the result of the single statement to be the return-value.
Thus this:
return new MyStream<>() {
Stream<T> stream() {
return stream;
}
};
can be written as:
() -> stream;
// ^^^^^^^ Return value
//^^ Argument list (in this case empty)
|
[
"stackoverflow",
"0012682249.txt"
] |
Q:
simple html dom and parsing table
I have to parse 2 kind of table
one is this
http://leghe.fantagazzetta.com/f12-13/ ("Classifica Generale")
and the other two table are here
http://leghe.fantagazzetta.com/f12-13/formazioni?id=30339&g=4
how can i extract this data to an array?
for the first table i wrote this code but I really don't know what I'm doing
<?php
require('simple_html_dom.php');
$html = new simple_html_dom();
$html->load_file('http://leghe.fantagazzetta.com/f12-13/classifica');
$tabClassifica = $html->find('table#classifica tr');
foreach($tabClassifica as $n) {
$team=$n->find('td',0)->outertext;
$arrayTeams[] = array('teamname' => $team);
}
?>
<pre>
<? print_r($arrayTeams); ?>
</pre>
I've to get this Array structure
[1] => Array
(
[TeamName] => A.C. Tua
[Pt.] => 9
[G] => 4
[V] => 3
[N] => 0
[P] => 1
[G+] => 8
[G-] => 5
[Somma Punti] => 293,50
)
[2] => Array
(
[TeamName] => Ehi Team
[Pt.] => 7
[G] => 4
[V] => 2
[N] => 1
[P] => 1
[G+] => 5
[G-] => 5
[Somma Punti] => 279,50
)
[3] => Array
(
[TeamName] => Brontolo
Could someone guide me?
A:
You can use PHPQuery to achieve what you want.
Here is an example code:
include('phpQuery-onefile.php');
$content = file_get_contents('http://leghe.fantagazzetta.com/f12-13/');
$html = phpQuery::newDocumentHTML($content);
$table = $html->find('#classifica tbody');
$general_ranking = array();
$i=0;
foreach($table->children('tr') as $tr){
/**
* @var DOMElement $tr
*/
$getTd = $tr->getElementsByTagName('td');
foreach($getTd as $td){
/**
* @var DOMElement $td
*/
$general_ranking['tr_'.$i][] = trim($td->textContent);
}
++$i;
}
This should display something similar to:
array (size=6)
'tr_0' =>
array (size=7)
0 => string 'A.C. Tua' (length=8)
1 => string '9' (length=1)
2 => string '4' (length=1)
3 => string '3' (length=1)
4 => string '0' (length=1)
5 => string '1' (length=1)
6 => string '293,50' (length=6)
'tr_1' =>
array (size=7)
0 => string 'Ehi Team' (length=8)
1 => string '7' (length=1)
2 => string '4' (length=1)
3 => string '2' (length=1)
4 => string '1' (length=1)
5 => string '1' (length=1)
6 => string '279,50' (length=6)
'tr_2' =>
array (size=7)
0 => string 'Brontolo' (length=8)
1 => string '7' (length=1)
2 => string '4' (length=1)
3 => string '2' (length=1)
4 => string '1' (length=1)
5 => string '1' (length=1)
6 => string '274,50' (length=6)
'tr_3' =>
array (size=7)
0 => string 'milanelcuore' (length=12)
1 => string '6' (length=1)
2 => string '4' (length=1)
3 => string '2' (length=1)
4 => string '0' (length=1)
5 => string '2' (length=1)
6 => string '281,00' (length=6)
'tr_4' =>
array (size=7)
0 => string 'LONGOBARDA' (length=10)
1 => string '5' (length=1)
2 => string '4' (length=1)
3 => string '1' (length=1)
4 => string '2' (length=1)
5 => string '1' (length=1)
6 => string '254,50' (length=6)
'tr_5' =>
array (size=7)
0 => string 'i puffi' (length=7)
1 => string '0' (length=1)
2 => string '4' (length=1)
3 => string '0' (length=1)
4 => string '0' (length=1)
5 => string '4' (length=1)
6 => string '258,00' (length=6)
Edit:
After answering I got interested in simple_html_dom so I decided to try it out.
The coding style is a little bit easier than PHPQuery but it's not that stable I think.
Anyway, here is the code you need to get it working:
include('simple_html_dom/simple_html_dom.php');
$html = new simple_html_dom();
$html->load_file('http://leghe.fantagazzetta.com/f12-13/classifica');
$tabClassifica = $html->find('table#classifica tr');
foreach($tabClassifica as $n) {
/**
* @var simple_html_dom_node $n;
*/
$tds = $n->find('td');
// Don't allow empty records.
$team = trim(strip_tags($tds[0]->innertext));
if($team == "" || $team == " ") continue;
$arrayTeams[] = array(
'TeamName' => $team,
'Pt.' => trim(strip_tags($tds[1]->innertext)),
'G' => trim(strip_tags($tds[2]->innertext)),
'V' => trim(strip_tags($tds[3]->innertext)),
'N' => trim(strip_tags($tds[4]->innertext)),
'P' => trim(strip_tags($tds[5]->innertext)),
'G+' => trim(strip_tags($tds[6]->innertext)),
'G-' => trim(strip_tags($tds[7]->innertext)),
'Somma Punti' => trim(strip_tags($tds[8]->innertext)),
);
}
|
[
"superuser",
"0000444984.txt"
] |
Q:
Excel hyperlink not redirecting properly (bug?)
I have an Excel hyperlink problem: I click on, let's say A1, copy the link in it (http://www.godaddy.com/domains/searchresults.aspx?ci=54814), right click on hyperlink and copy that SAME URL as the link (if it is not automatically detected and changed).
When I go to click on it, I am redirected to http://www.godaddy.com/domains/search.aspx?ci=53972.
If I copy and paste the link directly into the browser, it works fine (i.e., I am not redirected to a different URL).
Does anyone know what's going on?
A:
The URL you're using needs some more information from a cookie to display the search results rather than the search page. Paste the URL into a different browser (or remove your cookies) and you'll get the same results.
Clicking a URL in Excel seems to open it in your default browser. But that's not really true. Before opening it in your browser, Excel first runs Microsoft Office Protocol Discovery. This uses a Windows/Internet Explorer component to determine if the URL works. (It does not identify itself as Internet Explorer, but as "User Agent: Microsoft Office Existence Discovery".) And if the results are (somehow) okay then it will open the result of that check in your default browser.
Lacking the cookies (more precisely: lacking a session), GoDaddy gives that Internet Explorer component some redirect. And the result of that is opened in your default browser. That's the URL you're seeing.
Most likely your default browser is not Internet Explorer? Then pasting the URL into IE directly and clicking it, to get the cookies, might then also make the link work from Excel. (Just for testing; it's not a permanent solution.)
You will have more luck using a URL that does not rely on some hidden information from a cookie, like http://www.godaddy.com/domains/search.aspx?domainToCheck=superuser.com
A:
This is Excel fault. If you paste the link in Outlook email or WordPad and you open the link from there it will work correctly.
Excel should never create hidden session to verify the hyperlink. what's the point of it. It just needs to open it, nothing else. They use the same logic in MS Word. It doesn't work from there neither.
When Excel tries to verify the link in the background, new session is created that is not authenticated so it gets redirected to login page or something. After that instead of opening the original URL in the browser, Excel is opening the redirection url. They really know how to make simple thing complicated.
A:
This is a known Microsoft bug where hyperlinks are redirected to another page if:
You are using Microsoft Internet Explorer:
with a proxy server
while using a firewall that does not allow HTTP requests on your local network
Internet Explorer is not your default browser.
The ForceShellExecute registry key is not present or is not set to 1
You can apply the fix from here:
http://support.microsoft.com/kb/218153
|
[
"gis.meta.stackexchange",
"0000003585.txt"
] |
Q:
What happens to questions with no answer where person asking told the question is not relevant anymore?
This is my first post in meta. Check this question: https://gis.stackexchange.com/questions/91820/sharing-application-built-by-flex
A person asking is not expecting any answer any longer and has briefly described "the answer" in a comment. What shall we do/what happens to this question?
I've read that there are roughly 2K questions with no accepted answers and it is a pity if those are like this one.
A:
Some options I can think of to reduce such situations:
On good/common questions:
The first thing you may try is to leave a comment to the OP encouraging him or her to answer their own question as best as it can be.
If none reply is given, you can go ahead an post an answer based on what is written in the comments and additional info.
On off-topic/poor threads:
If the question is not relevant or not so good in quality, choose one option to flag it and put on hold.
If the question does not fit in close reasons but still has poor content, just downvote it. If it gets more than 3 downvotes it will go away.
|
[
"stackoverflow",
"0031188981.txt"
] |
Q:
Array.prototype.reduce vs a simple for loop for filtering and modifying data
"Reducing Filter and Map Down to Reduce" by Elijah Manor outlines the following use case for Array.prototype.reduce():
Given the following data (from the linked article):
var doctors = [
{ number: 1, actor: "William Hartnell", begin: 1963, end: 1966 },
{ number: 2, actor: "Patrick Troughton", begin: 1966, end: 1969 },
{ number: 3, actor: "Jon Pertwee", begin: 1970, end: 1974 },
{ number: 4, actor: "Tom Baker", begin: 1974, end: 1981 },
{ number: 5, actor: "Peter Davison", begin: 1982, end: 1984 },
{ number: 6, actor: "Colin Baker", begin: 1984, end: 1986 },
{ number: 7, actor: "Sylvester McCoy", begin: 1987, end: 1989 },
{ number: 8, actor: "Paul McGann", begin: 1996, end: 1996 },
{ number: 9, actor: "Christopher Eccleston", begin: 2005, end: 2005 },
{ number: 10, actor: "David Tennant", begin: 2005, end: 2010 },
{ number: 11, actor: "Matt Smith", begin: 2010, end: 2013 },
{ number: 12, actor: "Peter Capaldi", begin: 2013, end: 2013 }
];
We can both modify and filter the data at the same time using .reduce() as shown below (also from the linked article):
doctors = doctors.reduce(function(memo, doctor) {
if (doctor.begin > 2000) { // this serves as our `filter`
memo.push({ // this serves as our `map`
doctorNumber: "#" + doctor.number,
playedBy: doctor.actor,
yearsPlayed: doctor.end - doctor.begin + 1
});
}
return memo;
}, []);
However, why would one prefer this over a simple for loop? I doubt it out-performs a simple iterating loop with similar contents (though I can't test that claim since Jsperf is down).
Is there any reason (performance or otherwise) to use the .reduce() implementation over a simple loop, other than syntax preference?
A:
One objective benefit of array operations like map or reduce is the inherent variable scoping and reduction of boilerplate code. Compare:
var result = 0;
for (var i = 0, length = arr.length; i < length; i++) {
result += arr[i];
}
// vs:
var result = arr.reduce(function (acc, val) { return acc + val; }, 0);
The giant loop declaration has nothing inherently to do with what you're trying to do here, it's just boilerplate code. Further, your scope now has two additional variables i and length floating around which nobody asked for, which may or may not introduce some non-obvious bugs if you're not careful.
The reduce code on the other hand just contains the minimum necessary parts to do what it needs to do. In something like CoffeeScript its syntax can even further be reduced to arr.reduce (acc, val) -> acc + val, which is pretty darn concise. And even if you'd need to create additional variables during the operation inside the loop/the callback, those won't clutter the outer scope.
Secondarily, reduce is a well known paradigm and serves as a good statement of intend for that code block. You don't need to parse useless auxiliary variables and figure out what they're for, you can simply break down the operation into what array is being operated on (arr) and what result the callback expression (acc + val) will produce, then extrapolate that over the entire array to know what the result will be.
Potentially such operations can also be better optimised by a compiler under certain circumstances, but this is mostly not seen in practice at this time I believe.
|
[
"tex.stackexchange",
"0000536974.txt"
] |
Q:
Property reusability
I'm trying to create a command that will allow me to create multiple item for a game. My main problem comes from re-usability of that command. The fact that I have more than 9 arguments for some of them makes me go to key_define. I also looked at property but I have hard time finding usable documentation on how to use it adequately, so I stayed to key-values instead.
Globally, what my code do is creating a lot of shortcuts to be able to put in my document later on. Let's say that I create these two characters:
\createCharacter{Barry}<main>[lastname=Allen, prof=scientist]{39}
and
\createCharacter*{Jessy}<side>[lastname=Quick, nickname=Jess, prof=professional runner]{24}
When I call \mainFName I get "Barry" and \sideFName I get "Jessy", as intended, but when I call \sideLName I get "Quick" and \mainLName I get "Quick" as well. So what is happening is that instead of taking the value at the moment of the creation, it reevaluated it's "current value" (which is the last character created).
So here is the code I want to correct and make working without having to create all the tl_new for each character, and eventually every item, magic, and whatever else may come handy. If I was able to do withing my \createCharacter something like \tl_new:c {\l_#4_firstname_tl} It would be perfect.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CHARACTER MAKER
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\ExplSyntaxOn
% Define Special
\tl_new:N \l_character_firstname_tl
\tl_new:N \l_character_lastname_tl
\tl_new:N \l_character_title_tl
\tl_new:N \l_character_profession_tl
\tl_new:N \l_character_noblesse_tl
\tl_new:N \l_character_class_tl
\tl_new:N \l_character_nick_tl
\int_new:N \l_character_age_int
\keys_define:nn { Character/Identity } {
% firsname .tl_set:N = \l_character_firstname_tl,
lastname .tl_set:N = \l_character_lastname_tl,
title .tl_set:N = \l_character_title_tl,
prof .tl_set:N = \l_character_profession_tl,
noble .tl_set:N = \l_character_noblesse_tl,
class .tl_set:N = \l_character_class_tl,
race .tl_set:N = \l_character_race_tl,
nickname .tl_set:N = \l_character_nick_tl,
% age .int_set:N = \l_character_age_int
% , unknown .code:n = {}
}
\NewDocumentCommand{\createCharacter}{s t- m D<>{#3} o m}{
\IfValueT{#5}{\keys_set:nn{Character/Identity}{#5}}
\exp_args:Nc \NewDocumentCommand { #4 FName } {}{ #3 }
\exp_args:Nc \NewDocumentCommand { #4 LName } {}{ \l_character_lastname_tl }
\exp_args:Nc \NewDocumentCommand { #4 Polite } {}{ \use:c { #4 Title } ~ \use:c { #4 LName } }
\exp_args:Nc \NewDocumentCommand { #4 Sign } {}{ \use:c { #4 FPolite } , ~ \l_character_noblesse_tl }
\exp_args:Nc \NewDocumentCommand { #4 Age } {}{ #6 }
\exp_args:Nc \NewDocumentCommand { #4 Prof } {}{ \l_character_profession_tl }
\exp_args:Nc \NewDocumentCommand { #4 Class } {}{ \l_character_class_tl }
\exp_args:Nc \NewDocumentCommand { #4 Race } {}{ \l_character_race_tl }
\exp_args:Nc \NewDocumentCommand { #4 NName } {}{ \l_character_nick_tl }
%% more code here but irrelevent for the question %%
}
\ExplSyntaxOff
A:
I wouldn't use \NewDocumentCommand for those macros. The problem is that you're storing the variables, rather than their values.
\documentclass{article}
\usepackage{xparse}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CHARACTER MAKER
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\ExplSyntaxOn
% Define Special
\tl_new:N \l_character_firstname_tl
\tl_new:N \l_character_lastname_tl
\tl_new:N \l_character_title_tl
\tl_new:N \l_character_profession_tl
\tl_new:N \l_character_noblesse_tl
\tl_new:N \l_character_class_tl
\tl_new:N \l_character_nick_tl
\int_new:N \l_character_age_int
\keys_define:nn { Character/Identity } {
% firstname .tl_set:N = \l_character_firstname_tl,
lastname .tl_set:N = \l_character_lastname_tl,
title .tl_set:N = \l_character_title_tl,
prof .tl_set:N = \l_character_profession_tl,
noble .tl_set:N = \l_character_noblesse_tl,
class .tl_set:N = \l_character_class_tl,
race .tl_set:N = \l_character_race_tl,
nickname .tl_set:N = \l_character_nick_tl,
% age .int_set:N = \l_character_age_int
% , unknown .code:n = {}
}
\NewDocumentCommand{\createCharacter}{s t- m D<>{#3} o m}
{
% we don't want that the unset keys are carried over from the previous ones
\group_begin:
\IfValueT{#5}{\keys_set:nn{Character/Identity}{#5}}
\cs_new_protected:cpn { #4 FName } { #3 }
\cs_new_protected:cpx { #4 LName } { \exp_not:V \l_character_lastname_tl }
\cs_new_protected:cpx { #4 Title } { \exp_not:V \l_character_title_tl }
\cs_new_protected:cpn { #4 Polite } { \use:c { #4 Title } ~ \use:c { #4 LName } }
\cs_new_protected:cpx { #4 Sign } { \exp_not:c { #4 FPolite } , ~ \exp_not:V \l_character_noblesse_tl }
\cs_new_protected:cpn { #4 Age } { #6 }
\cs_new_protected:cpx { #4 Prof } { \exp_not:V \l_character_profession_tl }
\cs_new_protected:cpx { #4 Class } { \exp_not:V \l_character_class_tl }
\cs_new_protected:cpx { #4 Race } { \exp_not:V \l_character_race_tl }
\cs_new_protected:cpx { #4 NName } { \exp_not:V \l_character_nick_tl }
\group_end:
%% more code here but irrelevent for the question %%
}
\ExplSyntaxOff
\createCharacter{Barry}<main>[lastname=Allen, prof=scientist]{39}
\createCharacter*{Jessy}<side>[lastname=Quick, nickname=Jess, prof=professional runner]{24}
\begin{document}
\mainFName
\sideFName
\sideLName
\mainLName
\end{document}
You need to deliver the contents of the variables. Also the group is important, otherwise unset values for a character would be carried over from a previous one. OK, unless you set all values for every character.
|
[
"stackoverflow",
"0017527627.txt"
] |
Q:
Read and combine data from multiple csv files
I have 3 different files: NewRush4.csv, NewRush5.csv, NewRush6.csv.
I am trying to collect an 'All-Time Leaders' from each Season (4, 5, and 6).
I want to either read every player's name in every file and combine them if they are duplicates, or read the first file and compare it with the other two files to combine them.
Here is my python code. I have to read the first file. I'm not sure how to go about using DictReader.
#!/usr/bin/python
import csv
file = open("NewRush4.csv", "rb")
for line in csv.DictReader(file, delimiter=","):
name = line["Player"].strip()
yds = line["YDS"].strip()
car = line["CAR"].strip()
td = line["TD"].strip()
fum = line["FUM"].strip()
ypc = line["YPC"].strip()
print "%-20s%10s%10s%10s%10s%10s" % (name, car, yds, td, fum, ypc)
file.close()
Output:
49erswag 3 14.0 0 0 4.7
A Beast Playa 7 23.0 0 0 3.3
A Swanky Guy 2 29 154.0 1 2 5.3
ACIDRUST 1 4.0 0 0 4.0
Aj dahitman 227 1898.0 19 2 8.4
Aldizzl 10 45.0 0 0 4.5
Areis21 13 58.0 0 2 4.5
at43 48 214.0 1 1 4.5
Ayala2012xTCU 57 195.0 0 1 3.4
B O R Nx 25 13 31.0 0 1 2.4
B r e e z yx60 4 13.0 0 0 3.3
Beardown74 116 621.0 6 3 5.4
beatdown54 2010 26 126.0 3 1 4.8
behe SWAG 1 -5.0 0 0 -5.0
Big Murph22 73 480.0 6 2 6.6
BigBlack973 18 57.0 0 1 3.2
BiGDaDDyNaPSacK 184 1181.0 20 4 6.4
Season4 File:
Player,YDS,TD,CAR,FUM,YPC
49erswag, 14.0, 0, 3, 0, 4.7
A Beast Playa, 23.0, 0, 7, 0, 3.3
A Swanky Guy 2, 154.0, 1, 29, 2, 5.3
ACIDRUST, 4.0, 0, 1, 0, 4.0
Aj dahitman, 1898.0, 19, 227, 2, 8.4
Aldizzl, 45.0, 0, 10, 0, 4.5
Areis21, 58.0, 0, 13, 2, 4.5
at43, 214.0, 1, 48, 1, 4.5
Ayala2012xTCU, 195.0, 0, 57, 1, 3.4
B O R Nx 25, 31.0, 0, 13, 1, 2.4
B r e e z yx60, 13.0, 0, 4, 0, 3.3
...
Season5 File:
Player,YDS,TD,CAR,FUM,YPC
a toxic taz, 307.0, 4, 44, 0, 7.0
AbNL Boss, 509.0, 4, 174, 2, 2.9
AFFISHAUL, 190.0, 0, 35, 2, 5.4
AJ DA HITMAN, 1283.0, 19, 228, 6, 5.6
allen5422, 112.0, 2, 18, 0, 6.2
Allxdayxapx, 264.0, 1, 76, 2, 3.5
AlpHaaNike, 51.0, 1, 10, 1, 5.1
Aura Reflexx, 215.0, 1, 40, 0, 5.4
AWAKEN DA BEAST, -5.0, 0, 4, 1, -1.3
AxDub24, -3.0, 0, 2, 1, -1.5
Ayala2012xTCU, 568.0, 4, 173, 1, 3.3
BALLxXHAWKXx, 221.0, 1, 47, 2, 4.7
BANG FIGHTY007, 983.0, 6, 171, 3, 5.7
bang z ro, 29.0, 0, 9, 0, 3.2
BEARDOWN74, 567.0, 6, 104, 2, 5.5
...
So, if a player played in more than one season, add his stats and print. Otherwise, just print.
A:
Use collections.defaultdict:
I don't know what each field mean; I sum each field. Adjust as your need.
from collections import defaultdict
import csv
class PlayerStat(object):
def __init__(self, yds=0, car=0, td=0, fum=0, ypc=0, count=0):
self.yds = float(yds)
self.car = float(car)
self.td = float(td)
self.fum = float(fum)
self.ypc = float(ypc)
self.count = count
def __iadd__(self, other):
self.yds += other.yds
self.car += other.car
self.td += other.td
self.fum += other.fum
self.ypc += other.ypc
self.count += other.count
return self
filenames = 'NewRush4.csv', 'NewRush5.csv', 'NewRush6.csv',
stats = defaultdict(PlayerStat)
for filename in filenames:
with open(filename) as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
stat = PlayerStat(row['YDS'], row['CAR'], row['TD'], row['FUM'], row['YPC'], count=1)
stats[row['Player']] += stat
for player in sorted(stats, key=lambda player: stats[player].yds):
stat = stats[player]
if stat.count == 1:
continue
print '{0:<20}{1.car:>10}{1.yds:>10}{1.td:>10}{1.fum:>10}{1.ypc:>10}'.format(player, stat)
|
[
"stackoverflow",
"0008281370.txt"
] |
Q:
am i doing this right? - C code
when i run this it says the size is 4 when it is really six. it does this here:
printf("String Size: %u\n", sizeof some_string.basic_string);
i am new to c memory allocation and never used malloc before. am i using malloc right?
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct String String;
struct String {
char *basic_string;
};
String String_New(char basic_string[]) {
String temp;
temp.basic_string = (char *) malloc(sizeof basic_string);
strcpy(temp.basic_string, basic_string);
return temp;
}
void String_Delete(String *string) {
free(string->basic_string);
string->basic_string = NULL;
}
int String_GetSize(String string) {
int i = 0, s = 0;
while (string.basic_string[i] != '\0') {
i++;
s++;
}
return s;
}
int main(int argc, char *argv[]) {
String some_string = String_New("hello");
printf("String Literal: %s\n", some_string.basic_string);
printf("String Size: %u\n", sizeof some_string.basic_string);
printf("String Length: %d\n", String_GetSize(some_string));
String_Delete(&some_string);
if (some_string.basic_string == NULL) {
return 0;
}
return 1;
}
A:
In C a "string" is not a true data type. The sizeof operator takes a data type, or an object that has "type" as an operand. In your case the object is some_string.basic_string which has type char*, and the size of a pointer on your system is 4.
The solution is to define your String structure to have a size member:
struct String {
char *basic_string;
size_t length ;
};
And store the size when allocated in String_New(). This would simplify and make more efficient your String_GetSize() function (which is already over complicated since s == i).
Be aware also that in String_New(), that the basic_string parameter is also a pointer (despite the "array syntax" used in its signature). I would avoid this syntax, it is misleading since in C you cannot pass an array by copy unless the array is embedded in a struct; arrays always "degrade" to pointers when passed as arguments. Moreover the caller may pass a pointer rather than an array in any case. So in most cases you will have allocated too little memory (4 bytes). You should use strlen() or the method you originally used in String_GetSize() to determine the length.
String String_New(char* basic_string)
{
String temp;
temp.length = strlen( basic_string ) ;
temp.basic_string = (char *) malloc( temp.length + 1 );
strcpy(temp.basic_string, basic_string);
return temp;
}
size_t String_GetSize(String string)
{
return string.length ;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.