text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Can you make the Wii-u gamepad not disconnect after an hour?
I'm getting some new amiibo's for Christmas, and I want to train them while I'm AFK, but the problem is I don't know if the gamepad can stay on for more than an hour some how.
A:
In my experience, the gamepad never turned off while charging. In other words: Keeping the power cord plugged in should ensure that your gamepad will never turn off as long as the Wii U doesn't turn off by itself. At the very least, I've been able to leave my Amiibos fighting each other for over 1 hour and a half while playing on my other consoles or PC in the meantime. I never encountered any problems then.
The Wii U itself can be set to never automatically shut down. This is done under: Settings > Power Settings > Auto Power-Down where you can either enable or disable it. When you enable it, you will be asked to choose how many hours (from 1 to 12) the Wii U can remain idle before turning off. Simply disable the feature to get rid of it.
| {
"pile_set_name": "StackExchange"
} |
Q:
clickable phone button .svg stylesheet not clicking
Hello Im having problems on a mobile phone for it to be able to touch call the number under the image. the image is being called from the stylesheet. It works fine on chrome desktop but on the mobile the green call button (bottom right) isnt working nicely on mobile. IT seems not to be sitting at the top of the page as well.
site: bittersweetcafe.com.au
.callnowbutton {
width: 100px;
right: 0;
border-bottom-left-radius: 40px;
border-top-left-radius: 40px;
height: 80px;
bottom: -20px;
border-top: 2px solid #2dc62d;
background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgNjAgNjAiPjxwYXRoIGQ9Ik03LjEwNCAxNC4wMzJsMTUuNTg2IDEuOTg0YzAgMC0wLjAxOSAwLjUgMCAwLjk1M2MwLjAyOSAwLjc1Ni0wLjI2IDEuNTM0LTAuODA5IDIuMSBsLTQuNzQgNC43NDJjMi4zNjEgMy4zIDE2LjUgMTcuNCAxOS44IDE5LjhsMTYuODEzIDEuMTQxYzAgMCAwIDAuNCAwIDEuMSBjLTAuMDAyIDAuNDc5LTAuMTc2IDAuOTUzLTAuNTQ5IDEuMzI3bC02LjUwNCA2LjUwNWMwIDAtMTEuMjYxIDAuOTg4LTI1LjkyNS0xMy42NzRDNi4xMTcgMjUuMyA3LjEgMTQgNy4xIDE0IiBmaWxsPSIjMDA2NzAwIi8+PHBhdGggZD0iTTcuMTA0IDEzLjAzMmw2LjUwNC02LjUwNWMwLjg5Ni0wLjg5NSAyLjMzNC0wLjY3OCAzLjEgMC4zNWw1LjU2MyA3LjggYzAuNzM4IDEgMC41IDIuNTMxLTAuMzYgMy40MjZsLTQuNzQgNC43NDJjMi4zNjEgMy4zIDUuMyA2LjkgOS4xIDEwLjY5OWMzLjg0MiAzLjggNy40IDYuNyAxMC43IDkuMSBsNC43NC00Ljc0MmMwLjg5Ny0wLjg5NSAyLjQ3MS0xLjAyNiAzLjQ5OC0wLjI4OWw3LjY0NiA1LjQ1NWMxLjAyNSAwLjcgMS4zIDIuMiAwLjQgMy4xMDVsLTYuNTA0IDYuNSBjMCAwLTExLjI2MiAwLjk4OC0yNS45MjUtMTMuNjc0QzYuMTE3IDI0LjMgNy4xIDEzIDcuMSAxMyIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg==) center 2px no-repeat #090;
box-shadow: 0 0 5px #888;
z-index: 9999;
background-size: 58px 58px;
position:fixed;
}
<a href="tel:0394974144">
<div class="callnowbutton">
</div></a>
A:
I would suggest the following:
<div class="callnowbutton">
<a href="tel:0394974144"></a>
</div>
According to http://stackoverflow.com you need to add "-webkit-backface-visibility:hidden;" to your .callnowbutton class:
.callnowbutton {
/* your code here */
-webkit-backface-visibility:hidden;
}
It could help to:
.callnowbutton a {
display: block;
width: 100%;
height:100%;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Story about a multiverse theory of immortality
Please help me identify a short story I read about a guy who believed that the multiverse was true, but the one that we experienced was the one in which we lived the longest. He was also contemplating suicide, and every time he sat staring at the pills he was going to use to overdose, parallel universes (where he chose suicide) collapsed and the one he was in got weirder. Eventually an asteroid hit the Earth, and then he was resurrected somehow in the deep future.
I'm not sure where I read it, but it likely appeared in Dozois's The Year's Best Science Fiction or in a back issue of Analog (my dad had like a decade's worth in the den).
A:
"Divided By Infinity" by Robert Charles Wilson, I'm pretty sure. It's (legally) online on Tor's website.
| {
"pile_set_name": "StackExchange"
} |
Q:
Force update ActiveRecord association
I have a self-referencing loop that references the most recent associated record to see if it's caught up. However, it keeps referencing the first associated record, so it keeps going in an infinite loop. I think this is because the ActiveRecord transaction keeps running throughout the loop, so it never stops and updates itself.
Is there any way to force a model to reset itself before continuing on?
Here's my model (not that the exception raising is just so I can verify whether we've actually advanced to the next record).
class RecurringRule < ActiveRecord::Base
belongs_to :organization
has_one :last_run, :class_name => "Transaction", :order => 'id DESC'
has_many :transactions
attr_accessible :period, :last_run_id
after_create :destroy_if_period_empty
def destroy_if_period_empty
if !period?
self.destroy
end
end
def recur
@count = @count || 0
if @count > 0 then raise last_run.id.to_s end
if last_run.created_at.to_date.advance(period.pluralize.to_sym => 1) >= Date.today
new = Transaction.new({
amount: last_run.amount,
person_id: last_run.person_id,
organization_id: last_run.organization_id,
recurring_rule_id: last_run.recurring_rule_id
})
new.save!
@count += 1
self.recur
end
return @count
end
end
A:
You can try
Model.association(force_reload=true)
See here for reference (it is valid also for has many relations)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is changing default admin URLs an effective security measure?
Consider WordPress, which houses all of its admin functions in the /wp-admin/ directory. Accordingly, its admin URLs all begin with /wp-admin/. I'm wondering if it would be significantly more secure to have each installation use a unique name for the admin folder and URLs, For example, the admin folder for a particular installation might be /8404f25a73ec25d1/.
The first thing that comes to mind is that this is security through obscurity. However, this seems like it could be an effective, first-line-of-defense against automated scripts. If the name was sufficiently random and long enough, there is no way an attacker could guess the name of the admin folder. Also, in zero-day attack against a newly found security hole against
the admin side, this might be the only defense.
Should off-the-shelf web applications like WordPress provide a way to change default admin URLs?
To be clear, I am not thinking that this should replace any other security measure; I'm only wondering if the additional security (if any) would be worth the effort.
A:
It will unquestionably protect you from automated attacks that rely on the location of the wp-admin directory as part of their programming, which is not insignificant, since automated attacks make up the vast majority of wordpress compromises. You may call it security through obscurity, but you're not actually replacing any of your security apparatus with obscurity, you're augmeting it. So a better term would be defense in depth.
Note that a far better strategy is to require HTTP Authentication to access the wp-admin directory. Just plunk an .htaccess file and .htpasswd file in there and you're done. This is widely regarded and recommended as a good idea. That way not only do you have to log in to wordpress to use the admin features, but you also have to provide a password to the server just to allow it to show any content from that directory. That protects you against all sorts of authentication-bypass vulnerabilities if they ever crop up.
See the rest of the Hardening Wordpress documentation for more similar "good ideas".
A:
Non-standard URL are similar to using a non-standard port (e.g. putting your SSH server not on port 22, but on some other port): they may help against automated attacks, not really for actual security, but in order to reduce the noise. A standard "admin" URL will get hundreds of connection attempts per day, generating tons of logs, thus preventing efficient detection of non-automated attacks, the kind that you should worry about.
However, changing a URL to some non-standard, site-specific value can have hidden costs. For instance, if there is an "admin" button on the main page, that button will have to be adjusted to point to the actual admin URL; hardcoding the link value in a HTML file provided with the software won't work anymore. Note that this non-standard URL will not be exactly secret if it is advertised through such a button...
So if you can easily, with little or no overhead, change the "admin" URL to some non-standard value, then by all means, go for it. Just don't believe that it really increases security. Its job is to decrease noise from mindless attack automatons (and that can promote more efficient attack detection, which may indirectly help with your security).
| {
"pile_set_name": "StackExchange"
} |
Q:
memoir tutorials or introductions
I'm looking for memoir tutorials or introductions. The main manual is a wonderful piece of documentation, but at nearly 600 pages it is a bit overwhelming as a starting place. Likewise the more examples I can find (with associated code) the more quickly I can move to the real work of typesetting the book in question---a collection of short stories gathered together in one place for the first time.
A:
There's a video on zeeba.tv of a presentation by Steve Peter:
Introduction to memoir
Description: This presentation serves as a gentle introduction to Peter Wilson’s memoir class, an alternative to the standard LaTeX classes. Memoir is quite flexible, and makes it easy to create beautiful book, article, and report designs, without having to search for, install, and load numerous third-party packages.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get back project back after signed apk android studio
How to get back the whole android project after generate signed apk android studio ? I have generated the apk and send to dropbox, when I get the project file and open it using Android Studio, my project looked like this
Is there a way I can import the whole project back ?? Thanks
A:
Generating a signed apk does not modify your project. Did you delete your project?
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot insert an image - Textfield
I downloaded the new version of Orchard - 1.4.2.
Created a new Content Type. Added a new Text Field. Changed the flavour to HTML.
However, I can't insert an image to that WSIWYG. There is no error. But the Image Picker tool doesn't seem to work.
Am I missing something here?
A:
This was fixed in the later versions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ajax Delete,Cant focus On the Specific Row
At the folloing code,I try to delete a row using ajax .serialize() but it only deletes the first row.Using jQuery(this).closest('form').find('input[name="id"]').val(); also returns "Undefined" for ID.
Ajax Code
function AjaxDelete() {
var rowId = $("#sil").serialize();
var confirmation = confirm("Are you sure of deleting the following user:"+rowId);
if (confirmation) {
$.ajax({
type:'POST',
url:'sil.php', //deleting file
data: rowId,
success:function(cevap){
alert("User has been successfully removed.ID="+rowId);
}
});
}
return confirmation;
};
Table Structure
echo '<table id="kullanicilar" align=center>
<thead>
<tr>
<td></td>
<td>ID</td>
<td>Kullanıcı Adı</td>
<td>Yönetici</td>
<td colspan=4>İşlemler</td>
</tr>
</thead>
';
while($results->fetch()){ //fetch values
echo '<tr>
<td><input type="checkbox" name="select[]" value="'.$id.'"></td>
<td>'.$id.'</td>
<td>'.$kullanici_adi.'</td>
<td>'.$yonetici.'</td>
<td><a href="#" onclick="return AjaxDelete();" class="link"><form method="post" id="sil"><input type="hidden" name="id" value="'.$id.'" class="id"></form><img src="img/delete.png" title="Sil"></a></td>
<td><a href="#"><img src="img/edit.png" title="Düzenle"></img></a></td>
<td><a href="#" class="gor">Gönderilerini Gör</a></td>
<td><a target="_blank" href="#" class="gor">Profilini Gör</a></td>
</tr>
'
;
}
echo '</table><br/>';
A:
In your while loop, you are giving same id to inputs which is wrong. you can try:
<a href="#" onclick="return AjaxDelete("'.$id.'");" class="link"><form method="post" id="sil">
and then in your ajax:
function AjaxDelete(x) {
var rowId = x;
| {
"pile_set_name": "StackExchange"
} |
Q:
Python socket.send() can only send once, then socket.error: [Errno 32] Broken pipe occurred
I'm a newbie in network programming, so please forgive me if this is a dumb question :)
I created 1 client and 1 SocketServer.ThreadingMixIn server on Ubuntu 10.04.2 using Python2.7, but
it seems like I can only call sock.send() once in client, then I'll get a:
Traceback (most recent call last):
File "testClient1.py", line 33, in <module>
sock.send('c1:{0}'.format(n))
socket.error: [Errno 32] Broken pipe
Here's the code I wrote:
testClient1.py:
#! /usr/bin/python2.7
# -*- coding: UTF-8 -*-
import sys,socket,time,threading
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
sock.connect(('localhost',20000))
except socket.error:
print('connection error')
sys.exit(0)
n=0
while n<=1000:
sock.send('c1:{0}'.format(n))
result=sock.recv(1024)
print(result)
n+=1
time.sleep(1)
testServer.py:
#! /usr/bin/python2.7
# -*- coding: UTF-8 -*-
import threading,SocketServer,time
class requestHandler(SocketServer.StreamRequestHandler):
#currentUserLogin={} #{clientArr:accountName}
def handle(self):
requestForUpdate=self.rfile.read(4)
print(requestForUpdate)
self.wfile.write('server reply:{0}'.format(requestForUpdate))
class broadcastServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == '__main__':
server=broadcastServer(('localhost',20000),requestHandler)
t = threading.Thread(target=server.serve_forever)
t.daemon=True
t.start()
print('server start')
n=0
while n<=60:
print(n)
n+=1
time.sleep(1)
server.socket.close()
I ran them in 2 separate terminals:
output of 1st terminal:
$ python2.7 testServer.py
server start
0
1
2
3
4
c1:0
5
6
7
8
9
10
11
...
output of 2nd terminal:
$ python2.7 testClient1.py
server reply:c1:0
Traceback (most recent call last):
File "testClient1.py", line 33, in <module>
sock.send('c1:{0}'.format(n))
socket.error: [Errno 32] Broken pipe
I tried calling sock.send() twice directly in testClient.py,
for ex:
while n<=1000:
sock.send('c1:{0}'.format(n))
sock.send('12333')
result=sock.recv(1024)
print(result)
n+=1
time.sleep(1)
but the outputs of the terminals are still the same :(
Can anyone please point out what am I doing wrong here?
Thx in adv!
Here's the [Sol] I came up with. Thank you Mark:)
testClient1.py:
import sys,socket,time
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
sock.connect(('localhost',20000))
except socket.error:
print('connection error')
sys.exit(0)
n=0
while n<=10: #connect once
sock.send('c1:{0}'.format(n))
result=sock.recv(1024)
print(result)
n+=1
time.sleep(1)
sock.close()
#once you close a socket, you'll need to initialize it again to another socket obj if you want to retransmit
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
sock.connect(('localhost',20000))
except socket.error:
print('connection error')
sys.exit(0)
n=0
while n<=10: #connect once
sock.send('c3:{0}'.format(n))
result=sock.recv(1024)
print(result)
n+=1
time.sleep(1)
sock.close()
testServer.py:
import threading,SocketServer,time
class requestHandler(SocketServer.StreamRequestHandler):
#currentUserLogin={} #{clientArr:accountName}
def handle(self):
requestForUpdate=self.request.recv(1024)
print(self.client_address)
while requestForUpdate!='':
print(requestForUpdate)
self.wfile.write('server reply:{0}'.format(requestForUpdate))
requestForUpdate=self.request.recv(1024)
print('client disconnect')
class broadcastServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == '__main__':
server=broadcastServer(('localhost',20000),requestHandler)
t = threading.Thread(target=server.serve_forever)
t.daemon=True
t.start()
print('server start')
n=0
while n<=60:
print(n)
n+=1
time.sleep(1)
server.socket.close()
A:
handle() is called in the SocketServer.StreamRequestHandler once for each connection. If you return from handle the connection is closed.
If you want the server to handle more than one send/recv, you must loop until recv() returns 0, indicating the client closed the connection (or at least called shutdown() on sends).
Also note that TCP is a streaming protocol. You'll need to design a message protocol that indicates the length or end of a message, and buffer recv until you have a complete message. Check send return value to make sure all the message is sent as well, or use sendall.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can you read only part of an HttpWebResponse
I would like to read only part of an HttpWebResponse. Let's say the first 100k. How can I read only the first 100k of the Response but still end up with a non-corrupted substring? If I just throw the first 100k into a byte[] I believe I could end up with corrupted data.
HttpWebRequest request = HttpWebRequest.Create("http://www.yahoo.com") as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream))
{
string content = sr.ReadToEnd();
}
}
A:
You cannot expect to get non-corrupted substring by limiting the size by the length of bytes.
A better way would be reading by characters (Read, ReadBlock, ReadLine,) until you are satisfied.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fix Permission denied in python?
I am trying to access index.html from apache configuration.
my apache config is
Listen 8080
#ServerName localhost
WSGISocketPrefix /var/run/wsgi
<VirtualHost *:8080>
WSGIDaemonProcess <group-name> python-path=/opt/codebase/git/.pyenv/versions/3.5.2/envs/<project>/lib/python3.5/site-packages user=apache group=<group-name> display-name=%{GROUP}
WSGIProcessGroup <group-name>
WSGIScriptAlias /api /codebase/projects/<project>/src/apps/apps/wsgi.py process-group=<group-name>
Timeout 1800
SSLEngine off
SSLCertificateFile /etc/pki/tls/certs/apache.crt
SSLCertificateKeyFile /etc/pki/tls/private/apache.key
DocumentRoot /codebase/projects/<project>/src/client/<project>
<Directory /codebase/projects/<project>/src/client/<project>>
Require all granted
<IfModule expires_module>
ExpiresActive On
ExpiresDefault "modification plus 2 seconds"
# ExpiresDefault "access plus 1 day"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
</IfModule>
Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-eval'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; child-src 'self'; form-action 'self'; media-src 'self'; object-src 'self'; report-uri /api/csp/report"
</Directory>
<Directory /codebase/projects/<project>/src/files>
Require all granted
</Directory>
I am using centos 7 and apache2.4
I am getting:
13) Permission denied: [client 3.204.115.205:64720] AH00035: access to /index.html denied (filesystem path
'/codebase/projects/<project>/src/client/<project>/index.html') because search permissions are missing on a component of the path.
I gave full permission from parent most dir to file. but getting permission denied problem. can some one help me. I am running all this env in EC2 instance.
A:
Primary solution .
Do you have SELinux running? Try this: sudo setenforce 0 and then restart apache. If this works, DO NOT leave it like this. Turn SELinux back on with: sudo setenforce 1 and I'll post some links on how to create rules to allow apache access to those files. by – wholevinski
| {
"pile_set_name": "StackExchange"
} |
Q:
Update balise on Jquery/Ajax navigation Wordpress
I am doing an ajax navigation for a wordpress website. I update the #content with fade, this is ok, but I want to just update my head with my new page head, I don't find!
$(document).ready(function () {
//hash change
$(window).hashchange(function () {
//on retrouve le vrai lien
var arg = window.location.hash.substring(3);
var link = 'http://ladresse.graphsynergie.com/' + arg;
$.ajax({
url: link,
processData: true,
dataType: 'html',
success: function (data) {
data = innerShiv(data, false);
var contenu = $(data).find("#contenu");
//problem part
var head = $(data).find('head').text();
document.head = head;
//problem part end
$('#contenu').fadeOut('200', function () {
$(this).html(contenu.html()).fadeIn('200');
});
}
});
});
//end
//détection d'un hash onload
if (window.location.hash.substring(3) != '') {
$(window).trigger('hashchange');
}
});
A:
Have in consideration that .text() will only retrieve the "text" contained inside the html tags, review the jQuery documentation. I think that what you actually want is to use the .html() method.
So, I think that you may want to replace those 2 problematic lines of code with this:
$("head").html($(data).find("head").html());
Update:
Apparently all browsers strip out anything that it's not inside the "body" when they create the DOM object. The thing is that when you do: "$(data)" jQuery creates a DOM object with the content of the "data" variable, and your browser decides to ignore all the elements that are not inside the "body" tag, therefore in the internal DOM object that jQuery handles the "head" element is not there anymore. So you will have to find a workaround.
Try this, put these lines of code just after the line "success: function (data) {":
var headIni = data.toLowerCase().indexOf("<head");
var headEnd = data.toLowerCase().indexOf("</head>");
headIni = data.indexOf(">", headIni + 1) + 1;
var headHTML = data.substring(headIni, headEnd);
And then, replace the line that I initially suggested for this one:
$("head").html(headHTML);
This should do the job. I'm sure that there must be more elegant ways to do it, but hopefully this will be good enough for you.
Update 2:
If you follow this link you will find a much better way to do it. Just add the library "jquery.ba-htmldoc.js" that you will find there, and then do this:
$("head").html($.htmlDoc(data).find('head').html());
| {
"pile_set_name": "StackExchange"
} |
Q:
How to automatically scale up and down Amazon EC2 ubuntu micro instances
I am building a project in which i use amazon EC2 micro instance as a server which is running ubuntu on it. I want that if the resources of this server e.g. RAM to serve the requests are exhausted , it should automatically scale up and down . I have heard of it very often but don't know how to make this instance automatically scalable.
I connect to my instance using ssh through command line and i can make it start and stop etc. using AWS Management Console in browser.
A:
Generally speaking, when you are talking about auto scaling you are dealing with a system that adds more instance in response to more demand, and deleting instance in response to dwindling demand.
I am not saying its impossible to autoscale a single instance, but if you can, its at a minimum going to require the instance to go off-line for a bit while it reconfigures itself and reboots. Usually not an option for a lot of systems.
Much better, imo, to architect your solution to use additional instances when you need more horsepower if possible and delete those instances as they become idle instead of sizing up or down a single instance.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding PDF of $X^2$ when $X$ is standard normal
I'm given a standard normal $X$, and $Y=X^2$. To find the PDF of $Y$, we have $$F_Y(a)=P(X^2\le a)=P(X \le a^{1/2})=F_X(a^{1/2}),$$
so $$f_Y(a)=f_X(a^{1/2})*\frac{1}{2a^{1/2}}=\frac{1}{\sqrt{2\pi}}e^{-a/2}\frac{1}{2a^{1/2}}.$$
The latter isn't a PDF since its integral from 0 to infinity (the range of $Y$) is 1/2. What is my mistake?
A:
If $a\leqslant 0$ then $F_Y(a)=0$.
If $a>0$, then $F_Y(a)=\mathbb P(-\sqrt{a}\leqslant X\leqslant \sqrt{a})=F_X(\sqrt{a})-F_X(-\sqrt{a})$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Vagrant provisioning command does not add aliases to ~/.profile
I have a fairly vanilla Vagrant setup running trusty64. It's being configured by a single shell file. Among others, it contains an aliasing of python3 to python and pip3 to pip, respectively:
echo "Writing aliases to profile:"
echo "alias python=\"python3\"" >> ~/.profile
echo "alias pip=pip3" >> ~/.profile
. ~/.profile
For some mysterious reason, these lines never make it into ~/.profile. There is no error message, nor any other commotion, it's just that nothing happens. This being 2am, I am fairly sure I'm doing something wrong, I just can't figure out what it is.
A:
I am pretty sure you're calling the provisioner with something like
config.vm.provision "shell", path: "bootstrap.sh"
This works well but its executed as root user so all the lines are added for this user only. You want to use the privileged option
privileged (boolean) - Specifies whether to execute the shell script
as a privileged user or not (sudo). By default this is "true".
config.vm.provision "shell", path: "bootstrap.sh", privileged: "false"
will execute as your vagrant user and will add lines in to /home/vagrant/.profile file
| {
"pile_set_name": "StackExchange"
} |
Q:
Run Internet Explorer 9 on Windows Xp Professional for testing purposes?
I want to test my web application on Internet Explorer 9 but I don't want to buy a copy of Vista/Win 7 on my developer machine with Windows XP.
Anyone knows a workaround, free and easy?
A:
Use another machine.
Or better, get a set of Virtual Machines established which have an array of operating systems and browsers installed. Build enough VMs, and you are covered for all eventualities, regardless of whether you would personally use them or not.
Link to Internet Explorer Application Compatibility VirtualPC Images
A:
You can't. The closest you'll get is IE9Preview.
I've found that IETester is not a bad way to quickly switch between browser versions for testing.
| {
"pile_set_name": "StackExchange"
} |
Q:
uncertain number of inputs for my function
I recently came to a problem that I was supposed to define a function with uncertain number of inputs, that is, the number of inputs may vary depending on the practical context. Should I take use of a 2-D array or something else? I don't know if struct2cell helps and how if it really works.
Does anyone have an idea of the best way to go about doing this?
I've probably not been very clear, so please let me know if anything needs clarifying.
Thanks
A:
There are several ways to go about this:
Use optional input arguments if a given parameter means the same regardless of context, but if in some scenarios, additional input is needed.
function out = myFun(first,second,third,fourth)
%# first is always needed
if nargin < 1 || isempty(first)
error('need nonempty first input')
end
%# second is optional
if nargin < 2 || isempty(second)
second = defaultValueForSecondWhichCanBeEmpty;
end
%# etc
You can call this function as out = myFun(1,[],2,3), i.e. pass an empty array for non-needed inputs.
If two inputs mean that the function is used one way, and three inputs mean that the function is used in another way (and even the inputs mean different things), use VARARGIN
function out = myFun(varargin)
%# if 2 inputs, it's scenario 1, with 3 it's scenario 2
switch nargin
case 2
firstParameter = varargin{1};
secondParameter = varargin{2};
scenario = 1;
case 3
firstParameter = varargin{1}; %# etc
otherwise
error('myFun is only defined for two or three inputs')
end
Finally, you can also have your inputs passed as parameterName/parameterValue pairs. See for example this question on how to handle such input.
| {
"pile_set_name": "StackExchange"
} |
Q:
stream voice through wifi - android
I'm working on entry phone. The entry phone is sending to me voice and video through rtsp protocol so I can simply get voice and video from camera on my device. But I have no idea how to send a voice to that device. Is there anything that would help me send and receive audio in the same time (something like a call)?
A:
If I understand correct you want video calls. Just like sipdroid app. It is an open source project look at VideoCamera.java class in this project.
http://code.google.com/p/sipdroid/
| {
"pile_set_name": "StackExchange"
} |
Q:
Spurious white space when adding vertical space to start of the page, in redefinition of \section
As a followup question to Fullwidth section heading in twosided layout I'd also like to inquire about vertical spacing on new pages. The idea is that the top element of the section title starts somewhere in the middle of the page, and the text block on the next page starts equally as low. The MWE
\documentclass{article}
\usepackage{changepage}
\usepackage[paperwidth=483pt, paperheight=682pt, left=40pt, top=40pt, textwidth=283pt, marginparsep=20pt, marginparwidth=100pt, textheight=51\baselineskip, footskip=40pt]{geometry}
\usepackage[explicit]{titlesec}%
\newdimen\mydimen
\mydimen=0pt
\titleformat{name=\section}%
{}%
{}%
{0pt}%
{%
\thispagestyle{empty}%
\vspace*{\mydimen}
\begin{adjustwidth*}{0pt}{\dimexpr\marginparwidth+\marginparsep\relax}%
%
\begin{minipage}[t][.8\textheight]{\linewidth}
x
\end{minipage}
\end{adjustwidth*}%
}[\clearpage
\vspace*{\mydimen}
]%
\begin{document}
\section{x}
x
\clearpage
\noindent x
\end{document}
should intuitively have the result that all three x's at the top of the page are vertically as well as horizontally aligned. This doesn't seem to be the case (somehow). How can I align all three x's here?
A:
You don't need adjustwidth: just define a wide enough minipage and put it in a zero width box.
Next, set the spacings for \section to zero except the last that must be -\baselineskip.
\documentclass[draft]{article}
\usepackage[showframe]{geometry}
\usepackage[explicit]{titlesec}
\newlength\mydimen
\titleformat{name=\section}
{}
{}
{0pt}
{%
\thispagestyle{empty}%
\vspace*{\mydimen}%
\makebox[0pt][l]{%
\begin{minipage}[t][.8\textheight]{\dimexpr\textwidth+\marginparwidth+\marginparsep}
x
\end{minipage}%
}
}
[\clearpage\vspace*{\mydimen}]
\titlespacing*{\section}{0pt}{0pt}{-\baselineskip}
\begin{document}
\section{x}
x
\clearpage
\noindent x
\end{document}
I can't see what's the role of \mydimen.
| {
"pile_set_name": "StackExchange"
} |
Q:
Secur32Util.getUserNameEx replacement
I have a case where a Java application uses Secur32Util.getUserNameEx from jna to obtain the username in a format for a single-sign-on. There are some machines where this function call is executing for a few minutes. I was not able to figure out why that is yet. But in the meantime, I would like to ask if there is a replacement that can be used to substitute that call.
To start the discussion, I have already tested that NTSystem#getName() and NTSystem#getDomain() return immediately on the machine that is stuck on executing Secur32Util.getUserNameEx. Are those functions interchangeable?
A:
I have created a corresponding C++ application that executed without delay. But, it turned out that my application was using JNA version 3.3 and when I updated to the current version it does not have that problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I show that the derivative of the path $\det(I + tA)$ at $t = 0$ is the trace of $A$?
Here, I'm taking $A$ to be a linear operator on $\mathbb R^n$ for $n>1$. Can you please tell me how to solve such a problem?
A:
We have
$$\det(I+tA)=t^n\det\left(A+\frac1t I\right)=t^n\chi_A\left(\underbrace{-\frac 1t}_{=X}\right)=t^n\left((-1)^nX^n+(-1)^{n-1}\operatorname{tr}(A) X^{n-1}+\cdots+\det A\right)\\=1+ \operatorname{tr}(A)t+\cdots+\det(A)t^n$$
and the result follows.
A:
Letting $B=I+t A$, and using the Leibniz formula of the determinant, in terms of the permutations of the set $\{1,2, \ldots, n\}$:
$$p(t)=\det(I+tA)=\det(B)=\sum_\sigma {\rm sign}(\sigma) \prod_{i=1}^n b_{i,\sigma_i} \tag{1}$$
One of the terms of the sum consists of the permutation that picks the diagonal elements; this has the form:
$$(t\, a_{1,1}+1)(t\, a_{2,2}+1)\cdots (t\, a_{n,n}+1)=1+ \beta_1 t + \beta_2 t^2+\beta_3 t^3 + \cdots + \beta_n t^n$$
where $\beta_1 = a_{1,1}+a_{2,2}+\cdots + a_{n,n}={\rm tr}(A)$
The other terms in $(1)$ include at least two off-diagonal elements in the product, hence they include a factor $t^2$.
Hence, $p(t)=1+ {\rm tr}(A)\,t + t^2 g(t)$ where $g(t)$ is some polynomial; and the result follows.
A:
we will use the following facts:
(a) determinant of a matrix is the product of the eigenvalues,
(b) trace of a matrix is the sum of the eigenvalues,
(c) eigenvalues of $I + tA$ are $1 + t \lambda$ where $\lambda$ is an eigenvalue of $A.$
$\det(I + tA) = (1 + t\lambda_1)(1 + \lambda_2)\cdots = 1 + t(\lambda_1 + \lambda_2+\cdots) + \cdots = 1 + \operatorname{trace}(A) t + \cdots$
therefore, the derivative of $\det(I + tA)$ at $t = 0$ is the $\operatorname{trace}(A).$
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular: update scope with async AJAX data from a factory
What's the recommended way to do this?
1.
factory.updater = function(varObjToBeUpdated){
$http.post('/url', {})
.success(function(data){
for (data_field in data)
varObjToBeUpdated[data_field] = data[data_field];
});
}
...
myFactory.updater($scope.varObjToBeUpdated);
Or 2.,
myFactory.updater().success(function(data, ..){
$scope.varObjToBeUpdated = data;
});
...
factory.updater = function(){
return $http.post('/url', {});
}
Is it ok to to pass a reference scope variable to a factory? I always thought factories as delivering data.
And what's wrong with the second method (if it's less acceptable)?
A:
I prefer the second approach, as this allows you to just inject the service when you need it across multiple controllers. Use .then to continue the promise pattern:
myFactory.updater().then(function(data, ..){
$scope.varObjToBeUpdated = data;
});
app.factory('myFactor', function($http) {
return {
updater: function() {
return $http({'/url',}).then(function(result) {
return result.data;
});
}
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Python qgis script
How to get the path of points?
Because I want to open it using this code:
lyr = QgsVectorLayer(path,"YXC","ogr")
A:
Just call the name of your layer parameter (in your case, points):
lyr = QgsVectorLayer(points, "YXC", "ogr")
| {
"pile_set_name": "StackExchange"
} |
Q:
"tail -f" makes disk full?
our application server (sunOS) always gets disk full. and our Infrastructure team said it's caused by too many "tail -f" processes. Because the app rotates log file frequently, it caused the dead link and no disk space?
I've never heard of this before. does that command really cause disk full?
A:
The space a file occupies cannot be reclaimed until all references to that file are gone. Therefore, any process that has the file open will prevent the file from being deleted from the disk.
An active tail -f following the file, for example.
If these files need to be deleted to free disk space (e.g. because they are very big, or there are very many of them), then having processes lying around that hold references to them will prevent their deletion, and eventually lead to the disk filling up.
Edit in response to the comment on the other answer:
The diagnostics you report are exactly what you would expect to see in the situation that Adam and I describe. df reports that 56G of disk are in use, and du reports that only 10G are visible in the folder. The discrepancy is because there are 46G worth of files that have been removed from the folder, but cannot be physically removed from disk because some processes are holding a references to them.
It's easy enough to experiment with this yourself: find a filesystem it's safe to play with, and create a humongous file. Write a C program that opens the file and goes into an infinite loop. Now, do the following:
Start the program
Check the output of df
rm the file
Check the output of df again
Stop your program
Check the output of df again
You will see that the output of df doesn't change after rming the file, but does change once you stop the program (thus removing the last reference to the file).
If you need even more evidence that this is what's going on, you may be able to get information from the /proc filesystem, if you have it. Specifically, find the PID of one of the tail -f processes (or other processes you think might be the cause), and look at the directory /proc/<pid>/fd to see all of the files it has open.
(I don't have *nix at home, so I can't actually check to see just what you'll see /proc/<pid>/fd in this situation)
| {
"pile_set_name": "StackExchange"
} |
Q:
Hook Rails Engine into global layout
I'm currently writing a modular rails app where every functionality is inside a rails engine. I've set up my first engine and everything's working fine so far. now I'm wondering what is the best way to hook the engine into my global navigation that is currently rendered in app/views/layouts/application.html.haml, like this:
%nav#main-nav
%ul
%li
= link_to "Users", users_path, :class => "no-submenu settings"
%ul
%li ...
The closest thing I found was the HookListener of spree, which uses the deface gem. unfortunately deface only works with html/erb output since it parses the DOM with nokogiri, which isn't the best idea anyway.
A:
for the record, i've solved it like this:
move the base app to an engine/gem as well to make it easily require'able
add a Navigation class
register into this class from MyEngine
core/lib/navigation.rb:
class Navigation
@registered_blocks = {}
class << self
def register(name, &block)
@registered_blocks[name] ||= block
end
def bind(root)
@registered_blocks.each do |name, block|
block.call(root)
end
end
end
end
myext/lib/myext/engine.rb:
Navigation.register :myext do |root|
root.item :mylink, "My Link", "/"
end
config/navigation.rb (for simple-navigation):
navigation.items do |root|
Navigation.bind(root)
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this random() distribution look asymmetric?
Edit: This is using Google Chrome 36
I was messing around with html5 canvas, generating points randomly distributed inside a cube and projecting that onto a 2D canvas. Surprisingly, the results don't look very symmetric at all, and I suspect that Javascript's Math.random() is letting me down.
Can anyone tell me why this is happening? Is it possible to make it actually look random, without making it slower?
var ctx = canvas.getContext('2d');
for (var i = 0; i < 10000000; i++) {
var x = Math.random()*2-1, y = Math.random()*2-1, z = 2+Math.random()*2-1;
x = (.5 + .5*x/z) * canvas.width;
y = (.5 + .5*y/z) * canvas.height;
ctx.fillRect(Math.floor(x), Math.floor(y), 1, 1);
}
http://jsfiddle.net/y10tvj26/ (Takes a while to load)
A:
Chrome has a documented issue that subsequent calls to Math.random() are correlated. In your algorithm, correlated values will tend to fall on a line on the canvas. An extra call to Math.random() breaks that correlation. I haven't seen reports that other browsers are affected.
Just call Math.random() an extra time on each call, and you'll get what you want.
var ctx = canvas.getContext('2d');
function r() {
Math.random();
return Math.random();
}
for (var i=0; i<10000000; i++) {
var x = r()*2-1, y = r()*2-1, z = 2+r()*2-1;
x = (.5 + .5*(x/z)) * canvas.width;
y = (.5 + .5*(y/z)) * canvas.height;
ctx.fillRect(x, y, 1, 1);
}
Updated on: http://jsfiddle.net/y10tvj26/5/
| {
"pile_set_name": "StackExchange"
} |
Q:
Path file I send with => Send to C# script
I have a console script working so fine...but I made a GUI for that script and now I don't know how can I get the full path for that file I send?
I get only this one: Environment.GetCommandLineArgs()[0] but I get the folder from the script source.
It's a small WPF app but I'm stuck right now. (I searched a lot on google and I don't find anything good)
Here's the XAML:
<Window x:Class="Download_subtitles_GUI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Download_subtitles_GUI"
mc:Ignorable="d"
ResizeMode="NoResize"
Title="Download subtitles" Height="129" Width="525">
<Grid>
<TextBlock x:Name="TextBlock1" Margin="10,10,10,0" TextWrapping="Wrap" Text="" FontSize="14" Height="20" VerticalAlignment="Top"/>
<TextBlock x:Name="TextBlock2" Margin="10,30,10,0" TextWrapping="Wrap" Text="" FontSize="14" Height="20" VerticalAlignment="Top"/>
<TextBlock x:Name="TextBlock3" Margin="10,60,10,0" TextWrapping="Wrap" Text="" FontSize="14" Height="20" VerticalAlignment="Top"/>
</Grid>
namespace Download_subtitles_GUI
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TextBlock1.Text = Environment.GetCommandLineArgs()[0];
}
}
}
Thank you.
A:
If I understand you correctly, what you need is:
TextBlock1.Text = string.Join(" ", Environment.GetCommandLineArgs().Skip(1));
| {
"pile_set_name": "StackExchange"
} |
Q:
In iPhone App How to change fontstyle throughout the App?
In iPhone App I want to change the fontstyle throughout ( in whole App) the App
so is there any quicker way of doing that. suppose I want display all font in style "impact" ,
How can I set fontstyle "impact" throughout the app ?
Please Help and Suggest.
A:
The SDK does not allow you to change font settings on an application-wide basis. If you want to change the default font, you have to do it on a per-object basis.
Also, are you sure that this is a good idea? Changing the default font to "Impact" might not have the "impact" you're looking for...
| {
"pile_set_name": "StackExchange"
} |
Q:
NSIS file downloader
I need NSIS script witch download file from the internet and execute it.
I've read many examples but I still don't understand how to do it. For example
NSISdl::download http://www.domain.com/file localfile.exe
Pop $R0 ;Get the return value
StrCmp $R0 "success" +3
MessageBox MB_OK "Download Failed: $R0"
Quit
$R0 contains information about installation process ("cancel" or "success"). But I don't understand what the "localfile.exe" is?
In what part of program I need write this code(section or function)?
A:
localfile.exe is the path on the local system where you want to save the content you are downloading:
!include LogicLib.nsh
Section
NSISdl::download "http://cdn.sstatic.net/stackoverflow/img/sprites.png" "$pluginsdir\image.png"
Pop $0
${If} $0 == "success"
ExecShell "" '"$pluginsdir\image.png"' ;Open image in default application
${Else}
MessageBox mb_iconstop "Error: $0" ;Show cancel/error message
${EndIf}
SectionEnd
| {
"pile_set_name": "StackExchange"
} |
Q:
Create CSV from text file and define fields
I would like to take a text document with spaces between the text and create a CSV file using defined fields. I have searched a bit and not found a way to do this yet. I see a lot of examples handling well defined fields delims but not one that is arbitrary as the following.
Input file:
1001 Mitch, Bucanon NO NO Baywatch, TV
1002 SPARE SPARE SPARE NO NO SPARE
1003 Sparrow, Jack NO YES Pirates, carrb 2
Desired output:
"1001","Mitch, Bucanon","NO","NO","Baywatch,TV"
"1002","SPARE SPARE SPARE","NO","NO","SPARE"
"1003","Sparrow, Jack","NO","YES","Pirates, Carrib 2"
A:
It's fixed width, so you need the positions. So, here's an example:
$arr = @()
$arr += "1001 Mitch, Bucanon NO NO Baywatch, TV"
$arr += "1002 SPARE SPARE SPARE NO NO SPARE"
$arr += "1003 Sparrow, Jack NO YES Pirates, carrb 2"
foreach($item in $arr)
{
$code = $item.SubString(0,4);
$name = $item.SubString(5, 40).Trim();
$bin1 = $item.SubString(45, 6).Trim();
$bin2 = $item.SubString(51, 6).Trim();
$column5 = $item.SubString(57).Trim();
write-host ($code + ",""" + $name.Trim() + """,""" + $bin1 + """,""" + $bin2 + """,""" + $column5 + """")
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Alert 30 days before expiry date in C# Windows Forms application using SQL Server
I am working on a C# Windows Forms project in which I have one form with the following fields
Item_ID, Item_Manufacture_Date, Item_Expiry_Date, Price
I am saving this into a SQL Server table Item with following columns:
CREATE TABLE [dbo].[Medicine]
(
[Item_Code] [nvarchar](50) NULL,
[Item_Manufacture_Date] [date] NULL,
[Item_Expiry_Date] [date] NULL,
[Price] [nvarchar](50) NULL
) ON [PRIMARY]
It is saving properly now and I am displaying all this in datagridview as below respectively.
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " Select * from Medicine";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
I want to display item 30 days before or some days before its expiry date. By comparing comparing with current date.
For example I want to display those items on 17-01-2018 which will expire on or before 17-02-2018. For that I tried this query, I know this query is wrong please correct me so that I can see those item which will expire in coming 30 days.
select
Item_Code, ExpiryDate
from
Medicine
where
Date <= GETDATE() - interval 30 day
Please help Thank you all.
A:
You can use DATEADD
https://docs.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql
It will look something like
SELECT Item_Code, ExpiryDate FROM Medicine WHERE ExpiryDate BETWEEN DATEADD(DAY,-30,GETDATE()) and GETDATE()
| {
"pile_set_name": "StackExchange"
} |
Q:
Database management tool for handling many-to-many relationships?
Presently we're using phpMyAdmin for a project which has been working well enough, but as I've been normalizing the database and adding some many-to-many tables it's becoming quite painful to enter this data. I've had to either open multiple windows or print the tables out so that I could see all their IDs so I could figure out what needs to be linked to what.
I know Django's admin site does a really good job of this, and they've got a pretty sweet widget for entering many-to-many data without having to punch in IDs, but we're working in PHP, and I've got hundreds of tables to worth with. I don't think I can spare the time to write models for all of these in Python, especially not with how rapidly they change.
(source: googlecode.com)
Is there a tool that, with minimal effort, I can tell it which fields are FKs to which tables, and perhaps which fields should be used as display values, and then from there it can generate a GUI for entering data?
A:
MySQL Workbench. It's like PHPMyAdmin on roids. It's comparable to SQL Server Management Studio.
http://wb.mysql.com/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to partly update a database record?
I am struggling to implement a simple 'update profile' functionality(learning purposes). I simply want to be able not to update the profile image everytime I update a give profile. When the picture is there and some other part of the profile is update I want the picture to stay the same.
I came up with the following code for this :
Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "UserDetailsId,ImageData,FirstName,LastName,UserAddress,UserCountry,UserPostalCode,UserPhoneNumber,CompanyId,identtyUserId")] UserDetails userDetails, HttpPostedFileBase UploadImage)
{
if (ModelState.IsValid)
{
if (UploadImage!=null) {
byte[] buf = new byte[UploadImage.ContentLength];
UploadImage.InputStream.Read(buf, 0, buf.Length);
userDetails.ImageData = buf;
}
else {
var userFromDb = db.UsersDetails.Where(u => u.identtyUserId == userDetails.identtyUserId).First();//i am getting the old user data
userDetails.ImageData = userFromDb.ImageData; //saving the image to the modified state
}
db.Entry(userDetails).State = EntityState.Modified;//error here
db.SaveChanges();
return RedirectToAction("Index");
}
//ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName", userDetails.CompanyId);
return View(userDetails);
The error I am getting on this row db.Entry(userDetails).State = EntityState.Modified; is the following :
Attaching an entity of type 'eksp.Models.UserDetails' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
The model :
public class UserDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserDetailsId { get; set; }
public byte[] ImageData { get; set; }
[NotMapped]
public HttpPostedFileBase UploadImage { get; set; }
[NotMapped]
public string ImageBase64 => System.Convert.ToBase64String(ImageData);
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserPhoneNumber { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
public string identtyUserId { get; set; }
public virtual ICollection<WorkRolesUsersDetails> WorkRolesUsersDetails { get; set; }
Although it may looke pretty self explenatory for me it is not clear this is happening?
Can somebody guide me how to achieve what I want to achieve?
Thanks!
A:
When you update an entity, you should map the posted values onto an instance pulled from the database, rather than trying to directly save the instance created from the post data. This is yet another reason to avoid using Bind as it confuses the issue and makes developers who don't know better think it's okay to directly save the entity created from the post data. It's not, and never is.
Instead, use something like UserDetailsId to lookup the entity:
var userDetails = db.UserDetails.Find(model.UserDetailsId);
Where model is the parameter from your action. Then, you can map over the posted values onto your entity:
userDetails.FirstName = model.FirstName;
// etc.
Finally, save usersDetails, which is now the version from the database, with all the original data on the entity, modified to the posted data, where appropriate.
Now, given that you need to do this mapping over of the posted data anyways, go a step further can create a view model with just the properties you need to allow the user to modify. You can then post to that, instead of using Bind. Really, Bind is just awful. It's one of those things Microsoft hastily adds because they think it solves one problem, and it actually ends up causing ten other problems.
A:
You can retrieve data entity from the db in any case and update it with the details coming as part of the Post Model and Save that data entity back to the db.
var userFromDb = db.UsersDetails.Where(u => u.identtyUserId == userDetails.identtyUserId).First();
if (UploadImage!=null)
{
byte[] buf = new byte[UploadImage.ContentLength];
UploadImage.InputStream.Read(buf, 0, buf.Length);
userFromDb.ImageData = buf;
}
userFromDb.FirstName = userDetails.FirstName;
userFromDb.LastName = userDetails.LastName;
userFromDb.UserAddress = userDetails.UserAddress;
userFromDb.UserCountry = userDetails.UserCountry;
userFromDb.UserPostalCode = userDetails.UserPostalCode;
userFromDb.UserPhoneNumber = userDetails.PhoneNumber;
userFromDb.CompanyId = userDetails.CompanyId;
db.SaveChanges();
This should help you to achieve the feature you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
php include and closing tag
Saw a thread about omitting the closing ?> in PHP scripts and got me wondering.
Take this code:
foo.php
<?php
echo 'This is foo.php';
include('bar.php');
bar.php
<?php
echo 'This is bar.php';
If you create these two scripts and run them, php outputs:
This is foo.php
This is bar.php
(new line added for artistic license before anyone points that out)
So, how come:
baz.php
<?php
echo 'This is foo.php';
<?php
echo 'This is bar.php';
results in a predictable syntax error unexpected '<', when "include" does just that - or rather, my understanding of include is that PHP just dumps the file at that point as if it had always been there.
Does PHP check for opening tags and ignore future ones if the file is included? Why not do this when there are two sets of tags in one script?
Thanks for any clarification. Not exactly an important issue but would be nice to understand PHP a little more.
A:
If you include a file, PHP internally switches from parsing to literal mode (i.e. what it normally does on a closing tag. That's why this works:
<?php
include 'foo.php';
?>
//foo.php
<?php
echo 'yo';
?>
Even though when inlined it would become
<?php
<?php
echo 'yo';
?>
?>
Because interally it's transformed into something like this (for illustrative purposes, in reality it probably doesn't actually merge the contents of the files, it just jumps between them)
<?php
?>
<?php
echo 'yo';
?>
<?php
?>
You can omit the closing ?> because at the end of the include file, PHP switches back to parsing the including file, regardles of what mode it's currently in.
| {
"pile_set_name": "StackExchange"
} |
Q:
Zend_PDF drawImage turns images black
I used Zend_PDF's drawImage to draw images in a pdf. I check the images for aspect ratio since they are either horizontal or vertical. And then draw them into my PDF. All horizontal images turn out well. All vertical images turn black, but some not completely. It seems like colors are inverted. You can still see some parts of the image. The jpeg's all look good to me.
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
$orientation = $this->checkAspect($imageFullPath);
$image = Zend_Pdf_Image::imageWithPath($imageFullPath);
if($orientation == 'vertical') {
$imgWidth = 475;
$imgHeight = 672; // DINA4 shrinked to 475 width
$x = 68; // margin left
$y = 130; // start bottom
$page->drawImage($image, $x, $y, $x + $imgWidth, $y + $imgHeight);
} else {
$imgWidth = 500;
$imgHeight = 330;
$x = 68; // margin left
$y = 450; // start bottom
$page->drawImage($image, $x, $y, $x + $imgWidth, $y + $imgHeight);
}
I just don't get what I'm doing wrong...
Regards
A:
Actually the answer was simple. It had nothing to do with the images beeing vertical or horizontal but rather with colorspace. The vertical images, for some reason are all in CMYK and the horizontal images RGB.
Converted all images and now everything is fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cancelling a thread using pthread_cancel : good practice or bad
I have a C++ program on Linux (CentOS 5.3) spawning multiple threads which are in an infinite loop to perform a job and sleep for certain minutes.
Now I have to cancel the running threads in case a new configuration notification comes in and freshly start new set of threads, for which i have used pthread_cancel.
What I observed was, the threads were not getting stopped even after receiving cancel indication,even some sleeping threads were coming up after the sleep was completed.
As the behavior was not desired, usage of pthread_cancel in the mentioned scenario raises question about being good or bad practice.
Please comment on the pthread_cancel usage in above mentioned scenario.
A:
In general thread cancellation is not a really good idea. It is better, whenever possible, to have a shared flag, that is used by the threads to break out of the loop. That way, you will let the threads perform any cleanup they might need to do before actually exiting.
On the issue of the threads not actually cancelling, the POSIX specification determines a set of cancellation points ( man 7 pthreads ). Threads can be cancelled only at those points. If your infinite loop does not contain a cancellation point you can add one by calling pthread_testcancel. If pthread_cancel has been called, then it will be acted upon at this point.
A:
If you are writing exception safe C++ code (see http://www.boost.org/community/exception_safety.html) than your code is naturally ready for thread cancellation. glibs throws C++ exception on thread cancel, so that your destructors can do the appropriate clean-up.
| {
"pile_set_name": "StackExchange"
} |
Q:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:
Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")
Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")
Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")
Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")
Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")
Anybody has any good wishes?
Mod edit: Stanislav Malyshev is a core PHP developer.
A:
I wouldn't mind named parameters.
getData(0, 10, filter => NULL, cache => true, removeDups => true);
// instead of:
getData(0, 10, NULL, true, true);
// or how about:
img(src => 'blah.jpg', alt => 'an albino platypus', title => 'Yowza!');
Unfortunately the PHP devs shot that idea down already.
A:
More dereferencing:
echo something_that_returns_array()[4];
Others have mentioned named parameters, and shorter array syntax. I wouldn't mind shorter object syntax, as well.
$a1 = array(1, 2, 3, 4);
$a2 = [1, 2, 3, 4];
$b1 = (object)array('name' => 'foo');
$b2 = {'name' => 'foo'}; // or something?
A:
After working with PHP for about 13 years, and heavily with JS for about 4, there are a couple things I think PHP would do well to borrow from JS:
1) shorthand notation for Arrays and Objects. I believe this may have been discussed and shot down on Internals (so I hear – I don't like to see how the sausage is made), but I really, really find that the literal notation for arrays and objects in JS is a big productivity win.
For example:
$arr = [1,2,3,4];
$assoc = [foo=>'bar', baz=>'boo'];
$stdobj = {foo->'bar', baz->'boo'};
Is (IMHO) just much easier to write and cleaner than
$arr = array(1,2,3,4); // not too bad
$assoc = array("foo"=>'bar', baz=>'boo'); // not too bad either
$stdobj = new stdClass; // this gets pretty rough
$stdobj->foo = 'bar';
$stdobj->baz = 'boo';
I've heard that some concern about potential confusion was raised, but really, is this any more confusing than, say, heredoc notation? At very least, making a stdClass object in PHP is verbose enough to discourage the practice, I think.
2) Being able to redefine previously-defined functions and methods would be really useful. It would particular simplify situations extending a class and instantiating the new class is either overly complex or impractical. I do think we should avoid redefinition of core/non-userspace functions and methods, though.
In addition to those two, I think PHP must transparently support unicode. This is becoming more and more of a problem for developers, and the solutions currently offered in PHP are confusing and frequently non-performant. Making all standard string functionality unicode-friendly out of the box would be a massive win for PHP programmers.
Thanks for asking!
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery Alternative to DOMSubtreeModified
I have the following Javascript/Jquery code:
<script type="text/javascript">
function ChangeMathOnPage() {
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
$('.markdownx-preview').each(function(){
$(this).on('DOMSubtreeModified', ChangeMathOnPage);
});
</script>
This does my job. However, as explained here, use of
DOMSubtreeModified is deprecated.
To somebody new to Javascript/Jquery world, please explain ways to convert same logic into non-deprecated code.
A:
Try this:
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
Source: MDN: MutationObserver
| {
"pile_set_name": "StackExchange"
} |
Q:
Property-like structure in a model category
In a model category, I have tools to show that mapping spaces are contractible. But if I want to show a mapping space is empty or contractible, is there anything I can do on general grounds?
The idea is this. Suppose I have a type of structure I'm interested in, and a collection of objects. To each object I assign a space parameterizing the choices required to equip that object with the structure in question. If all these parameter spaces are empty-or-contractible, that means the structure is "property-like": an object either has the structure or it doesn't; it can't carry different versions of the same structure. If the parameter spaces are all contractible, this means that in fact every object carries a unique version of the structure. Let me illustrate with an example of each.
A contractible space of choices: property-like structures that always exist. For example, in Joyal's model structure for quasicategories, suppose I want to show that the space of composites of two composable morphisms in a quasicategory $X$ is always contractible. This reduces to showing that the horn inclusion $\Lambda^1[2] \to \Delta[2]$ is an acyclic cofibration (since this implies that the fibers of $X^{\Delta[2]} \to X^{\Lambda^1[2]}$ are contractible).
Of course, this is immediate from typical descriptions of the model structure, but more generally I should consider myself lucky if all I have to do to answer a question is show that one explicit map is an acyclic cofibration, since I can work with explicit generators to make this a matter of combinatorics. (There's an asterisk in this case because in this model structure really I only know how to understand anodyne extensions combinatorially and not acyclic cofibrations in general, but in practice this understanding usually suffices.)
An empty-or-contractible space of choices: property-like structures that don't always exist. But now, again working in the Joyal model structure, suppose I want to show that the space of retracts of a given idempotent in a quasicategory is always either empty or contractible. This doesn't reduce to showing that the inclusion of the free idempotent into the free retract is an acyclic cofibration, because that would be too strong -- it would imply that every idempotent has a retract, which is not the case.
The closest thing I can think of is to perform a Bousfield localization to force every idempotent to have a retract, and then show that this map is an acyclic cofibration in the new model structure. But this only shows that if a quasicategory has all split idempotents (and I have to check that these are exactly the fibrant objects in the localized model structure), then the space of retracts for a given idempotent is contractible -- it doesn't tell me anything about quasicategories where some but not all idempotents split.
In this particular case, Lurie shows this fact using the theory of cofinality. But this is something specific to the example, not a general approach to the understanding property-like structures, even if we restrict our attention to quasicategories.
Question: Do model categories afford some general method for understanding property-like structures on their objects/morphisms, analogous to the method of showing that certain maps are acyclic cofibrations? Or can these things only be understood on a case-by-case basis?
A:
Let us say that a map $f : X \to Y$ in an $\infty$-category is an embedding if, for every object $Z$, the map of spaces $\mathrm{Hom}(Z,X) \to \mathrm{Hom}(Z,Y)$ is an embedding (that is, has either empty or contractible fibers). It is easy to define this notion on the level of model categories. A map $f : X \to Y$ in a model category is an embedding if, for every (cofibrant) object $Z$, the map of homotopy function complexes $\mathrm{hMap}(Z,X) \to \mathrm{hMap}(Z,Y)$ is an embedding.
I believe this is all that can be said in a general model category about this notion. The reason is that embeddings in $\infty$-categories can behave very adly (just as monomorphisms in ordinary categories), so there is no reason to believe that there should be some nice general theory that allows to work with them in arbitrary model category.
If we have some specific model category in mind, then we can try to choose some nice presentation of homotopy function complexes to prove that some specific map is an embedding. For example, in the case of the Joyal model structure, there are at least two such choices. Both of them were discussed here: Homotopy function complex for quasi-categories.
Now, let's say we have a map of quasicategories $i : A \to B$ and we want to show that, for every quasicategory $X$, the map $X^B \to X^A$ is an embedding ($i$ is the inclusion of the free idempotent into the free retract in your example). This is equivalent to asking the map $\mathrm{hMap}(B,X) \to \mathrm{hMap}(A,X)$ to be an embedding. If we choose the first presentation of $\mathrm{hMap}$ in the question cited above, then this map is an embedding if and only if $X$ has the right lifting property with respect to the pushout-product of $i$ with maps $\partial \Delta'[n] \to \Delta'[n]$, $n > 0$ (we need to assume that $i$ is a cofibration for this). Here, $\Delta'[n]$ is the nerve of the groupoid $\{ 0 \simeq \ldots \simeq n \}$.
This is similar to the situation with the map $\Lambda^1[2] \to \Delta[2]$ that you mentioned, but the problem is that objects $\Delta'[n]$ are more complicated than the objects $\Delta[n]$ that we have in the latter, so it is quite hard to prove this directly. If we define $\mathrm{hMap}(X,Y)$ as the largest Kan complex contained in $Y^X$, then the combinatorics of the involved simplicial sets becomes more manageable, but even then I don't see how to prove this directly.
A:
Specifically for the case of quasi-categories (or any other model for $\infty$-categories) the following observation can be useful: suppose that $f: {\cal C} \to {\cal D}$ is a map of quasi-categories such that the induced map ${\rm Tw}(f):{\rm Tw}({\cal C}) \to {\rm Tw}({\cal D})$ on twisted arrow categories is coinitial, i.e., for every $e \in {\rm Tw}({\cal D})$ the comma category ${\rm Tw}({\cal C})_{/e}$ is weakly contractible (this is the dual property of cofinal, and implies in particular that reindexing diagrams along ${\rm Tw}(f)$ induces an equivalence on limits, rather than colimits). Then for any quasi-category ${\cal E}$ the induced map on functor categories ${\rm Fun}({\cal D},{\cal E}) \to {\rm Fun}({\cal D},{\cal E})$ is fully-faithful (and in particular, the induced map on functor spaces is an embedding). To see this, use the fact that if $g,h: {\cal D} \to {\cal E}$ are two functors then the space of natural transformations from $g$ to $h$ can be written as a limit on the twisted arrow category:
$$ {\rm Map}_{{\rm Fun}({\cal D},{\cal E})}(g,h) \simeq {\rm lim}_{x \to y \in {\rm Tw}({\cal D})} {\rm Map}_{\cal E}(g(x),h(y)) $$
The coinitiality of ${\rm Tw}(f)$ now implies that ${\rm Map}_{{\rm Fun}({\cal D},{\cal E})}(g,h) \stackrel{\simeq}{\to} {\rm Map}_{{\rm Fun}({\cal C},{\cal E})}(g \circ f,h \circ f)$ is an equivalence.
Examples:
1) The map $\Delta^1 \to J$ from the walking arrow to the walking isomorphism induces a coinitial map on twisted arrow categories (this is because ${\rm Tw}(J) \simeq J \simeq \ast$ and ${\rm Tw}(\Delta^1)$ has a contractible geometric realization). This reflect the (simple, but important) fact that an arrow being an equivalence is a property.
2) Consider the map ${\rm Idem} \to {\rm Ret}$ from the free idempotent to the free retract (so that ${\rm Idem}$ has a single object equipped with an idempotent self map and ${\rm Ret}$ has two objects which sit in a retract diagram). Then one can show that the map ${\rm Tw}({\rm Idem}) \to {\rm Tw}({\rm Ret})$ is coinitial (this is a bit more tedious, but can still be done completely by hand: ${\rm Tw}({\rm Idem})$ has two objects, ${\rm Tw}({\rm Ret})$ has five). This reflects the fact you mentioned that a splitting of an idempotent is a property.
| {
"pile_set_name": "StackExchange"
} |
Q:
Return dictionary + CookieContainer cookies from task
I have some code That Runs a Task to return a dictionary ... but sometimes i need it to return both the dictionary and a cookiecontainer with cookies ... here's the code
static public async Task<Dictionary<String,String>> login(string server, string id, string pw)
{
CookieContainer cookies = new CookieContainer();
HttpWebRequest newRequest = GetNewRequest(server, cookies);
Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
dictionary2.Add("name", id);
dictionary2.Add("password", pw);
dictionary2.Add("uni_url", server);
Dictionary<string, string> parameters = dictionary2;
HttpWebResponse response = await MakeRequest(newRequest, cookies, "login", server, parameters);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
if (!reader.EndOfStream)
{
Dictionary<String, String> answer = new Dictionary<string, string>();
answer.Add("HTML", reader.ReadToEnd());
return answer;// here i need it to return CookieContainer .
}
}
Dictionary<String, String> answerFailed = new Dictionary<string, string>();
answerFailed.Add("LoginFailed", "LoginFailed! No Internet Connection!");
return answerFailed;
}
my question : How do I return two different things from the same method?
A:
If you can change method you can use Tuple<T1,T2> To return two values from task:
static public async Task<Tuple<Dictionary<String,String>,CookieContainer>> login(string server, string id, string pw)
{
CookieContainer cookies = new CookieContainer();
Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
// create result tuple
var result = Touple.create(dictionary2,cookies);
return result;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the critical mass of a rocky planet before its gravity traps enough gas in its atmosphere to start becoming a gassy planet
Looking at the latest theories, I've noticed that most rocky planets are below a certain mass range. I speculate that maybe the way gas giants and gas dwarfs form is a rocky planet during the planetary formation phase of its history accumulates enough mass to begin gaining a hydrogen atmosphere that keeps building until it's no longer a rocky planet.
What would be the critical mass of a rocky planet before it would start down the path of becoming a gassy planet?
A:
In most planet formation theories, the boundary is around 10 Earth masses - the build up of the core mass before that is relatively slow, but once it crosses that threshold, the planet gains mass quickly via attracting gas from the surrounding nebula via the core’s gravitational pull, a process called “runaway accretion.” As this summary shows, you can still end up with some planets in between.
One interesting result that has emerged from recent studies of exoplanets is that small planets seem to be divided into two groups, those with radii around 1-1.5 Earth radii, and those with radii of ~ 2-3 Earth radii, but with a gap in between where there are few planets:
The current theory explaining this is that the larger group of planets managed to accrete some atmosphere, while the smaller group are bare, rocky worlds with little or no atmosphere.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing JSON array in swift
I am trying to parse the following JSON
[
{
"id": "5",
"name": "Test",
"team1": "thingy team",
"team2": "clicky team",
"category": "4",
"end_date": "1415217600",
"cat_name": "new thingy",
"team1_bets": 1,
"team2_bets": 1
}
]
This is the JSON I am getting from my web services, and I am using the following code to parse it:
let urlAsString = "http://codespikestudios.com/betting_app/bet/get_events/4"
//let urlAsString = "http://api.topcoder.com/v2/challenges?pageSize=2"
let url: NSURL = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
println(jsonTime)
})
jsonQuery.resume()
I am getting the following error
The operation couldn’t be completed. (NSURLErrorDomain error -1005.)
fatal error: unexpectedly found nil while unwrapping an Optional value
how can I solve this?
A:
Your URL is returning the following JSON -
[
{
"id": "5",
"name": "Test",
"team1": "thingy team",
"team2": "clicky team",
"category": "4",
"end_date": "1415217600",
"cat_name": "new thingy",
"team1_bets": 1,
"team2_bets": 1
}
]
The outermost square brackets indicate that the root object is an array, so attempting to cast the result of your JSON parse to an NSDictionary causes problems.
Your code should be -
let urlAsString = "http://codespikestudios.com/betting_app/bet/get_events/4"
let url: NSURL = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSArray?
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
println(jsonResult!)
})
jsonQuery.resume()
| {
"pile_set_name": "StackExchange"
} |
Q:
How find this $\int_{0}^{\pi}\frac{\cos{(nx)}}{\cos{x}+a}dx$
Fin the integral
$$I_{n}=\int_{0}^{\pi}\dfrac{\cos{(nx)}}{\cos{x}+a}dx$$
where $n\in {\mathbb N}\,,\ a>1$
My try:
let
$$I_{n}-I_{n-1}=\int_{0}^{\pi}\dfrac{\cos{(nx)}-\cos{(n-1)x}}{\cos{x}+a}dx$$
and note
$$\cos{x}-\cos{y}=-2\sin{\dfrac{x+y}{2}}\sin{\dfrac{x-y}{2}}$$
so
$$I_{n}-I_{n-1}=-2\int_{0}^{\pi}\dfrac{\sin{(nx-\dfrac{x}{2})}\sin{\dfrac{x}{2}}}{\cos{x}+a}dx$$
Then I can't ,Thank you for your help.
A:
A little complex analysis helps. First, by the evenness of $\cos$, we have
$$I_n = \frac12 \int_{-\pi}^\pi \frac{\cos (nx)}{a+\cos x}\,dx,$$
and by Euler's formula, we have $\cos (nx) = \operatorname{Re} e^{inx}$, so
$$I_n = \frac12 \operatorname{Re} \int_{-\pi}^\pi \frac{e^{inx}}{a+\cos x}\,dx.$$
Since the imaginary part is odd, the integral is real, and we can omit the $\operatorname{Re}$.
Now we write $z = e^{ix}$, then we have
$$\cos x = \frac12(z+z^{-1});\quad e^{inx} = z^n;\quad dx = \frac{dz}{iz};$$
so we obtain
$$I_n = \int_{\lvert z\rvert = 1} \frac{z^n}{2a + z + z^{-1}}\, \frac{dz}{iz} = 2\pi\cdot\frac{1}{2\pi i}\int_{\lvert z\rvert = 1} \frac{z^n}{z^2 + 2az + 1}\,dz.$$
We need the zeros of the denominator $z^2 + 2az + 1 = (z+a-\sqrt{a^2-1})(z+a+\sqrt{a^2-1})$ to apply the Cauchy integral formula. Of the zeros, $-a+\sqrt{a^2-1}$ lies inside the unit disk, and $-a-\sqrt{a^2-1}$ outside the closed unit disk. With $f(z) = \frac{z^n}{z+a+\sqrt{a^2-1}}$, the Cauchy integral formula yields
$$\begin{align}
I_n &= 2\pi\cdot\frac{1}{2\pi i}\int_{\lvert z\rvert = 1} \frac{f(z)}{z+a-\sqrt{a^2-1}}\,dz\\
&= 2\pi\cdot f(-a+\sqrt{a^2-1})\\
&= \frac{\pi}{\sqrt{a^2-1}}(\sqrt{a^2-1}-a)^n.\tag{1}
\end{align}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Any tips to learn how to program with severe ADHD?
I have a difficult time trying to learn how to program from straight text-books. Video training seems to work well for me in my past experiences with PHP. I am trying my hardest to stay focussed and push through. Specifically I am looking to start indie game development.
Over the last two weeks I have been trying to pick the "right" language and framework to develop with. I started going through Python, but I am not really enjoying the language so far. I am constantly looking through this website to compare this language to that, and keep getting distracted.
Aside from all of this, is it possible to become a programmer when you have trouble focussing? Has anyone been through this that can recommend some advice?
A:
Commit to a language and framework. Once you have made that commitment, forsake all others. Be faithful to that one language and framework, at least for awhile. Then...
Pick one thing to code, and work on that. Focus on coding that only. Get it done, quickly. Then work on the next thing. If you find yourself getting bogged down in a task, break it down into smaller pieces and work on each one individually.
If you can control your focus, you will find that you have better productivity than your non-ADHD peers. That is the great paradox of ADHD; once you are focused, you are hyper-focused.
Do things quickly; stay in that zone. But concentrate on one thing at a time. That is the secret.
A:
I was diagnosed (at around age 9) with ADD. That was 26 years ago and "ADHD" seems to be the more prominent diagnosis these days.
You've probably found two things to be quite true:
It is very difficult for you to become engrossed in something that you don't find stimulating
It is very difficult for you to disengage from something that you DO find stimulating
Modern medicine wants us to take all kinds of stimulants (It's amazing what any hydrochloride will do to boost attention span), but I discontinued Ritalin (and others) within a year of starting them. The side effects on my mood, sleep cycle and the few social skills that I had was just too much to deal with.
This means, your criteria should be "What grabs me?" vs "What does everyone else think the right tool would be?".
Additionally, I think you might be ignoring some low hanging and language agnostic fruit. Have you come up with an idea for a game? Have you thought of how (in meta terms) the mechanics of it might be implemented? From my own experience, I find it much easier to conduct research when the criteria is quite narrow. Finding the solution to a specific problem is much easier than tackling a question that almost always entails answers that start with "that depends".
I also agree with others. Stay off this site for a while. What you are doing now is trying to convince yourself that you are working to a solution by soliciting advice. You are basically trying to study in an amusement park; that isn't going to work.
Incidentally, have you looked at C or C++ with Lua?
A:
I was diagnosed very late with ADHD. As such I wondered all my life why it was so hard to concentrate and why I failed so often to deliver a project till the end.
One of the best thing that ever happened to me was to firstly know what my problem was, and secondly gain access to medication that helps alleviate the symptoms.
I use the medication and cannot work without it. It is not a panacea and I have to fight every day to shed the bad habits the condition distilled in me but slowly I get by and it becomes easier and easier to deliver. I have not failed once since I started medication and promised I would not ever again.
My best ally, besides the medication, is routine. here are some pointers that have helped me, I hope you find them helpful as well.
Regulate sleeping habits, lack of sleep can completely counter the effect of the medication.
Regulate eating habits. Make your meals a regular thing in your day. Hunger also will cancel the benefits of meds.
TAKE YOUR MEDS this is the single thing that still allows me to not only keep a job but be good at it. There are many alternatives, plain Ritalin can make it difficult to get a good balance as you go from peak do down many times a day. I found each pill only gave me a 30 minutes window of real productive attention and then degraded over the next 4 hours. I switched to long lasting pills, single daily dose, I found the side effects to be much more bearable and gave me a good 4-6 hours of productive attention. If the one you have does not fit you, talk to your doctor, he will have alternatives. I have tried alternatives but nothing really equates to the real thing.
Take control over your body and of your experiences. you are the one stuck with a miss wired brain (or whatever the root cause of it). It is ultimately your responsibility to do what needs to be done. If you feel your doctor is not proactive enough most likely you are not pushing him enough. Take notes, when is it more difficult. When is it easier, when you took medicine, how much you slept, when and what you had for lunch etc. You do not have to do this all your life but at least until you have stabilized your condition in a satisfactory way.
Keep it to yourself. This one is hard because it is counter intuitive. The goal is not that you should not share your experience, neither that you should hide it. However there is still a strong stigma even in the medical community that ADHD is not a real problem but is either abused to gain the drugs or just another name for being lazy. Publishing it at large could create a negative impression that will drag you down. It is hard enough as it is no need to add to it unless absolutely necessary. also, this perhaps applies more to me, but I found that if I told people about it and whatever I was doing did not go well it provided an easy way to escape the situation. Keeping it from others put me on equal footing and pressured myself to deliver. My friends and loved ones all know about it, they knew before I did in some cases, but my co-workers it's none of their business. I am most likely exposing by answering you here but then again this is why I use an alias.
Talk to others in the same situation. We all live with it differently but maybe someone found a mean to cope you had not though of. These exchanges will help you a lot if you put interest in it.
Quit drinking coffee (or any form of caffeine for that matter). Caffeine is insidious as it first give you a boost of energy and attention but the effects fade away rapidly. Basically you will have the same patterns as taking normal ritalin, except caffeine will cause addiction. Over the long term, when taken regularly, Caffeine will not longer provide an extra boost but only give you what you would normally would be. If I can make a parallel Caffeine will substitute your normal levels, thus in the beginning your body feels a boost because it adds to your natural levels, but after a while you produce less and you will need Caffeine to just be normal. Methylphenidates will not cause this addictive effect and thus will always add to your normal level. Taking both Caffeine and Ritalin will provide a boost but it will be difficult to stabilize and the ups and downs will be detrimental to your attention. I will use Caffeine for periods of two or three days when I need a temporary boost, for example to counter jet-lag, in other words I use it so that I can get back to normal routine as fast as possible, but otherwise I stay off it.
Some proposed to stick to a single framework and-or language. If you are just starting then yes, though this is good advice to anyone that wish to learn programming. First learn one very well, then learn a second that is different paradigm (procedural vs functional vs object oriented etc). Basically it goes along the lines of first learn to walk then you can try running. Which one would be good for you depends greatly on what you want to do and how you plan to pay for your rent. this said, choose the first one because it allows you do to interesting stuff, because it will keep you seated in front. If you are lucky that language will become your means of procrastination and you will learn it very well.
Good luck, hope this helped.
| {
"pile_set_name": "StackExchange"
} |
Q:
What rate of descent would kill you?
I was watching a video where a plane an MD-82 descended 18,000 feet per minute and crashed into a mountain.
The plane was not upside down/on its side/spiraling- it had about a 5 degree pitch up the whole time.
My question is: Would this rapid descent kill you, or at least make you pass out? What is the descent rate that would simply just make you go unconscious?
A:
There is no descent rate that would directly kill you or make you pass out, the notion is nonsense from a physics standpoint. It may be possible to rupture eardrums from the pressure change in some people with pre-existing sinus and ear trouble. It would also be possible to die from the heat of air speeds over mach 2, but the exact speed depends greatly on the aircraft design and is not unique to a descent trajectory.
A:
I always thought the whole notion of falling from a great height killing you before you hit the ground as complete and utter nonsense. The old wives tale of dieing from a heart attack during the fall is just that, an old wives tale perpetuated by the frequent retelling of it. Minus any pre-existing medical conditions, it is not a sound theory.
Skydiving proves this. After all, skydivers in extreme cases can reach terminal velocities of up to 300 mph.
However, you can lose useful consciousness due to hypoxia above 20,000 feet MSL without supplemental oxygen. The higher you are (and stay), the quicker it will happen.
| {
"pile_set_name": "StackExchange"
} |
Q:
compute and sum the data from a table based on month
i would like to compute the data from a table where it consists date, and data ..there are a lot of data inside the table. example are as below:
DATE hour data1 data2
-------------------------------
01/01/2010 1 10860 1234
01/01/2010 2 10861 1234
01/01/2010 3 10862 1234
01/01/2010 4 10863 567
01/01/2010 5 10864 458
02/01/2010 1 10865 3467
02/01/2010 2 10866 7890
02/01/2010 3 10867 863
02/01/2010 4 10868 0
02/01/2010 5 10868 698
03/01/2010 1 10868 4693
03/01/2010 2 10868 7853
03/01/2010 3 10868 5987
and from above data. i would like to compute it into a table like this:
DATE sdata1 sdata2
-------------------------------
01/01/2010 54310 4727
02/01/2010 54334 12918
03/01/2010 32604 18533
the sdata1 and sdata2 are the sum of the data that computed ... is there any way for me to compute the data into above data display? thank you ... hehe ...
A:
SELECT DATE, SUM(data1) AS sdata1, SUM(data2) AS sdata2 FROM table1 GROUP BY DATE;
Try this and let me know if that is what you're looking for. You can also use the WHERE DATE BETWEEN startDate AND endDate if you needed a range.
Another trick if you wanted this data in another table to do "stuff" with, would be to:
CREATE TABLE table2 (SELECT DATE, SUM(data1) AS sdata1, SUM(data2) AS sdata2 FROM table1 GROUP BY DATE);
This will perform query above but create a new table with the results. I'm not sure why you might need that but sometimes de-normalizing and having computed information in a table for display can speed up your app.
If you have a table already then you can do the following:
INSERT INTO table2 (DATE, sdata1, sdata2) VALUES (SELECT DATE, SUM(data1) AS sdata1, SUM(data2) AS sdata2 FROM table1 GROUP BY DATE);
| {
"pile_set_name": "StackExchange"
} |
Q:
Circuitikz voltage source American style
I am having an issue with an specific element in Circuitikz, the voltage source.
When I place horizontally this element on a circuit, the (−) and (+) symbols are also rotated, but this behavior is not right, the (−) symbol turns into a awful ( | ) because of the rotation of the voltage source. The same happens to get an oblique voltage source in any rotation angle, for example, when it is rotated 45°, the (+) symbol of the voltage source looks more like a (×) and so on.
What I want to know, is possible to get NON-ROTATED polarity symbols of the voltage source, that is, independent of the voltage source rotation?
Just like the books, they have a perfect representation of an American voltage source rotated in any angle without changing the position of the polarity symbols. (I could use the European style, but these people are not used to it and they might get confused).
Thanks in advance. ☺
A:
\documentclass{article}
\usepackage{circuitikz}
%% Independent voltage source - American style
\makeatletter
\pgfcircdeclarebipole{}{\ctikzvalof{bipoles/vsourceam/height}}{vsourceAM}{\ctikzvalof{bipoles/vsourceam/height}}{\ctikzvalof{bipoles/vsourceam/width}}{
\pgfsetlinewidth{\pgfkeysvalueof{/tikz/circuitikz/bipoles/thickness}\pgfstartlinewidth}
\pgfpathellipse{\pgfpointorigin}{\pgfpoint{0}{\pgf@circ@res@up}}{\pgfpoint{\pgf@circ@res@left}{0}}
\pgfusepath{draw}
\pgfscope
\pgftransformxshift{\ctikzvalof{bipoles/vsourceam/margin}\pgf@circ@res@left}
\pgftext[rotate=-\pgf@circ@direction]{$-$}
\pgfusepath{draw}
\endpgfscope
\pgfscope
\pgftransformxshift{\ctikzvalof{bipoles/vsourceam/margin}\pgf@circ@res@right}
\pgftext[rotate=-\pgf@circ@direction]{$+$}
\pgfusepath{draw}
\endpgfscope
}
\makeatother
\begin{document}
\begin{circuitikz}[american voltages]
\ctikzset{bipoles/vsourceam/margin=.5}% default too big
\draw (0,0) to[V={v1}] (3,0) to[V={v2}] (3,3) to[V={v3}] (0,3) to[V={v4}] (0,0);
\draw (4,0) to[V={v5}] (6,2);
\end{circuitikz}
\end{document}
For a controlled voltage source you could use
%% Controlled voltage source - American
\makeatletter
\pgfcircdeclarebipole{}{\ctikzvalof{bipoles/cvsourceam/height}}{cvsourceAM}{\ctikzvalof{bipoles/cvsourceam/height}}{\ctikzvalof{bipoles/cvsourceam/width}}{
\pgfsetlinewidth{\pgfkeysvalueof{/tikz/circuitikz/bipoles/thickness}\pgfstartlinewidth}
\pgfpathmoveto{\pgfpoint{\pgf@circ@res@left}{\pgf@circ@res@zero}}
\pgfpathlineto{\pgfpoint{\pgf@circ@res@zero}{\pgf@circ@res@up}}
\pgfpathlineto{\pgfpoint{\pgf@circ@res@right}{\pgf@circ@res@zero}}
\pgfpathlineto{\pgfpoint{\pgf@circ@res@zero}{\pgf@circ@res@down}}
\pgfpathlineto{\pgfpoint{\pgf@circ@res@left}{\pgf@circ@res@zero}}
%\pgftext[bottom,rotate=90,y=\ctikzvalof{bipoles/cvsourceam/margin}\pgf@circ@res@left]{$+$}
%\pgftext[top,rotate=90,y=\ctikzvalof{bipoles/cvsourceam/margin}\pgf@circ@res@right]{$-$}
\pgfusepath{draw}
\pgfscope
\pgftransformxshift{\ctikzvalof{bipoles/vsourceam/margin}\pgf@circ@res@left}
\pgftext[rotate=-\pgf@circ@direction]{$-$}
\pgfusepath{draw}
\endpgfscope
\pgfscope
\pgftransformxshift{\ctikzvalof{bipoles/vsourceam/margin}\pgf@circ@res@right}
\pgftext[rotate=-\pgf@circ@direction]{$+$}
\pgfusepath{draw}
\endpgfscope
}
\makeatother
| {
"pile_set_name": "StackExchange"
} |
Q:
Use more than one Spring JpaTransactionManager in a controller?
I have a Spring MVC application using JPA 2. All the controllers are annotated with @Transactional at the class level.
Is it possible to keep that annotation at the class level and simply override it with another @Transactional annotation at the method level? I have one method I'd like to make SERIALIZABLE.
A:
You can add multiple transaction managers by adding qualifiers to distinguish which one that should be used, provided that they have been configured:
@Transactional("global")
public class SomeService {
public void methodThatUsesTheGlobalTxManager() {
// ...
}
@Transactional("special")
public void methodThatUsesTheSpecialTxManager() {
// ...
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set variables in a thymeleaf fragment?
I understand Thymeleaf is made for rendering the views however, I just wanted to know if there is any way to set a variable may be in request scope in a Thymeleaf fragment?
I have a very large conditional expression that I have to repeat a lot of times across the application so it will be really helpful if I can set a variable in main layout then reuse it in all other child fragments.
I am aware of using a Spring interceptor and setting the variable in model but I prefer not to.
Please advise.
Thanks
Prash
A:
In the fragment template, define fragment with parameters:
<div th:fragment=”myfragment(myvariable)”>
<p th:text=”${myvariable}”></p>
</div>
and in layout template, include fragment with that variable specified:
<div th:include=”template :: myfragment(${variable})”></div>
Then variable is passed to the fragment template.
A:
If you need the result of your expression only in the fragments you could use
th:with="var=${verylargeexpression}"
This creates a local variable which you can use everywhere within the dom element you defined it, including fragments.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change Windows 10 title bars color back to white?
Windows 10 Build 10532 brought some requested visual improvements like a new composition with changing title bars' colors. Unfortunately I don't like the new look and I would like to bring back the white titlebars. How can I achieve it?
The only idea that comes to my mind is to apply visual style from one of the previous builds but I didn't make a backup.
A:
I have finally managed to change it by accessing legacy 'Color and Appearance'.
You can launch it by typing rundll32.exe shell32.dll,Control_RunDLL desk.cpl,Advanced,@Advanced in Command Prompt. There you can tweak colors and you are not limited to default set of shades.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java: number of times that the max value occurs in the array
this code only display maximum occurred value not greatest value with maximum occurred.
System.out.println(countMax(new int[] {6,3,1,3,4,3,6,5}));
static int countMax(int[]a) {
int count = 1, tempCount;
int maxCount = a[0];
int temp = 0;
for(int i =0; i < a.length - 1; i++) {
temp = a[i];
tempCount = 0;
for(int j = 1; j < a.length; j++) {
if(temp == a[j])
tempCount++;
}
if(tempCount > count)
maxCount = temp;
count = tempCount;
}
return maxCount;
}
A:
You have to keep an additional variable with the count of the current maximal value as you go. You don't need two loops for this, only one:
static int countMax(int[] a) {
int max = Integer.MIN_VALUE;
int count = 0;
for (int curr : a) {
if (curr > max) {
max = curr;
count = 1;
} else if (curr == max) {
++count;
}
}
return count;
}
Alternatively, Java 8's streams provide a pretty easy, albeit not too performant way of doing all the heavy lifting for you:
static int countMax(int[] a) {
return Arrays.stream(a)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.orElse(0L)
.intValue();
}
A:
You should approach a two-step solution:
Find the maximum value in the array
Count, how often this maximum value occurs
Therefore, you have to iterate the array twice - once to find the maximum value and once to count it.
If you have still problems, here is the code snippet:
public static int countMax(int[] values) {
// first, find the maximum value
int maxValue = Integer.MIN_VALUE;
for (int i = 0; i < values.length; ++i) {
maxValue = Math.max(maxValue, values[i]);
}
// then count the maximum value
int maxCount = 0;
for (int i = 0; i < values.length; ++i) {
if (values[i] == maxValue) maxCount++;
}
return maxCount;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
In what occupations did Aristotle consider virtue impossible to acquire?
Source: Thomas Morris PhD (Yale). Philosophy For Dummies (1999 1 ed). p. 87.
There are some occupations in which it is impossible for a man to be virtuous.
— Aristotle (384–322 B.C.)
To which occupations was he referring?
A:
Not exactly what Aristotle says ...
Politics,1278a : As there are several forms of constitution, it follows that there are several kinds of citizen, and especially of the citizen in a subject position; hence under one form of constitution citizenship will necessarily extend to the artisan and the hired laborer, while under other forms this is impossible, for instance in any constitution that is of the form entitled aristocratic and in which the honors are bestowed according to goodness and to merit, since a person living a life of manual toil or as a hired laborer cannot practise the pursuits in which goodness is exercised [emphasis added].
An alternative translation of the sentence is :
"it is impossible to pursue the things of virtue when one lives the life of a vulgar person or a laborer".
A:
Money-making
According to Aristotle, legitimate trade consisted
of providing needs essential for the "good life."
Barter was an acceptable means of trade, but profit
making seemed absurd. Aristotle held that those who
sought a profit were despicable characters lacking in
proper virtues. After all, one who made a profit had
only two options, to hoard the money or to spend it
on excessive wants and desires. Thus, to Aristotle,
this line of work seemed to be unvirtuous and
even despicable. (Denis Collins, 'Aristotle and Business', Journal of Business Ethics, Vol. 6, No. 7 (Oct., 1987), pp. 567-572: 572.
To spell this out in more detail (references are to Aristotle's Politics except for 'EN' = Nicomachean Ethics):
Aristotle introduces money as a development of exchange, and he sees this
as evolving through four forms. The first (i) is barter or the exchange of
commodities without money (1257al5-30), which we can represent as C-C.
Barter is inconvenient because the acts of sale and purchase are fused into a
single act. Money came into existence in the first place, he says, in order to make this sort of exchange easier (1258b4-5), by allowing the sale (C-M)
and the purchase (M-C) to be separated in time and place (EN., V,
1133bl0f). This gives (ii) the second form of exchange, natural chrematistike (1257a30-41), which may be represented as C-M/M-C, or for short C-
M-C. Once people have become accustomed to this, Aristotle says, another
form of exchange arises, (iii) unnatural chrematistike, in which people can
come to market, not with surplus goods they have made or grown which
they want to exchange for things they need, but with money. Their aim is to
get money by buying goods and selling them for a greater sum (1 257b 1-40);
it can be represented as M-C/C-M, or M-C-M for short. This is justly
discredited, he says, because it involves 'people taking things from one
another' (1258blf). (iv) The fourth form is usury (obolostatike), the lending
of money at interest, M-M, or 'the breeding of money from money', which
he says is the most hated sort and with reason (1258b 1-8). (Scott Meikle, 'Aristotle on Money', Phronesis, Vol. 39, No. 1 (1994), pp. 26-44: 26-7.)
Aristotle and banausia [manual labour]
[I]n the De Philosophia of his transitional phase, where
he gives the name of wisdom (sophia) to each of the five stages he
distinguishes in the growth of civilization: first, the introduction of
work and of the techniques required to satisfy the most pressing
needs of ordinary life; second, the introduction of the arts of
refinement and elegance; then, the creation of laws, the study of
nature, and finally, the contemplation of the first cause. Labour and
technical skills, then, are already held to be sophia. Later, in the
first chapter of the Metaphysics, Aristotle expresses this concept
more clearly, distinguishing two elements in labour: the invention
and supervision of the technique; and its actual execution. He
considers those who direct the work to be more gifted than those
who merely carry it out mechanically, never stopping to think of the
reason for what they do. (Rodolfo Mondolfo and D. S. Duncan, 'The Greek Attitude to Manual Labour', Past & Present, No. 6 (Nov., 1954), pp. 1-5: 4.)
Such 'mechanical work', of which those who do it never stop 'to think of the reason for what they do', stymies the development of virtue. Some remarks of Julia Annas are helpful here:
Humans are equipped by mere nature to develop virtue, but do not do so unless habit is directed by reason to
produce a rational direction of one's life and employment of external
goods. In the context of the Politics we also need to remember the
thesis that humans are by nature politika (πολιτικά) - social and political beings. For it is only when habit is directed by reason to produce dispositions to engage socially, culturally, and politically with
others in a form of society (one which Aristotle identifies with the polis) that humans achieve the goal of natural development. (Julia Annas, 'Aristotle's "Politics": A Symposium: Aristotle on Human Nature and Political Virtue', The Review of Metaphysics, Vol. 49, No. 4 (Jun., 1996), pp. 731-753: 736-7.
Aristotle assumes that, for the manual worker, habit cannot be directed by reason to produce a rational direction of one's life and employment of external goods. The conditions of life of the banausos, the class of manual labourers, is such that this class has neither the leisure, the education, nor the command of external goods to acquire the ethical and intellectual virtues outlined in the Nicomachean Ethics, III-VI.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does 舐めんじゃねぇぞ mean don’t fuck with me?
I know that なめんじゃねよ means don’t fuck with me but does 舐めんじゃねぇぞ have the same meaning or not ? if not what is the real meaning of the sentence 舐めんじゃねぇぞ?
A:
The only difference (other than the kanji being used in the latter) is the particle ぞ, which can be seen as a "stronger よ", so yes, meaning-wise they are the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to handle the crabs in Adventure Time - Time Tangle?
What's the best way to handle giant crabs in Adventure Time Time Tangle? You can't jump over them, you can't punch through them and you can't go around them.
Actually, you can jump if their claws are down, if you land the punch at just the right time you come to a stop long enough to maybe get around.
At present if I come up against a crab it's 50/50 if I'll get past or lose a heart.
Interestingly in the gallery with hints, this 'baddie' is greyed out so you can't get to the tips - which are sometimes helpful.
A:
Use a charged punch to crack through that jerk crab's shell!
| {
"pile_set_name": "StackExchange"
} |
Q:
Every derived table has its own alias
i have the following query:
select userid, name, checktime, campaign,
CASE WHEN Hoursworked - 9 > 0 THEN Hoursworked - 9 ELSE 0 END Overtime
from
(
select
a.userid,a.name,a.campaign,
date(a.CHECKTIME),
timediff(max(b.CHECKTIME), min(a.CHECKTIME)) as Hoursworked
from CHECKINOUT a
join CHECKINOUT b
on date(a.CHECKTIME) = date(b.CHECKTIME) and a.userid = b.userid
where
a.CHECKTYPE = 'I'
AND b.CHECKTYPE = 'O'
group by date(a.CHECKTIME), userid
)
And it's giving this error
1248 - Every derived table must have its own alias
can you help me what wrong?
A:
You need to add a name for the subquery that you have used.
Subqueries are legal in a SELECT statement's FROM clause. The actual
syntax is:
SELECT ... FROM (subquery) [AS] name ...
The [AS] name clause is mandatory, because every table in a FROM
clause must have a name. Any columns in the subquery select list must
have unique names.
So give your subquery an alias by:
select userid, name, checktime, campaign,
CASE WHEN Hoursworked - 9 > 0 THEN Hoursworked - 9 ELSE 0 END Overtime
from
(
select
a.userid,a.name,a.campaign,
date(a.CHECKTIME),
timediff(max(b.CHECKTIME), min(a.CHECKTIME)) as Hoursworked
from ...
) AS T --here is the alias
| {
"pile_set_name": "StackExchange"
} |
Q:
I want to call a Action onSubmit redux form
I made action on my actions folder now I want to access "send new message"
to my handleSubmit function
Below is my action code :
export const types = {
MESSAGES: {
SYNC: 'MESSAGES.SYNC',
NEW: {
CHANGE: 'MESSAGES.NEW.CHANGE',
SEND: 'MESSAGES.NEW.SEND'
}
}
}
export const syncMessages = messages => ({
type: types.MESSAGES.SYNC,
messages
})
export const changeNewMessage = text => ({
type: types.MESSAGES.NEW.CHANGE,
text
})
export const sendNewMessage = () => ({
type: types.MESSAGES.NEW.SEND
})
now I want to access it on my form "handleSubmit" function
Below is my code for message.jsx file
import React from 'react';
import SubMenu from './SubMenu';
import MessageForm from './form/MessageForm';
import * as action from "../../actions/messages.actions";
export default class Messages extends React.PureComponent {
handleSubmit = (e) => {
console.log(e.target.value)
}
render() {
return (
<section className="page-notifications">
<SubMenu/>
<MessageForm onSubmit={this.handleSubmit}/>
</section>
)
}
}
Thanks in advance
A:
import { sendNewMessage } from './path'
class Messages extends React.PureComponent {
handleSubmit = (e) => {
this.props.sendNewMessage();
}
render() {
return (
<section className="page-notifications">
<SubMenu/>
<MessageForm onSubmit={this.handleSubmit}/>
</section>
)
}
}
const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
sendNewMessage: () => dispatch(sendNewMessage()),
}
}
export default connect(
null,
mapDispatchToProps
)(Messages)
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL get rows, but for any matching get the latest version
I'm developing a CMS, and implementing versioning by adding a new entry to the database with the current timestamp.
My table is set up as follows:
id | page | section | timestamp | content
"Page" is the page being accessed, which is either the path to the page ($page_name below), or '/' (to indicate 'global' fields).
"Section" is the section of the page being edited.
I want to be able to select all rows for a given page, but each section should only be selected once, the one with the latest timestamp being selected.
I've tried using the following CodeIgniter Active Record code:
$this->db->select('DISTINCT(section), content');
$this->db->where_in('page', array('/', $page_name));
$this->db->order_by('timestamp', 'desc');
$query = $this->db->get('cms_content');
Which is producing the following SQL:
SELECT DISTINCT(section), `content`
FROM (`cms_content`)
WHERE `page` IN ('/', 'index.html')
AND `enabled` = 1
ORDER BY `timestamp` desc
Which is returning both test rows (rows have all same fields except id, timestamp and content).
Any ideas as to where I'm going wrong?
Thanks!
A:
Your mistake is thinking that DISTINCT applies only to section - an easy mistake to make as the parentheses are misleading here. In fact the DISTINCT applies to the entire row whether or not you have parentheses. It is therefore best to omit the parentheses to avoid confusion.
Your problem is a classic 'max per group' problem. There are many, many ways to write this query and it is probably one of the most popular SQL questions on this site so you can search Stack Overflow to find ways to solve it. One way to get you started is to only select rows which hold the maximum timestamp for that section:
SELECT section, content
FROM cms_content T1
WHERE page IN ('/', 'index.html')
AND enabled = 1
AND timestamp = (
SELECT MAX(timestamp)
FROM cms_content T2
WHERE page IN ('/', 'index.html')
AND enabled = 1
AND T1.section = T2.section
)
I'm sorry but I do not know how to convert this SQL code into CodeIgniter Active Record. If another user more familiar with Active Record wishes to use this as a starting point for their own answer, they are welcome.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does "i" stand for petrol?
As illustrated by this list of car engine names by manufacturer, car manufacturers like to give the petrol and diesel variants of their engines often confusing names.
The least confusing of these naming schemes is to refer to diesel engines with d, as in BMW 525d, and petrol engines with i, as in BMW 525i. The above article shows that BMW, Citroen and Mazda all refer to the petrol variants of their engines using i.
D for diesel is self-explanatory, but what exactly does the i stand for when referring to petrol?
A:
It stands for Injection as in Fuel Injection.
A:
The i is a leftover from the 1970s, when a few companies (BMW and Mercedes, notably) started replacing the carburetor on their petrol engines with fuel injection. The marketing department saw an opportunity (for bragging about the superior fuel management on those cars) and added the i (or E, in Mercedes' case, for Einspritzung, German for injection) to the car's type number.
This worked for a few years, then the catalytic converter became mandatory and everyone switched to fuel injection. 45 years later, BMW still uses the i (as in '320i'). To make things more confusing, they are labelling their electric cars as i3 and i8.
Mercedes dug themselves a hole with their old naming scheme (which became increasingly convoluted with the introduction of the 190), so they switched to using letters (C, E, S etc.) indicating the model range. The 300 E became the E 300. So their midrange product is now called the E-class, and you can have an E-class diesel.
Similar things happened with other technologies. Turbocompressors had a T in the type name (esp. turbodiesels, TD), then came intercoolers (TDic or TDI), direct fuel injection (GDI, *SI). Most of these disappear when they become ubiquitous, some endure.
The list itself is a bit misleading. Take this entry for example, for Honda:
Petrol: i-VTEC
Diesel: i-DTEC
Hybrid: IMA Hybrid
Honda doesn't call all its petrol engines i-VTEC, just the engines that use the i-VTEC variable valve timing system. The same goes for other entries in the list: lots of them are specific technologies (or engine series), not generic petrol/diesel indicators.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculating the number of disconnected components of a NetworkX graph
Starting with a randomly generated tree, I want to consider each node of the tree and potentially remove it with some probability p. Since trees have no cycles and there is a unique path between any pair of nodes, the removal of a node should leave d disconnected trees in its wake, where d is the degree of that node.
My question is, once I've done this for the whole graph, how can I check how many of these unconnected segments there are?
import networkx as nx
import random as rand
n = 20
p = 0.1
G = nx.random_tree(n)
for i in range(0, n):
if rand.random() < p:
G.remove_node(i)
x = G.count_disconnected_components() # is there anything that accomplishes this?
For example, for this graph, G.count_disconnected_components() should return 3.
A:
It seems to me you actually want to count the number of connected parts. Try number_connected_components:
print(list(nx.connected_components(G)))
print(nx.number_connected_components(G))
| {
"pile_set_name": "StackExchange"
} |
Q:
Sample HTML Document That Includes All Tags
Does anyone know where I might find a single HTML document that includes an example of every non-depricated tag in the HTML5 specification?
I want to compare default styling (of such a document) across all browsers.
If you have (or can located) an example. Please post the html in your answer along with a link to its source. Links go bad over time, so pasting the HTML itself will preserve the usefulness of your answer over time.
A:
I think your best bet is to make one yourself. If you are too lazy to make it here's one I did: https://pastebin.com/QU4kcJfz
<!DOCTYPE html>
<html>
<head>
<title> TEST HTML PAGE </title>
<meta charset="UTF-8">
<meta name="description" content="Most of HTML5 tags">
<meta name="keywords" content="HTML5, tags">
<meta name="author" content="http://blazardsky.space">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<header>
<nav>
<p>HEADER</p>
<menu type="context" id="navmenu">
<menuitem label="Home" icon="icon.png"> <a href="#">Home</a> </menuitem>
</menu>
</nav>
</header>
<main>
<h1> Heading... </h1>
<h2> Heading... </h2>
<h3> Heading... </h3>
<h4> Heading... </h4>
<h5> Heading... </h5>
<h6> Heading... </h6>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nisi lacus, auctor sit amet purus vel, gravida luctus lectus. Aenean rhoncus dapibus enim, sit amet faucibus leo ornare vitae. <br>
<span> span </span>
<b>Bold word</b>
<i>italic</i>
<em>emphasis</em>
<mark>mark</mark>
<small> small </small>
<sub> sub </sub>
<sup> sup </sup>
<u> Statements... </u>
<abbr title="National Aeronautics and Space Administration">NASA</abbr>
<strike> strikethrough </strike>
<span><del> deprecated info </del> <ins> new info </ins> </span>
<s> not relevant </s>
<a href="#link">link</a>
<time datetime="2020-08-17 08:00">Monday at 8:00 AM</time>
<ruby><rb>ruby base<rt>annotation</ruby>
<br>
<kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>CANC</kbd>
</p>
</main>
<p> This is a <q>short quote</q> </p>
<blockquote> This instead is a long quote that is going to use a lot of words and also cite who said that. —<cite>Some People</cite> </blockquote>
<ol>
<li><data value="21053">data tag</data></li>
<li><data value="23452">data tag</data></li>
<li><data value="42545">data tag</data></li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
</ol>
<ul>
<li>List item</li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
</ul>
<hr>
<template>
<h2>Hidden content (after page loaded).</h2>
</template>
<video width="640" height="480" src="https://archive.org/download/Popeye_forPresident/Popeye_forPresident_512kb.mp4" controls>
<track kind="subtitles" src="subtitles_de.vtt" srclang="de">
<track kind="subtitles" src="subtitles_en.vtt" srclang="en">
<track kind="subtitles" src="subtitles_ja.vtt" srclang="ja">
Sorry, your browser doesn't support HTML5 <code>video</code>, but you can
download this video from the <a href="https://archive.org/details/Popeye_forPresident" target="_blank">Internet Archive</a>.
</video>
<object data="flashmovie.swf" width="600" height="800" type="application/x-shockwave-flash">
Please install the Shockwave plugin to watch this movie.
</object>
<pre>
_,'/
_.-''._:
,-:`-.-' .:.|
;-.'' .::.|
_..------.._ / (:. .:::.|
,'. .. . . .`/ : :. .::::.|
,'. . . . ./ \ ::. .::::::.|
,'. . . . . / `.,,::::::::.;\
/ . . / ,',';_::::::,:_:
/ . . . . / ,',','::`--'':;._;
: . . / ,',',':::::::_:'_,'
|.. . . . / ,',','::::::_:'_,'
|. /,-. /,',':::::_:'_,'
| .. . . /) /-:/,'::::_:',-'
: . . . // / ,'):::_:',' ;
\ . . // /,' /,-.',' ./
\ . . `::./,// ,'' ,' . /
`. . . `;;;,/_.'' . . ,'
,`. . :;;' `:. . ,'
/ `-._,' .. ` _.-'
( _,'``------''
`--''
</pre>
<code>
// code tag
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
</code>
<p>
<var> variable </var> = 1000;
<samp>Traceback (most recent call last):<br>NameError: name 'variabl' is not defined</samp>
</p>
<table>
<thead>
<tr>
<th>Numbers</th>
<th>Letters</th>
<th>Colors</th>
</tr>
</thead>
<tfoot>
<tr>
<td>123</td>
<td>ABC</td>
<td>RGB</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>1</td>
<td>A</td>
<td>Red</td>
</tr>
<tr>
<td>2</td>
<td>B</td>
<td>Green</td>
</tr>
<tr>
<td>3</td>
<td>C</td>
<td>Blue</td>
</tr>
</tbody>
</table>
<p> A <dfn>definition</dfn> is an explanation of the meaning of a word or phrase. </p>
<details>
<summary>Summary of content below</summary>
<p>Content 1</p>
<p>Content 2</p>
<p>Content 3</p>
<p>Content 4</p>
</details>
<section>
<h1>Content</h1>
<p>Informations about content.</p>
</section>
<progress value="33" max="100"></progress>
<meter value="11" min="0" max="45" optimum="40">25 out of 45</meter>
<p> 2+2 = <output>4</output> </p>
<select>
<optgroup label="Choice [1-3]">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</optgroup>
<optgroup label="Choice [4-6]">
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
</optgroup>
</select>
<div>
<div>
<p> div > div > p </p>
</div>
<br>
</div>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<br>
<textarea id="textarea" name="textarea" rows="4" cols="50">
Write something in here
</textarea>
<br>
<audio controls>
I'm sorry. You're browser doesn't support HTML5 <code>audio</code>.
<source src="https://archive.org/download/ReclaimHtml5/ReclaimHtml5.ogg" type="audio/ogg">
<source src="https://archive.org/download/ReclaimHtml5/ReclaimHtml5.mp3" type="audio/mpeg">
</audio>
<p>This is a recording of a talk called <cite>Reclaim HTML5</cite> which was orinally delieved in Vancouver at a <a href="http://www.meetup.com/vancouver-javascript-developers/" taget="_blank">Super VanJS Meetup</a>. It is hosted by <a href="https://archive.org/details/ReclaimHtml5" target="_blank">The Internet Archive</a> and licensed under <a href="http://creativecommons.org/licenses/by/3.0/legalcode" target="_blank">CC 3.0</a>.</p>
<iframe src="https://open.spotify.com/embed?uri=spotify%3Atrack%3A67HxeUADW4H3ERfaPW59ma?si=PogFcGg9QqapyoPbn2lVOw" width="300" height="380" frameborder="0" allowtransparency="true"></iframe>
<article>
<header>
<h2>Title of Article</h2>
<span>by Arthur T. Writer</span>
</header>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam volutpat sollicitudin nisi, at convallis nunc semper et. Donec ultrices odio ac purus facilisis, at mollis urna finibus.</p>
<figure>
<img src="https://placehold.it/600x300" alt="placeholder-image">
<figcaption> Caption.</figcaption>
</figure>
<footer> <dl> <dt>Published</dt> <dd>17 August 2020</dd> <dt>Tags</dt> <dd>Sample Posts, html example</dd> </dl> </footer>
</article>
<form>
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name</label><br>
<input name="name" id="name"><br>
<label for="dob">Date of Birth<label><br>
<input name="dob" id="dob" type="date">
</fieldset>
</form>
<aside>
<p> P inside ASIDE tag </p>
</aside>
<map name="shapesmap"> <area shape="rect" coords="29,32,230,215" href="#square" alt="Square"> <area shape="circle" coords="360,130,100" href="#circle" alt="Circle"> </map>
<img src="https://placehold.it/100x100" alt="placeholder-image">
<form action="" method="get">
<label for="browser">Choose your browser from the list:</label>
<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
<option value="Edge">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
<input type="submit">
</form>
<footer>
<address> relevant contacts <a href="mailto:[email protected]">mail</a>.</address>
<div> created by <a href="https://blazardsky.space">@blazardsky</a></div>
</footer>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL to find discrepancy between 2 tables with same identifier
I'm trying minus command but not working
Table A column ID , column Date
Table B column ID , column Date
Compare using column ID in both table, e.g. table A ID 1 Date vs Table B ID 1 Date
if dates are the same --> skip
if dates are different, then list the ID and Date column
Is it possible to list both tables in one view?
A:
SELECT tb1.ID, tb1.Date, tb2.Date
FROM table1 as tb1
INNER JOIN table2 as tb2
on tb1.ID = tb2.ID
WHERE tb1.Date <> tb2.Date
only shows dates that are different. does not take into account that an id could be missing on either table
| {
"pile_set_name": "StackExchange"
} |
Q:
Elección de un elemento mediante un número aleatorio, suma acumulativa
Tengo el siguiente estructura:
probabilidad = runif(5)
probabilidad= probabilidad/sum(probabilidad)
names(probabilidad) = LETTERS[1:5]
probabilidad
A B C D E
0.30918062 0.17969799 0.15695684 0.09655216 0.25761238
sum(probabilidad)
[1] 1
Cómo podéis ver, la suma de sus valores es 1, ya que son probabilidades. Genero un número aleatorio entre 0-1:
runif(1)
Éste número me servirá cómo selector para mi estructura, es decir, si el número aleatorio fuese 0.34 elegiríamos el elemento B ya que el número se encuentra en el segmento entre la suma A y B, son sumas acumulativas,
0.30918062 + 0.17969799 = 0.48
No sé cómo puede elegir el elemento por medio de la probabilidad proporcionada.
A:
Una forma que se me ocurre, es calculando en primer lugar la suma acumulativa mediante cumsum(), luego buscamos la menor suma mayor al elemento buscado y mediante match() ubicamos el índice sobre el vector original. Algo así:
valor = 0.41
s <- cumsum(probabilidad)
probabilidad[match(min(s[s>=valor])[1],s)]
valor
probabilidad
s
La salida:
> valor
[1] 0.41
> probabilidad
A B C D E
0.18413659 0.23991206 0.26581474 0.07141827 0.23871835
> s
A B C D E
0.1841366 0.4240486 0.6898634 0.7612817 1.0000000
> probabilidad[match(min(s[s>=valor]),s)[1]]
B
0.2399121
Verificamos que efectivamente el valor 0.41 se encuentra entre los intervalos Ay B (de la suma acumulativa) , por lo que nos quedamos con el límite superior según tu definición, es decir el valor de B.
Nota: Hacemos match(...)[1] para los eventuales casos que tuviéramos dos valores iguales, nos quedamos con el primero.
La otra forma, incluso más simple que podría usarse es mediante la función findInterval:
probabilidad[findInterval(valor, cumsum(probabilidad)) + 1]
Nota: como por defecto nos devuelve el límite inferior, debemos sumar 1 al índice
| {
"pile_set_name": "StackExchange"
} |
Q:
How to have No primary Key Entity using ManyToOne Relation to fetch data from mysql database
I am having problem with fetching data from a table which doesn't contain any primary key (a Weak Entity). I have two tables - Data and Prescription. In Prescription there is a primary key - token_id and Data contains more than 1 row containing different types of information about a single token_id. How I can do that?
I can't add any primary key to the table. The table is provided to me so I cannot change that.
I tried and followed some tutorials in YouTube but that didn't worked. I also checked some answers in stackoverflow but that didn't seem to go with my api structure. I am completely stuck. I tried to use @MantToOne as shown in the tutorial and then use a repository for a function but that doesn't seem to work.
I have two model classes -
Data.java
@Repository
@Entity
@Table(name="data")
public class Data {
@Column(name="ticket_no")
private String ticket_no;
@Column(name="type")
String type;
@Column(name="unit")
private String unit;
@Column(name="value")
private float value;
@ManyToOne
private Prescription pres;
//getters and setters
}
Prescription.java
@Entity
@Table(name="prescriptions")
public class Prescription {
@Id
@Column(name="ticket_no")
private String ticket_no;
@Column(name="description")
String description;
@Column(name="download_link")
private String download_link;
//getters and setters
Two Repositories: DataRepository.java
public interface DataRepository extends JpaRepository<Data, String> {
public List<Data> findByPrescriptionTicket_no(String token);
}
PrescriptionRepository.java
public interface PrescriptionRepository extends JpaRepository<Prescription, String> {
}
Two Dao Classes : DataDao.java
@Service
public class DataDao {
@Autowired
DataRepository datarepo;
public List<Data> findOne(String token) {
List<Data> meddat=new ArrayList<>();
datarepo.findByPrescriptionTicket_no(token).forEach(meddat::add);
return meddat;
}
}
PrescriptionDao.java
@Service
public class PrescriptionDao {
@Autowired
PrescriptionRepository presrepo;
public Prescription findOne(String token) {
return presrepo.findOne(token);
}
}
The Controller Class
@RestController
@RequestMapping(value = "/rest/users")
public class MainController {
@Autowired
DataDao datadao;
@Autowired
PrescriptionDao presdao;
@Autowired
ProcessData pd;
@GetMapping("/persons")
public String loadPersons(@RequestParam("access_token") String access_token) throws ParseException{
String decode_token = pd.testDecodeJWT(access_token);
String token = pd.jsondata(decode_token);
String pres=presdao.findOne(token).toString();
List<Data> med= datadao.findOne(token);
String tot_data= "{"+"\"medical_data\":"+med+","+"\"hb_prescription\":"+pres+"}";
return tot_data;
}
}
I actually converted the whole program from a simple fetching of data from two tables to this one so there can be more than one error. I am new to this concept but I have to do this for the project submission.
If the result is in Data List than it would be great.
Thanks in Advance.
A:
You cannot have Entities without primary key:
From the Spec:
2.4 Primary Keys and Entity Identity
Every entity must have a primary key.
The primary key must be defined
on the entity class that is the root of the entity hierarchy or on a
mapped superclass that is a (direct or indirect) superclass of all
entity classes in the entity hierarchy. The primary key must be
defined exactly once in an entity hierarchy.
Source: https://download.oracle.com/otn-pub/jcp/persistence-2_1-fr-eval-spec/JavaPersistence.pdf?AuthParam=1561040540_b447233fdfd994fdb2338dd9407c4977
So you must create a primary key of the fields of data.
If they are unique in combination you could create a composite key like this:
public class DataKey implements Serializable {
@Id
private String ticket_no;
@Id
String type;
@Id
private String unit;
@Id
private float value;
// getters, setters, equals and hashCode implementations
}
@Entity
@Table(name="data")
@IdClass(DataKey.class)
public class Data {
@Id
@Column(name="ticket_no")
private String ticket_no;
@Id
@Column(name="type")
String type;
@Id
@Column(name="unit")
private String unit;
@Id
@Column(name="value")
private float value;
@ManyToOne
private Prescription pres;
//getters and setters
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the result of resultset in a arraylist?
I have a method - read() - and I want store resultSet in an ArrayList. I also have a getter/setter class according to my column name. How can I store resultSet in an ArrayList?
public T read(T t) {
if(t instanceof AddressData) {
try
{
if(dbConnect.getConnectionStatus())
{
connection = dbConnect.openConnection();
}
else
{
throw new InstantiationException();
}
preparedStatement = (PreparedStatement) connection.prepareStatement("SELECT * FROM AddressData");
resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
((AddressData) t).setAddressId("addressId");
((AddressData) t).setAddressLine1("addressLine1");
((AddressData) t).setAddressLine2("addressLine2");
((AddressData) t).setCity("city");
((AddressData) t).setState("state");
((AddressData) t).setCountry("country");
((AddressData) t).setPinCode("pinCode");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
A:
With the current method signature you probably can't. The issue is that you return only one instance of T and not a List<T>. Worse still, you fill data on the variable t given as parameters.
Assuming I understand your need, the following code should be a good beginning (assuming all strings).
public List<T> read (T t) {
List<AddressData> addresses = new ArrayList<AddressData>();
if (t instanceof AddressData) {
try {
if (dbConnect.getConnectionStatus()) {
connection = dbConnect.openConnection();
} else {
throw new InstantiationException();
}
preparedStatement = (PreparedStatement) connection.prepareStatement("SELECT * FROM AddressData");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
AddressData a = new AddressData();
a.setAddressId("addressId"));
a.setAddressLine1(resultSet.getString("addressLine1"));
a.setAddressLine2(resultSet.getString("addressLine2"));
a.setCity(resultSet.getString("city"));
a.setState(resultSet.getString("state"));
a.setCountry(resultSet.getString("country"));
a.setPinCode(resultSet.getString("pinCode"));
addresses.add(a);
}
} catch (Exception e) {
e.printStackTrace();
}
return addresses;
} else {
// ...?
}
}
Note that one new AddressData instance is created per iteration on the ResultSet and is added to the List<AddressData> that is returned from the method. You should reconsider what to do in case t is not an instance of AddressData, but this is out of scope of your question.
| {
"pile_set_name": "StackExchange"
} |
Q:
ansible and reloading AWS dynamic inventory
See also: https://stackoverflow.com/questions/29003420/reload-ansibles-dynamic-inventory.
My question: is there a better way of doing what's below?
I have an ansible role that provisions AWS machines, and runs correctly (notice the provision tag):
- name: AWS provision
hosts: localhost
gather_facts: no
vars_files:
- vars/dev.yml
user: ec2-user
roles:
- provision
tags:
- provision
I then have a base role, that I want to be able to run independently (for example during development, so I don't have to wait for re-provisioning (notice the base tag). I run a play find running instances that filters and stores the hosts in the group started:
- name: find running instances
hosts: localhost
vars_files:
- vars/dev.yml
gather_facts: no
tags:
- base
tasks:
- name: gather remote facts
ec2_remote_facts:
region: "{{ target_aws_region }}"
filters:
instance-state-name: running
"tag:Name": "{{ instance_name }}"
register: ec2_facts
- debug: var=ec2_facts
- name: add hosts to groups
add_host:
name: "{{ item.id }}"
ansible_ssh_host: "{{ item.public_dns_name }}"
groups: started
changed_when: false
with_items: ec2_facts.instances
- name: base setup
hosts: started
gather_facts: no
vars_files:
- vars/dev.yml
user: ec2-user
roles:
- base
tags:
- base
My question: the plays are working, but is there a better way of doing this? For example I'm got gather_facts: no followed by ec2_remote_facts and the filters - it all seems rather convoluted.
A clarification: thanks for the comment about ec2.py -- I'm already using it in my first play (when I call the provision role).
But for testing purposes I want to jump into subsequent plays without re-doing the (slow) provisioning. So how do I re-populate my hosts data? Is ec2_remote_facts followed by add_host the right way? Or can I somehow use gather_facts: yes?
A:
I'd probably use the EC2 dynamic inventory script instead, which you can employ by configuring ec2.ini and passing -i ec2.py to ansible-playbook.
See http://docs.ansible.com/ansible/intro_dynamic_inventory.html#example-aws-ec2-external-inventory-script for more info.
Note that there are plenty of options in ec2.ini. Be sure to have a look at those, e.g. cache_max_age. You can also make the inventory generation faster by filtering unnecessary resources (e.g. set rds = False if you are only interested in EC2 instances).
UPDATE: With Ansible 2.x+ you can also use - meta: refresh_inventory mid-play.
| {
"pile_set_name": "StackExchange"
} |
Q:
No grounding wire in an old house?
My new house was built in 1966 and I've been told by the inspector and the electrician that put in the GFCI outlets that the meter and box are grounded but that no third wire was run through the house. I was told that I could either replace all outlets with GFCI outlets or that I could run a grounding wire from the green screw on the outlet to the metal box. Which is better?
A:
They are both attempts to solve the same problem, life safety. A side effect is equipment protection.
I would say GFCIs are better for life safety, because there are lots of ways to get shocked even with a ground, like dropping a 2-prong hair dryer in the tub... but GFCI puts the kibbosh on most of them.
Grounding is better for equipment durability, as it helps it deal with static electricity better, and helps power strips dispose of voltage surges.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP image upload issues
<td valign="top">
<input type="hidden" name="MAX_FILE_SIZE" value="12485760" />
Image?</td>
<td><input type="file" name="image">
$path = "uploads/";
$path .= basename($_FILES['image']['name']);
$path = addslashes($path);
$name = $_FILES['image']['name'];
echo $path;
move_uploaded_file($_FILES['image']['tmp_name'], $path);
The above code should work as i have a very similar one working neatly. However, it does not seem to pick anything up from the form (the very top code). If anyone could point out how i'm being a fool and breaking this, i would be much appreciative.
A:
Make sure you have the attribute enctype="multipart/form-data" on your <form> tag.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to modify the line width of ipython notebook markdown cell
I use ipython notebook to keep my diary using the markdown cell. The problem is that The linewidth of the cell is a little too wide, not very fine looking as a blog. The question is: how can I decrease the width of the line and keep it stay in the middle(or left) of the page?
The method should be easy and not affect other cells.
A:
You can change the CSS applied to the text cells via your custom.css
Simply add the following lines
div.text_cell {
width:550px;
}
with this the notebook looks like
There are a bunch of questions here, dealing with styling the notebook via the custom css, see e.g. here, here, or here.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to draw MVC diagram in Microsoft modeling tools?
I want to draw a MVC diagram in Microsoft Modeling tools like visio or Visual studio and the diagram looks like this:
http://www.tonymarston.net/php-mysql/model-view-controller-03.png
How can I do it?
A:
It's an easy job:
First, open Visio and select 'Blank Drawing'.
Second, select 'More Shapes' on the left panel and then select 'Software and Database', next Web Diagram, finally Conceptual Web Site Shape.
Last, select the left top one: a rectangle shape with a header to stand for the package, and select normal rectangle shape for sub package or sub module.
To use arrow, just go to 'More Shapes'/'FlowChart'/'Arrow Shapes'. The procedure is same as above.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery and the click function
This code doesn't work as intended, what am I doing wrong?
$(document).ready(function(){
$("a.hide-para").click(function(){
$('p').hide();
$(this).html('Show Paragraphs').removeClass('hide-para').addClass('show-para');
});
$("a.show-para").click(function(){
$('p').show();
$(this).html('Hide Paragraphs').removeClass('show-para').addClass('hide-para');
});
});
A:
It doesn't work because you are dynamically adding/removing the class after the elements are bound to specific element/class combinations. That is to say, you are adding the click event to links with a class of "show-para" before there are any links with that class (or maybe the other way around depending on your default)
In either case, jQuery has the live function to get around that, just change your click handlers to .live('click', function(){ })
A:
You're losing the bindings as you are modifying the DOM. Either stop changing the classnames or bind the events using live():
$('a.hide-para').live('click', function() { ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Binary XML file line #2: Error inflating class
I am new to Android. Whenever I run app on emulator it say"Unfortunalty stopped" when I run and checked the ADT logs it says
05-01 15:43:26.597: E/dalvikvm-heap(1022): Out of memory on a 36864016-byte allocation.
05-01 15:43:26.687: W/dalvikvm(1022): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-01 15:43:26.817: E/AndroidRuntime(1022): FATAL EXCEPTION: main
05-01 15:43:26.817: E/AndroidRuntime(1022): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jaisri.myapp/com.jaisri.myapp.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.os.Looper.loop(Looper.java:137)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 15:43:26.817: E/AndroidRuntime(1022): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 15:43:26.817: E/AndroidRuntime(1022): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 15:43:26.817: E/AndroidRuntime(1022): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 15:43:26.817: E/AndroidRuntime(1022): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 15:43:26.817: E/AndroidRuntime(1022): at dalvik.system.NativeStart.main(Native Method)
05-01 15:43:26.817: E/AndroidRuntime(1022): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.createView(LayoutInflater.java:613)
05-01 15:43:26.817: E/AndroidRuntime(1022): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:807)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
05-01 15:43:26.817: E/AndroidRuntime(1022): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.Activity.setContentView(Activity.java:1881)
05-01 15:43:26.817: E/AndroidRuntime(1022): at com.jaisri.myapp.MainActivity.onCreate(MainActivity.java:78)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.Activity.performCreate(Activity.java:5104)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-01 15:43:26.817: E/AndroidRuntime(1022): ... 11 more
05-01 15:43:26.817: E/AndroidRuntime(1022): Caused by: java.lang.reflect.InvocationTargetException
05-01 15:43:26.817: E/AndroidRuntime(1022): at java.lang.reflect.Constructor.constructNative(Native Method)
05-01 15:43:26.817: E/AndroidRuntime(1022): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.LayoutInflater.createView(LayoutInflater.java:587)
05-01 15:43:26.817: E/AndroidRuntime(1022): ... 26 more
05-01 15:43:26.817: E/AndroidRuntime(1022): Caused by: java.lang.OutOfMemoryError
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:502)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:355)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.content.res.Resources.loadDrawable(Resources.java:1965)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.View.<init>(View.java:3330)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.view.ViewGroup.<init>(ViewGroup.java:431)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.widget.LinearLayout.<init>(LinearLayout.java:176)
05-01 15:43:26.817: E/AndroidRuntime(1022): at android.widget.LinearLayout.<init>(LinearLayout.java:172)
05-01 15:43:26.817: E/AndroidRuntime(1022): ... 29 more
05-01 15:45:58.767: W/lenght(1085): 1
05-01 15:46:03.977: E/dalvikvm-heap(1085): Out of memory on a 36864016-byte allocation.
05-01 15:46:04.237: W/dalvikvm(1085): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-01 15:46:04.548: E/AndroidRuntime(1085): FATAL EXCEPTION: main
05-01 15:46:04.548: E/AndroidRuntime(1085): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jaisri.myapp/com.jaisri.myapp.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.os.Looper.loop(Looper.java:137)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 15:46:04.548: E/AndroidRuntime(1085): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 15:46:04.548: E/AndroidRuntime(1085): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 15:46:04.548: E/AndroidRuntime(1085): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 15:46:04.548: E/AndroidRuntime(1085): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 15:46:04.548: E/AndroidRuntime(1085): at dalvik.system.NativeStart.main(Native Method)
05-01 15:46:04.548: E/AndroidRuntime(1085): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.createView(LayoutInflater.java:613)
05-01 15:46:04.548: E/AndroidRuntime(1085): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:807)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
05-01 15:46:04.548: E/AndroidRuntime(1085): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.Activity.setContentView(Activity.java:1881)
05-01 15:46:04.548: E/AndroidRuntime(1085): at com.jaisri.myapp.MainActivity.onCreate(MainActivity.java:78)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.Activity.performCreate(Activity.java:5104)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-01 15:46:04.548: E/AndroidRuntime(1085): ... 11 more
05-01 15:46:04.548: E/AndroidRuntime(1085): Caused by: java.lang.reflect.InvocationTargetException
05-01 15:46:04.548: E/AndroidRuntime(1085): at java.lang.reflect.Constructor.constructNative(Native Method)
05-01 15:46:04.548: E/AndroidRuntime(1085): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.LayoutInflater.createView(LayoutInflater.java:587)
05-01 15:46:04.548: E/AndroidRuntime(1085): ... 26 more
05-01 15:46:04.548: E/AndroidRuntime(1085): Caused by: java.lang.OutOfMemoryError
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:502)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:355)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.content.res.Resources.loadDrawable(Resources.java:1965)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.View.<init>(View.java:3330)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.view.ViewGroup.<init>(ViewGroup.java:431)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.widget.LinearLayout.<init>(LinearLayout.java:176)
05-01 15:46:04.548: E/AndroidRuntime(1085): at android.widget.LinearLayout.<init>(LinearLayout.java:172)
05-01 15:46:04.548: E/AndroidRuntime(1085): ... 29 more
05-01 15:46:21.367: E/Trace(1130): error opening trace file: No such file or directory
Please help me . wher should I check the problem. I am not getting it.
Here is the xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF5D00" >
<RelativeLayout
android:id="@+id/jkheading"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:background="@drawable/jkhead" >
<ImageView
android:id="@+id/jkheadingtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_toLeftOf="@+id/search"
android:src="@drawable/header" />
<ImageButton
android:id="@+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:background="@android:color/transparent"
android:src="@android:drawable/ic_menu_search" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/jksearch"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:background="@drawable/jkhead" >
<EditText
android:id="@+id/jkedit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_toLeftOf="@+id/search1"
android:hint="Search"
android:textColor="@android:color/black" />
<ImageButton
android:id="@+id/search1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:background="@android:color/transparent"
android:src="@drawable/jksearch" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/jkrunn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/jkheading"
android:layout_marginTop="3dp"
android:background="#FFAF00" >
<TextView
android:id="@+id/jkruntext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="Welcome"
android:textColor="@android:color/white" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/jkrunn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/jkrunn"
android:layout_marginTop="3dp"
android:background="#FFAF00" >
<com.jaisri.jklinks.Scrolltext
android:id="@+id/jkruntext1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome"
android:textColor="@android:color/white" >
</com.jaisri.jklinks.Scrolltext>
</RelativeLayout>
<ViewFlipper
android:id="@+id/viewFlipper1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/jkheading"
android:layout_centerHorizontal="true" >
<include
android:id="@+id/firstlayout"
layout="@layout/flip9" />
<include
android:id="@+id/listlayout"
layout="@layout/flip8" />
<include
android:id="@+id/listlayout1"
layout="@layout/flip7" />
<include
android:id="@+id/listlayout2"
layout="@layout/flip6" />
</ViewFlipper>
<RelativeLayout
android:id="@+id/slider"
android:layout_width="60dp"
android:layout_height="match_parent"
android:layout_above="@+id/jkfooter"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/jkrunn1"
android:layout_centerHorizontal="true"
android:background="@drawable/glasseffect" >
<ImageButton
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@android:color/transparent"
android:src="@drawable/face" />
<ImageButton
android:id="@+id/jklike"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:background="@android:color/transparent"
android:src="@drawable/like" />
<ImageButton
android:id="@+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:background="@android:color/transparent"
android:src="@drawable/login2" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/register1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/jkheading"
android:background="@drawable/jklogin" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Login"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="18dp"
android:layout_marginTop="15dp"
android:text="Username" />
<EditText
android:id="@+id/signinusername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/signinpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/signinusername"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="@+id/jksignin"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/signinpassword"
android:layout_marginTop="15dp"
android:background="@drawable/iconback"
android:text="Enter"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/signinusername"
android:text="Password" />
<Button
android:id="@+id/signup"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/jksignin"
android:layout_alignBottom="@+id/jksignin"
android:layout_alignRight="@+id/textView1"
android:background="@drawable/iconback"
android:text=" Signup "
android:textColor="@android:color/white" />
<Button
android:id="@+id/close"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/signup"
android:layout_alignBottom="@+id/signup"
android:layout_alignParentRight="true"
android:layout_marginRight="38dp"
android:background="@drawable/iconback"
android:text="Exit"
android:textColor="@android:color/white" />
/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/register2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/jkheading"
android:background="@drawable/jklogin" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Register"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="18dp"
android:layout_marginTop="0dp"
android:text="Email-id" />
<EditText
android:id="@+id/signupemail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/signupusername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/signupemail"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:ems="10" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/signupemail"
android:text="Username" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/signupusername"
android:text="Password" />
<EditText
android:id="@+id/signuppassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/signupusername"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:ems="10"
android:inputType="textPassword" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/signuppassword"
android:text="Confirm Password" />
<EditText
android:id="@+id/signuppassword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/signuppassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="@+id/Jksignup"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/signuppassword2"
android:layout_marginTop="15dp"
android:layout_toLeftOf="@+id/textView1"
android:background="@drawable/iconback"
android:text=" Sign Up "
android:textColor="@android:color/white" />
<Button
android:id="@+id/close1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/signuppassword2"
android:layout_marginLeft="22dp"
android:layout_marginTop="15dp"
android:layout_toRightOf="@+id/textView1"
android:background="@drawable/iconback"
android:text="Exit"
android:textColor="@android:color/white" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/jkfooter"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:background="@drawable/jkfoot" >
<TextView
android:id="@+id/jkadv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Your Ad Image Here "
android:textColor="@android:color/white" />
</RelativeLayout>
<ImageButton
android:id="@+id/slide"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:layout_marginRight="-8dp"
android:background="@android:color/transparent"
android:src="@drawable/sideopen" />
<ImageButton
android:id="@+id/slide1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="-8dp"
android:layout_toLeftOf="@+id/slider"
android:background="@android:color/transparent"
android:src="@drawable/sideclose" />
</RelativeLayout>
Thanks alot
A:
If you examine the Caused by: lines, it looks like the root cause is an OutOfMemoryError that's occurring in BitmapFactory.nativeDecodeAsset(). (Note also the references to "Out of memory on a 36864016-byte allocation").
Are you trying to include a very large image file in your layout somewhere?
A:
Just for future people having this issue you can add in manifest:
android:largeHeap="true"
this fixed the issue for me.
A:
I think the problem is that your xml class definition doesn't match the package you have in your custom class. Assuming it is correct in your class, try changing the xml to
<com.jaisri.myapp.Scrolltext
android:id="@+id/jkruntext1"
I haven't used custom Views much but I'm pretty sure this is a problem. Hope this helps
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get a pointer on a function's arguments in C?
Is there a generic method to get pointer on each argument in C like
you would do with a vararg function ?
A special syntax like $1, $2, $3
And if not is there some preprocessor macro that define that ?
If not possible in C I'm also interested in a Objective C solution.
I know I can get a selector on current method with _cmd special hidden
parameter. Is there some kind of _arg1, _arg2 ??
Also would it be possible to directly point on memory after _cmd ? Is it
"safe" to consider parameter pointers are next to each other ?
UPDATE TO MY OWN QUESTION
If I access the frame stack by using some assembler code I can get a hold
on the function pointer with ebp right ? So is it possible to access arguments
the same way ? Sorry if this is obvious, I don't know much about assembler.
A:
What is possible but perhaps not entirely useful in your case would be to extract the current and previous stack frame pointers (i e bp register) and, using the standard stack frame structure, determine how many 4 byte (for a 32-bit application) parameter units have been passed in the call to the current routine. You won't be able to determine which units are char, short or long and if two of them together might be a long long/__int64 parameter.
I've thought about this some more. Consider a typical function call "func (a,b)". The calling code unless you have parameters in registers (some x86-32 compiler options and intel recommended for x86-64) the code would turn out like this
; long *esp,*ebp;
push b ; *(--esp)=b;
push a ; *(--esp)=a;
call func ; *(--esp)=return_address_location;
return_address_location:
add esp,8 ; esp+=2; // free memory allocated for passing parameters
Then you come to processing in func
func:
push ebp ; *(--esp)=(long) ebp; // save current ebp <=> current stack frame
mov ebp,esp ; ebp=esp; // create new stack frame in ebp
sub esp,16 ; esp-=4; // reserve space for local variables <=> sizeof(long)*4
(func code ...)
Now when you're in func and you need access to parameters you address them with ebp+2 and ebp+3 (*ebp contains previous ebp, ebp+1 the return address. When you need access to local variables you address them with ebp-4 to ebp-1 (may be over-simplified if they are not all longs and you have some packing option set).
After a while func has done its thing and you need to return:
mov esp,ebp ; esp=ebp; // unreserve space for local variables
pop ebp ; ebp=*(esp++); // restore previous ebp <=> previous stack frame
ret ; eip=*(esp++); // pop return address into instruction pointer
From the first snippet you will also see how the first stack allocation (for passing parameters) is freed right after returning.
A few tips:
Do the math for yourself while
single-stepping (instruction by
instruction) through a call/return
sequence and you'll get ideas on how
to solve the original problem. This
is basic stack handling which looks
more or less the same on all
architectures and implementations so
it's a good thing to know
Imagine an incorrectly calculated
memset/memcpy to a local buffer and
how it will destroy the data on the
stack including return addresses,
previous stack frames etc
Take note of the values in ds and ss
(data and stack selectors) and if
they contain the exact same value a
solution of yours could use memcpy to
copy the parameters from the stack to
data memory for examination or
whatever if that helps
If ds=ss you can use & to find the
address of the passed parameters from
inside func (¶m1, ¶m2)
If ds and ss or not equal (as they
might be in a multi-threaded
application) you will need a
memcpy variant that uses "far
addressing" which will handle the
situation where ds and ss differ
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the height of text in a panel
I have panel that I have customized. I use it to display text. But sometimes that text is too long and wraps to the next line. Is there some way I can auto resize the panel to show all the text?
I am using C# and Visual Studio 2008 and the compact framework.
Here is the code I am wanting to adjust the size for:
(Note: HintBox is my own class that inherits from panel. So I can modify it as needed.)
public void DataItemClicked(ShipmentData shipmentData)
{
// Setup the HintBox
if (_dataItemHintBox == null)
_dataItemHintBox = HintBox.GetHintBox(ShipmentForm.AsAnObjectThatCanOwn(),
_dataShipSelectedPoint,
new Size(135, 50), shipmentData.LongDesc,
Color.LightSteelBlue);
_dataItemHintBox.Location = new Point(_dataShipSelectedPoint.X - 100,
_dataShipSelectedPoint.Y - 50);
_dataItemHintBox.MessageText = shipmentData.LongDesc;
// It would be nice to set the size right here
_dataItemHintBox.Size = _dataItemHintBox.MethodToResizeTheHeightToShowTheWholeString()
_dataItemHintBox.Show();
}
I am going to give the answer to Will Marcouiller because his code example was the closest to what I needed (and looks like it will work). However, this is what I think I will use:
public static class CFMeasureString
{
private struct Rect
{
public readonly int Left, Top, Right, Bottom;
public Rect(Rectangle r)
{
this.Left = r.Left;
this.Top = r.Top;
this.Bottom = r.Bottom;
this.Right = r.Right;
}
}
[DllImport("coredll.dll")]
static extern int DrawText(IntPtr hdc, string lpStr, int nCount,
ref Rect lpRect, int wFormat);
private const int DT_CALCRECT = 0x00000400;
private const int DT_WORDBREAK = 0x00000010;
private const int DT_EDITCONTROL = 0x00002000;
static public Size MeasureString(this Graphics gr, string text, Rectangle rect,
bool textboxControl)
{
Rect bounds = new Rect(rect);
IntPtr hdc = gr.GetHdc();
int flags = DT_CALCRECT | DT_WORDBREAK;
if (textboxControl) flags |= DT_EDITCONTROL;
DrawText(hdc, text, text.Length, ref bounds, flags);
gr.ReleaseHdc(hdc);
return new Size(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top +
(textboxControl ? 6 : 0));
}
}
This uses the os level call to draw text. By P-Invoking it I can get the functionality I need (multi line wrapping). Note that this method does not include any margins. Just the actual space taken up by the text.
I did not write this code. I got it from http://www.mobilepractices.com/2007/12/multi-line-graphicsmeasurestring.html. That blog post had my exact problem and this fix. (Though I did make a minor tweak to make it a extension method.)
A:
You could use the Graphics.MeasureString() method.
With a code sample of your text assignment onto your panel, I could perhaps provide a code sample using the MeasureString() method, if you need it.
I have no way to know whether the Graphics.MeasureString() method is part of the Compact Framework, as it is not said on the page I linked.
EDIT #1
Here's a link where I answered to another text-size related question, while I look for writing a sample for you. =)
EDIT #2
Here's another link related to your question. (Next edit is the sample code. =P)
EDIT #3
public void DataItemClicked(ShipmentData shipmentData) {
// Setup the HintBox
if (_dataItemHintBox == null)
_dataItemHintBox = HintBox.GetHintBox(ShipmentForm.AsAnObjectThatCanOwn(),
_dataShipSelectedPoint,
new Size(135, 50), shipmentData.LongDesc,
Color.LightSteelBlue);
// Beginning to measure the size of the string shipmentData.LongDesc here.
// Assuming that the initial font size should be 30pt.
Single fontSize = 30.0F;
Font f = new Font("fontFamily", fontSize, FontStyle.Regular);
// The Panel.CreateGraphics method provides the instance of Graphics object
// that shall be used to compare the string size against.
using (Graphics g = _dataItemHintBox.CreateGraphics()) {
while (g.MeasureString(shipmentData.LongDesc, f).Width > _dataItemHintBox.Size.Width - 5) {
--fontSize;
f = new Font("fontFamily", fontSize, FontStyle.Regular);
}
}
// Font property inherited from Panel control.
_dataItemHintBox.Font = f;
// End of font resizing to fit the HintBox panel.
_dataItemHintBox.Location = new Point(_dataShipSelectedPoint.X - 100,
_dataShipSelectedPoint.Y - 50);
_dataItemHintBox.MessageText = shipmentData.LongDesc;
// It would be nice to set the size right here
_dataItemHintBox.Size = _dataItemHintBox.MethodToResizeTheHeightToShowTheWholeString()
_dataItemHintBox.Show();
}
Disclaimer: This code has not been tested and is off the top of my head. Some changes might be obligatory in order for you to test it. This provides a guideline to achieve what you seem to want to accomplish. There might be a better way to do this, but I know this one works. Well, the algorithm works, as you can see in my other answers.
Instead of the line:
SizeF fontSize = 30.0F;
You could as well do the following:
var fontSize = _dataItemHintBox.Font.Size;
Why is this?
Because Font.Size property is readonly. So, you need to create a new instance of the System.Drawing.Font class each time the Font.Size shall change.
In your comparison, instead of having the line:
while (g.MeasureString(shipmentData.LongDesc, f)...)
you could also have:
while (g.MeasureString(shipmentData.LongDesc, _dataItemHintBox.Font)...)
This would nullify the need for a second Font class instance, that is f.
Please feel free to post feedbacks as I could change my sample to fit your reality upon the feedbacks received, so that it better helps you. =)
I hope this helps! =)
| {
"pile_set_name": "StackExchange"
} |
Q:
Uploading image with one to one relationship laravel
I am having some difficulty doing this problem, what I want to do is to upload an image to my database where this image must have a user_id equal to the id of the personal_information table.
This is what I am making: when logging in, I am an admin and I can see all the users name which are all taken from the user_information table, and I can click on their name to see their information and also I can upload pictures so that I know how they look like.
This is what it look like inside my view when I click on the person name:
Current code that I have:
test.blade.php (shown based on screenshot)
@foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
<a href="{{ url('/user/show/'.$object->id.'/edit') }}">Edit</a><br>
@foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['user'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
@endforeach
@endforeach
CreateController (controller for uploading image and also for upload page)
public function create1(personal_info $user){
return view('create1')->withUser($user);
public function store1(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$userImage = new UserImage;
$personal_info = new personal_info;
$userImage->name = $name;
$userImage->size = $size;
$user= personal_info::find($id);
$user->UserImages()->save($userImage);
}
return redirect('/home');
}
public function test($id){
$user = personal_info::where('id',$id)->first();
return view('create1', compact('user'));
}
}
Create1.blade.php (upload page)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id()}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
UserImage model:
class UserImage extends Eloquent
{
protected $fillable = array('name','size','user_id');
public function personal_infos() {
return $this->belongsTo('App\personal_info', 'user_id', 'id');
}
}
personal_info model:
class personal_info extends Eloquent
{
protected $fillable = array('Name');
protected $table = 'personal_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
Route:
Route::get('/userUpload/{id}/create1','CreateController@create1')->name('user.upload.iamge');
Route::post('/userUpload','CreateController@store1');
Route::get('/user/showImage/{id}', 'HomeController@Insert')->name("image");
Route::post('/userUpload/create1', 'CreateController@test');
Getting this error:
A:
The Upload button only displays when the $data3 is not empty. to display it even when its empty, use a conditional to check if its empty and do something else if its not. like this:
@foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
<a href="{{ url('/user/show/'.$object->id.'/edit') }}">Edit</a><br>
@if($data3->count())
@foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
@endforeach
@else
<a href="{!! route('user.upload.image', ['id'=>$object->id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
@endif
@endforeach
The relationships have already been set in the controller. All you need is to display the button and the controllers would handle the rest
EDIT
You are getting the error because your route name is 'user.upload.iamge' instead of 'user.upload.image'
| {
"pile_set_name": "StackExchange"
} |
Q:
Given a φ independent of PA which is true in the standard model, will always (PA+ ¬φ) be Σn-unsound for some n?
Given a φ independent of PA which is true in the standard model, will always (PA+ ¬φ) be Σn-unsound for some n?
This is a follow up from a previous question:
Given a φ independent of PA which is true in the standard model, will always (PA+ ¬φ) be ω-inconsistent?.
A:
Yes. Every formula "is" $\Sigma^0_n$ for sufficiently large $n$, and the rest follows directly from the definition of a theory being $\Sigma^0_n$ unsound.
There are two ways to read the above statement. Some people would define the arithmetical hierarchy so that each formula has infinitely many rankings. But even if we only give a formula its lowest ranking, every formula $\phi$ will be logically equivalent to a formula $\psi$ that is $\Sigma^0_n$ for some $n$; just add dummy quantifiers to the prenex form of $\phi$ until it starts with an existential quantifier. Then any theory that proves $\phi$ also proves $\psi$. This is why, for most purposes, we can look at the arithmetical hierarchy "modulo logical equivalence" or even modulo provable equivalence in our theory.
| {
"pile_set_name": "StackExchange"
} |
Q:
rsync incremental file list taking forever
I'm copying from one NAS to another. (Netgear ReadyNAS -> QNAP) i tried Pulling the files by running rsync on the QNAP, and that took forever, so I'm currently trying to push them from the Netgear. The code I'm using is:
rsync -avhr /sauce/folder [email protected]:/dest/folder
i'm seeing:
sending incremental file list
and nothing after that.
File transfer is 577gb and there are a lot of files, however I'm seeing 0 network traffic on the QNAP (It fluctuates between 0kb/s to 6kb/s) so it looks like its not sending any kind of incremental file list.
all folders are created on the destination and then nothing happens after that.
Anyone have any thoughts? Or any ideas on if there is a better way to copy files from a ReadyNAS to QNAP
A:
The documentation for -v says increase verbosity.
If the only thing you're interested in is seeing more progress, you can chain -v together like so:
rsync -avvvhr /sauce/folder/ [email protected]:/dest/folder/
and you should see more interesting progress.
This could tell you if your copying requirements -a are stricter than you need and thus take a lot of unnecessary processing time.
For example, I attempted to use -a, which is equivalent to -rlptgoD, on over 100,000 images. Sending the incremental file list did not finish, even overnight.
After changing it to
rsync -rtvvv /sauce/folder/ [email protected]:/dest/folder/
sending the incremental file list became much faster, being able to see file transfers within 15 minutes
A:
After leaving it over night and it doing nothing, i came in and tried again.
the code that worked appended a '*' to the end of the sauce folder. so this was what worked:
rsync -avhr /sauce/folder/* [email protected]:/dest/folder
If anyone else has troubles - give this a shot.
| {
"pile_set_name": "StackExchange"
} |
Q:
Recognize selected text in start and end of text with regex c#
I have text that starts with (parag1 level="All") as start tag and end with (/parag1) as end tag, and between them is text.
How can I with regex in C# check that the user selected text with start tag or end tags?
I use parentheses for tags: (tag)text(/tag)
Example:
(Parag1 level="All")
This is my string1. This is my string2. This is my string3.
(/Parag1)
The user may select:
(Parag1 level="All")
This is my
Or
level="All")
This is my
Or (this one is does not have the start tag)
is my string1
Or (this one has the start tag with l") and end tag with ( )
l")
This is my string1. This is my string2. This is my string3.
(
I want to check:
Does it start with "start tag" or part of "start tag"?
Selected text 1 and 2,4 is ok, but 3 is no.
Does it end with "end tag" or part of "end tag"?
Selected text 1,2,3 is no, but 4 is ok.
How can i change my regex patern that include all below text.
pattern :
(<Parag)\d+\s(Level=")\w+(">)
text :
<Parag1 Level="all">
<Parag2 Level="Total">
Parag3 Level="all">
arag4 Level="all">
rag5 Level="all">
ag6 Level="all">
g7 Level="all">
8 Level="all">
Level="all">
Level="all">
evel="all">
vel="all">
el="all">
l="all">
="all">
="all">
"all">
all">
ll">
l">
">
>
Change regex pattern c#
A:
I know this isn't a RegEx solution as you requested, but here's an outside the box idea. Since your example text has some XML-like qualities, have you considered replacing the ( and ) with < and > and parsing it with an XML parser?
To use this solution though, your text could not have any parenthesis other than the tags, and you would have to replace any illegal characters with their respective escape sequences.
One other issue you would have to deal with is a root-level tag. If one does not exist, you would have to wrap your original string in one:
String data = // your string here with all opening and closed tags
data = "<root>" + data + "</root>" //if your data does not have a root tag, if it does, you can omit this
data = data.Replace('(', '<').Replace(')', '>');
XElement element = XElement.Parse(data);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to output the name of their foreign key id
I have a problem, I want that each id in the foreign key can output the name instead of their id. Here is the image.
Here's my code :
<table class="altrowstable" data-responsive="table" >
<thead >
<tr>
<th> IDno</th>
<th> Lastname </th>
<th> Firstname </th>
<th> Department </th>
<th> Program </th>
<th> Action</th>
</tr>
</thead>
<tbody>
<div style="text-align:center; line-height:50px;">
<?php
include('../connection/connect.php');
$YearNow=Date('Y');
$result = $db->prepare("SELECT * FROM student,school_year where user_type =3 AND student.syearid = school_year.syearid AND school_year.from_year like $YearNow ");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr class="record">
<td><?php echo $row['idno']; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['firstname']; ?></td>
//name belong's to their id's
<td><?php echo $row['dept_id']; ?></td>
<td><?php echo $row['progid']; ?></td>
<td><a style="border:1px solid grey; background:grey; border-radius:10%; padding:7px 12px; color:white; text-decoration:none; " href="addcandidates.php?idno=<?php echo $row['idno']; ?>" > Running</a></div></td>
</tr>
<?php
}
?>
</tbody>
</table>
Thanks guys need a help
A:
Just replace this line
<td><?php echo $row['progid']; ?></td>
by this one
<td><?php echo $row['prog_name']; ?></td>
To use the field you want
You also need to adapt your query to select program infos if not already in the table school_year or student (with a join) :
$result = $db->prepare("SELECT * FROM student
INNER JOIN school_year ON student.syearid = school_year.syearid
INNER JOIN program ON student.progid = program.progid
WHERE user_type =3
AND school_year.from_year like $YearNow ");
Assuming the program table is called "program"
| {
"pile_set_name": "StackExchange"
} |
Q:
pip3, python does nothing on Windows cmd
Yes, I already read that question but it didn't help me.
C:\Users\*\Documents\git-workspace\redditCountdownGui>"C:\Program Files\WPy64-3741\python-3.7.4.amd64\Scripts\pyinstaller.exe"
C:\Users\*\Documents\git-workspace\redditCountdownGui>
I tried using this method:
C:\Users\*\Documents\git-workspace\redditCountdownGui>"C:\Program Files\WPy64-3741\python-3.7.4.amd64\python.exe" -m pyinstaller
C:\Program Files\WPy64-3741\python-3.7.4.amd64\python.exe: No module named pyinstaller
C:\Users\*\Documents\git-workspace\redditCountdownGui>
I can't get it to work. It's also not working for pip:
C:\Users\*\Documents\git-workspace\redditCountdownGui>"C:\Program Files\WPy64-3741\python-3.7.4.amd64\Scripts\pip.exe"
C:\Users\*\Documents\git-workspace\redditCountdownGui>"C:\Program Files\WPy64-3741\python-3.7.4.amd64\Scripts\pip3.exe"
C:\Users\*\Documents\git-workspace\redditCountdownGui>
I also tried adding to PATH but then it's the same - no output at all.
Can anyone help me?
A:
When using WinPython, you need to start WinPython Command Prompt to get all Paths set correctly. Within that shell, you can use pip as usual:
D:\WPy64-3740\scripts>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'D:\\WPy64-3740\\python-3.7.4.amd64\\python.exe'
>>> exit()
D:\WPy64-3740\scripts>python -m pip install requests
Requirement already satisfied: requests in d:\wpy64-3740\python-3.7.4.amd64\lib\site-packages (2.22.0)
Requirement already satisfied: certifi in d:\wpy64-3740\python-3.7.4.amd64\lib\site-packages (from requests) (2019.6.16)
Requirement already satisfied: urllib3 in d:\wpy64-3740\python-3.7.4.amd64\lib\site-packages (from requests) (1.25.3)
Requirement already satisfied: chardet in d:\wpy64-3740\python-3.7.4.amd64\lib\site-packages (from requests) (3.0.4)
Requirement already satisfied: idna in d:\wpy64-3740\python-3.7.4.amd64\lib\site-packages (from requests) (2.8)
D:\WPy64-3740\scripts>
| {
"pile_set_name": "StackExchange"
} |
Q:
Discarding characters in C?
I'm doing intro to C and I need to write a program that prompts the user to enter in characters, an equal sign, and an integer. I need to use getchar() until the '=' then scanf() for the integer. The program should then output only the integer back to the user.
Right now it prints out unnecessary code re the location for every character input, then at the end outputs the correct integer. This is the code I have:
#include <stdio.h>
#define EQUAL '='
int main(void)
{
char ch;
int integer = 0;
printf("Enter some text, an equal sign and an integer:\n");
while ((ch = getchar())!= '\n') //while not end of line
{
if (ch == EQUAL){
scanf("%d", &integer);
}
printf("The integer you entered is: %d\n", integer);
}
return 0;
}
I can't find an example and need clarification on how to fix the issue.
A:
You got bit by a gotcha in C. The problem is this:
if( ch == EQUAL )
scanf("%d", &integer);
printf("The integer you entered is %d\n", integer);
if with no braces will only include the single statement following it. That code is really this:
if( ch == EQUAL ) {
scanf("%d", &integer);
}
printf("The integer you entered is %d\n", integer);
To avoid this gotcha, I would recommend two things:
Always indent your code properly.
Never use if, else, or while without braces.
gcc supports a warning about this, -Wmisleading-indentation.
For more gotchas like this read "C Traps And Pitaflls" by Andrew Koenig.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can the map file of a Windows executable be made writable?
When a Windows EXE is loaded it is mapped into memory. This map locks the file and prevents any normal modifications to, or replacements of, the file. However, since it is mapped as Copy-on-Write, could you change it to Write and then modify memory to change the contents of the file?
A:
No. Changing the protection to Write and updating the memory merely updates your process's private copy of the file's bytes. (You have effectively created process-local memory that is conveniently initialized to the file's current contents.) The actual file remains unchanged.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Async Tasks. Include "Future" trouble
My compiler doesn't find #include <future> when I need to execute an Async Task. How can I include it properly? Can I download the headers and make a reference to them?
A:
std::future is C++11 onwards.
Visual Studio 2005 does not support the C++11 and C++14 standards, so no.
(It barely gets the for scoping correct!)
Consider upgrading your toolchain, but note that VC2012 only partially supports C++11 features. You could try boost (www.boost.org). It contains material that's often accepted into future standards, so may well contain a future that can be compiled with VC2005.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between Dandelion focus-confirmation chips and others?
New member here with a question regarding the mysteries of focus confirmation when fitting a manual focus lens to Canon EOS type digital and film bodies.
I have a fair number of M42 Pentax Takumar lenses I'd like to use on my EOS 40D or 5DMkIV digital cameras, as well as on a number of EOS film cameras.
Having the green focus confirmation light come on would be welcome, but the more I read about adapters with focus confirmation chips, the more confused I become.
For starters, is there a difference between so-called Dandelion chips and the others that claim to allow camera to confirm focus?
Something else that gives me the willies is the apparently complex process of programming the chip to one's camera based on manufacturers' instructions in bad English. What's worse - this arcane process must be done for each lens you'd want to use with the adapter! And, possibly re-done for different apertures.
Then, we have Fotodiox warning vaguely not to use such adapters with EOS FILM cameras, as they will muck up the computer or otherwise "damage" such cameras.
THUS - and please only answer if you've had FIRST HAND experience with chipped adapters and Canon EOS 5D MkIV - is there an adapter with confirmation chip that does NOT have to be "programmed" to the camera to allow focus confirmation when using MF Takumar M42 lenses on EOS digital AND film cameras.
Lastly, is it true that focus confirmation only works with certain f/ stops on a given lens?
A:
Sorry, I don't have the 5D Mk IV but I expect the 5D Mk III should be similar.
Not all AF confirmation chips are created equal. There are 1st gen, 2nd gen, 3rd Gen, and 4th Gen. I think only the 4th generation "EMF" versions work with some of the latest cameras from Canon. My SL1 seems to be an exception as it does work with early generation Non-EMF AF chips while my 5D3 does not.
There are even differences between the 4th generation "Dandelion" chips. I would recommend the "Euro Dandelion" sold by Tagotech and some others sellers.
It is more expensive, but is better designed, is fully programmable, and looks nicer as well. Here is a comparison from an eBay seller showing the differences between the original vs Chinese copies of Dandelion AF chips.
I use AF confirmation chips on three of my adapted MF lenses with my SL1 and 5D Mk III.
These are the three lenses I use and the AF chips on each:
1) Canon FDn 50mm 1.4 with Big_Is AF chip (programmed to 50mm f/1.4) (factory default)
2) Samyang 500mm 8.0 with Adplo AF chip (programmed to 500mm f/5.6) (due to f/5.6 AF limit on the SL1)
3) Samyang 14mm 2.8 with Tagotech “Dandelion” AF chip (programmed to 14mm f/2.8)
I find they all of them are not very accurate for focus confirmation at wide apertures like f/1.4 or even f/2.8 and I use Live View at 10x magnification to get the best focus. Another good option is “Focus Peaking” available on some cameras.
Later generations can be programmed to show the correct EXIF information and having the correct f/stop seems to help with exposure metering.
The warning about not working with certain f/ stops probably refers to not using f/8 lenses or even stopping down to f/8 on a faster lens with cameras that can only AF at f/5.6
I did have trouble with using 2 different Dandelion AF chips on my 7D. Here is a video showing the erratic behavior. Canon 7D Dandelion AF Chip Erratic behavior Other 7D users in the comments section report the same problems.
| {
"pile_set_name": "StackExchange"
} |
Q:
requirejs, is it possible to create a shim that loads deps after path
Here is what I am trying to achieve.
I have a primary library that needs to be loaded with several other libraries that need to be loaded after the primary library.
All the secondary libraries require the primary library to be loaded.
Is there something like the reverse of shim deps?
primarylib.js
secondarylib1.js
secondarylib2.js
secondarylib3.js
secondarylib4.js
secondarylib5.js
....
i would like to call something like:
require(['primarylib'], function(){
})
primarylib.js should be loaded first and then all of the secondary libraries should be loaded.
If I use the normal shim method I need to set each secondary library to require the primary lib.
When I want to call the libs I need to call all of the secondary libraries in my require() call instead of a single lib which I would like to avoid at all costs.
EDIT: Some additional comments and context
I am trying to implement blueimp's file uploader.
It was crying about load-image dependancies.
The final config for the load-image files looks something like this.
"load-image": {
"path": "lib\/blueimp-load-image\/load-image"
},
"load-image-exif-map": {
"path": "lib\/blueimp-load-image\/load-image-exif-map",
"shim": {
"deps": [
"load-image"
]
}
},
"load-image-exif": {
"path": "lib\/blueimp-load-image\/load-image-exif",
"shim": {
"deps": [
"load-image"
]
}
},
"load-image-ios": {
"path": "lib\/blueimp-load-image\/load-image-ios",
"shim": {
"deps": [
"load-image"
]
}
},
"load-image-meta": {
"path": "lib\/blueimp-load-image\/load-image-meta",
"shim": {
"deps": [
"load-image"
]
}
},
"load-image-orientation": {
"path": "lib\/blueimp-load-image\/load-image-orientation",
"shim": {
"deps": [
"load-image"
]
}
}
would be great if something like this worked:
"load-image": {
"path": "lib\/blueimp-load-image\/load-image",
"shim": {
"post-deps": [
"lib\/blueimp-load-image\/load-image-exif-map",
"lib\/blueimp-load-image\/load-image-exif",
"lib\/blueimp-load-image\/load-image-ios",
"lib\/blueimp-load-image\/load-image-meta",
"lib\/blueimp-load-image\/load-image-orientation"
]
}
}
See how much extra config has had to be done to accomplish this.
Why can't require just have something like a post-deps key that loads post path dependencies?
There are several libraries I have come across causing needing to be loaded in this fashion unnecessarily inflating my config file.
A:
When I want to call the libs I need to call all of the secondary libraries in my require() call instead of a single lib which I would like to avoid at all costs.
That's sort of the point of a library like require, it forces you to define all the dependencies of the script for a couple of reasons
Ensures the lib is loaded before it's used by the dependant module
Provides visibility over what libs a particular module needs to work
If I understand your problem correctly, you don't like the idea of having to do
require(['secondarylib1', 'secondarylib2', 'secondarylib3', ...], function(...) {
...
});
Whenever you want to load all the libs. Assuming each secondarylib requires primarylib then the simplest way to avoid this is to have a "bootstrapper" lib that loads all the dependant libraries for you e.g.
Bootstrapper.js
require(['secondarylib1', 'secondarylib2', 'secondarylib3', ...], function() {});
Main.js
require(['bootstrapper'], function() {
// all libs would be loaded
...
});
| {
"pile_set_name": "StackExchange"
} |
Q:
VueJs dynamically bind data to a route
I have an object which has all the question paper ids and I render those ids to a table as well.
What is need is when some one hit the Take Exam button,
relevant paperid should pass to the route.
I tried
this.$router.push('/startExam/{{paperid}}');
and
this.$router.push('/startExam/this.paperid');
but both doesn't worked.
How do I dynamically pass data to a route?
My code is here.
<tbody>
<tr v-for="paperid in QuestionPapersArray">
<td>{{paperid}}</td>
<td></td>
<th></th>
<th><button class="btn" @click="takeExam">Take Exam</button></th>
</tr>
</tbody>
and
methods:{
takeExam(){
console.log("Inside the function");
this.$router.push('/startExam');
}
}
A:
<tbody>
<tr v-for="paperId in QuestionPapersArray">
<td>{{ paperId }}</td>
<td></td>
<th></th>
<th><button class="btn" @click="takeExam(paperId)">Take Exam</button></th>
</tr>
</tbody>
Try the following.
methods: {
takeExam (paperId) {
this.$router.push(`/startExam/${paperId}`)
}
}
Alternatively, you can try the following inside the takeExam() method
this.$router.push({
path: '/startExam',
params: {
id: paperId
}
})
Your route config file should be path: '/startExam/:id'
| {
"pile_set_name": "StackExchange"
} |
Q:
Let centered text overflow on both sides
I'd like to make an "coming in" animation on a horizontal and vertical centered text. Before the animation runs, the text will be wider than the view port. During the animation, the font-size and the letter-spacing of the text will be reduced, so that the text will fit in the view port after the animation.
The problem is, that the text only overflows the the left and is not centered as long as the text is wider than the view port. See my code here
HTML:
<div id="welcome">
<div id="welcome_text_wrap">
<div id="welcome_text">sometext</div>
</div>
</div>
<div id="page_container">
<h2>Page Content</h2>
</div>
CSS:
#welcome {
width: auto;
min-width: 100%;
max-width: 100%;
height: 100%;
min-height: 100%;
max-height: 100%;
background: black;
z-index: 1000;
display: none;
}
#welcome_text_wrap {
display: table-cell;
vertical-align: middle;
text-align: center;
}
#welcome_text {
font-size: 40vw;
letter-spacing: 1em;
font-family: serif;
color: white;
text-transform: lowercase;
opacity: 0;
border: 1px solid red;
display: inline;
}
.after_animation {
font-size: 12vw !important;
letter-spacing: 0em !important;
opacity: 1 !important;
}
JS:
function show_welcome() {
$("#welcome").css("display", "table");
$("#welcome_text").addClass("after_animation", {
duration: 5000,
children: true,
easing: 'easeInOutQuint',
complete: function() {
setTimeout(4000, $("#welcome").fadeOut(800));
}
});
}
$(document).ready(function(e) {
show_welcome();
});
How can I center the text, even if it does not fit into the view port? Also, is there a better way to do this kind of animation? Maybe using CSS 3 transitions?
Thanks allot,
Nick
A:
I wrapped #welcome with #welcome_container with css:
#welcome_container {
overflow:hidden;
}
For #welcome I changed:
#welcome {
...
min-width: 4000px;
max-width: 4000px;
...
position:absolute;
left:50%;
margin-left:-2000px;
top:0;
}
See it in action here http://jsfiddle.net/mattydsw/P3sJe/13/
| {
"pile_set_name": "StackExchange"
} |
Q:
Can the reaction wheels also be used to store energy?
My understanding is that the parts of a typical flywheel energy storage are pretty much the same as the parts of a typical reaction wheel subsystem --
both have a flywheel, electric motor/generator, etc.
Is it possible for a spacecraft to use a flywheel to store and later supply energy, and also (perhaps at an even later time) re-use the same subsystem as a reaction wheel for attitude control?
Is it possible for a spacecraft to use a sufficient(*) number of flywheels to simultaneously control attitude and store energy, and later simultaneously control attitude and supply energy?
(*) 3 flywheels are not sufficient, but my understanding is that many spacecraft already have 4 or more reaction wheels
( Optimal placement of 4 reaction wheels? ).
A:
It would be highly problematic for reaction wheels to serve dual purposes as reaction control devices and energy storage mechanisms. It might be possible, but the implementation would be extremely complicated.
Starting with a simpler case of a three-wheel design, a desired spacecraft attitude and/or slew rate uniquely determines the wheel speed. That is, given a set of initial conditions that include spacecraft attitude and current wheel speed, the wheel speeds at the desired attitude and rate is completely determined.
This means reaction wheels would make crummy energy storage devices, because if you want to control attitude you wouldn't be able control how much energy was stored in the wheels, and conversely if you needed to store or use energy, it would change the spacecraft orientation.
Perhaps if the spacecraft was not 3-axis controlled that would be acceptable. Likewise, with enough reaction wheel redundancy you might have enough degrees of freedom to control energy storage and attitude simultaneously, but the math involved sounds like Ph. D work to me.
Lastly, batteries aren't really that expensive, supply very clean power, have high energy density, are reliable, and can be recharged with solar arrays very efficiently. In contrast, wheels tend to be expensive because they have to be precisely balanced and have moving parts; this also causes wheels to have generally lower reliability than solid-state subsystems. I'm not inclined to replace a battery with a wheel.
A:
When you have two reaction-wheels on the same axis, you can accelerate one in one direction and the other in the opposite direction. The net torque would be 0, but you would have energy stored in both. When you then want to still use them as reaction-wheels, you just have to transfer momentum from one of the wheels to the other to get a net torque.
However, keep in mind that it is mechanically impossible to create a flywheel which is completely free of friction, even in microgravity. That means that this contraption is only suitable for short-term energy storage.
| {
"pile_set_name": "StackExchange"
} |
Q:
pymongo remove/update command returns
When we delete something or update something in mongodb.It returns the as result
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
I want to know how to access those fields in pymongo to check weather the update/delete was sccess or failure.
A:
Prior pymongo 3.0 you need to access the number of modified document with the nModified key.
In [19]: import pymongo
In [20]: pymongo.version
Out[20]: '2.8'
In [21]: client = pymongo.MongoClient()
In [22]: db = client.test
In [23]: col = db.bar
In [24]: col.insert({'a': 4})
Out[24]: ObjectId('55fa5f890acf45105e95eab5')
In [25]: n = col.update({}, {'$set': {'a': 3}})
In [26]: n['nModified']
Out[26]: 1
From pymongo 3.0 you need to use the modified_count attribute
In [27]: n = col.update_one({}, {'$set': {'a': 8}})
In [28]: n.modified_count
Out[28]: 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if \w{1,4} also contains a dash with regex
I'm trying to match a string (test_one) with regex.
I'm splitting up these two in different groups:
\b(\w{1,4})_(\w*)
The first group can just be between 1 and 4 (alphabetic chars) in lenght and could contain a hyphen (not always), but \w only covers [a-zA-Z0-9_], so if I try this:
\b([a-zA-Z0-9-]{1,4})_(\w*)
And put a hyphen: "tes-t_one" it finds a match, but the full match is just: -t_one.
How can I get match on whole first group when a hyphen is in the string?
The expected output is it should match for example test_one or tes-t_one. Not -test_one or test-_one
A:
It seems a conditional construct will help you: if there is a single hyphen in between alphanumeric symbols after a word boundary and before a _, then match {1,5} chars, else match {1,4} alphanumeric or - chars in the first group.
\b((?([^\W_]+-[^\W_]+_)[-\w-[_]]{1,5}|[^\W_]{1,4}))_([^\W_]*)
See the regex demo.
Details:
\b - a word boundary
((?([^\W_]+-[^\W_]+_)[-\w-[_]]{1,5}|[^\W_]{1,4})) - Group 1:
(? - if...
([^\W_]+-[^\W_]+_) - there is a sequence of:
[^\W_]+ - 1 or more alphanumerics
- - a hyphen
[^\W_]+ - 1 or more alphanumerics
_ - an underscore
[-\w-[_]]{1,5} - 1 to 5 alphanumerics or - symbols
| - else
[^\W_]{1,4}) - match 1 to 4 alphanumerics
_ - an underscore
([^\W_]*) - 0+ alphanumerics (letters or digits).
To make the pattern match ASCII only, pass the RegexOptions.ECMAScript option to the regex constructor.
Note that [^\W_] is equal to [\w-[_]] matching any letters or digits (the _ is subtracted from the \w pattern).
| {
"pile_set_name": "StackExchange"
} |
Q:
ggplot2: How to get geom_text() to play nice with facet_grid()?
So I'm trying to plot a couple of curves using ggplot(), and I would like to have each curve sitting in its own plot in a facet_grid. All of this works fine.
The problem is that I'd also like to annotate the curve with the x value corresponding to the peak y value. I tried using geom_text(), and I tried implementing it as shown below, but it doesn't seem to quite work. It's clearly printing something onto the plot, but not the way I hoped it would; i.e., each plot has its corresponding x value printed on it at the location (x, max(y)).
I suspect I've not implemented the ifelse() correctly, but I'm not experienced enough with R to figure out what exactly the problem is.
Any suggestions on where I'm going wrong?
Output:
Data + code:
library('ggplot2')
x <- seq(5, 15, length=1000)
y <- dnorm(x, mean=10, sd=1)
z <- rep_len("z", length.out = 1000)
x1 <- seq(5, 15, length=1000)
y1 <- dnorm(x1, mean=10, sd=2)
z1 <- rep_len("z1", length.out = 1000)
x <- c(x, x1)
y <- c(y, y1)
z <- c(z, z1)
df <- data.frame(x, y, z)
ggplot(data = df, aes(x, y)) + geom_line() + facet_grid(.~z) + geom_text(data = df, aes(x, y, label = ifelse(y == max(y), as.numeric(x), '')), inherit.aes = FALSE, hjust = 0, vjust = 0)
Edit: the output I'm expecting is something like this:
A:
You need to fix two things.
(1) calculate max per z
(2) avoid duplicate y_values
The following code should fix both:
library(dplyr)
df2 <- df %>%
distinct(y, .keep_all = TRUE) %>%
group_by(z) %>%
mutate(y_label = ifelse(y == max(y), as.numeric(x), ''))
as.data.frame(df2)
ggplot(data = df2, aes(x, y)) + geom_line() + facet_grid(.~z) + geom_text(aes(label = y_label), hjust = 0, vjust = 0)
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding button text / label inside SpeedDialAction - Material-UI v1 / React
I am trying to add labels to nested <SpeedDialAction /> components, and have button text displayed next to icons like so:
but it seems like children do not get rendered:
...
<SpeedDialAction
key={action.name}
icon={action.icon}
tooltipTitle={action.name}
onClick={this.handleClick}
>
Foo
</SpeedDialAction>
...
I also tried using the ButtonProps prop as listed in the docs but that did not do the trick either.
A:
I take a look at the SpeedDialAction source code https://github.com/mui-org/material-ui/blob/6f9eecf48baca339a6b15c5fcfb683cba11e4871/packages/material-ui-lab/src/SpeedDialAction/SpeedDialAction.js
The title of Tooltip only shows on hover, but it can be easily done by changing default state to true, eg: state={ tooltipOpen: true } in SpeedDialAction.js file.
However, Tooltip component in SpeedDialAction has no reference, so there is no easy way to setState from outside.
The easiest solution is to create a custom SpeedDialAction component.
SpeedDialAction component contents only Tooltip and Button, which it's hard to modify.
There is the codesandbox https://codesandbox.io/s/9zpyj4o0zo
You can simply add SpeedDialAction.js file to your project.
Update:
Removed onClose event in Tooltip in codesandobox. Fixed the problem where title disappear after click.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rebinding a variable not working inside a for loop
I'm trying to write a loop that iterates a number of times, which also updates a variable in Rust.
fn get_next(input: &[u8]) -> (u8, &[u8]) {
(input[0], &input[1..])
}
fn main() {
let slice: &[u8] = &vec![1, 2, 3, 4];
for _ in 0..4 {
let (mynum, slice) = get_next(slice);
println!("Here's mynum {} slice {:?}", mynum, slice);
}
}
Code is on the Rust Playground.
This is the output:
Here's mynum 1 slice [2, 3, 4]
Here's mynum 1 slice [2, 3, 4]
Here's mynum 1 slice [2, 3, 4]
Here's mynum 1 slice [2, 3, 4]
I would expect the slice variable to be changed each time to point to the next sub slice. How can I get the slice variable to be updated?
This is a minimum example, if I really were iterating over u8's in a slice, I'd do it differently.
A:
You're defining a new variable that shadows the outer one. Perhaps:
let mut slice: &[u8] = &vec![1, 2, 3, 4];
for _ in 0..4 {
let (mynum, slice_) = get_next(slice);
slice = slice_;
println!("Here's mynum {} slice {:?}", mynum, slice);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
md-toolbar cuts off from right when resizing screen width
I am using material design for angular 2 and every time I reduce the width of the screen, the bar gets cut from the right and gives me extra whitespace.
navbar img small width
navar img original
Here is my code
<md-toolbar color="primary">
<span>
Crayons and Clay</span>
<span class="fill-remaining-space"></span>
<div fxLayout="row" fxShow="false" fxShow.gt-sm>
<button md-button routerLink='' >Home</button>
<button md-button routerLink='/ourschool' >Our School</button>
<button md-button routerLink='/communityevents'>Community Events</button>
<button md-button routerLink='/admission'>Admissions</button>
<button md-button routerLink='/contact'>Contact</button>
</div>
<button md-button [md-menu-trigger-for]="menu" fxHide="false" fxHide.gt-sm>
<md-icon>menu</md-icon>
</button>
</md-toolbar>
<md-menu x-position="before" #menu="mdMenu">
<button md-menu-item routerLink="/signin">Sign in</button>
<button md-menu-item routerLink="/dashboard">Inquiry</button>
</md-menu>
<style>
.fill-remaining-space {
flex: 1 1 auto;
}
</style>
A:
Put your md-toolbar inside another div with 100% width and flex-shrink & flex-grow set to 0. Also set a min-width for your toolbar.
In your component.css:
.fill-remaining-space {
flex: 1 1 auto;
}
.header {
min-width: 1024px;
width: 100%;
flex-shrink: 0;
flex-grow: 0;
}
... and in your component.html:
<div class="header">
<md-toolbar color="primary" layout-fill>
<span>Crayons and Clay</span>
<span class="fill-remaining-space"></span>
<div fxLayout="row" fxShow="false" fxShow.gt-sm>
<button md-button routerLink=''>Home</button>
<button md-button routerLink='/ourschool'>Our School</button>
<button md-button routerLink='/communityevents'>Community Events</button>
<button md-button routerLink='/admission'>Admissions</button>
<button md-button routerLink='/contact'>Contact</button>
</div>
<button md-button [md-menu-trigger-for]="menu" fxHide="false" fxHide.gt-sm>
<md-icon>menu</md-icon>
</button>
</md-toolbar>
<md-menu x-position="before" #menu="mdMenu">
<button md-menu-item routerLink="/signin">Sign in</button>
<button md-menu-item routerLink="/dashboard">Inquiry</button>
</md-menu>
</div>
Here is a working plunker: DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
Directory look up for .mdf failed with operation system error 3 (the system cant find the specified path(microsoft.sqlServer.Express.smo)
I have taken SQL backup(.bak) from Windows server 2003 machine and trying to restore in Windows 7. when i am trying to do i have "Directory look up for .mdf failed with operation system error 3 (the system cant find the specified path(microsoft.sqlServer.Express.smo)" message.
I understand that it's trying to find out the path '.MDF' which is not available in this machine (Windows 7). so how i can restore this database.
A:
This manual available also HERE
Perform backup restore using T-SQL:
RESTORE DATABASE LNE FROM DISK = 'C:\LNE-22012016.bak'
WITH MOVE 'LNE' TO 'C:\SQL_data\LNE.mdf',
MOVE 'LNE_log' TO 'C:\SQL_data\LNE.ldf';
| {
"pile_set_name": "StackExchange"
} |
Q:
returning list from dolist loop, instead return NIL
Can you help me with my code, I don't see why it's not returning my wireList, it's just returning NIL
(defun table-wires-position(inputTable inputPosition)
(let ((wireList () ))
(dolist (x (table-wires inputTable) wireList)
(if (or (equal-position-p (wire-OriginCoin x) inputPosition)
(equal-position-p (wire-destinCoin x) inputPosition))
(cons x wireList)))))
A:
First, note that you are technically correct (the best kind of correct) in writing code like this:
(let ((wireList ()))
(dolist (x (table-wires inputTable) wireList)
…)
This does mean that dolist is returning wireList. The question title, “returning list from dolist loop, instead return NIL” is a bit misleading then, because: (i) nil is a list, so you're returning a list; (ii) you are returning wireList. The problem is that you haven't actually modified wireList during the execution of the dolist. The function cons simply returns a new cons cell; it doesn't modify places, so you're not modifying wireList. You can use push, instead, as the following code does. Since you're using an if with no else part, you can use when.
(defun table-wires-position(inputTable inputPosition)
(let ((wireList ()))
(dolist (x (table-wires inputTable) wireList)
(when (or (equal-position-p (wire-OriginCoin x) inputPosition)
(equal-position-p (wire-destinCoin x) inputPosition))
(push x wireList))))) ; or (setf wireList (cons x wireList))
On a stylistic node, I often use &aux variables for these kind of result variables; it avoids a level of nesting:
(defun table-wires-position (inputTable inputPosition &aux (wireList '()))
(dolist (x (table-wires inputTable) wireList)
(when (or (equal-position-p (wire-OriginCoin x) inputPosition)
(equal-position-p (wire-destinCoin x) inputPosition))
(push x wireList))))
Note that by pushing elements into the list, you're getting them in reverse order from inputTable. You could get them in the same order by returning (nreverse wireList) instead, if you wanted. Even better, since you're really just returning an list with certain elements removed, you might as well just use remove-if-not:
(defun table-wires-position (inputTable inputPosition)
(remove-if-not #'(lambda (x)
(or (equal-position-p (wire-OriginCoin x) inputPosition)
(equal-position-p (wire-destinCoin x) inputPosition)))
inputTable))
| {
"pile_set_name": "StackExchange"
} |
Q:
Cell stops responding to selection after pan
The Problem:
After I finish a pan gesture, the cell under the initiating tap no longer responds to selection. didSelectItemAtIndexPath will fire when tapping other cells, but not the cell that was under the pan gesture.
How can I get that cell to respond to touch input again? Alternatively, how can I check if that cell is stuck responding to an event?
Background:
I have a UICollectionView with a bunch of cells. Tapping a cell in this collection view fires didSelectItemAtIndexPath.
The collection view has a pan gesture recognizer. Panning creates an image of the view and translates it around the screen. The collection view is left underneath the other views for the duration of the pan gesture.
Theories:
It's possible that the selection is never completing due to the pan. Maybe there's a touch event hanging around in the UI. If I could clear it, maybe the cell would respond again. I tried setting [panHandler setCancelsTouchesInView:YES], but it didn't change anything.
Update 1:
In the comments, a couple people suggested that the image may be hanging around and blocking the touch. In the completion block passed to animateWithDuration, I have the following lines:
[self.regionScreenshot removeFromSuperview];
self.regionScreenshot = nil;
I verified that these lines are executed.
Another factor that leads me to believe that that is not the issue is that, of all the cells, only ones that have been used to drag are affected. Surrounding cells still respond.
Update 2: Code & Gif
- (IBAction)handlePanFrom:(UIPanGestureRecognizer*)recognizer
{
CGPoint translation = [recognizer translationInView:recognizer.view];
float transparencyLevel = 0.85;
if (recognizer.state == UIGestureRecognizerStateBegan)
{
SFCYRegion* centerRegion = self.region;
//North
if (centerRegion.regionToNorth != nil)
{
self.region = centerRegion.regionToNorth;
[self reloadRegion];
self.regionToNorthScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
}
else
{
self.regionToNorthScreenshot = [[UIView alloc] init];
self.regionToNorthScreenshot.backgroundColor = [UIColor darkGrayColor];
}
[self.view.superview addSubview:self.regionToNorthScreenshot];
self.regionToNorthScreenshot.alpha = transparencyLevel;
self.regionToNorthScreenshot.frame = northFrame;
//East
if (centerRegion.regionToEast != nil)
{
self.region = centerRegion.regionToEast;
[self reloadRegion];
self.regionToEastScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
}
else
{
self.regionToEastScreenshot = [[UIView alloc] init];
self.regionToEastScreenshot.backgroundColor = [UIColor darkGrayColor];
}
[self.view.superview addSubview:self.regionToEastScreenshot];
self.regionToEastScreenshot.alpha = transparencyLevel;
self.regionToEastScreenshot.frame = eastFrame;
//South
if (centerRegion.regionToSouth != nil)
{
self.region = centerRegion.regionToSouth;
[self reloadRegion];
self.regionToSouthScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
}
else
{
self.regionToSouthScreenshot = [[UIView alloc] init];
self.regionToSouthScreenshot.backgroundColor = [UIColor darkGrayColor];
}
[self.view.superview addSubview:self.regionToSouthScreenshot];
self.regionToSouthScreenshot.alpha = transparencyLevel;
self.regionToSouthScreenshot.frame = southFrame;
//West
if (centerRegion.regionToWest != nil)
{
self.region = centerRegion.regionToWest;
[self reloadRegion];
self.regionToWestScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
}
else
{
self.regionToWestScreenshot = [[UIView alloc] init];
self.regionToWestScreenshot.backgroundColor = [UIColor darkGrayColor];
}
[self.view.superview addSubview:self.regionToWestScreenshot];
self.regionToWestScreenshot.alpha = transparencyLevel;
self.regionToWestScreenshot.frame = westFrame;
//Northeast
if (centerRegion.regionToNorth != nil && centerRegion.regionToNorth.regionToEast != nil)
{
self.region = centerRegion.regionToNorth.regionToEast;
[self reloadRegion];
self.regionToNortheastScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
}
else
{
self.regionToNortheastScreenshot = [[UIView alloc] init];
self.regionToNortheastScreenshot.backgroundColor = [UIColor darkGrayColor];
}
[self.view.superview addSubview:self.regionToNortheastScreenshot];
self.regionToNortheastScreenshot.alpha = transparencyLevel;
self.regionToNortheastScreenshot.frame = northeastFrame;
//Southeast
if (centerRegion.regionToSouth != nil && centerRegion.regionToSouth.regionToEast != nil)
{
self.region = centerRegion.regionToSouth.regionToEast;
[self reloadRegion];
self.regionToSoutheastScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
}
else
{
self.regionToSoutheastScreenshot = [[UIView alloc] init];
self.regionToSoutheastScreenshot.backgroundColor = [UIColor darkGrayColor];
}
[self.view.superview addSubview:self.regionToSoutheastScreenshot];
self.regionToSoutheastScreenshot.alpha = transparencyLevel;
self.regionToSoutheastScreenshot.frame = southeastFrame;
//Southwest
if (centerRegion.regionToSouth != nil && centerRegion.regionToSouth.regionToWest != nil)
{
self.region = centerRegion.regionToSouth.regionToWest;
[self reloadRegion];
self.regionToSouthwestScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
}
else
{
self.regionToSouthwestScreenshot = [[UIView alloc] init];
self.regionToSouthwestScreenshot.backgroundColor = [UIColor darkGrayColor];
}
[self.view.superview addSubview:self.regionToSouthwestScreenshot];
self.regionToSouthwestScreenshot.alpha = transparencyLevel;
self.regionToSouthwestScreenshot.frame = southwestFrame;
//Northwest
if (centerRegion.regionToNorth != nil && centerRegion.regionToNorth.regionToWest != nil)
{
self.region = centerRegion.regionToNorth.regionToWest;
[self reloadRegion];
self.regionToNorthwestScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
}
else
{
self.regionToNorthwestScreenshot = [[UIView alloc] init];
self.regionToNorthwestScreenshot.backgroundColor = [UIColor darkGrayColor];
}
[self.view.superview addSubview:self.regionToNorthwestScreenshot];
self.regionToNorthwestScreenshot.alpha = transparencyLevel;
self.regionToNorthwestScreenshot.frame = northwestFrame;
//Self
self.region = centerRegion;
[self reloadRegion];
self.regionScreenshot = [self.collectionView snapshotViewAfterScreenUpdates:YES];
self.regionScreenshot.frame = mainFrame;
self.regionScreenshot.center = mainFrameCenter;
[self.view.superview addSubview:self.regionScreenshot];
self.collectionView.alpha = 0;
}
else if (recognizer.state == UIGestureRecognizerStateChanged)
{
//Track the movement:
self.regionScreenshot.center = [self movePoint:mainFrameCenter
byX:translation.x andY:translation.y];
self.regionToNorthScreenshot.center = [self movePoint:northFrameCenter
byX:translation.x andY:translation.y];
self.regionToEastScreenshot.center = [self movePoint:eastFrameCenter
byX:translation.x andY:translation.y];
self.regionToSouthScreenshot.center = [self movePoint:southFrameCenter
byX:translation.x andY:translation.y];
self.regionToWestScreenshot.center = [self movePoint:westFrameCenter byX:translation.x andY:translation.y];
self.regionToNortheastScreenshot.center = [self movePoint:northeastFrameCenter
byX:translation.x andY:translation.y];
self.regionToSoutheastScreenshot.center = [self movePoint:southeastFrameCenter
byX:translation.x andY:translation.y];
self.regionToSouthwestScreenshot.center = [self movePoint:southwestFrameCenter
byX:translation.x andY:translation.y];
self.regionToNorthwestScreenshot.center = [self movePoint:northwestFrameCenter
byX:translation.x andY:translation.y];
//[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
else if (recognizer.state == UIGestureRecognizerStateEnded)
{
SFCYRegion* newRegion;
UIView* viewToMoveToCenter;
CGSize slideVector;
NSInteger movedByX = 0;
NSInteger movedByY = 0;
float thresholdPercentage = 0.4;
BOOL isOverThresholdToNorth = translation.y > (mainFrame.size.height * thresholdPercentage);
BOOL isOverThresholdToSouth = -translation.y > (mainFrame.size.height * thresholdPercentage);
BOOL isOverThresholdToEast = -translation.x > (mainFrame.size.width * thresholdPercentage);
BOOL isOverThresholdToWest = translation.x > (mainFrame.size.width * thresholdPercentage);
if (isOverThresholdToNorth && self.region.regionToNorth != nil)
{
movedByY = -1;
if (isOverThresholdToEast && self.region.regionToNorth.regionToEast != nil)
{
//Northeast
newRegion = self.region.regionToNorth.regionToEast;
viewToMoveToCenter = self.regionToNortheastScreenshot;
movedByX = 1;
}
else if (isOverThresholdToWest && self.region.regionToNorth.regionToWest != nil)
{
//Northwest
newRegion = self.region.regionToNorth.regionToWest;
viewToMoveToCenter = self.regionToNorthwestScreenshot;
movedByX = -1;
}
else
{
//North
newRegion = self.region.regionToNorth;
viewToMoveToCenter = self.regionToNorthScreenshot;
}
}
else if (isOverThresholdToSouth && self.region.regionToSouth != nil)
{
movedByY = 1;
if (isOverThresholdToEast && self.region.regionToSouth.regionToEast != nil)
{
//Southeast
newRegion = self.region.regionToSouth.regionToEast;
viewToMoveToCenter = self.regionToSoutheastScreenshot;
movedByX = 1;
}
else if (isOverThresholdToWest && self.region.regionToSouth.regionToWest != nil)
{
//Southwest
newRegion = self.region.regionToSouth.regionToWest;
viewToMoveToCenter = self.regionToSouthwestScreenshot;
movedByX = -1;
}
else
{
//South
newRegion = self.region.regionToSouth;
viewToMoveToCenter = self.regionToSouthScreenshot;
}
}
else if (isOverThresholdToEast && self.region.regionToEast != nil)
{
//East
newRegion = self.region.regionToEast;
viewToMoveToCenter = self.regionToEastScreenshot;
movedByX = 1;
}
else if (isOverThresholdToWest && self.region.regionToWest != nil)
{
//West
newRegion = self.region.regionToWest;
viewToMoveToCenter = self.regionToWestScreenshot;
movedByX = -1;
}
else
{
//None, so return to start:
newRegion = self.region;
viewToMoveToCenter = self.regionScreenshot;
}
slideVector = CGSizeMake(mainFrameCenter.x - viewToMoveToCenter.center.x,
mainFrameCenter.y - viewToMoveToCenter.center.y);
[UIView animateWithDuration:0.2
animations:^
{
viewToMoveToCenter.alpha = 1;
if (![self.regionScreenshot isEqual:viewToMoveToCenter])
{
self.regionScreenshot.alpha = transparencyLevel;
}
self.regionScreenshot.center = [self movePoint:self.regionScreenshot.center
byX:slideVector.width andY:slideVector.height];
self.regionToNorthScreenshot.center = [self movePoint:self.regionToNorthScreenshot.center
byX:slideVector.width andY:slideVector.height];
self.regionToEastScreenshot.center = [self movePoint:self.regionToEastScreenshot.center
byX:slideVector.width andY:slideVector.height];
self.regionToSouthScreenshot.center = [self movePoint:self.regionToSouthScreenshot.center
byX:slideVector.width andY:slideVector.height];
self.regionToWestScreenshot.center = [self movePoint:self.regionToWestScreenshot.center
byX:slideVector.width andY:slideVector.height];
self.regionToNortheastScreenshot.center = [self movePoint:self.regionToNortheastScreenshot.center
byX:slideVector.width andY:slideVector.height];
self.regionToSoutheastScreenshot.center = [self movePoint:self.regionToSoutheastScreenshot.center
byX:slideVector.width andY:slideVector.height];
self.regionToSouthwestScreenshot.center = [self movePoint:self.regionToSouthwestScreenshot.center
byX:slideVector.width andY:slideVector.height];
self.regionToNorthwestScreenshot.center = [self movePoint:self.regionToNorthwestScreenshot.center
byX:slideVector.width andY:slideVector.height];
}
completion:^(BOOL finished)
{
if (finished)
{
//Remove the old views:
self.collectionView.alpha = 1;
[self.regionScreenshot removeFromSuperview];
[self.regionToNorthScreenshot removeFromSuperview];
[self.regionToEastScreenshot removeFromSuperview];
[self.regionToSouthScreenshot removeFromSuperview];
[self.regionToWestScreenshot removeFromSuperview];
[self.regionToNortheastScreenshot removeFromSuperview];
[self.regionToSoutheastScreenshot removeFromSuperview];
[self.regionToSouthwestScreenshot removeFromSuperview];
[self.regionToNorthwestScreenshot removeFromSuperview];
self.regionScreenshot = nil;
self.regionToNorthScreenshot = nil;
self.regionToEastScreenshot = nil;
self.regionToSouthScreenshot = nil;
self.regionToWestScreenshot = nil;
self.regionToNortheastScreenshot = nil;
self.regionToSoutheastScreenshot = nil;
self.regionToSouthwestScreenshot = nil;
self.regionToNorthwestScreenshot = nil;
}
}];
if (![self.regionScreenshot isEqual:viewToMoveToCenter])
{
self.region = newRegion;
[self reloadRegion];
[self movedRegionByX:movedByX andY:movedByY];
}
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
}
Here is an image demonstrating the issue. I perform a selection on the "Suburb" cell, then pan, and then am no longer able to perform a selection on that cell, but can still select others:
Update 3: All Gestures
This occurs when I do swipe gestures and pinch gestures as well. If I add in two-finger swipe gestures, both cells under the origin points are affected.
A:
When I was panning, I called [self.collectionView reloadData] in the process of generating the screenshots to use for the adjacent regions. Reloading the cells while a gesture was active seemed to interfere with that individual cell's ability to handle gestures.
As a workaround, I instead added a second, hidden UICollectionView to the controller and load the data into that view and take screenshots of it instead of the main view. The main collection view never has to reload the data until the gestures are complete and a new region is selected.
UIView* aScreenshot = [self.secondaryCollectionView snapshotViewAfterScreenUpdates:YES];
| {
"pile_set_name": "StackExchange"
} |
Q:
"scicosim: error. Type 0 not yet supported for outtb." how to solve this problem?
I'm having an incomprehensible problem in Scicoslab in the last few days.
I've been writing some communication blocks (to send data to an external application) for scicos in C and then wrap them with it's own code. The problem is that, even if the code is working (I've checked every output possible), scicos gives me this error message: sicosim: error. Type 0 not yet supported by outtb. Error Screenshot
Here is the code for the c function of the Sensor Dispatcher Block:
int bro_sens_send (scicos_block *block)
{
int rc, i;
bro_fist_t packet[BUFFER_SIZE];
for (i = 1; i < block->nin; i++) {
bro_encode_sci_datablock(&packet[i-1], block->inptr[i]);
};
printf ("Data for first block: %i, %i, %.2f\n", packet[0].port, packet[0].operation, packet[0].data);
rc = send(block->inptr[0][0], packet, sizeof(bro_fist_t) * BUFFER_SIZE, 0);
if (rc < 0)
{
perror("send() failed");
return -1;
}
printf("%d bytes of data were sent\n", rc);
return 0;
}
int bro_sens_read (scicos_block *block)
{
int rc, i;
bro_fist_t packet[BUFFER_SIZE];
rc = recv(block->inptr[0][0], packet, sizeof(bro_fist_t) * BUFFER_SIZE, 0);
printf("%d bytes of data were received\n", rc);
if (rc < 0)
{
perror("recv() failed");
return -1;
}
printf("Starting to set outputs :3 [%i]\n", block->nout);
for (i = 0; i < block->nout; i++) {
printf("Next Step defining outputs :D [%i]\n", i);
bro_decode_sci_datablock(&packet[i], &block->outptr[i][0]);
printf("Output value for port %i is: %.2f[%i]\n", i, block->outptr[i][0], block->outsz[(2*block->nout)+i]);
}
return 0;
}
void bro_comm_sens_disp (scicos_block *block, int flag)
{
switch (flag) {
case 1: /* set output */
bro_sens_send(block);
bro_sens_read(block);
break;
case 2: /* get input */
break;
case 4: /* initialisation */
break;
case 5: /* ending */
break;
default:
break;
}
}
And this is the code for the block definition (In scilab code):
function [x,y,typ] = SENS_Disp(job,arg1,arg2)
x=[];y=[];typ=[];
select job
case 'plot' then
exprs=arg1.graphics.exprs;
standard_draw(arg1)
case 'getinputs' then
[x,y,typ]=standard_inputs(arg1)
case 'getoutputs' then
[x,y,typ]=standard_outputs(arg1)
case 'getorigin' then
[x,y]=standard_origin(arg1)
case 'set' then
x=arg1
model=arg1.model;graphics=arg1.graphics;
exprs=graphics.exprs;
case 'define' then
model = scicos_model()
model.sim = list('bro_comm_sens_disp',4)
model.out = [1;1;1;1;1;1;1]
model.out2 = [1;1;1;1;1;1;1]
model.outtyp= [1;1;1;1;1;1;1]
model.in = [1;3;3;3;3;3;3;3]
model.in2 = [1;1;1;1;1;1;1;1]
model.intyp = [3;1;1;1;1;1;1;1]
model.evtin = []
model.rpar = []
model.ipar = []
model.dstate=[1];
model.blocktype='c'
model.dep_ut=[%t %f]
exprs=[]
gr_i=['xstringb(orig(1),orig(2),[''Sensors'';+''Dispatcher''],sz(1),sz(2),''fill'');']
x=standard_define([3 2],model,exprs,gr_i)
end
endfunction
The first inpput port for the block is the socket descriptor for communications while the other seven are connected to setup blocks. The outputs returns the data received from the external application.
I've tried to navigate through Scilab code and I've understood that the error I'm getting tells me that the type of data has been set wrongly, but I've checked and it's not quite the case.
Here is the code of Scicoslab that outputs the error:
/*set vectors of outtb*/
for (j=0; j<nlnk; j++) { /*for each link*/
subheader=(int *)(listentry(il_state_outtb,j+1)); /*get header of outtbl(j+1)*/
outtbsz[j]=subheader[1]; /*store dimensions*/
outtbsz[j+nlnk]=subheader[2];
switch (subheader[0]) { /*store type and address*/
/*matrix of double*/
case 1 :
switch (subheader[3]) {
case 0 :
outtbtyp[j]=SCSREAL_N; /*double real matrix*/
outtbptr[j]=(SCSREAL_COP *)(subheader+4);
break;
case 1 :
outtbtyp[j]=SCSCOMPLEX_N; /*double complex matrix*/
outtbptr[j]=(SCSCOMPLEX_COP *)(subheader+4);
break;
default :
Scierror(888,\
"%s : error. Type %d of double scalar matrix not yet supported "
"for outtb.\n",\
fname,subheader[3]);
FREE(outtbptr);
FREE(outtbtyp);
FREE(outtbsz);
FREE(opar);
FREE(oparsz);
FREE(opartyp);
FREE(oz);
FREE(ozsz);
FREE(oztyp);
FREE(lfunpt);
freeparam;
FREE(outtb_elem);
break;
}
break;
/*matrix of integers*/
case 8 :
switch (subheader[3]) {
case 1 :
outtbtyp[j]=SCSINT8_N; /*int8*/
outtbptr[j]=(SCSINT8_COP *)(subheader+4);
break;
case 2 :
outtbtyp[j]=SCSINT16_N; /*int16*/
outtbptr[j]=(SCSINT16_COP *)(subheader+4);
break;
case 4 :
outtbtyp[j]=SCSINT32_N; /*int32*/
outtbptr[j]=(SCSINT32_COP *)(subheader+4);
break;
case 11 :
outtbtyp[j]=SCSUINT8_N; /*uint8*/
outtbptr[j]=(SCSUINT8_COP *)(subheader+4);
break;
case 12 :
outtbtyp[j]=SCSUINT16_N; /*uint16*/
outtbptr[j]=(SCSUINT16_COP *)(subheader+4);
break;
case 14 :
outtbtyp[j]=SCSUINT32_N; /*uint32*/
outtbptr[j]=(SCSUINT32_COP *)(subheader+4);
break;
default :
Scierror(888,\
"%s : error. Type %d of integer scalar matrix not yet supported "
"for outtb.\n",\
fname,subheader[3]);
FREE(outtbptr);
FREE(outtbtyp);
FREE(outtbsz);
FREE(opar);
FREE(oparsz);
FREE(opartyp);
FREE(oz);
FREE(ozsz);
FREE(oztyp);
FREE(lfunpt);
freeparam;
FREE(outtb_elem);
break;
}
break;
default :
Scierror(888,"%s : error. Type %d not yet supported for outtb.\n",fname,subheader[0]);
FREE(outtbptr);
FREE(outtbtyp);
FREE(outtbsz);
FREE(opar);
FREE(oparsz);
FREE(opartyp);
FREE(oz);
FREE(ozsz);
FREE(oztyp);
FREE(lfunpt);
freeparam;
FREE(outtb_elem);
return 0;
break;
}
A:
Ok. After a lot of time I've solved the problem. There was a function that was setting a value in a wrong memory space. The problem was that there weren't any error messages nor warnings.
The problem was in a function that did this:
block->outptr[0][3] = 0;
In a block that had only 3 output ports. This wrote the wrong data inside the data registry. After I removed it everything works fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
opening people picker through hyperlink and add those people as site collection administrator
My share-point 2010 experience is limited but I can follow clear instructions.
Can someone explain step by step how can I open people picker through hyperlink and add those people as site collection administrator.
I have created a site definition for creating site collections. It's like an administrator can create a blog. There I have a hyperlink to edit/add administrator. So there I have to open a people picker and add those people as site administrator.
Any help is appreciated.
Thanks. :)
A:
You can add a link to _layouts/mngsiteadmin.aspx. This is the page which is used to manage site collection admins.
But....
Why not use the built in Site Actions -> Site Settings Menu?
What did you mean by Admin? Blog owners? Editors?
You can also write your Visual Webpart to show People Picker and add/edit Adminstrator programatically.
Edit:
You can use SPUser.isSiteAdmin to set Site Admin. This is okay if you just want to add a new Site Admin. You have to use a People Editor and get the list of slected users and use the above property to add new Site Admin. But when it comes to editing existing administrators you will have to fetch them and give the option to remove if required.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prescribing finitely many unparameterised planar geodesics
Given a finite collection of embedded $C^\infty$ curves which pass through the origin in $\mathbb{R}^2$ with different tangent directions and never again intersect, is there a clean way of prescribing a Riemmannian metric whose geodesics include those curves?
A:
Sorry, I misread your question and answered a local version instead. I'll leave it here (under the horizonal line) in case it turns out to be useful.
If your finite set of curves is rectifiable (can be made into lines by a diffeomorphism of the plane), then do that and then take the Euclidean metric. So the question: how wild are your curves?
$------------------------------------$
The answer is no. Being the geodesics of some Riemannian metric even in two dimensions is a quite restrictive condition. Even if you weaken this by only asking the curves to be the geodesics of some affine connection, it is still quite restrictive. Here is my favorite example of how rigid is this situation:
Theorem (A. Khovanskii). If (the pieces of) six circles on the plane that intersect at the origin are the geodesics of an affine connection defined on a neighbourhood of the origin, then all six circles must meet again at another common point.
If my memory serves me right this is in this paper. Maybe there is a little thing to add to the way he formulates his result in order to get to the theorem I stated: the exponential map of a $C^2$ connection is $C^2$ at the zero section. This allows you to use it to "rectify" the circles.
On the other hand, Finsler metrics are much more flexible for this sort of thing (and their exponential maps are just $C^1$ on the zero section). You can take a look at this paper and its reference for this sort of thing.
One more comment: even if your curves are the geodesics of an affine connection, they still have some way to go before being the geodesics of some Riemannian metric. This was studied here by Bryant, Dunajski, and Eastwood.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.