text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
long run error after calling the javascript method from the action script
I am trying to call a method of a javascript from the actionscript using the ExternalInterface.
Here is the code in action script
private function onKickEvent(e:LogoutEvent):void{
ExternalInterface.call("LoginFound","message");
return;
}
And this is my javascript mwthod
function LoginFound(message){
alert(message);
anotherInstanceExists=true;
}
Everything is working fine, but the only thing is when act on the alert box which is shown in the javascript after some 20 secs, the exception is thrown from the flash player that a script has been running longer than expected time 15 sec.
How can i avoid this?
A:
When you call js function from the actionscript, that function have to work and return value not longer than in 15 sec. Javascript works in single thread,and when you call LoginFound function, alert stops farther executions on the thread.
function LoginFound(message){
alert('something');
//Nothing will be executed unless `alert` window will be closed
}
However you can handle such situation (the execution,which is longer than 15 sec) in Actionsript by using try/catch:
private function onKickEvent(e:LogoutEvent):void{
try{
ExternalInterface.call("LoginFound","message");
}catch(e:Error){
//Do something
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the easiest way to find the scope of Lifehack site?
Sometimes when someone have off topic question and I want to send him a link to the page with Life-hack's scope, it is hard for me to find it. There is no link on visible place where everyone can check what is on/off topic. How can I easily find it, and can we add somewhere a visible link to the scope?
A:
Normally, the scope would be here in the Help Center, but, as you probably know, we've been having trouble creating our scope. As of now, the best resource for finding out about what is on and off topic is A Lifehacks Manifesto. In the manifesto, Robert Cartaino helps decide what is and isn't a lifehack. Hopefully we'll be able to put this scope in the Help Center soon. If you haven't gotten the chance you should definitely read it.
Edit
The scope is now in the Help Center. It contains the information the Robert Cartaino posted a A Lifehack Manifesto.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
golang no such device in syscall.Mount
I'm trying to use the syscall.Mount function to mount a usb pendrive and autodetect the filesystem to some folder. I fetch the device path from the kernel's netlink socket and try to mount it to /tmp/+devicename, in my instance /dev/sdd1 should be mounted to /tmp/sdd1
I have the following lines of code in a go program
if err := syscall.Mount(src, target, "auto", 0, "ro"); err != nil {
log.Printf("Mount(\"%s\", \"%s\", \"auto\", 0, \"ro\")\n",src,target)
log.Fatal(err)
}
Output:
main.go:47: Mount("/dev/sdd1", "/tmp/sdd1", "auto", 0, "ro")
main.go:48: no such device
I'm running the application with root privileges with "sudo", however it seems unable to mount using the syscall package. If i however in the terminal type sudo mount /dev/sdd1 /tmp/sdd1 then that works fine.
What is the issue here? Is the device path somehow different when using the system call?
Any help is appreciated.
Cheers
A:
You didn't specify your OS but I think the problem is the same on many implementations.
On Linux syscall.Mount just wraps mount(2) which doesn't itself support the concept of an "auto" fstype.
The reason the mount(8) command works with "auto" is because it does its own magic:
If no -t option is given, or if the auto type is specified,
mount will try to guess the desired type. Mount uses the
blkid library for guessing the filesystem type; if that does
not turn up anything that looks familiar, mount will try to
read the file /etc/filesystems, or, if that does not exist,
/proc/filesystems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convert code in Opengl es 1.0 to Opengl es 2
This is the code:
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, mFont->mTexId);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Bind our vertex data
glVertexPointer(2, GL_FLOAT, 0, mVertices);
glEnableClientState(GL_VERTEX_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, mUVs);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// Draw the text
glDrawElements(GL_TRIANGLES, 6 * mNumberOfQuads, GL_UNSIGNED_BYTE, mIndices);
I tried with the next code, but it is not working, the problem is that I´m beginning to learn Opengl Es and I don´t understand a lot of things.
// Enable texturing, bind the font's texture and set up blending
//glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, mFont->mTexId);
//glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Bind our vertex data
//glVertexPointer(2, GL_FLOAT, 0, mVertices);
//void VertexPointer(int size,enum type,sizei stride, void *pointer );
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 20, mVertices);
//void VertexAttribPointer( uint index, int size, enum type, boolean normalized, sizei stride, const void *pointer );
//glEnableClientState(GL_VERTEX_ARRAY);
//glEnableVertexAttribArray(VERTEX_ARRAY);
// glTexCoordPointer(2, GL_FLOAT, 0, mUVs);
//glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// Bind the VBO so we can fill it with data
glBindBuffer(GL_ARRAY_BUFFER, 2);
// Draw the text
glDrawArrays(GL_TRIANGLES, 0, 6 * mNumberOfQuads);
//void DrawArrays( enum mode, int first, sizei count );
//glDrawElements(GL_TRIANGLES, , GL_UNSIGNED_BYTE, );
//void DrawElements(enummode,sizeicount,enumtype, void *indices );*/
A:
Try compiling and binding a vertex and pixel shader before you submit your geometry. There's no fixed-function pipeline at all in ES 2.0.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use Enzyme in Jest test to find a name-spaced child component in React
I am building a component using some react-bootstrap components, specifically Modal and its name-spaced children, e.g. Modal.Heading (or Modal.Title, Modal.Body, etc.). For example:
...
import { Modal } from 'react-bootstrap/lib';
import OtherComponent from './OtherComponent';
class MyComponent extends React.Component {
...
render() {
return (
<div>
<Modal>
<p>{someContent}</p>
<OtherComponent/>
<Modal.Header>{someOtherContent}</Modal.Header>
</Modal>
</div>
);
}
}
Using Enzyme within a Jest test suite I can find various children of the Modal component including DOM elements and other custom React components. However I can't find name-spaced child components:
const modal = shallow(<MyComponent/>).find('Modal');
it('should find the Modal element', () => {
expect(modal).toHaveLength(1); // passes
});
it('should find a child DOM element', () => {
expect(modal.find('p')).toHaveLength(1); // passes
});
it('should find a regular child component', () => {
expect(modal.find('OtherComponent')).toHaveLength(1); // passes
});
it('should find a name-spaced child component', () => {
expect(modal.find('Modal.Header')).toHaveLength(1); // fails *****
});
I have tried:
.find('Modal.Header'), i.e. including the namespace, as shown above
.find('Header'), i.e. leaving off the namespace,
mount(<MyComponent/>) instead of shallow(<MyComponent/>) in combination with both of the above find options
So how do I use Enzyme to find a name-spaced child component?
A:
A non-name-spaced component can be identified as a parameter for the find method as either a variable (e.g. OtherComponent) or a string (e.g. 'OtherComponent') but a name-spaced component can only be identified as a variable (e.g. Namespace.Component) but not as a string (e.g. not as 'Namespace.Component'). i.e.:
it('should find a non-name-spaced component as a variable', () => {
expect(modal.find(OtherComponent)).toHaveLength(1); // passes
});
it('should find a non-name-spaced component as a string', () => {
expect(modal.find('OtherComponent')).toHaveLength(1); // passes
});
it('should find a name-spaced component as a variable', () => {
expect(modal.find(Modal.Heading)).toHaveLength(1); // passes
});
it('should (not) find a name-spaced component as a string', () => {
expect(modal.find('Modal.Heading')).toHaveLength(1); // fails
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Client side Sorting inside < li> tag values
I have a HTML like this
<div>
<ul id="ulId">
<li id="liId1">
<span id="spn1-Li1">YVariable1</span>
<span id="spn2-Li1">XVariable2</span>
<span id="spn3-Li1">ZVariable3</span>
</li>
<li id="liId2">
<span id="spn1-Li2">ZVariable1</span>
<span id="spn2-Li2">YVariable2</span>
<span id="spn3-Li2">XVariable3</span>
</li>
<li id="liId3">
<span id="spn1-Li3">XVariable1</span>
<span id="spn2-Li3">ZVariable2</span>
<span id="spn3-Li3">YVariable3</span>
</li>
</ul>
</div>
The view has like this
YVariable1 XVariable2 ZVariable3
ZVariable1 YVariable2 XVariable3
XVariable1 ZVariable2 YVariable3
But I need to sort the result based on the first span value, the remaining "< li>" should be same. Means the result should be as following on click of "sort by button".
XVariable1 ZVariable2 YVariable3
YVariable1 XVariable2 ZVariable3
ZVariable1 YVariable2 XVariable3
I need this in client side (javascript or jQuery).
I have tried in multiple ways, But I didn't get what I'm expecting.
This code I have now, and same altered similar ways
$('#btnOrderBy').click(function () {
var data = [];
$('#ulId li').each(function (item, value) {
$('span', value).each(function (i, v) {
data.push($(this).text());
});
});
console.log(data.sort());
});
A:
I used this code.
$('#ulId').html($("#ulId li").sort(asc_sort));
function asc_sort(a, b){
return ($(b).find('span:first-child').text()) < ($(a).find('span:first-child').text()) ? 1 : -1;
}
link to jsFiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Issue with posting via Ajax to MySql
The Data base is not updated although I am pretty sure my code is good (did several tests). So there must be an issue (async, etc.). I need help to figure out what is wrong.
Here is my Ajax call (by the press of a Save button, it is tested and it fires well):
$.ajax({
url: "../../../../admin/includes/classes/class.article_front_Post.php",
type: "POST",
data: {
'articleid': $articleid,
'contenu': $contenu,
'name': $name
}
});
And here is the content of the ... front_Post.php file:
include_once('../../../../init.php');
$articleid = $_GET['articleid'];
$contenu = $_GET['contenu'];
$name = $_GET['name'];
// $name = 'special1';
// $contenu = '<p>test</p>';
// $articleid = '17';
// above to test the update (it works)
mysql_query("
UPDATE al_articles SET $name='$contenu'
WHERE (ArticleID='$articleid')
") or die(mysql_error());
A:
Your ajax is using "POST" :
$.ajax({
url: "../../../../admin/includes/classes/class.article_front_Post.php",
type: "POST", //<====================================================!!!!
data: {
'articleid': $articleid,
'contenu': $contenu,
'name': $name
}
});
But your PHP is using "GET", so, replace the "GET" by "POST" :
include_once('../../../../init.php');
$articleid = $_POST['articleid']; //<===============================
$contenu = $_POST['contenu']; //<===============================
$name = $_POST['name']; //<===============================
// $name = 'special1';
// $contenu = '<p>test</p>';
// $articleid = '17';
// above to test the update (it works)
mysql_query("
UPDATE al_articles SET $name='$contenu'
WHERE (ArticleID='$articleid')
") or die(mysql_error());
Or replace the "POST" by "GET" in your ajax. Anyway, GET parameters can be seen on the URL, so I recommend POST.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to trigger JQUERY on Event?
I would like to make a selection box when clicked, the items on the left will shift to right automatically. However, using trigger I cannot achieve this.
Here is my code.
<script type="text/javascript">
$( document ).ready(function(){
$('#assignedSelected').on('click',function(){
$('#unassignedItems option:selected').clone().appendTo('#assignedItems');
$('#unassignedItems option:selected').remove();
});
$('#assignedItems').on('click','option', function(){
$('#assignedSelected').trigger('click');
});
});
</script>
<table class="selectArea">
<tr>
<td>
<select id="unassignedItems" name="unassignedItems" class="selectBox" size="8" multiple>
<option value="A">A</option>
</select>
</td>
<td class="selectButtonPanel">
<input type="button" id="assignedSelected" class="selectButton" value=">">
</td>
<td>
<select id="assignedItems" name="assignedItems" class="selectBox" size="8" multiple>
<option value="1">1</option>
</select>
</td>
</tr>
</table>
A:
You can't bind click on select options, use .change() instead
$('#assignedItems').on('change', function(){
$('#assignedSelected').trigger('click');
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Walter Rudin's mathematical analysis: theorem 2.43. Why proof can't work under the perfect set is uncountable.
I found several discussions about this theorem, like this one. I understand the proof adopts contradiction by assuming the perfect set $P$ is countable.
My question is if the assumption is $P$ is uncountable, the proof seems remains the same, i.e., the $P$ can't be uncountable either. In other words, I think whatever the assumption is, we can draw the contradiction in any way.
I don't understand in which way the uncountable condition could solve the contradiction in the proof.
A:
First, there's a typo in your question: the proof proceeds by assuming for contradiction that $P$ is countable (not uncountable, as you've written).
More substantively, countability is used right away: we write $P$ as $\{x_n: n\in\mathbb{N}\}$ and recursively define a sequence of sets $V_n$ ($n\in\mathbb{N}$).
If $P$ were uncountable, we couldn't index the elements of $P$ by natural numbers. We'd have to index them by something else - say, some uncountable ordinal. So now $P$ has the form $\{y_\eta:\eta<\lambda\}$ for some $\lambda>\omega$.
We can now proceed to build our $V$-sets as before, but at the "first infinite step" we run into trouble: we need $V_\eta\cap P$ to be nonempty for each $\eta$, but how do we keep that up forever? In fact, our $V$-sets might disappear entirely: while at each finite stage we've stayed nonempty, but we could easily "become empty in the limit" (consider the sequence of sets $(0,1)\supset(0,{1\over 2})\supset (0,{1\over 3})\supset ...$). The recursive construction of the $V_n$s - which is the heart of the whole proof - relies on always having a "most recent" $V$-set at each stage, that is, only considering at most $\mathbb{N}$-many $V$-sets in total. That this is sufficient follows from the countability of $P$. As soon as we drop this, our contradiction vanishes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ansible failing on condition check for role. What is a proper one?
I'm trying to do an advanced version of your script where ansible running a role basing on a result of "when" condition. In my scenario ansible connects as root, creates ansible_bot user, grants him privilegies and denies access to root.
It all works on the first run, but it doesn't work on the second run, because ansible is unable to connect as a root on the first step.
I'm trying to omit that step by using the following logic, but it returns an error "error while evaluating conditional: root_connection.rc == 0".
- hosts: ansible-test
gather_facts: false
vars:
- ansible_ssh_user: "{{ initial_ssh_user }}"
tasks:
- name: Test SSH connection for {{ initial_ssh_user }}
local_action: shell ssh {{ initial_ssh_user }}@{{ inventory_hostname }} exit
register: root_connection
ignore_errors: True
roles:
- { role: add-ansible-bot, when: root_connection.rc == 0 }
- hosts: ansible-test
sudo: yes
roles:
- common
Can you advice anything?
Thanks!
A:
This is probably just an issue where your task isn't run before the role. If you really need to do what you are doing you can use pre_task::
- hosts: ansible-test
gather_facts: false
vars:
- ansible_ssh_user: "{{ initial_ssh_user }}"
pre_tasks:
- name: Test SSH connection for {{ initial_ssh_user }}
local_action: shell ssh {{ initial_ssh_user }}@{{ inventory_hostname }} exit
register: root_connection
ignore_errors: True
roles:
- role: add-ansible-bot
when: root_connection.rc == 0
|
{
"pile_set_name": "StackExchange"
}
|
Q:
построчная работа с текстом
Есть переменная типа string, инициализированная таким образом:
std::string str = "qwert\n"
"khrkrvne\n"
"hbkb124f";
Каждая строчка отделена от другой "\n". Как работать с каждой строчкой по отдельности?
A:
istringstream input(str);
vector<string> vs;
for (string line; getline(input, line); ) {
vs.push_back(line);
}
и делайте со строками в vs что хотите...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Intercepting SOAP web service calls using HttpModule and making REST API call to deliver response
I have this requirement to intercept web method calls in an existing legacy .asmx web service, read the request to identify the business case which needs to be handled by a new Web API end point.
The client that talks to the asmx service is also some legacy system that probably has service reference added and makes web method calls and not aware of the new rest api to make direct calls. Hence, should be unaware of the change and consumes the SOAP response as always.
So far i've managed to add a custom HttpModule class, intercept the request, read the input stream and make an api call to get the response from it. But how do i send the SOAP response back to the client and end the request so that it doesn't go to the targeted web method.
Here is my Custom HttpModule class :
public class CustomHttpModule : IHttpModule
{
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source, EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
// Initialize soap request XML
XmlDocument xmlSoapRequest = new XmlDocument();
// Move to begining of input stream and read
context.Request.InputStream.Position = 0;
StreamReader readStream = new StreamReader(context.Request.InputStream, Encoding.UTF8);
// Load into XML document
if (readStream.BaseStream != null && readStream.BaseStream.Length > 0)
{
//string streamString = readStream.ReadToEnd();
xmlSoapRequest.Load(readStream);
}
context.Request.InputStream.Position = 0;
// Check if the request is for the web method to be intercepted
if (xmlSoapRequest.GetElementsByTagName("SomeWebMethodName").Count > 0)
{
string response = "";
using (WebClient wc = new WebClient())
{
string URI = "http://localhost:19875/api/home";
wc.Headers[HttpRequestHeader.Accept] = "application/xml";
wc.Headers[HttpRequestHeader.ContentType] = "application/xml";
response = wc.UploadString(URI, xmlSoapRequest.InnerText);
}
context.Response.ContentType = "text/xml";
context.Response.Write(response);
context.Response.End();
}
}
}
I get the error "Unrecognized message version." on the client now.
I'm guessing the response needs to be a SOAP response, how can i create that? also, is there a better approach to the whole ask?
Thank you.
A:
I've got this working. Basically I had to embed the output in the SOAP response body structure like so
var soapResponse = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
.Append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">")
.Append("<soap:Body>")
.Append("<WebMethodResponse xmlns=\"http://tempuri.org/\">")
.Append(String.Format("<WebMethodResult>{0}</WebMethodResult>",HttpUtility.HtmlEncode(webApiResponse)))
.Append("</WebMethodResponse>")
.Append("</soap:Body>")
.Append("</soap:Envelope>");
context.Response.ContentType = "text/xml";
context.Response.Write(soapResponse);
context.Response.End();
To manually create the SOAP response like above, I had to know what the response xml is like when the request is served by the web method directly. For this, we can plug in a SOAP extension to intercept the outgoing message stream and read it like shown in
http://www.codeproject.com/Articles/445007/Intercept-a-raw-SOAP-message
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Derivative of $tr((AX)^tAX)$
I'm trying to calculate the derivative (with respect to the matrix $X$) of the function
$f(X) = tr((AX)^t(AX))$,
Chain's rule gives that $\nabla_X(f(X))=\nabla_X(tr(AX))\nabla_x(AX)$
However I'm having trouble with those two derivatives.
What is $\nabla_X tr(AX)$? Is it $A^t$? I did the math and obtained that $\frac{\partial(tr(AX))}{\partial x_{ij}} = a_{ji}$, but I'm not sure...
And also what is $\nabla_X AX$? Is it simply $A$? I tried differentiating this but failed to see if this holds or not.
Thanks in advance
A:
The gradient $\nabla_{X}f$ is defined as the vector in $\mathcal{M}_{n}(\mathbb{R})$ such that :
$$ f(X+H) = f(X) + \left\langle \nabla_{X}f, H \right\rangle + o(\Vert H \Vert) $$
where $\left\langle \cdot,\cdot \right\rangle$ is the usual inner product on $\mathcal{M}_{n}(\mathbb{R})$ (i.e. $\left\langle A,B \right\rangle = \mathrm{tr}(A^{\top}B)$). By expanding $f(X+H)$, you get :
$$ f(X+H) = f(X) + \underbrace{2\mathrm{tr}(H^{\top}A^{\top}AX)}_{= \; \left\langle 2A^{\top}AX,H \right\rangle} + \underbrace{\mathrm{tr}(H^{\top}A^{\top}AH)}_{= \; o(\Vert H \Vert)} $$
By identification : $\nabla_{X}f = 2A^{\top}AX$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nexus 7 4.2.2 canvas drawtext letters f and j wont display
I have odd behaviour on my Nexus 7
I have been using Sassoon Primary ttf to draw a single letter using drawText on the center of a canvas in my own view. This has been working fine on all models I have tested except my nexus 7.
all letters still work except lower-case f and j
I have tested on 4.2.2 emulator and it works fine as well as 4.0.3 , 4.1.2 and 2.3
For good measure I have set it back to default font and it now draws F but not J.
Has anyone had the same problem or can recreate?
My Paint
textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(650);
textPaint.setAntiAlias(true);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTypeface(font);
textPaint.setDither(true);
the onDraw command
canvas.drawText(letter, center, center, textPaint);
EDIT: turns out its the size 650, which i need it to be. When lowered this then worked. How can I keep it at the size I need?
Thanks
A:
You are using a font size that's way too big to fit in the font cache. You could use a combination of a smaller font size and a scale transform on Canvas to achieve the effect you want. You could also use a software layer (see View.setLayerType()) on the View that draws the letter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Joomla 3 - How to override jQuery with newer version?
In Joomla 3.x jQuery is coming by default with Joomla, but the version is a bit outdated (v.1.8.3) and I have a script that needs a newer version.
What can I do?
A:
In your template you can also override the jQuery file.
Like this:
JOOMLA_ROOT/templates/YOURTEMPLATE/js/jui/jquery.min.js
Where jquery.min.js is a newer version of jQuery.
That way Joomla will load your file and not the default version when using JHtml::_('jquery.framework');
Caution: Test well, so that you don't have other issues with the newer jQuery version.
Credits: Thanks Michael.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL - how to select all rows between two tables with relations,
First of all, I'm sorry with my bad english.
I wanted to select all row in this two table (Company and Contacts), but when there's a related data between two tables then display as 1 rows.
Table Company:
+---------+-----------+----------+
| cmpy_id | Company | Cntct_id |
+---------+-----------+----------+
| 1 | Company 1 | 1 |
| 2 | Company 2 | |
| 3 | Company 3 | |
+---------+-----------+----------+
Table Contacts:
+----------+-----------+
| Cntct_id | Contact |
+----------+-----------+
| 1 | Contact 1 |
| 2 | Contact 2 |
| 3 | Contact 3 |
+----------+-----------+
Result I need:
+-----------+------------+
| Contact | Company |
+-----------+------------+
| Contact 1 | Company 1 |
| Contact 2 | |
| Contact 3 | |
| | Company 2 |
| | Company 3 |
+-----------+------------+
How can i achieve that result?
A:
SELECT Contact,Company
FROM Contacts contact
LEFT JOIN Company company ON company.Cntct_id=contact.Cntct_id
UNION
SELECT Contact,Company
FROM Contacts contact
RIGHT JOIN Company company ON company.Cntct_id=contact.Cntct_id;
Explanation:
First LEFT JOIN would get us all the records from the left table(Table:Contacts) regardless of whether or not they have a match in the right table(Table : Company), like this:
SELECT Contact,Company
FROM Contacts contact
LEFT JOIN Company company ON company.Cntct_id=contact.Cntct_id;
Contact Company
==============================
Contact 1 Company 1
Contact 2 NULL
Contact 3 NULL
Then the second RIGHT JOIN would get us all the records from the right table(Table : Company) regardless of whether or not they have a match in the left table(Table:Contacts), like this:
SELECT Contact,Company
FROM Contacts contact
RIGHT JOIN Company company ON company.Cntct_id=contact.Cntct_id;
Contact Company
==============================
Contact 1 Company 1
NULL Company 2
NULL Company 3
Finally the UNION - "run both of these queries, then stack the results on top of each other"; some of the rows will come from the first query and some from the second.
SELECT Contact,Company
FROM Contacts contact LEFT JOIN Company company ON company.Cntct_id=contact.Cntct_id
UNION
SELECT Contact,Company
FROM Contacts contact RIGHT JOIN Company company ON company.Cntct_id=contact.Cntct_id;
Contact Company
==============================
Contact 1 Company 1
Contact 2 NULL
Contact 3 NULL
NULL Company 2
NULL Company 3
Note:If you use UNION ALL instead of UNION,it will list out duplicates.
Contact Company
==============================
Contact 1 Company 1
Contact 2 NULL
Contact 3 NULL
Contact 1 Company 1
NULL Company 2
NULL Company 3
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Inheritance for builders in lombok
I was trying to use lombok for my project.
I have a class A:
@Data
@Builder
public class A {
Integer a1;
}
and a class B:
@Data
public class B extends A {
Integer b1;
@Builder
public B(Integer b1, Integer a1) {
super(a1);
this.b1 = b1;
}
}
I am getting an error saying builder() in B cannot override builder() in A, as return type in BBuilder is not compatible with return type in ABuilder.
Is there some way to do this using lombok?
I do not want to write the complete builder for for B, unless I don't have any other option.
PS: I have given explicit constructor for class B due to Issue.
I tried searching, but I could not find a good solution for the same.
A:
Here we just need to call super of the builder.
@Data
public class B extends A {
Integer b1;
@Builder
public B(Integer b1, Integer a1) {
super(a1);
this.b1 = b1;
}
public static class BBuilder extends ABuilder{
BBuilder() {
super();
}
}
}
A:
If you are using Lombok 1.18.4 along with IntelliJ, following code shall work for you:
@Data
@Builder
class A {
Integer a1;
}
@Data
class B extends A {
Integer b1;
@Builder (builderMethodName = "BBuilder")
public B(Integer b1, Integer a1) {
super(a1);
this.b1 = b1;
}
}
public class Main {
public static void main(String[] args){
System.out.println(B.BBuilder().a1(1).b1(1).build());
}
}
One a side note, @SuperBuilder annotation didn't work in IntelliJ at time of writing this answer. If you have multiple level of inheritance, please avoid Lombok or it will make your Java models messy.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do all properties need to be protected?
Hello I was wondering why some popular PHP libraries make all properties protected, then add get and set methods for them like:
protected
$a = false;
public function getA(){
return $this->a;
}
public function setA($value){
$this->a = (bool)$value;
}
What's the benefit of this and why not simply make the property public?
A:
OOP real world scenario:
Imagine you have a class Vehicles and they have (protected) wheels. You have different Vehicles with wheels, but to addWheel to a Bike, is different from addWheel to an Aircraft.
Code advantage:
Using getter and setter, you can use typehinting.
Compare those snippets:
class Car {
public $wheels;
}
$bmw = new Car;
$bmw->wheels = 'piece of paper';
The above code let's you add anything as a wheel, but can you use a piece of paper as a wheel?
Now with getter and setter:
class Car {
protected wheels;
public function __construct() {
$this->wheels = new ArrayIterator;
}
public function addWheel(Wheel $wheel) {
$this->wheels->add($wheel);
return $this;
}
public function removeWheel(Wheel $wheel) {
$this->wheels->remove($wheel);
return $this;
}
}
class Wheel {
}
$bmw = new Car;
$bmw->addWheel('piece of paper'); // <-- throws an error!
// paper cannot be used as a wheel
$bmw->addWheel(new Wheel); // <-- good :-)
More code, to be more straightforward. Imagine you have RearWheels and FrontWheels:
class Wheel {
}
class FrontWheel extends Wheel {
}
class RearWheel extends Wheel {
}
class Car {
protected wheels;
public function __construct() {
$this->wheels = new ArrayIterator;
}
public function addWheel(Wheel $wheel) {
// check for already existing Wheels here.
// Pseudo Code:
if (wheels typeof RearWheel > 2) {
throw new Exception('cannot add more than 2 RearWheels to the Car');
}
return $this;
}
public function removeWheel(Wheel $wheel) {
$this->wheels->remove($wheel);
return $this;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Assembly Version Conflict .net 4
Does anyone know about resolving this error??
The type 'Microsoft.Reporting.WebForms.ReportViewer' exists in both 'c:\Windows\assembly\GAC_MSIL\Microsoft.ReportViewer.WebForms**9.0.0.0**__b03f5f7f11d50a3a\Microsoft.ReportViewer.WebForms.dll' and 'c:\Windows\assembly\GAC_MSIL\Microsoft.ReportViewer.WebForms**10.0.0.0**__b03f5f7f11d50a3a\Microsoft.ReportViewer.WebForms.dll'
I have referenced v10, when I check my GAC i found three versions of Microsoft.ReportViewer.WebForms. v9, v10, v11..! cant even able to remove older version of assembly from GAC.
A:
I have resolved this with trail and error method. Assembly version was not updated in config file for some reasons. changed the version to 10 manually like this:
<httpHandlers>
<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"/>
</httpHandlers>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I upgrade ubuntu server 14.04 LTS to 18.04 LTS?
I want to upgrade ubuntu server 14.04 LTS to 18.04 LTS without upgrading 16.04 LTS. can you please help me for the same.
A:
No. You can not upgrade.
Ubuntu does have LTS→LTS upgrades, allowing you to skip intermediate non-LTS releases...
But you can't skip intermediate LTS releases. You have to go via 16.04.
Unless you want to do a fresh install of 18.04 on release.
I should also note that the LTS upgrade pathways are usually only available sometime after the main release. So don't expect to be able to upgrade from 16.04 on the day of 18.04's release.
Reference post - https://askubuntu.com/questions/1015728/how-to-upgrade-ubuntu-from-14-04-to-18-04
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding CSS file to page with extension's init
I'm reading this tutorial
That is how CSS file is loaded:
var linkTargetFinder = function () {
return {
init : function () {
gBrowser.addEventListener("load", function () {
// ...
}
}, false);
},
run : function () {
var head = content.document.getElementsByTagName("head")[0],
style = content.document.getElementById("link-target-finder-style")
if (!style) {
style = content.document.createElement("link");
style.id = "link-target-finder-style";
style.type = "text/css";
style.rel = "stylesheet";
style.href = "chrome://linktargetfinder/skin/skin.css";
head.appendChild(style);
}
// ...
}
};
}();
window.addEventListener("load", linkTargetFinder.init, false);
I can't understand why the CSS file can't be injected into page in init:
var linkTargetFinder = function () {
return {
init : function () {
gBrowser.addEventListener("load", function () {
var head = content.document.getElementsByTagName("head")[0]
style = content.document.createElement("link");
style.id = "link-target-finder-style";
style.type = "text/css";
style.rel = "stylesheet";
style.href = "chrome://linktargetfinder/skin/skin.css";
head.appendChild(style);
// ...
}
}, false);
},
run : function () {
// ...
}
};
}();
window.addEventListener("load", linkTargetFinder.init, false);
Styles just don't work in this case.
Why can't it be placed in init?
A:
Looks reasonable but for the gBrowser event use DOMContentLoaded not load.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Navigation controller is not working in multiple storyboard
I have a login page a the beginning of my app. when user is granted I'll redirect it to another storyboard.
In this below photo1: the white screen check is user granted or not. if yes I'll redirect the to Photo2. else I'll redirect them to the login page ( red pages in photo1).)
In below Photo2:(I'll show a table view which contains some data. when the user clicks one of them, it goes to the next page (right one).)
And Photo3 is just to clarify Photo2.
The problem is Photo2 after a user clicked a row in the table view. the back button does not work (it is visible in the app)
The code below shows the white screen's code in Photo1:
if let token = UserDefaults.standard.string(forKey: ConstantsKey.token){
if !token.isEmpty{
let storyboard : UIStoryboard = UIStoryboard(name: "MainTabBar", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MainTabBarVC")
let rootController = UINavigationController(rootViewController: vc)
rootController.navigationBar.barTintColor = UIColor.init(red: 229/255, green: 28/255, blue: 60/255, alpha: 1)
self.present(rootController, animated: true, completion: nil)
}else{
// let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LoginVc")
self.present(vc, animated: true, completion: nil)
}
}else{
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LoginVc")
self.present(vc, animated: true, completion: nil)
}
The code below shows the login page after the user is granted:
let storyboard : UIStoryboard = UIStoryboard(name: "MainTabBar", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MainTabBarVC")
let rootController = UINavigationController(rootViewController: vc)
self.present(rootController, animated: true, completion: nil)
The code below shows the way I redirect the user to the page which has the problem in the photo 2:
let next = self.storyboard?.instantiateViewController(withIdentifier: "ShopVc") as! ShopViewController
self.navigationController?.pushViewController(next, animated: true)
I Also have added the code below to Delegate :
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
UINavigationBar.appearance().shadowImage = UIImage()
Am I doing something wrong here which might cause this problem?
////////////////////////////////////////////////////////////////
ANSEWER
I created a new project which works fine there! I think it was the xCode's problem!
A:
restart your project , this could be an Xcode problem
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Shoulda Matcher with custom validation causing all shoulda validations to fail
I am running into a problem where a custom validation on my model is causing all of the shoulda validations to fail.
Essentially:
class User < ActiveRecord::Base
validates_presence_of :name
validate :some_date_validation
private
def some_date_validation
if date_given > birthday
errors.add(:birthday, "Some sort of error message")
end
end
end
And then in the spec:
require 'rails_helper'
RSpec.describe User, type: :model do
describe "shoulda validations" do
it { should validate_presence_of(:name) }
end
end
This will cause my test to fail because the other validation won't pass. Why is this?
A:
You need to test using an instance of an object which is valid by default.
When you use the implicit subject in your Rspec test, Rspec will create a new instance of the object under test for you using the default initializer. In this case, User.new. This instance will be invalid because neither name is present nor is the custom validation going to pass.
If you are using factories (e.g. factory_girl) then you should create a User factory which sets all the attributes which make the validations pass.
FactoryGirl.define do
factory :user do
name "John Doe"
date_given Time.now
birthday 25.years.ago
end
end
Then use it in your tests
require 'rails_helper'
RSpec.describe User, type: :model do
describe "shoulda validations" do
subject { build(:user) }
it { should validate_presence_of(:name) }
end
end
You've now explicitly set the subject of your tests to be a new instance of User created by your factory. The attributes will be pre-set which means your instance is valid by default, and the tests should now be able to test each individual validation properly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to trigger Bean after j_security_check complete authentication in Java
I'm quite new to java web page environment. Recently I try to develop an E-Business platform by using Java.
Hence, I'm using j_security_check Form-Based as my authentication tool. It was successfully to re-direct to desire page after authentication completed.
However, due to I have to load end user setting and information from Database (MS SQL 2005), so I have to load all the information after authentication completed and before page re-direct.
I had tried some method by using primefaces but it was unable to trigger the bean method that load user information.
One of the methods that I tried is using oncomplete to trigger the bean method
<h:form id="login" prependId="false"
onsubmit="document.getElementById('login').action='j_security_check';">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="j_username" value="Username:" />
<p:inputText value="#{loginBean.username}"
id="j_username" required="true" label="j_username" />
<h:outputLabel for="j_password" value="Password:" />
<h:inputSecret value="#{loginBean.password}"
id="j_password" required="true" label="j_password" />
<f:facet name="footer">
<p:commandButton id="loginButton" value="Login" type="submit" ajax="false"
oncomplete="#{loginBean.login()}"/>
</f:facet>
</h:panelGrid>
</h:form>
I also been tried something similar to this which just change oncomplete to onclick and others. End up doesn't has any method is workable.
Hence, I hope that anyone of you can give me advise how should I overcome this problem.
Million thanks,
A:
There are several solutions for this.
Create a servlet filter which checks the remote user and the presence of User entity in the session. If the remote user is not null, but the User entity is, then load it from the DB and set it in session. This is concretely answered here: Accessing user details after logging in with Java EE Form authentication
Perform lazy loading in the getter of a session scoped bean which should return the User entity. This is concretely answered in 1st part of this answer: Performing user authentication in Java EE / JSF using j_security_check
Perform programmatic login using a real JSF bean action method and obtain the User entity directly. This is concretely answered in 2nd part of this answer: Performing user authentication in Java EE / JSF using j_security_check
Unrelated to the concrete problem, you should be using <form action="j_security_check" method="post"> instead of a <h:form prependId="false">. Then you also don't need that nasty JS hack to change the form's action.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My first Stored Procedure is not working
This works:
mysql> select user_id, meta_value from 1_um where meta_key='1_caps';
What I want is:
insert into 1_um (user_id, meta_key, meta_value) values (user_id=$uid, meta_key='2_caps', meta_value=$mval);
But I keep getting zero rows affected from my attempts at a SP. Here's what I have:
Delimiter //
create procedure import_um()
BEGIN
declare done int default FALSE;
declare $uid bigint(20) unsigned default 0;
declare $mval longtext default "";
declare curs cursor for select user_id, meta_value from 1_um where meta_key='1_caps';
declare continue handler for not found set done = TRUE;
open curs;
read_loop: LOOP
fetch curs into $uid,$mval;
insert into 1_um (user_id, meta_key, meta_value) values (user_id=$uid, meta_key='2_caps', meta_value=$mval);
if done then leave read_loop;
end if; end LOOP; close curs; END//
moving "if done then leave read_loop; end if;" directly below the fetch statement (above the insert statement) has no effect, either.
It appears that the fetch into variable,var2 is not working, as I try to replace the insert statement with select concat('my var is', $uid); and get nothing to STDOUT.
the table 1_um contains four columns: umid (auto inc), user_id, meta_key, meta_value. Do I have to select all of them into the cursor?
A:
Why are you using a loop in your code? Just use insert . . . select:
insert into 1_um (user_id, meta_key, meta_value)
select user_id, '2_caps', meta_value
from 1_um
where meta_key = '1_caps';
No doubt a bit part of your problem is the misformed VALUES clause (you have boolean expressions for the values, which doesn't seem right). You should learn how to use VALUES correctly as well. But for this problem, use the correct SQL construct.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Transforming URLs so that LaTeX understands them
I frequently have to show snippets of Python code in slides, and I like to show their behaviour in PythonTutor. Unfortunately, a mere \href{my_url}{my_title} is problematic, since the URL will contain a lot of characters like % and & which is a problem for LaTeX.
I can of course escape all of these instances, but is there a more elegant / practical solution? I'm aware of PythonTutor's shortened URL option which circumvents the problem but won't be ideal if I change my code; a preferred option would be a command that reads data from some myprogram.py file and generates a valid link to PythonTutor with the code.
Update
I found a fix while preparing an example as righfully suggested by moewe: just make the frame fragile. Compilation works, and link is fully functional; but I'd still be interested in a command like \linkmyfile{pathtofile}{mycaption} that would behave as described above.
\documentclass{beamer}
\begin{document}
\begin{frame}[fragile]
\centering
\href{http://www.pythontutor.com/visualize.html#code=print%28%22Hello%20World!%22%29&cumulative=true&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false}{\bf Visualize my code}
\end{frame}
\end{document}
A:
A command \pythontutorlink{filename}{label} to automatically link to that website is not too hard to implement. The crucial parts are
Reading the Python file and storing the result,
escaping all non-letter and non-digit characters into the corresponding %-sequence,
and finally creating the link using \href.
Reading the file without having LaTeX complain about special characters, unbalanced braces etc. seemed tricky at first, but it's pretty simple using the catchfile package. That package already provides a command \CatchFileDef which reads a file and stores its contents in a new macro. Before we read the file, we need to make sure that special characters are handled correctly. This can be done by changing the catcodes of all special characters to class "other" (done in \@setupcatcodes).
We now have the file contents stored in \@tempfile. Next is building a URL from it. The final URL will be stored in a token register \@encodedurl which starts prefilled with the part of the URL before the actual code part. Now we map each character from the file contents to its corresponding %-sequence or keep it the same if it's a letter or digit. \@urlencode does this whole replacement by traversing its parameter text and calling \@encodechar on each character, which appends the appropriate result to \@encodedurl. Finally, some additional URL query parameters can be added, and then the result is passed to \href to produce the final output.
Here's the full code with an example link:
\documentclass{article}
\usepackage{filecontents}
\usepackage{catchfile}
\usepackage{hyperref}
\begin{filecontents*}{fibs.py}
def F(n):
if n == 0: return 0
elif n == 1: return 1
else: return F(n-1)+F(n-2)
print(F(6))
\end{filecontents*}
\makeatletter
\endlinechar=-1
\newtoks\@encodedurl
\def\@addtourl#1{\global\addto@hook\@encodedurl{#1}}
\def\@addtourlesc#1{\expandafter\@addtourl\expandafter{\@perc#1}}
{
\catcode`\#=12\relax
\catcode`\%=12\relax
\catcode`\&=12\relax
\gdef\@perc{%}
\gdef\@hash{#}
\gdef\@amp{&}
}
\def\@urlencode#1{\@@urlencode#1{}\@end}
\def\@@urlencode#1#2\@end{
\@encodechar{#1}
\if\relax\detokenize{#2}\relax
\else
\@@urlencode#2\@end
\fi
}
\def\@encodechar#1{
\ifnum`#1=`\^^M \@addtourlesc{0D}\else
\ifnum`#1=`\ \@addtourl{+}\else
\ifnum`#1=`\! \@addtourlesc{21}\else
\ifnum`#1=`\" \@addtourlesc{22}\else
\ifnum`#1=`\# \@addtourlesc{23}\else
\ifnum`#1=`\$ \@addtourlesc{24}\else
\ifnum`#1=`\% \@addtourlesc{25}\else
\ifnum`#1=`\& \@addtourlesc{26}\else
\ifnum`#1=`\' \@addtourlesc{27}\else
\ifnum`#1=`\( \@addtourlesc{28}\else
\ifnum`#1=`\) \@addtourlesc{29}\else
\ifnum`#1=`\* \@addtourlesc{2A}\else
\ifnum`#1=`\+ \@addtourlesc{2B}\else
\ifnum`#1=`\, \@addtourlesc{2C}\else
\ifnum`#1=`\- \@addtourlesc{2D}\else
\ifnum`#1=`\. \@addtourlesc{2E}\else
\ifnum`#1=`\/ \@addtourlesc{2F}\else
\ifnum`#1=`\: \@addtourlesc{3A}\else
\ifnum`#1=`\; \@addtourlesc{3B}\else
\ifnum`#1=`\< \@addtourlesc{3C}\else
\ifnum`#1=`\= \@addtourlesc{3D}\else
\ifnum`#1=`\> \@addtourlesc{3E}\else
\ifnum`#1=`\? \@addtourlesc{3F}\else
\ifnum`#1=`\@ \@addtourlesc{40}\else
\ifnum`#1=`\[ \@addtourlesc{5B}\else
\ifnum`#1=`\\ \@addtourlesc{5C}\else
\ifnum`#1=`\] \@addtourlesc{5D}\else
\ifnum`#1=`\{ \@addtourlesc{7B}\else
\ifnum`#1=`\| \@addtourlesc{7C}\else
\ifnum`#1=`\} \@addtourlesc{7D}\else
\@addtourl{#1}
\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
}
\def\@setupcatcodes{
\let\do=\@makeother\dospecials
\@makeother\ \relax
\@makeother\^^M\relax
}
\def\pythontutorlink#1#2{
\begingroup
\@setupcatcodes
\CatchFileDef\@tempfile{#1}{}
\global\@encodedurl={http://www.pythontutor.com/visualize.html\@hash code=}
\expandafter\@urlencode\expandafter{\@tempfile}
\@addtourl{\@amp mode=display}
\expandafter\href\expandafter{\the\@encodedurl}{#2}
\endgroup
}
\endlinechar=`\^^M
\makeatother
\begin{document}
Example link: \pythontutorlink{fibs.py}{Fibonacci numbers}
\end{document}
If other non-ASCII characters occur in the Python code, more character mappings may have to be added. An interesting addition would also be to use macros similar to the ones in A fully expandable conversion to hexadecimal numbers to directly calculate the hexcode from the character code, especially when used with XeLaTeX and Unicode input.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Write and replace string into txt file down an excel list
I would be incredibly appreciative if someone could point me to the right approach to accomplish this.
I have an excel table that is list of batters for a little league softball team. I would like to write each name into a txt file, one at a time as they come to bat, and replace the previous one. The contents of the txt file will be overlayed onto a video stream. So each time a girl comes up, I would like to do something easy that will allow the next line in the excel table to be written into the text file replacing the previous text.
Thanks!
A:
This set up automatically changes to next batter, and resets at the start of the lineup. Click button every new batter.
Sub saveAsTxt()
Dim ws As Worksheet
Set ws = Sheets("Sheet1")
Dim wsTwo As Worksheet
Set wsTwo = Sheets("Sheet2")
Dim NextBatterCounter As String
NextBatterCounter = ws.Range("C4")
Dim filePath As String
filePath = "Z:\New folder\"
Dim fileName As String
fileName = "BatterUp"
' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Dim fso As New FileSystemObject
Dim fileStream As TextStream
Set fileStream = fso.CreateTextFile(filePath & fileName)
fileStream.WriteLine ws.Range("A" & NextBatterCounter)
fileStream.Close
If ws.Range("C4") < 16 Then
ws.Range("C4") = ws.Range("C4") + 1
Else
ws.Range("C4") = 2
End If
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change a browsed page's ?
I'm jQuery beginner.
I'm trying to modify the source code of a page I'm browsing, using Firefox plus Greasemonkey.
How can I modify:
<input id="HiddenCategory" type="hidden" name="PageCategory"></input>
to:
<input id="HiddenCategory" type="text" name="PageCategory" value="OTHER"></input>
?
A:
Something like this?
$("#HiddenCategory").attr("type", "text").val("OTHER");
This is untested but i think it should work ok.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compare two lists of files and their content
While this might seem simple (and it might be!) I can't seem to find a way to solve it.
What I am trying to do is compare two lists of filtered files by their content. A example of this would be if two lists came back saying that they had a item called file.config at the location Stuff\files\morefiles then this would compare those files together and output where and what the changes were. Essentially, doing a diff of the .config files and showing where the changes are. This is normally simple for comparing two files (compare-object and such can be used) but because it is two lists of files rather then individual ones I am at a loss.
I need to do this to show a list of all changes needed to config files in a upgrade of software, so from one version of the software to the next, what are the changes made to the config files. I'm doing this in powershell because of the ability to easily interact with HG mercurial and be run by less experienced users (via a bat file).
The goal is to have a .txt file listing all the files that are changed in the new installation compared with the old one, or something similar.
Here's what I have so far:
$A = Get-ChildItem -Recurse -path "C:\repos\Dev\Projects\Bat\CurrentVersionRepoCloneTemp" -filter "*.config"
$B = Get-ChildItem -Recurse -path "C:\repos\Dev\Projects\Bat\UpgradeVersionRepoCloneTemp" -filter "*.config"
$C = Compare-Object $A $B -Property ('Name', 'Length') -PassThru | Where-Object {$_.FullName -eq $_.FullName} | ForEach-Object
{
Compare-Object (Get-Content FileA)(Get-Content FileB) #I know this doesn't work
}$C
Ideas or solutions?
A:
You could do a checksum of each file and compare that...
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($file)))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Permutation characters and regular orbits
Let a group $G$ act on a finite set $\Omega$. Suppose that the corresponding permutation character has a regular component. Does it follow that $\Omega$ has a regular $G$-orbit?
(The converse is obviously true.)
A:
No, this is false in general, and the smallest counterexample is the Klein 4-group $G=C_2\times C_2$. It can act transitively on a set of order 2 in three different ways, with 3 different $C_2$'s in the kernel. Call these sets $\Omega_1, \Omega_2, \Omega_3$, and their permutation characters $1+\chi_1, 1+\chi_2, 1+\chi_3$. Then the character of $\Omega=\Omega_1\coprod\Omega_2\coprod\Omega_3$ is $3+\chi_1+\chi_2+\chi_3$, which is 1+1+regular character of $G$, but $\Omega$ does not have a regular orbit.
A:
Not every non-cyclic finite group has such a relation. E.g., the quaternion group of order 8 doesn't.
(I meant this as a comment on Alex's answer, but I don't have enough reputation to comment.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to know if a push notification has been read or at least delivered in Marketing Cloud?
I added a push notification in my JB and my requirement is to send an SMS after some hours if the subscriber did not open or see the push notification.
Is there a way to get this information any how?
Thank you
A:
You can register a listener to be notified.
See NotificationManager.NotificationMessageDisplayedListener
In your application, you could set a tag (ref. Device/Contact Registration) based on the message being received or opened. That tag would be sent up with the device registration and become visible in MobilePush Demographics. It could then be used to create inclusion/exclusion lists to target people with messages via automations.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In the Horcrux Cave, was the Aguamenti spell too fundamentally weak to work?
I'm trying to ascertain if when Harry's spell (aguamenti) in the Horcrux cave was blocked by voldemort's protections, if it was too 'low level' a spell to have ever worked and Harry would have needed to know a more powerful spell (Aqua Eructo?). Or if Harry simply needed to cast it better than Voldemort cast his protection?
Here by better casting or a better spell I mean that the water would have lasted long enough to be drunk. Surely there is a way to overcome the anti-water protections in place?
A:
Actally, Aguamenti did indeed work.
Voldemort's protections simply vanished any water that was produced (successfully) by Harry.
"Aguamenti!" he shouted, jabbing the goblet with his wand. The goblet filled with clear water; Harry dropped to his knees beside Dumbledore, raised his head, and brought the glass to his lips — but it was empty. Dumbledore groaned and began to pant. "But I had some — wait — Aguamenti!" said Harry again, pointing his wand at the goblet. Once more, for a second, clear wa-ter gleamed within it, but as he approached Dumbledores mouth, the water vanished again. "Sir, I'm trying, I'm trying!" said Harry desperately, but he did not think that Dumbledore could hear him; he had rolled onto his side and was drawing great, rattling breaths that sounded agoniz-ing. "Aguamenti —Aguamenti —AGUAMENTI!"
The goblet filled and emptied once more. (Harry Potter and the Half-Blood Prince, Chapter 26: The Cave)
While it's not clear from canon, I don't think any "stronger" spell would have worked - the spells to produce water are not designed or concerned with what happens to the water AFTER it appears (e.g. they don't create "unvanishable" water).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does a right angle triangle ABC, right angled at A has A-symmedian?
A symmedian is defined to be the isogonal of a median in a triangle .
In EGMO , lemma 4.24 (Constructing the Symmedian),which states, "Let $X$ be the intersection of the tangents to $(ABC)$ at $B$ and $C$. Then line $AX$ is a symmedian."
My question is what happens to a right angle triangle , when we do this construction, the tangent lines don't meet . Is this construction of symmedian limited to only acute triangles and obtuse triangles.
The author of the book hasn't commented anything about this .
Though , by a simple angle chase, we can see that for a right angle triangle, the symmedian is the altitude.
Can someone clarify ?
Note: By EGMO, I mean the book, Euclidean Geometry in Mathematical Olympiads by Evan Chen.
A:
In the projective real plane, if $A$ is a right angle then
the tangents at $B$ and $C$ both are perpendicular to the side $BC$
and therefore are parallel to each other and meet at a point at infinity.
Let this point at infinity be $X$.
Then the line $AX$ is parallel to the tangents at $B$ and $C,$
and therefore it also is perpendicular to side $BC$.
The altitude from $A$ to $BC$ lies along line $AX,$ as required.
You can also do this without a point at infinity if you are willing to consider limiting cases for $A$ an acute angle approaching a right angle and $A$ an obtuse angle approaching a right angle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to change contents in switch dynamicaly on mouse click?
this is my script,here I wonder insert all questions in switch function and I'll like to change it and then display each questions with mouse click,but only 1st question is displaying, other clicks are not changing..what should i need to change over here.
window.onload = init;
var currentQuestion=1;
function init() {
switch (currentQuestion) {
case 1: $('.question').html('what is your name?');
break;
case 2: $('.question').html('where are you from?');
break;
case 3: $('.question').html('what is your fav color?');
break;
case 4: $('.question').html('what is your fav flower?');
break;
case 5: $('.question').html('which is your native?');
break;
default: break;
}
}
$("#next").click(function(){
currentQuestion++;
var before=currentQuestion-1;
console.log(currentQuestion);
console.log(before);
//$("before").hide();
});
.next img,.prev img
{
width:100px;
height:50px;
position:absolute;
}
.prev img
{left:115px;
}
<div class="question"></div>
<div class="input1" contenteditable="true"></div>
<div class="next">
<img id="next" src ="images/next-button.png" />
</div>
<div class="prev">
<img src ="images/download.jpg" />
</div>
<div class="answer"></div>
A:
You need to call the function init after every click.
Pass argument as currentQuestion so that switch will work accordingly. To use init on window.onload, I am accepting argument as currentQuestion
var currentQuestion = 1;
window.onload = function() {
init(currentQuestion);
};
function init(currentQuestion) {
switch (currentQuestion) {
case 1:
$('.question').html('what is your name?');
break;
case 2:
$('.question').html('where are you from?');
break;
case 3:
$('.question').html('what is your fav color?');
break;
case 4:
$('.question').html('what is your fav flower?');
break;
case 5:
$('.question').html('which is your native?');
break;
default:
break;
}
}
$("#next").click(function() {
currentQuestion++;
var before = currentQuestion - 1;
init(currentQuestion);
});
.next img,
.prev img {
width: 100px;
height: 50px;
position: absolute;
}
.prev img {
left: 115px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="question"></div>
<div class="input1" contenteditable="true"></div>
<div class="next">
<img id="next" src="images/next-button.png" />
</div>
<div class="prev">
<img src="images/download.jpg" />
</div>
<div class="answer"></div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Looping through a 2d array in ruby to display it in a table format?
How can i represent a 2d array in a table format in the terminal, where it lines up the columns properly just like a table?
so it looks like so:
1 2 3 4 5
1 [ Infinity | 40 | 45 | Infinity | Infinity ]
2 [ Infinity | 20 | 50 | 14 | 20 ]
3 [ Infinity | 30 | 40 | Infinity | 40 ]
4 [ Infinity | 28 | Infinity | 6 | 6 ]
5 [ Infinity | 40 | 80 | 12 | 0 ]
instead of:
[ Infinity,40,45,Infinity,Infinity ]
[ Infinity,20,50,14,20 ]
[ Infinity,30,40,Infinity,40 ]
[ Infinity,28,Infinity,6,6 ]
[ Infinity,40,80,12,0 ]
A:
a = [[Infinity, 40, 45, Infinity, Infinity],
[Infinity, 20, 50, 14, 20 ],
[Infinity, 30, 40, Infinity, 40 ],
[Infinity, 28, Infinity, 6, 6 ],
[Infinity, 40, 80, 12, 0 ]]
Step by Step Explanation
You first need to acheive the column width. col_width below is an array that gives the width for each column.
col_width = a.transpose.map{|col| col.map{|cell| cell.to_s.length}.max}
Then, this will give you the main part of the table:
a.each{|row| puts '['+
row.zip(col_width).map{|cell, w| cell.to_s.ljust(w)}.join(' | ')+']'}
To give the labels, do the following.
puts ' '*(a.length.to_s.length + 2)+
(1..a.length).zip(col_width).map{|i, w| i.to_s.center(w)}.join(' ')
a.each_with_index{|row, i| puts "#{i+1} ["+
row.zip(col_width).map{|cell, w| cell.to_s.ljust(w)}.join(' | ')+
']'
}
All in One This is for ruby1.9. Small modification shall make it work on ruby 1.8.
a
.transpose
.unshift((1..a.length).to_a) # inserts column labels #
.map.with_index{|col, i|
col.unshift(i.zero?? nil : i) # inserts row labels #
w = col.map{|cell| cell.to_s.length}.max # w = "column width" #
col.map.with_index{|cell, i|
i.zero?? cell.to_s.center(w) : cell.to_s.ljust(w)} # alligns the column #
}
.transpose
.each{|row| puts "[#{row.join(' | ')}]"}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a rule against taking food through TSA security checkpoints?
Twice in the last six months, when I went through the TSA checkpoint at San Jose airport, the screening agents specifically checked that I didn't have any food in my bags. The first time, I asked the agent about it and he said that there was a new rule as of March(?) 2018 prohibiting any food from being brought through a security checkpoint - including (but not limited to) dry food and processed food like cookies, nuts, granola bars, or so on. The thing is, other people I talk to in other parts of the country have never heard of this rule, I can't find any documentation about it online, and when I flew from another airport in the northeast, they didn't mention anything about food.
So... is there actually a TSA rule against taking food through security? Or if not a general rule, is there something going on that's specific to San Jose?
If I'd only encountered it once, I could dismiss it as a fluke, but I've been told about this twice, from two different agents, several months apart, which makes it harder to dismiss.
A:
The TSA "Can I Bring?" tool, in general, says that food is allowed. There are a number of foods that are not allowed, but these are mainly due to the LAG (Liquid, Aerosol, Gel) regulations and thus limited to 100ml.
I fly out of SJC on average about once every 4-6 weeks, and I have never been asked about food at any point, and I always travel with some food in my bag (a few granola bars at a minimum), so it's something that I would remember being asked. I've also never heard it at any other airport, nor have I had any friends/work colleges/etc mention it to me.
SJC airport does frequently use dogs for security (all passengers are made walk past a dog, and then generally get "pre-check like" checking such as going through metal detectors rather than millimeter wave scanners). Whilst it is possible that the food question might have been related to the use of a dog, I've still never been asked it (even when they are using a dog).
UPDATE: Just went through TSA at EWR airport. They asked for food to be taken out of all bags (just like they do for laptops/etc). I asked the staff and they said it's a new policy as they can't always see it clearly. I took a zip-lock bag of biscuits out, but left a number of granola bags in my bags and they didn't say anything about them.
A:
Recently the TSA has been asking for food to be taken out of carry-on bags like electronic devices, and liquids. I mainly travel with prepackaged granola bars or cliff bars. I pulled them out and there wasn't any problems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
prove two matrices are similar
determine if the following matrices are similar, if yes, prove it.
\begin{pmatrix}
2 & 1 \\
0 & 2 \\
\end{pmatrix}
\begin{pmatrix}
2 & 0 \\
0 & 2 \\
\end{pmatrix}
I checked some shared properties between similar matrices, such as determinant, characteristic polynomial and trace. Everything seems fine, I guess they are similar, but how to prove this? Thank you in advance.
A:
They are not similiar, cause you can't diagonalize the first one, as you only find one eigenvector, but the second one is already diagonal.
A:
Note that the second matrix is $2I$. IF the two matrices are similar, then $\pmatrix{2&1\\ 0&2}=P(2I)P^{-1}$ for some invertible matrix $P$. Now, do you know what is $P(2I)P^{-1}$ equal to?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use files with multiple extensions with Prettier?
I have following Prettier commands:
prettier --parser typescript --write ./src/**/*.ts
prettier --parser typescript --write ./src/**/*.tsx
I would like to merge them to single one - use some king of regex to listen (write) on both .ts and also .tsx extensions.
Something like:
prettier --write ./src/**/*.ts(x?)
A:
Just found solution. Following command will target both ts and tsx:
prettier --write "./src/**/*.{ts,tsx}"
Prettier is using Glob syntax which is syntax similar to Regex, used in shell.
See GLOB syntax details: https://github.com/isaacs/node-glob/blob/master/README.md#glob-primer
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why are there no stars visible in cislunar space?
It’s very puzzling that the moon landing had no stars in the background, the ISS clips have no stars in the background. I listened to multiple astronaut interviews speak on what it looks like up in space and about half of them speak of the “darkest black space”. I’m sure there is a very good explanation for this.
Is star light only visible through the medium of earth atmosphere? But once in the vacuum of space where there is no medium they disappear? What’s the explanation?
Minute 47-49 stars, press conference all three Apollo 11 astronauts
BBC interview with Neil Armstrong only
A:
It is a matter of exposure and dynamic range. A sensor like a camera can only handle inputs in a certain range of intensities, and much of photographic skill (or smart presets) is about mapping the outside light onto this range so the details you care about show up rather than turn into white or black.
If you take a picture of a brightly lit scene, in order to make out the details of the bright parts (such as a lunar landscape, the Earth, the ISS etc) you will have to adjust the exposure making faint objects like the stars too dim to see against a dark sky background. You could try to set the exposure to show the stars instead, but now the landscape and Earth would be too bright (and likely also mess up the picture by causing flaring).
One can try to work around it by taking several pictures at different exposure levels and later digitally compositing them together. But this requires a lot of extra work.
A:
Anders's answer is entirely fine, but I'd like to add some extra information. As evidenced by the transcripts, reflected Earth light is quite strong even at this distance:
The earthshine coming through the window is so bright you can read a book by it.
That is, even with the lights turned off, it would probably be tricky to see the stars unless you turned in a way that didn't allow the earthshine through the windows.
However, as the capsule comes into the shadow cast by the Moon (a pure accident - they didn't plan for the approach to go this way), there comes:
Houston, it's been a real change for us. Now we are able to see stars again and recognize constellations for the first time on the trip. It's - the sky is full of stars. Just like the nightside of Earth. But all the way here, we have only been able to see stars occasionally and perhaps through the monocular, but not recognize any star patterns.
So for a few minutes, they did see "the sky full of stars". Other than that, they've seen a few stars once in a while, but only singular, bright stars (perhaps also when looking in a way that minimized the brightness from the Earth and Sun):
Houston, it's been a real change for us. Now we are able to see stars again and recognize constellations for the first time on the trip. It's - the sky is full of stars. Just like the nightside of Earth. But all the way here, we have only been able to see stars occasionally and perhaps through the monocular, but not recognize any star patterns.
The core of Anders's answer is still true, though. Exposure is the main problem here - both cameras and human eyes have a certain dynamic range, and even the brightest stars are entirely too dim in comparison with both the Sun, the Earth (in distance comparable to the Moon's distance from the Earth) and the Lunar surface (if you're in sunshine, as most of the mission was). A modern camera might be able to take a HDR picture that would allow the stars to be visible at the same time as the Earth or the Sun, and it'd be quite easy to do if you could occlude the main light sources (the same way we do it when photographing the Sun's corona etc.). But technically, that would be a "doctored" image - taken at two different exposures and combined in a way that uses different exposures for different parts of the image.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MYSQL Join From Two Tables
I am not sure what I am missing but I know it should not be this hard. I have two tables. First table lists all the possible jobs for a site. The second table has when a job was completed at a site. I want a query where by I get all the possible jobs and join in the data from the seconds table should there be some. Site that have not completed the job would have a NULL value.
Example:
Table 1:
ID
name
decsription
Table 2:
ID
siteID
status
jobID
SELECT table1.* , table2.*
FROM table1
LEFT JOIN table2
ON table1.id = table2.jobID
WHERE siteID = 12
This only returns jobs that have been completed and not all jobs completed and uncompleted.
Thanks in advance for your help.
A:
you should drop then where statement (when the row in second table is emty it doesn't meet the condition siteID=12) or change it (add "OR siteID is NULL" ) if you want this specific site or null
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Strange cakePHP Auth issue for IE (login not working)
I am facing a strange issue here.
I am using CakePHP 1.3.6 & for IE 6-7-8 it is not allowing me to login. I am using the correct credentials. tested these with recorded in logs.
There is no any auth error displayed. (If i use wrong credentials then it shows the auth error, but for correct credentials it shows nothing :( )
I have tested all the possibility with auth component by logging logs into the error.log file.
I checked the Auth->user method. It populates Auth session, but even though it is not redirecting me to the desired location.
I also checked the authLoginurl : it is aslo correct in logs.
I have checked the following possibilities,
1) Changed some settings from Core.php
-- Session.checkAgent set to false
-- Security.level set to low
-- Session.start set to false
2) used disableCache() for login action to avoid the caching of the login data in browser.
3) After logout i have destroyed the session.
Here is the code,
App Controller in beforeFilter :
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'myaccount');
$this->Auth->userScope = array('User.is_active' => '1', 'User.is_verified' => '1');
//$this->referer();
//auth errors //add it
$this->Auth->loginError = "Invalid username or password";
$this->Auth->authError = "Sorry, you must be logged in to visit these pages";
//logout
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
User Controller beforeFilter() :
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(allowed_actions);
}
Thnaks,
Vijay
A:
I've had the same problem, it was with a different cake version, but maybe this solution will help.
In config I made a my_session.php file with the following values:
ini_restore('session.referer_check');
ini_set('session.use_trans_sid', 0);
ini_set('session.name', Configure::read('Session.cookie'));
ini_set('session.cookie_lifetime', 0);
// Cookie path is now '/' even if you app is within a sub
// directory on the domain
$this->path = '/';
ini_set('session.cookie_path', $this->path);
ini_set('session.cookie_domain', env('HTTP_BASE'));
The important part is the $this->path value, sessions are now available for the whole domain.
In core.php for sessions add:
Configure::write('Session.save', 'my_session');
Hopes this helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Connecting Tables in Rails
Table City Model
class TableCity < ActiveRecord::Base
has_many :near_cities, :foreign_key => "nearcity_id"
end
NearCity Model
class NearCity < ActiveRecord::Base
belongs_to :table_city
end
Controller
@table_cities = TableCity.find(:all, :conditions=>{:state => params[:gm], :language => params[:sp]}, :include => :near_cities)
View
<% @table_cities.each do |table_city| %>
<%= table_city.name %>
<% table_city.near_cities.each do |city| %>
<%= city.text %>
<% end %>
<% end %>
This is not working, Kindly give me some suggestions.
A:
Your relationships look strange. A NearCity belongs to a TableCity therefore, you should be storing the foreign key of the TableCity in your near_cities table. To achieve this make sure your near_cities table has a column called table_city_id.
Your models can simply be:
class TableCity < ActiveRecord::Base
has_many :near_cities
end
class NearCity < ActiveRecord::Base
belongs_to :table_city
end
|
{
"pile_set_name": "StackExchange"
}
|
Q:
run-time error '438' Object does'nt support this property or method
I'm trying to copy the contents of a range in my active workbook to another workbook, and I found a piece of vba code that i think fits perfectly for my needs.
Altough, everytime I try to run it, I receive the following error: run-time error '438' Object does'nt support this property or method.
I suppose the problem is the way I'm selecting the range in the destination workbook, but nothing os working.
Could anyone help?
Here is what I have:
Sub Retânguloarredondado1_Click()
Dim InputFile As Workbook
Dim OutputFile As Workbook
Dim Inputpath As String
Dim Outputpath As String '
Dim TP As Worksheet
' Set path for Input & Output
fileInputpath = "C:\Users\Nuno Bonaparte\Desktop\"
Outputpath = "C:\Users\Nuno Bonaparte\Desktop\"
'## Open both workbooks first:
Set InputFile = ActiveWorkbook
Set OutputFile = Workbooks.Open(Outputpath & "file2.xlsm")
Set TP = OutputFile.Worksheets("Folha1")
'Now, copy what you want from InputFile:
InputFile.Sheets("file2").Activate
InputFile.Sheets("file2").Range("A1:A12").Copy
'Now, paste to OutputFile worksheet:
OutputFile.Sheets("Folha1").Activate
TP.Range("A1").PasteSpecialOutputFile.Save
'Close InputFile & OutputFile:
InputFile.Close
OutputFile.Close
End Sub
A:
See if you get the same error with this code:
Sub Retânguloarredondado1_Click()
Dim Paths As String
' Set path
Paths = "C:\Users\Nuno Bonaparte\Desktop\"
'## Open both workbooks first:
Workbooks.Open(Paths & "file1.xlsm")
Workbooks.Open(Paths & "file2.xlsm")
'Now, copy what you want from InputFile:
Workbooks("file1.xlsm").Sheets("file2").Range("A1:A12").Copy
'Now, paste to OutputFile worksheet:
Workbooks("file2.xlsm").Worksheets("Folha1").Range("A1").PasteSpecial
Workbooks("file2.xlsm").Save
'Close InputFile & OutputFile without saving
InputFile.Close False
OutputFile.Close False
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using hashes in a chaining manner
Using hashes in a chaining manner confuses me a lot. For instance, I read the following Perl codes, how to understand them piece by piece?
$model->{result}->{forcast}->[$index]->{label} = 1;
$Neg{$examples->{result}->[$index]->{title}} = 1
In addition, why some items has $ , like $index; while others do not have, like label.
$index is wrapped in [ ] while others are wrapped in { }, what are the differences here?
Is $Neg{$examples->{result}->[$index]->{title}} = 1 equivalent to $Neg{$examples->{result}->[$index]->{title}} = 1
A:
Consider:
$model->{result}->{forcast}->[$index]->{label} = 1;
->[] is used to dereference an array reference.
->{} is used to dereference a hash reference.
Let us scan it from the left:
$model is a hash reference (due to it being used in the context: $model->{})
result is a hash key (as it does not have a $ sigil prepended)
$model->{result} is again a hash reference
$model->{result}->{forcast} is an array reference (due to it being used in the context: $model->{result}->{forcast}->[])
$index is a variable set by the user that possibly contains the index of an array item
$model->{result}->{forcast}->[$index] is a hash reference
label is a hash key
$model->{result}->{forcast}->[$index]->{label} sets 1 as the value for the hash key
Hash keys can be barewords, which will be automatically quoted. So, specifying the hash key as result or 'result' are the same.
perldoc perldsc is the cookbook for data structures. Data::Dumper is very helpful in viewing such data structures.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maven "import" scope
I have module and tests for that module.
Tests need resteasy-client, but module doesn't.
I don't want mix module dependencies and dependencies for tests, how can i do this? I trying to use maven 'import' scope.
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.my.project</groupId>
<artifactId>my-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>my-module-1</artifactId>
<packaging>jar</packaging>
<name>This is one of my modules</name>
<dependencies>
<dependency>
<groupId>ru.my.project</groupId>
<artifactId>my-module-2</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!--I want to import dependencies for test from this pom:-->
<dependency>
<groupId>ru.my.project.test</groupId>
<artifactId>my-module-1-test</artifactId>
<type>pom</type>
<version>1.0</version>
<scope>import</scope>
</dependency>
</dependencies>
</project>
and my-module-1.pom in local nexus repository:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.my.project.test</groupId>
<artifactId>my-module-1-test</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<name>Dependencies for testing module-1</name>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.11.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.11.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
I seems that mvn sees this file, but compilation fails:
[ERROR] /home/xxx.java:[5,38] error: package org.jboss.resteasy.client.jaxrs does not exist
[ERROR] /home/xxx.java:[6,38] error: package org.jboss.resteasy.client.jaxrs does not exist
[ERROR] /home/xxx.java:[7,38] error: package org.jboss.resteasy.client.jaxrs does not exist
But when I copy-paste those dependensies in module-1`s pom.xml everything is fine! But I don't want to mix, it becomes unreadable fast.
A:
This is because the import scope does work only within <dependencyManagement>. (Under the cover it basically just paste the imported content.)
So, it can be used for managing (setting up) versions of dependencies you will potentially use, but the actual depending on them needs separate declaration (within <dependencies>).
The best way I found so far for achieving your goal (as I get it) is to create module like my-module-1-testing-support which depends on JUnit, Mockito, etc. using compile scope. Then you can depend on my-module-1-testing-support using test scope and get its dependencies (transitively) using test scope as well, as described at Introduction to the Dependency Mechanism.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Retrieving data from span with jquery and c#
I'm trying to retrieve some values from span which are inside a td. I have this function:
function reorder() {
alert("Entrando en reorder");
strorder = "";
var totalid = $('#ctl00_ContentPlaceHolder1_grdResultados tr td input').length;
alert(totalid);
for (var i = 0; i < totalid; i++) {
strorder = strorder +$('#ctl00_ContentPlaceHolder1_grdResultados tr td span')[i].text()+"*"+ $('#ctl00_ContentPlaceHolder1_grdResultados tr td input')[i].getAttribute("value") + "|";
alert("strorder1");
}
//strorder = window.location.href;
alert("strorder2");
}
And the source code is this (a piece of the code):
<table class="table table-hover tablaDimensiones" cellspacing="0" border="0" id="ctl00_ContentPlaceHolder1_grdResultados" style="border-collapse:collapse;">
<tr>
<th scope="col">
<a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$grdResultados','Sort$titulo')">Título</a>
</th>
<th scope="col">Opciones</th>
</tr>
<tr>
<td>
<span id="ctl00_ContentPlaceHolder1_grdResultados_ctl02_lblTitulo">Dimension1</span>
<input type="hidden" name="ctl00$ContentPlaceHolder1$grdResultados$ctl02$hdnid" id="ctl00_ContentPlaceHolder1_grdResultados_ctl02_hdnid" value="1" />
</td>
<td>
<a id="ctl00_ContentPlaceHolder1_grdResultados_ctl02_cmdEditar" title="Editar" class="btn btn-default" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$grdResultados$ctl02$cmdEditar','')">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
<a onclick="return confirm('¿Desea elimnar la dimensión?');" id="ctl00_ContentPlaceHolder1_grdResultados_ctl02_cmdEliminar" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$grdResultados$ctl02$cmdEliminar','')">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
</td>
</tr>
<tr>
How can I do it?, because in this way I don't have what I want. Regards
A:
I beleive that the following example is what you looking for you've almost correct code you should just organize it a little.
NOTE : The only error in your code is in the long line :
strorder = strorder +$('#ctl00_ContentPlaceHolder1_grdResultados tr td span')[i].text()+"*"+ $('#ctl00_ContentPlaceHolder1_grdResultados tr td input')[i].getAttribute("value") + "|";
Hope this helps.
function reorder() {
var strorder = "";
var table_spans = $('#ctl00_ContentPlaceHolder1_grdResultados span[id^="ctl00_ContentPlaceHolder1"]');
var table_inputs = $('#ctl00_ContentPlaceHolder1_grdResultados input');
for (var i = 0; i < table_inputs.length; i++)
{
var span_text = table_spans.eq(i).text();
var input_value = table_inputs.eq(i).val();
strorder += span_text + "*" + input_value + "|";
}
console.log(strorder);
}
reorder();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<table class="table table-hover tablaDimensiones" cellspacing="0" border="0" id="ctl00_ContentPlaceHolder1_grdResultados" style="border-collapse:collapse;">
<tr>
<th scope="col">
<a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$grdResultados','Sort$titulo')">Título</a>
</th>
<th scope="col">Opciones</th>
</tr>
<tr>
<td>
<span id="ctl00_ContentPlaceHolder1_grdResultados_ctl02_lblTitulo">Dimension1</span>
<input type="hidden" name="ctl00$ContentPlaceHolder1$grdResultados$ctl02$hdnid" id="ctl00_ContentPlaceHolder1_grdResultados_ctl02_hdnid" value="1" />
</td>
<td>
<a id="ctl00_ContentPlaceHolder1_grdResultados_ctl02_cmdEditar" title="Editar" class="btn btn-default" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$grdResultados$ctl02$cmdEditar','')">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
<a onclick="return confirm('¿Desea elimnar la dimensión?');" id="ctl00_ContentPlaceHolder1_grdResultados_ctl02_cmdEliminar" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$grdResultados$ctl02$cmdEliminar','')">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
</td>
</tr>
</table>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Organise tables on mobile so that user can easily scroll
I have a mobile site that contains multiple tables of data. These tables are relatively long, but have a height restriction, meaning that when a user scrolls over the table on a mobile, it scrolls the table instead of the page.
Can anyone suggest a better way to deal with this, so that it is easy to scroll up and down the page and equally as easy to scroll through the tables?
Thanks in advance.
A:
Make sure that the table doesn't fill up the entire vertical space of the screen so that a user can drag a spot below the table to keep scrolling down the page. If you do this, here are some excellent guidelines to make it obvious that the table is scrollable.
Alternatively, can you use tabs to separate the tables? Without knowing more about your dashboard/application, I can't say if this is reasonable, but it's worth considering.
Finally, here's a helpful article about using tables in responsive design. It presents some options for displaying large tables.
A:
I don't have a larger context of your design but presenting you few options that might help:
Option 1:
Show upto few rows for each table without any scroll and have a +SEE ALL button. Clicking that would reveal the full table with a -SEE LESS button. Full table will not have a scroll within the table but just goes with the page scroll.
Option 2:
Just show the table headings. On click, show the table in a popup / full screen with a close / back button. The table can have a fixed height and scrollable content.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Loop within custom post type generating the_title as text
Looking for an ACF custom post type php junkie to help me with this. I couldn't find another question on here like this so I might be off as far as the best practice solution for this, but hopefully not!
Within a specific post type, I am trying to load another post type in a loop.
As a practical example here, within each neighborhood I want to list apartments dynamically.
My original idea was to do an ACF checkbox listing the neighborhood titles so the value property loaded the neighborhood's the_title dynamically.
This worked, but for some reason the load also pulls in the_title as text above the loop.
Thoughts? (code below)
<?php
$apartments = query_posts(array(
'meta_query' => array(
array(
'key' => 'apartment_neighborhood',
'value' => the_title(),
'compare' => 'LIKE'
)
),
'post_type' => 'apartments',
'orderby'=> 'title',
'order' => 'ASC' ));
$loop = new WP_Query( $apartments );
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
A:
Use get_the_title(); as it return the value while the_title(); prints it
<?php
$apartments = query_posts(array(
'meta_query' => array(
array(
'key' => 'apartment_neighborhood',
'value' => get_the_title(),
'compare' => 'LIKE'
)
),
'post_type' => 'apartments',
'orderby'=> 'title',
'order' => 'ASC' ));
$loop = new WP_Query( $apartments );
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
Refer Here
Get The Title
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why UWP ApplicationPageBackgroundThemeBrush is always white?
I am beginner. I have below simplest code:
<Page
x:Class="ClientFramework.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ClientFramework"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>
</Page>
I test it in Windows mobile 10 emulator. No matter how I change OS theme, dark or light, my app's background is always white. So what is correct way to set theme-dependent app-wide colours?
A:
I eventually find out the problem by googling about. The problem is caused by the VS2015 project template. In app.xaml, there is a line to set RequestedTheme="Light". I removed the line and things are fine now. Wasted me 2 hours. Hope you see my answer and therefore save time.
https://social.msdn.microsoft.com/Forums/vstudio/en-US/c12cdba4-093f-474a-9d21-6e447aaa2adf/uwp-applicationpagebackgroundthemebrush-is-always-white?forum=wpdevelop
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Move global constexpr class into class as static constexpr
I have some global constexpr Masks that I would like to make a part of my Mask class as a static constexpr to reduce globals in main.cpp
Currently this works:
main.cpp has:
constexpr Mask cg_completeMask(0xffffffffffffffffull, 0x1ffff);
Mask.hpp has (reduced for SO):
class Mask {
unsigned long long m_64;
unsigned int m_32;
public:
constexpr Mask(const unsigned long long ac_64, const unsigned int ac_32) :
m_64(ac_64),
m_32(ac_32)
{}
};
What I tried to move the global Masks from main.cpp:
Mask.hpp has:
class Mask {
unsigned long long m_64;
unsigned int m_32;
public:
static constexpr Mask completeMask;
constexpr Mask(const unsigned long long ac_64, const unsigned int ac_32) :
m_64(ac_64),
m_32(ac_32)
{}
};
Mask.cpp has:
constexpr Mask Mask::completeMask(0xffffffffffffffffull, 0x1ffff);
What I tried produces these errors:
In file included from main.cpp:3:0:
Mask.hpp:12:27: error: constexpr static data member 'completeMask' must have an initializer
static constexpr Mask completeMask;
^
In file included from Mask.cpp:1:0:
Mask.hpp:12:27: error: constexpr static data member 'completeMask' must have an initializer
static constexpr Mask completeMask;
^
A:
Best I could get was this, which ought to do what you want - but does unfortunately expose your constants in the interface. This is unavoidable I'm afraid.
* Mask.hpp
class Mask {
unsigned long long m_64;
unsigned int m_32;
// private constructor
constexpr Mask(const unsigned long long ac_64, const unsigned int ac_32) :
m_64(ac_64),
m_32(ac_32)
{}
public:
// public declarations
inline static constexpr Mask complete();
inline static constexpr Mask partial();
};
// inline definitions
constexpr Mask Mask::complete()
{
return Mask(0xffffffffffffffffull, 0x1ffff);
}
constexpr Mask Mask::partial()
{
return Mask(0xf0f0f0f0f0f0f0f0ull, 0x1ffff);
}
example of use:
auto main() -> int
{
auto m1 = Mask::complete();
auto m2 = Mask::partial();
return 0;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Download file by Jquery
i search google and got a code snippet for downloading file by jquery. the syntax is like below
var downloadURL = function(url)
{
var iframe;
iframe = document.getElementById("hiddenDownloader");
if (iframe === null)
{
iframe = document.createElement('iframe');
iframe.id = "hiddenDownloader";
iframe.style.visibility = 'hidden';
document.body.appendChild(iframe);
}
iframe.src = url;
}
but could not understand how it works. how call it and how to pass url. so please help me to use the above function and tell me how to pass url as argument. please also tell me what type of code is the above it is not a function.
var downloadURL = function(url)
how it works. variable name equal to function name. a function can be called but the above code snippet can not be called. so please discuss in detail. thanks.
A:
Your sample code is an equivalent to doing this:
function downloadURL(url)
{
var iframe;
iframe = document.getElementById("hiddenDownloader");
if (iframe === null)
{
iframe = document.createElement('iframe');
iframe.id = "hiddenDownloader";
iframe.style.visibility = 'hidden';
document.body.appendChild(iframe);
}
iframe.src = url;
}
Therefore you can call the function this way:
downloadURL('file.txt');
Now, what the function is doing is creating an iframe element in the page and setting the address to the url passed as argument, this will make the browser to show the download dialog for that file.
Hope this makes it clear.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I add 2 64 bit numbers in a 32 bit machine
I was asked this in an interview and my feeling at first was that each 64 bit number will be stored in two 32 bit memory locations and then the system can do normal addition arithmetic based on its Endian rules. But I did not get confirmation on whether my answer was right or not and i have been having doubts. I know this might be very basic but I need to know. Thanks
A:
If you don't have the overflow bit, then you have to add the 31 lowest bits together first, and then you can check if the 2^31 place overflows*. Then you set that bit correctly. Then you add the highest 32 bits together, add 1 if it overflowed in *. Overflow on the highest 32 bits are OK, and handles the two's complement arithmetic nicely.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PDF of distance from origin to simplex in high dimension
Let $\Delta^{n-1}$ be the standard simplex in $n$ dimensions:
$$ \Delta^{n-1} = \{ \mathbf{x}\in \mathbb{R}^n: \sum_i x_i=1 , \mathbf{x}\geq0\} $$
And assuming that we are uniformly sampling points $\mathbf{X}$ from this simplex, then the Euclidean distance $|\mathbf{X}|$ can also be considered a random variable. In the limit of $n\rightarrow\infty$, does the probability distribution of $|\mathbf{X}|$ approach some limit distribution that can be written in closed form?
A:
Let's change a bit the symbols and define
$$
\eqalign{
& T(n - 1,c) = \left\{ {{\bf x} \in R^{\,n} \;:\;\sum\limits_{1\, \le k\, \le \,n} {x_{\,k} } = c\quad \left| {\;0 \le x_{\,k} } \right.} \right\} \cr
& U(n,c) = \left\{ {{\bf x} \in R^{\,n} \;:\;\sum\limits_{1\, \le k\, \le \,n} {x_{\,k} } \le c\quad \left| {\;0 \le x_{\,k} } \right.} \right\} \cr}
$$
Let's then introduce a second euclidean reference system $\bf y$,
having the $y_n$ axis aligned with the diagonal axis $x_1=x_2=\cdots = x_n$, normal to $T(n-1,c)$
$$
{\bf y} \in R^{\,n} \;:\;{\bf y} = {\bf Q}\,{\bf x}\; \wedge y_{\,n} = {1 \over {\sqrt n }}\sum\limits_{1\, \le k\, \le \,n} {x_{\,k} }
$$
The matrix $Q$ being orthogonal.
Indicating by $V(n,\, c)$ the volume of $U(n,\, c)$, and by $A(n-1,\, c)$ the volume of $T(n-1,\, c)$, we know that
$V(n,\, c)=c^n/n!$ and that the relation with $A(n-1,\, c)$ is given by
$$
\eqalign{
& V(n,c) = {{c^{\,n} } \over {n!}} = \cr
& = \mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,U(n,\,c)} dx_{\,1} \cdots dx_{\,n}
= \mathop {\int { \cdots \int {} } }\limits_{{\bf y}\, \in \,U(n,\,c)} dy_{\,1} \cdots dy_{\,n} = \cr
& = \int_{t = 0}^{\;c} {\left( {\mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,T(n - 1,\,t)} dy_{\,1} \cdots dy_{\,n - 1} } \right){{dt} \over {\sqrt n }}} = \cr
& = {1 \over {\sqrt n }}\int_{t = 0}^{\;c} {A\left( {n - 1,t} \right)dt} \cr}
$$
so that
$$
\eqalign{
& A\left( {n - 1,c} \right) = \sqrt n {{c^{\,n - 1} } \over {\left( {n - 1} \right)!}}\quad \left| {\;A\left( {1,c} \right) = \sqrt 2 \,c} \right. \cr
& V\left( {n,c} \right) = \int_{t = 0}^{\;c} {V\left( {n - 1,t} \right)dt} = {{c^{\,n} } \over {n!}} \cr
& {{A\left( {n,c} \right)} \over {\sqrt {n + 1} }} = \int_{t = 0}^{\;c} {{{A\left( {n - 1,t} \right)} \over {\sqrt n }}dt} = {{c^{\,n} } \over {n!}} \cr}
$$
Coming to the problem, we are practically asked to determine the 2nd moments of T(n-1,1) wrt the origin.
Let's start and determine the moments of U(n,c):
$$
\eqalign{
& Y(n,c) = \mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,U(n,\,c)} \left( {\sum\limits_{1\, \le k\, \le \,n} {x_{\,k} ^2 } } \right)dx_{\,1} \cdots dx_{\,n} = \cr
& = \mathop {\int { \cdots \int {} } }\limits_{{\bf y}\, \in \,U(n,\,c)} \left( {\sum\limits_{1\, \le k\, \le \,n} {y_{\,k} ^2 } } \right)dy_{\,1} \cdots dy_{\,n} = \cr
& = \int_{t = 0\;}^{\;c} {\left( {\mathop {\int { \cdots \int {} } }\limits_{{\bf y}\, \in \,T(n - 1,\,t)} \left( {\sum\limits_{1\, \le k\, \le \,n} {y_{\,k} ^2 } } \right)
dy_{\,1} \cdots dy_{\,n - 1} } \right){{dt} \over {\sqrt n }}} = \cr
& = \int_{t = 0}^{\;c} {\left( {\mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,T(n - 1,\,t)} \left( {\sum\limits_{1\, \le k\, \le \,n} {x_{\,k} ^2 } } \right)
dA\left( {n - 1,t} \right)} \right){{dt} \over {\sqrt n }}} \cr}
$$
Then
$$
\sqrt n {d \over {dc}}Y(n,c)
= \mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,T(n - 1,\,c)} \left( {\sum\limits_{1\, \le k\, \le \,n} {x_{\,k} ^2 } } \right)
dA\left( {n - 1,c} \right)
= I(n - 1,c)
$$
and
$$
{{I(n - 1,1)} \over {A(n - 1,1)}}
$$
will give the required expected value of the sum.
Let's put up a recursion to compute $Y(n,c)$.
$$
\eqalign{
& Y(n,c) = \mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,U(n,\,c)} \left( {\sum\limits_{1\, \le k\, \le \,n} {x_{\,k} ^2 } } \right)dx_{\,1} \cdots dx_{\,n} = \cr
& = \int_{x_{\,n} = 0}^{\;c} {\left( {\mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,U(n - 1,\,c - x_{\,n} )}
\left( {\left( {\sum\limits_{1\, \le k\, \le \,n - 1} {x_{\,k} ^2 } } \right) + x_{\,n} ^2 } \right)dx_{\,1} \cdots dx_{\,n - 1} } \right)dx_{\,n} } = \cr
& = \int_{t = 0}^{\;c} {t^{\,2} \left( {\mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,U(n - 1,\,c - t)} dx_{\,1} \cdots dx_{\,n - 1} } \right)dt} + \cr
& + \int_{t = 0}^{\;c} {\left( {\mathop {\int { \cdots \int {} } }\limits_{{\bf x}\, \in \,U(n - 1,\,c - t)}
\left( {\left( {\sum\limits_{1\, \le k\, \le \,n - 1} {x_{\,k} ^2 } } \right)} \right)dx_{\,1} \cdots dx_{\,n - 1} } \right)dt} = \cr
& = \int_{t = 0}^{\;c} {t\,^2 \;V(n - 1,\,c - t)dt} + \int_{t = 0}^{\;c} {Y\left( {n - 1,\,c - t} \right)dt} = \cr
& = {1 \over {\left( {n - 1} \right)!}}\int_{t = 0}^{\;c} {t^{\,2} \;\left( {c - t} \right)^{\,n - 1} dt} + \int_{t = 0}^{\;c} {Y\left( {n - 1,\,c - t} \right)dt} = \cr
& = {{c^{\,n + 2} } \over {\left( {n - 1} \right)!}}\int_{s = 0}^{\;1} {s^{\,2} \;\left( {1 - s} \right)^{\,n - 1} ds} + \int_{s = 0}^{\;c} {Y\left( {n - 1,\,s} \right)ds} = \cr
& = {{c^{\,n + 2} } \over {\left( {n - 1} \right)!}}{\rm B}(3,n) + \int_{s = 0}^{\;c} {Y\left( {n - 1,\,s} \right)ds} = \cr
& = {{2c^{\,n + 2} } \over {\left( {n + 2} \right)!}} + \int_{s = 0}^{\;c} {Y\left( {n - 1,\,s} \right)ds} \cr}
$$
The first two values for $Y$ are
$$
\eqalign{
& Y(1,c) = \int\limits_{0\, \le \,x\, \le \,c} {x^2 dx} = {{c^{\,3} } \over 3} \cr
& Y(2,c) = \int\!\!\!\int\limits_{0\, \le \,x + y\, \le \,c} {\left( {x^2 + y^2 } \right)dxdy} = \cr
& = \int_{y = 0}^c {\left( {\int_{x = 0}^{c - y} {\left( {x^2 + y^2 } \right)dx} } \right)dy} = \cr
& = \int_{y = 0}^c {\left( {\left( {{{\left( {c - y} \right)^3 } \over 3} + y^2 \left( {c - y} \right)} \right)} \right)dy} = \cr
& = {{c^4 } \over {12}} + {{c^4 } \over 3} - {{c^4 } \over 4} = {{c^4 } \over 6} = \cr
& = {{2c^{\,4} } \over {4!}} + \int_{s = 0}^{\;c} {{{s^{\,3} } \over 3}ds} \cr}
$$
The recurrence can be solved to give
$$
Y(n,c) = {{2n} \over {\left( {n + 2} \right)!}}c^{\,n + 2}
$$
and finally
$$
{{I(n - 1,c)} \over {A(n - 1,c)}} = {{\sqrt n {d \over {dc}}Y(n,c)} \over {\sqrt n {{c^{\,n - 1} } \over {\left( {n - 1} \right)!}}}} = {2 \over {\left( {n + 1} \right)}}c^{\,2}
$$
i.e., in your notation
$$
E\left[ {\left| {\,{\bf X}\,} \right|^{\,2} } \right] = {2 \over {n + 1}}
$$
Now, the PDF of each point is given by $dA(n-1,1)/A(n-1,1)$.
$dA(n-1,1)$ can be conveniently expressed in terms of the $y$ coordinates, but the bounds of $T(n-1,1)$ in terms
of $0 \le x_k$ are not simply convertible into $y$.
For the case of $ f( \bf X)= |\bf X |$, we have better and use cylindrical coordinates around the diagonal axis, according
to the following sketch
We can deduce that the PDF of $ x= |\, \bf X \, |$ will be
- null till $x$ reaches the distance of $T(n-1,1)$ from the origin: $d=1/ \sqrt{n}$;
- after that we will have that $x=\sqrt{d^2+r^2}$, where $r$ is the radius of a $(n-2)$-sphere, lying in the plane of $T(n-1,1)$ and centered with it;
- while $r$ increases from $0$ to the in-radius $R_I = 1/\sqrt{n(n-1)}$ the corresponding sphere remains inside the simplex, with a surface area of
$$
S(n - 2) = {{2\pi ^{\,\,(n - 1)/2} } \over {\Gamma \left( {(n - 1)/2} \right)}}r^{\,n - 2}
$$
- after $r$ has surpassed the in-radius, the sphere it individuates will partly debord out of the simplex,
the circle in red in the sketch; the section of its area intercepted by the simplex will be that inside the solid angles defined by the vertices;
- the intercepted area will become null at the circum-radius $R_C = \sqrt{(n-1)/n}$.
The problem is that for high $n$, the volume gets concentrated on the border of the sphere.
This makes so that the maximum of $PDF(r)$ moves beyond the in-radius and it becomes fundamental to express
the area intercepted by the vertices.
I could not yet succeed in that, and could not find on the web a simple formulation .
--- 2nd step ---
Let's summarize our knowledge till here and introduce $J(n-1,c)$ as the sum of the 2nd moments of $T(n-1,c)$ wrt its centroid.
$$
\left\{ \matrix{
d\left( {n,c} \right) = {c \over {\sqrt n }} \hfill \cr
A\left( {n - 1,c} \right) = \sqrt n {{c^{\,n - 1} } \over {\left( {n - 1} \right)!}} \hfill \cr
Y(n,c) = {{2n} \over {\left( {n + 2} \right)!}}c^{\,n + 2} \hfill \cr
I(n - 1,c) = \sqrt n {d \over {dc}}Y(n,c) = {{2n\sqrt n } \over {\left( {n + 1} \right)!}}c^{\,n + 1} = \hfill \cr
= A\left( {n - 1,c} \right)d\left( {n,c} \right)^{\,2} + J(n - 1,c) \hfill \cr
J(n - 1,c) = I(n - 1,c) - A\left( {n - 1,c} \right)d\left( {n,c} \right)^{\,2} = \hfill \cr
= {{\left( {n - 1} \right)\sqrt n } \over {\left( {n + 1} \right)!}}c^{\,n + 1} \hfill \cr
S(n - 2,r) = {{2\pi ^{\,\,(n - 1)/2} } \over {\Gamma \left( {(n - 1)/2} \right)}}r^{\,n - 2} \hfill \cr
R_{\,I} (n - 1,c) = {c \over {\sqrt {n\left( {n - 1} \right)} }} \hfill \cr
R_{\,C} (n - 1,c) = {c \over {\sqrt {n/\left( {n - 1} \right)} }} \hfill \cr} \right.
$$
Clearly we can write, in "polar coordinates", that
$$
\left\{ \matrix{
J(n - 1,c) = {{\left( {n - 1} \right)\sqrt n } \over {\left( {n + 1} \right)!}}c^{\,n + 1} = \hfill \cr
= \int_{r\, = \;0\;}^{\;R_{\,I} } {r^{\,2} \;S(n - 2,r)dr} + \int_{r\, = \;R_{\,I} \;}^{\;R_{\,C} } {r^{\,2} \;S_{\,P} (n - 2,r)dr} \hfill \cr
A\left( {n - 1,c} \right) = \sqrt n {{c^{\,n - 1} } \over {\left( {n - 1} \right)!}} = \hfill \cr
= \int_{r\, = \;0\;}^{\;R_{\,I} } {S(n - 2,r)dr} + \int_{r\, = \;R_{\,I} \;}^{\;R_{\,C} } {S_{\,P} (n - 2,r)dr} \hfill \cr} \right.
$$
where $S_{\,P} (n - 2,r)$ is the surface of the sphere included in the simplex.
Using the duplication formula for Gamma
$$
\Gamma \left( n \right) = {{2^{\,n - 1} } \over {\sqrt \pi }}\Gamma \left( {n/2} \right)\Gamma \left( {n/2 + 1/2} \right)
$$
we reach then to
$$
\eqalign{
& \int_{r\, = \;\;R_{\,I} (n - 1,\,c)\;}^{\;R_{\,C} (n - 1,\,c)} {S_{\,P} (n - 2,r)dr} = \cr
& = \left( {{{n^{\,1/2} } \over {\Gamma \left( n \right)}} - {{2\pi ^{\,\,(n - 1)/2} } \over {n^{\,\,(n - 1)/2} \left( {n - 1} \right)^{\,\,(n + 1)/2} \Gamma \left( {(n - 1)/2} \right)}}} \right)c^{\,n - 1} = \cr
& = \left( {1 - {{2^{\,n - 1} \;\pi ^{\,\,n/2 - 1} \;\Gamma \left( {n/2} \right)} \over {n^{\,\,n/2} \left( {n - 1} \right)^{\,\,(n - 1)/2} }}} \right)A\left( {n - 1,c} \right) = \cr
& = \eta (n - 1)\;A\left( {n - 1,c} \right) \cr}
$$
So, using in case also the formula for $J$, the problem comes to determine $\eta (n-1,r)$ knowing its integral
from $R_I$ to $R_C$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is Azure SQL Database current version and which SSMS shall I use to backup database?
I have to backup Azure SQL database using Export Data Tier feature. I am getting error - Database source is not a supported version of SQL Server xxx: . (Microsoft.SqlServer.Dac). I am using SSMS version 12.0.2000.8 on local. I need to know Azure SQL Database version and which SSMS version shall I use to backup Azure SQL database but before that I need to know SSMS and Azure SQL Database compatibility. I don't find any clear doc about SSMS and Azure SQL Database compatibility.
A:
The current version of Azure SQL Database is "V12".
And the current General Availability (GA) version of SSMS is: SSMS 17.9.1.
I also didn't find any clear doc about SSMS and Azure SQL Database compatibility. But according the link which Azure SQL Database provides for us, we can infer that Microsoft recommends we use the SSMS 17.9.1 or the latest SSMS Preview.
You can update you SSMS to the latest version and try Export Data Tier feature again.
You can download the latest SSMS version here.
Here's an another blob maybe is useful for you: How to upgrade from V11 to V12 SQL Azure.
Hope this can helps you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to calibrate my monitor to match the 18% gray tone?
How do I to calibrate my monitor (using maybe something to help me ?) so the images I get with my digital dslr is shown on monitor correctly - at least on monitor.
When I say, something to help me, I imaging from a digital photo on Internet that I can use it to make the calibration up to a robot that comes to my office and make the calibration :)
In 1995 I was have create this page for calibrate my monitor. You need to blur your eyes to compare the colors, the outside is 18% gray shade between your black and white of your monitor. The Is this correct or not ? Did this page works ? I still think that is correct. Some infos for that page - just blur your eyes and try to not see the cycle to get the middle tone on each color and on all together.
A:
Essentially your web page is correct.
Display Calibration depends on your operating system.
By far the easiest, least error prone way is to use a colorimeter, like the Eye-One or Spider systems. These plug into your computer, then you place the sensor on your montior, run it's software, wait a minute or too, and it'll generate a proper color profile for your display. The downside is colorimeters are not cheap. I think I paid $150 for mine, and it was used.
The next way, on a PC, is to use Adobe Gamma. It has you walk through a series of steps, much like your web-page with the eye blur, and lets you eye-ball set the calibration. It's not as accurate as a hardware based setup, but it works better than the default.
On a Mac, under System Preferences->Display->Color there is an option to calibrate your display, again by eye, using a setup similar to your page.
This is a decent article on color management.
A:
To calibrate your monitor you need a calibration device like a DataColor Spyder or X-Rite DTP94, or a monitor with inbuild calibration device like the Eizo CG245w.
These will calibrate the colors of your monitor, but usually not the brightness. To really calibrate brightness you need to take the lighting of your working place into account, you need controlled lighting, which might be overkill for your situation.
Simplified you can use some calibration tools to set the monitor brightness to around 100cm/m2, which is quite good for working on pictures (most monitors are way too bright).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WordPress Algolia - indexing ACF repeater fields as custom attributes
I am trying to index ACF fields as custom attributes. As per Algolia documentation (https://community.algolia.com/wordpress/advanced-custom-fields.html) I managed to index simple ACF fields. I managed to index also repeater field but I am not sure if this is the best way to do it. Is there anyone that managed to resolve this issue and is able to not only index the ACF repeater fields but later pull them on Instantsearch template when searching on WordPress site?
add_filter( 'algolia_post_shared_attributes', 'my_event_attributes', 10, 2 );
add_filter( 'algolia_searchable_post_shared_attributes', 'my_event_attributes', 10, 2 );
function my_event_attributes( array $attributes, WP_Post $post ) {
if ( 'events' !== $post->post_type ) {
return $attributes;
}
$attributes['description'] = get_field( 'event_description', $post->ID );
$attributes['time'] = get_field( 'event_time', $post->ID );
$attributes['date'] = get_field( 'event_date', $post->ID );
$repeater = get_field( 'event_schedules', $post->ID );
$x = 0;
foreach ($repeater as $item) {
unset($item['schedule_info']);
$schedules = array ('location'=>$item['location'],'location_new'=>$item['location_new'],'event_date'=>$item['event_date'],'start_time'=>$item['start_time'],'end_time'=>$item['end_time'], 'all_day'=>$item['all_day'], 'cancel'=>$item['cancel'], 'is_location_change'=>$item['is_location_change']);
$attributes['event_schedules'][$x] = $schedules;
$x = $x + 1;
}
return $attributes;
}
Algolia Dashboard
A:
There is fundamental difference here in the WordPress backend and the way Algolia indexes CPT. You can index all the CPT's in Plugin settings -> Autocomplete and you can index the general main list under Plugin settings -> Search Page. If you are creating your own search template you can index only specific CPT that you are currently working with, but if you are working on the default search instantsearch template then you need to index the general index.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Effective ArrayAdapter
First of all, my problem:
My ListView woun't scroll smoothly.
Now a bunch of details:
I'm currently using an ArrayAdapter<CustomClass> in my App for displaying Text and and Image in each element of the ListView. I've been trying to make the ListView to scroll as smooth as possible. But as soon as the text becomes longer (about 40 characters), the ListView starts to stutter when scrolling.
I am displaying about 9 rows at the same time. If I make the ListView smaller (about 6 rows) it works fine..
I am not implementing onScrollListener and I am not running big background tasks.
This is the code I'm currently using (only getView and Holder):
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//View row = convertView;
Holder holder = null;
if(convertView == null){
//Log.e("adapter", "convertview == null");
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
holder = new Holder();
holder.imgIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.txtTitle = (TextView)convertView.findViewById(R.id.folder_name);
holder.txtInfo = (TextView)convertView.findViewById(R.id.info_text);
holder.pBar = (ProgressBar)convertView.findViewById(R.id.pBar);
convertView.setTag(holder);
}else{
holder = (Holder)convertView.getTag();
}
TrackInfo tInfo = data.get(position);
if(tInfo == null){
return convertView;
}
holder.imgIcon.setImageResource(icon);
holder.txtTitle.setText(tInfo.getTitle());
return convertView;
}
static class Holder
{
ImageView imgIcon;
TextView txtTitle;
TextView txtInfo;
ProgressBar pBar;
}
You may notice there are more elements than I actively use. This is due to the reason that I normally use the others, too, but I am currently ignoring them since I was trying to find out why it's not scrolling smoothly.
As already mentioned, it seems to be the length of the string tInfo.getTitle(). I can't change the length of the strings, since those are filenames I can't influence.
Now my QUESTION:
What's the problem? Is it that much data to handle? Or is my code bad?
I'm testing on a Moto G (1.2GHz Quad-Core, more details here).
Thank you for your attention, have a good flight!
A:
I was working with marquee effect in the ListView. I always thought that as long as I don't call TextView.setSelected(true), this wouldn't cause any further processing. Therefore, I had android:ellipsize="marquee" as a parameter for my TextView in the layout-file of the ListView-element, while only one to-be-highlighted element was set selected.
Apparently, I was wrong.
As long as the text wasn't too long for the given space (about 40 characters), there was no problem. But if the size of the text exceeded the given space, the problems started.
I am not sure what exactly the problem is, but after having a look into the source of the TextView, I recognized that there is a lot more to do when marquee is enabled:
The TextView is faded out on the right side (instead of ...)
A Spannable is used as a CharSequence
It needs to be checked if marquee should start
...
So long story short:
I removed marquee and ListView scrolls very smoothly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTTPS configuration, SSL
I'm currently configuring LibreNMS with HTTPS, and have followed this guide for setting up HTTPS:
https://www.digitalocean.com/community/tutorials/how-to-create-a-self-signed-ssl-certificate-for-apache-in-ubuntu-18-04
The default-ssl.conf file contains this section:
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>
However in the HTTP virtual host file for the LibreNMS site this section exist:
<Directory "/opt/librenms/html/">
Require all granted
AllowOverride All
Options FollowSymLinks MultiViews
</Directory>
So what I've done is that I have copied the directory section from the LibreNMS HTTP virtual host into the default-ssl.conf file, so that the default-ssl.conf virtual host contains both the original directory and the one from the LibreNMS HTTP virtual host.
Everything seems to work just fine sudo apache2ctl configtest passes and I can access the LibreNMS site using HTTPS (cert visible etc). But since I'm not that experienced with Linux I'm wondering if having two "directory" sections in the same virtual host file will pose any possible problems?
For example is the second directory section overwriting the information of the first when the file is read, and if so what is the implications of not using the directory section which exist in the default-ssl.conf file?
A:
Having multiple directory options is fully supported. A site may have many directories, to which different settings shall be applied.
If it's for testing and development, running everything under the default site is not really problematic. However, it may limit your ability to run further sites, depending on your set up. If it's production, I would suggest to set up a proper VirtualHost for each and every site.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I turn on "always-on" for an Azure Function?
I have a Function App with 3 functions, one of them timer-triggered every 2 minutes. I observed that after a while, the function stops being triggered, but restarts when I go to the portal.
As I understand it, the reason is that by default, "Always On" is turned off. However, when I go to Application Settings / General Settings, I cannot activate the "On" state, which is grayed out. I can un-check "Off", which doesn't seem to stick or activate "On".
Am I missing something obvious? Is Always-On the solution to my problem, or is there something else I should do?
Note: the functions are written in F#; I doubt it matters, but I thought I would mention it just in case.
A:
This answer applies to all Azure Function scenarios with the exception of those that are triggered by an http request.
There are 3 cases to look at:
You have a Function App running in a Free/Shared App Service Plan: Always On is not available, and those scenarios are simply not supported.
You have a Function App running in a Basic/Standard/Premium App Service Plan: Always On is available and can be turned on. In fact it is on by default, and you'll get a warning in the Functions UI if you turn it off.
You have a Function App using a Consumption Plan: there is no need for Always On as the system takes care of waking up your functions whenever they need to run. This is the recommended approach for most users.
A:
Azure Functions are managed together by Azure App Service which restricts always on to modes that are Basic or above (no free or shared)
In Basic or Standard mode, you can enable Always On to keep the app loaded all the time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I create a library where the linker only links functions used by my program?
I am compiling an application program for an 8-bit AVR micro-controller (AVR-GCC). To reduce the flash memory usage in a micro-controller it is essential that the linker only links functions which are used by the application code. I am writing my own library and I came across the following statement.
"Write one function per code module. This will compile to one function per object module" - Source: http://nongnu.org/avr-libc/user-manual/library.html
What does this mean? How do I create separate object files for each of my functions? Right now I only have one .h file and a .c file in my library.
A:
"One function per code module" means one function per C source file. That will give you one object file per function.
This seems awkward, the typical way to do this when using GCC is as described here:
Compile with the -fdata-sections -ffunction-sections options, that tell GCC to put data and functions in separate sections. Sections are just a concept in the object files, basically a stand-alone region. A single object file can contain many sections.
Then link with --gc-sections, telling the linker to garbage-collect unused sections. This will remove dead code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Popup with functional close button (HTML, CSS, JavaScript)
I'm a total rookie, but I'm trying to make a website and I bumped into an issue, unfortunately.
I have a set of articles (cards) in a grid. Each card contains a "thumbnail" with the title, an image and a short preview of the text. The idea is that when you click the card item, a pop up will appear with the full article that may including varying HTML and CSS. Once clicked, the background also gets blurry.
The pop up will have a close button in the top right corner.
The issue I'm experiencing is that the full article is a child of the card item. This means that the click function keeps happening when inside the article. So even when I click the close button, it is immediately reopened. I want users to be able to click and interact with the article without accidently closing it, unless they clicked on the .close div.
Allow me to share the code (it is written in pug/jade):
HTML(Pug):
.card(onclick="expandFunction()")
.image
.information
h4.title Preview Title
p.description Preview Description
#blurry.hideme
article#full.hideme
h4.m-title Main Title
p.m-description Main Description
p.m-body Main Article
.close(onclick="contractFunction()")
Javascript:
function expandFunction() {
var y = document.getElementById("full");
var x = document.getElementById("blurry");
y.classList.toggle("hideme");
x.classList.toggle("hideme");
}
function contractFunction() {
var y = document.getElementById("full");
var x = document.getElementById("blurry");
y.classList.toggle("hideme");
x.classList.toggle("hideme");
}
The hideme class is merely a display: none that is applied to the divs.
Furthermore, right now my javascript is hardcoded to open one of the card articles using an ID. Is it instead possible to use the relative path so I don't have to create a unique function for each card I have?
A:
As far as I can see you just have to prevent the click event from propagate through the DOM, i will change your script like this:
function expandFunction(event) {
event.stopPropagation();
var y = document.getElementById("full");
var x = document.getElementById("blurry");
element.classList.toggle("hideme");
x.classList.toggle("hideme");
}
function contractFunction(event) {
event.stopPropagation();
var y = document.getElementById("full");
var x = document.getElementById("blurry");
element.classList.toggle("hideme");
x.classList.toggle("hideme");
}
In this way any click you do will affect just the element that fire it and will not travel along the DOM firing other event
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to layout the dashboard sections vertically with ActiveAdmin?
In the dashboards.rb file generated by ActiveAdmin 0.3.4, I added three sections consisting on wide tables with several columns. However ActiveAdmin displays each section next to the other, creating an unnecessary horizontal scrollbar.
How can I change this to a vertical layout?
dashboards.rb:
ActiveAdmin::Dashboards.build do
section "Inactive users" do
table do
...
end
end
section "Deleted posts" do
table do
...
end
end
section "Latest comments" do
table do
...
end
end
end
What I get:
I already tried using a div as the container for each table with no luck.
A:
This answer for active_admin >= 0.5.1
Dashboard is structured in columns and panels
Columns are... well, columns, which define the horizontal layout.
Panels are like sections that stack verticaly.
A 2 column, 3 sections en each column, would be defined by:
columns do
column do
panel "top on column 1"
# some code
end
panel "second on column 1"
# some code
end
panel "last on column 1"
# some code
end
end
column do
panel "top on column 2"
# some code
end
panel "second on column 2"
# some code
end
panel "last on column 2"
# some code
end
end
end
A:
I finally fixed this with some CSS, in a new stylesheet:
active_admin_ex.css:
table.dashboard > tbody > tr > td {
display:block;
}
Then, in config/initializers/active_admin.rb, I added:
config.register_stylesheet 'active_admin_ex.css'
And this fixed the display problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Keras: Why isn't observed batch size matching up with the specified batch size?
I specify a batch size of 500 by doing this in my code:
model.fit(x_train, y_train, validation_data=(x_test, y_test), nb_epoch=100, batch_size=500, verbose=1)
When I run the code, the first batch size is 500, and the batch sizes after that are like 5000 and larger, why does this happen?
The reason I think the batch size are larger is because it seems like the model goes from row 500 to row 6000, which is 5500 rows.
Epoch 100/100
500/31016 [..............................] - ETA: 0s - loss: 0.1659 - acc: 0.7900
6000/31016 [====>.........................] - ETA: 0s - loss: 0.1679 - acc: 0.7865
11500/31016 [==========>...................] - ETA: 0s - loss: 0.1688 - acc: 0.7850
17000/31016 [===============>..............] - ETA: 0s - loss: 0.1692 - acc: 0.7842
23000/31016 [=====================>........] - ETA: 0s - loss: 0.1694 - acc: 0.7839
29000/31016 [===========================>..] - ETA: 0s - loss: 0.1693 - acc: 0.7841
31016/31016 [==============================] - 0s - loss: 0.1693 - acc: 0.7841 - val_loss: nan - val_acc: 0.6799
A:
This is really interesting issue. The part of code which is responsible for displaying a progress bar is a util called progbar and it's defined here. It accepts as a parameter a minimum visual progress update interval which is by default set to 0.01 seconds. This default value is also used during printing a progress bar during fit computations and this is probably the reason behind this weird behaviour.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I keep receiving Uncaught TypeError: Object [object global] has no method error during function call
I created a function that would do something unique on it's 3rd call. In this case, alert the incremented number. However, when trying to call this function from another function:
"MyFunction();", I get Uncaught TypeError: Object [object global] has no method 'MyFunction'. Can you please tell me what I'm doing wrong?
var counter = 0;
var num = 0;
function = MyFunction() {
// increment outside counter
counter++;
if (counter === 3) {
// do something every third time
num++;
alert('the new number is: ' + num);
// reset counter
counter = 0;
}
}
I've also tried removing the = sign, as you can see here http://jsfiddle.net/DN3yC/6/ it doesn't work.
A:
LIVE DEMO
Just remove the = sign function MyFunction() { and make sure in your fiddle that JS <script> is in the right placeSee additional explanation below.
Example:
var element = document.getElementById('button');
var counter = 0;
var num = 0;
function MyFunction() {
counter = ++counter % 3; // loop count
if ( !counter ) {
num++;
alert('the new number is: ' + num);
}
}
//On click:
element.addEventListener('click', MyFunction, false);
your new fiddle: http://jsfiddle.net/DN3yC/7
The old one of yours was not working cause you did not used No Wrap - in body for the JS in your fiddle. (See options panel at the left up corner)
So basically you need to put your <script> tags before your </body> closing tag in order to make sure the DOM is ready and parsed by JavaScript before elements manipulation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP include using jquery AJAX from a dropdown select option?
I am trying to include an external php (on my own server) in another php page using jQuery AJAX from a select form.
basically I want to let the user include the external php file if they select YES option from the dropdown select form and remove it if they select NO.
I have the following code:
<html>
<head>
<script>
$('#test2').change(function(){
var selectedValue = $(this).val();
if (selectedValue === 'Yes') {
$("#content").load("include.php");
} else {
//WHAT DO I NEED TO PUT HERE TO REMOVE THE "include.php" if it has been inlcluded?
}
});
</script>
</head>
<body>
<form>
<select id="test2">
<option value=""></option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
</form>
<br>
<div id="content"></div>
</body>
</html>
First question: am I doing this right?
Second question: what do I need to do in order to remove the include.php file if they select NO option?
any help would be appreciated.
Thanks in advance.
P.S. i do have jquery included in my page.
A:
If yes is selected then
Include file
else
$( ".page" ).empty();
//make the page content empty Simple
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Implementation of check marks after the Button has been activated
The code below is the code for a label next to a button which starts certain calcualtions. When I put this code into the Tabelmodul it works just fine (when i test it through the F8 key). However, i am going to need this code for the label in the macro-modul so that when the button is pushed the Label gets startet.
The issue is when I put the code into the macromodul I Keep getting the error message "Byref argument type mismatch". Which means that some things is not defined properly.
Code in the Tablemodule:
Private Sub Button_Klicken()
Call prcSetLabel(probjLabel:=Label1)
End Sub
Private Sub prcSetLabel(ByRef probjLabel As MSForms.Label)
With probjLabel
.Caption = "P"
End With
End Sub
A:
If the macros are where I believe they are you should be able to make the calling using this:
Private Sub Button_Klicken()
Call prcSetLabel Me.Label1
End Sub
Private Sub prcSetLabel(ByRef probjLabel As MSForms.Label)
With probjLabel
.Caption = "P"
End With
End Sub
This is assuming your label name is Label1. If not then just change that name.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"How far is it from here? VS "How far is it from here to there?"
Imagine you are talking about the distance between two states like NYC and Texas. You are in NYC and don't know what is the precise distance and your friend who you're talking to is aware. You want to ask them. You would probably ask:
How far is it from here to there?
I guess the bold part is redundant and whereas you are indicating Texas by the pronoun "it", the part "to there" can be omitted without any change in meaning.
But My question is that if I guess right and then if saying the sentence in the way it is (without removing "to there" would be considered a mistake or not?
A:
Dummy pronoun
A dummy pronoun, also called an expletive pronoun or pleonastic pronoun, is a pronoun used for syntax without explicit meaning.
- wikipedia
You ask whether "to there" is required (or alternatively, whether it is a mistake) in the question:
How far is it from here (to there)?
If you consider "it" to be a dummy pronoun, then you need "to there" for the question to make sense.
If you consider "it" to be a referential pronoun (referring to the destination), then you should exclude "to there" to avoid clumsy redundancy.
Since both readings of "it" are possible, both variants of the question are fine.
Your question notes that both origin and destination are known. So consider a conversation that includes the following snippet:
You came all the way from Texas? How far is it from here (to Texas)?
Both forms are natural. However, "How far is it from here to there?" sounds a little less natural to my ear. In that case, drop "to there" altogether. As an aside, since both origin and destination have been established, you can even shorten the second question to just "How far (away) is it?"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Golang Бесконечный цикл и загрузка ЦП
Почему обычный цикл нагружает процессор?! (у меня нагрузку показывает на 50-60%) Например:
package main
func main() {
for {
}
}
А к примеру цикл на прослушивание порта НЕ нагружает процессор? (~1%) Например:
package main
import "net/http"
func main() {
http.ListenAndServe(":8080", nil)
}
Во 2-ом примере тоже используется бесконечный цикл!
UPDATE:
Такой пример тоже не нагружает процессор, почему? ведь тут тоже используется бесконечный цикл!
package main
import (
"io"
"log"
"net"
"time"
)
func main() {
listener, err := net.Listen("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
handleConn(conn)
}
}
func handleConn(c net.Conn) {
defer c.Close()
for {
_, err := io.WriteString(c, time.Now().Format("15:04:05\n"))
if err != nil {
return
}
time.Sleep(1 * time.Second)
}
}
A:
Во втором случае нет бесконечного цикла. Функция Listen... использует низкоуровневое API операционной системы, которое реализовано достаточно хорошо, что бы не использовать бесконечый цикл. Высокоуровневый код вызывает что-то на подобии WaitFor..., и операционная система передает управление вызывающему коду только тогда, когда кто-то присоединится. Во время ожидания эта функция имеет почти нулевую нагрузку на процессор.
Бесконечный цикл всегда загружает одно ядро процессора. Если у вас такой цикл создает нагрузку 50%, значит у вас 2 ядра.
A:
В Linux:
Почему обычный цикл нагружает процессор?!
Потому что его выполнение никогда не уходит из кода процесса, а работа в нём есть всегда.
ОС продолжает исправно выделять процессу время на выполнение, он всегда полностью съедает всё то время, что ему выделили, постоянно гоняя "курсор исполнения" вокруг одной команды (абстрактное "goto чуть назад", как бы оно реально ни выглядело), прерываясь только когда у ОС есть другие дела/процессы.
А к примеру цикл на прослушивание порта НЕ нагружает процессор?
Потому что его выполнение уходит в ядро ОС по системному вызову listen, и процесс фактически останавливается. Его код временно перестаёт выполняться. ОС запоминает, что "процесс просил его разбудить, когда на указанный сокет кто-то придёт".
До тех пор ОС не будет выделять процессу время на выполнение.
Так работает синхронный ввод-вывод в целом. Бывает ещё асинхронный, который не вызывает остановки процесса. Но процесс, его использующий, должен сам в удобные ему моменты спрашивать у ядра, "не пришёл ли кто". А в свободное от таких вопросов время может заниматься чем-то своим, грузить или не грузить процессор.
Такой пример тоже не нагружает процессор, почему?
По той же причине, выполнение уходит в ядро, но на сей раз по системному вызову sleep (возможно, он только оборачивает другой вызов, а не является им сам, но тем не менее), который инструктирует ОС возобновить выполнение только спустя какое-то время.
До тех пор ОС не будет выделять процессу время на выполнение.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What kind of activation is used by ScikitLearn's MLPClasssifier in output layer?
I am currently working on a classification task with given class labels 0 and 1. For this I am using ScikitLearn's MLPClassifier providing an output of either 0 or 1 for each training example. However, I can not find any documentation, what the output layer of the MLPClassifier is exactly doing (which activation function? encoding?).
Since there is an output of only one class I assume something like One-hot_encoding is used. Is this assumption correct? Is there any documentation tackling this question for the MLPClassifier?
A:
out_activation_ attribute would give you the type of activation used in the output layer of your MLPClassifier.
From Documentation:
out_activation_ : string
Name of the output activation function.
The activation param just sets the hidden layer's activation function.
activation : {‘identity’, ‘logistic’, ‘tanh’, ‘relu’}, default ‘relu’
Activation function for the hidden layer.
The output layer is decided internally in this piece of code.
# Output for regression
if not is_classifier(self):
self.out_activation_ = 'identity'
# Output for multi class
elif self._label_binarizer.y_type_ == 'multiclass':
self.out_activation_ = 'softmax'
# Output for binary class and multi-label
else:
self.out_activation_ = 'logistic'
Hence, for binary classification it would be logistic and for multi-class it would be softmax.
To know more details about these activations, see here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Projective Normality
What is the significance of studying projective normality of a variety ? How does it relate to non-singularity, rationality of a variety ?
A:
First let me emphasize that projective normality is defined only for varieties $X\subset \mathbb P^n$ embedded in some projective space, not for an abstract variety.
Let us say that such a subvariety is $k$-normal ($k\gt 0$) if the canonical morphism $$\Gamma(\mathbb P^n,\mathcal O_{\mathbb P^n}(k))\to \Gamma(X,\mathcal O_X(k)) $$ is surjective.
Equivalently $H^1(\mathbb P^n,\mathcal I_X(k))=0$, where $\mathcal I_X$ is the ideal sheaf defining $X$.
The equivalence follows by taking the appropriate segment of the long exact sequence of cohomology associated to $$0\to \mathcal I_X(k)\to O_{\mathbb P^n}(k)\to \mathcal O_X(k)\to 0 $$ and remembering that $H^1(\mathbb P^n, \mathcal O(k))=0$.
Then $X$ is said to be projectively normal if it is $k$-normal for all $k\gt 0$ and if it is normal.
For example any curve $X\subset \mathbb P^2$ of degree $d$ is $k$-normal for all $k\gt 0$ : indeed $$H^1(\mathbb P^2,\mathcal I_X(k))=H^1(\mathbb P^2,\mathcal O_{\mathbb P^2}(-d+k))=0$$
Hence a plane projective curve is projectively normal if and only if it is normal.
More generally any normal complete intersection in $\mathbb P^n$ is projectively normal (the converse is false: see Edit below).
Also, any Segre embedding $\mathbb P^n\times \mathbb P^m\hookrightarrow \mathbb P^N$ is projectively normal.
However a normal projective variety is not necessarily projectively normal: an example is the image $X\subset \mathbb P^3 $ of the embedding $\mathbb P^1 \hookrightarrow \mathbb P^3:(u:v)\mapsto(u^4:u^3v:uv^3:v^4)$ .
This degree $4$ curve is not even $1$-normal: the linear map $\Gamma(\mathbb P^3,\mathcal O_{\mathbb P^3}(1))\to \Gamma( X,\mathcal O_X(1)) $ is not surjective because the source has dimension $4$ whereas the target has dimension $h^0( X,\mathcal O_X(1)) =h^0(\mathbb P^1,\mathcal O(4))=5$.
Edit: caution!
We have just seen a non projectively normal embedded copy $X$ of $\mathbb P^1$ in $\mathbb P^3$.
But the standard embedding $\mathbb P^1\hookrightarrow \mathbb P^3: (u:v)\mapsto(u^3:u^2v:uv^2:v^3)$ has as image a cubic curve which is projectively normal (even though it is not a complete intersection !): cf.Hartshorne Chapter III, Ex.5.6.(b)(3) p.231, taking into account that this curve has bidegree (1,2) on the quadric $x_0x_3=x_1x_2$ on which it lies.
This confirms that projective normality is not an intrinsic property of a projective variety but depends on the choice of an embedding of it into $\mathbb P^n$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scala Macros: "cannot create TypeTag from a type T having unresolved type parameters"
I'm playing around with Scalas new macros and found this gist from akshaal. As it seams I did not quite get it.
Given the following trait (the fieldsMacro is more or less the same as in akshaal example)
case class Field[I <: AnyRef](name: String, get: I => Any)
type Fields[I <: AnyRef] = List[Field[I]]
trait FieldAccess {
import FieldMacors._
import Field._
import language.experimental.macros
def fields[T <: AnyRef]: Fields[T] = macro fieldsMacro[T]
def field[T <: AnyRef](name: String): Fields[T] = fields[T].headOption <-- does not work!
^
}
object FieldMacors {
import language.experimental.macros
import Field._
def fields[T <: AnyRef]: Fields[T] = macro fieldsMacro[T]
/**
* Get a list of fiels
*/
def fieldsMacro[T <: AnyRef: c.TypeTag](c: Context): c.Expr[Fields[T]] = {
import c.universe._
val instanceT = c.typeOf[T]
val fields = instanceT.members.filter(member => member.isTerm && !member.isMethod)
// transform an iterable of expr in a expr of list.
def foldIntoListExpr[T: c.TypeTag](exprs: Iterable[c.Expr[T]]): c.Expr[List[T]] =
exprs.foldLeft(reify { Nil: List[T] }) {
(accumExpr, expr) =>
reify { expr.splice :: accumExpr.splice }
}
val fieldAccessores = for (field <- fields) yield {
val name = field.name.toString.trim // Why is there a space at the end of field name?!
val nameExpr = c literal name
// Construct expression (x : $I) => x.$name
val getFunArgTree = ValDef(Modifiers(), newTermName("x"), TypeTree(instanceT), EmptyTree)
val getFunBodyTree = Select(Ident(newTermName("x")), newTermName(name))
val getFunExpr = c.Expr[T => Any](Function(List(getFunArgTree), getFunBodyTree))
reify {
Field[T](name = nameExpr.splice, get = getFunExpr.splice)
}
}
foldIntoListExpr(fieldAccessores)
}
}
the compiler complains about
'Cannot create TypeTag from a type T having unresolved type parameters'
How do I manage to get the T to the macro or must I implement another macro that uses the fieldsMacro
A:
T: TypeTag context bound for a type parameter T means that you require type arguments provided in place of this parameter to be concrete (i.e. not contain references to untagged type parameters or abstract type members). Otherwise an error occurs.
Examples:
scala> val ru = scala.reflect.runtime.universe
ru @ 6d657803: scala.reflect.api.JavaUniverse = scala.reflect.runtime.JavaUniverse@6d657803
scala> def foo[T: ru.TypeTag] = implicitly[ru.TypeTag[T]]
foo: [T](implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[T]
scala> foo[Int]
res0 @ 7eeb8007: reflect.runtime.universe.TypeTag[Int] = TypeTag[Int]
scala> foo[List[Int]]
res1 @ 7d53ccbe: reflect.runtime.universe.TypeTag[List[Int]] = TypeTag[scala.List[Int]]
scala> def bar[T] = foo[T] // T is not a concrete type here, hence the error
<console>:26: error: No TypeTag available for T
def bar[T] = foo[T]
^
scala> def bar[T] = foo[List[T]] // T being not concrete renders
// the entire compound type not concrete
<console>:26: error: No TypeTag available for List[T]
def bar[T] = foo[List[T]]
^
scala> def bar[T: TypeTag] = foo[T] // to the contrast T is concrete here
// because it's bound by a concrete tag bound
bar: [T](implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[T]
scala> bar[Int]
res2 @ 7eeb8007: reflect.runtime.universe.TypeTag[Int] = TypeTag[Int]
scala> def bar[T: TypeTag] = foo[List[T]]
bar: [T](implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[List[T]]
scala> bar[Int]
res3 @ 1a108c98: reflect.runtime.universe.TypeTag[List[Int]] = TypeTag[scala.List[Int]]
scala> bar[List[Int]]
res4 @ 76d5989c: reflect.runtime.universe.TypeTag[List[List[Int]]] = TypeTag[scala.List[scala.List[Int]]]
Having a notion of concrete types to be enforcible at compile-time is useful. Having concrete type tags on by default is useful as well as described in https://issues.scala-lang.org/browse/SI-5884.
However as you've seen yourself, concrete type tags in macros can be a source of confusion, because typically macros should work both for concrete and non-concrete types. Therefore one should always use c.AbsTypeTag instead. Due to this reason we no longer allow c.TypeTag context bounds in 2.10.0-M7: https://github.com/scala/scala/commit/788478d3ab.
Edit. In 2.10.0-RC1 some AbsTypeTag has been renamed to WeakTypeTag. Everything else about type tags remains the same.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Xcode looking in wrong folder
Xcode 4.2 is looking in my tags folder when I build. This is causing duplicate interface errors, since it believe I have defined classes twice. My folder structure is:
tags
trunk
My current build is in trunk and Xcode is also looking in tags. How can I make it stop doing that?
A:
After editing the pbxproj file, I found references into the other folder. I then removed those files via Xcode and added them back from the correct location. Problem solved.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Localization in asp.net Web Forms on the basis of Time-zone
Is there a way to provide Localization in my asp.net Web-Form on the basis of local time-zone of my system ? I want to change the page's Culture (CurrentCulture and CurrentUICulture) from the time-zone. I have already implemented this by providing the manual links on the web page as all the websites do...By clicking on Spanish, we find a Spanish UI. What I did is, I generate a page request from that link and get the language from that request and finally set the Culture. as
protected override void InitializeCulture()
{
if(Request["Language"] != null)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(Request["Language"].ToString());
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request["Language"].ToString());
}
base.InitializeCulture();
}
Now I want to do the same thing with the help of time-zone of the user's system.
Please let me know if my question is not clear.
A:
ASP.NET has some native support for automatic locale switching via the web.config section.
<configuration>
<system.web>
<globalization culture="auto:en-US" uiCulture="fr" />
</system.web>
</configuration>
This setting automatically switches the ASP.NET request to the browser client’s language if a match can be found. If the browser doesn’t provide a language or the language can’t be matched to one of the .NET installed cultures, the fallback value is used – in this case en-US.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How could I get api cache with external query (not with ActiveRecord)
The query response is not from ActiveRecord
and the response is in JSON format.
How could I cache the return result
def get_drug_usage_history_by_symptoms
pipeline_work = [
{"$unwind" => "$records"},
{'$match' => {'records.items' => {'$in' => items} }},
{'$limit' => 8 } # FOR DEVELOPMENT USE
]
cur = db[collection].find.aggregate(pipeline_work).allow_disk_use(true)
respond_to do |format|
format.json { render json: cur.to_a }
end
end
A:
Rails provides a generic low-level data cache that I've found extremely useful for caching API call results and so forth. Learn about it here and here. Basically this is how it works:
Rails.cache.fetch("unique_key_for_this_data", expires_in: 30.minutes) do
# make the API call
# Whatever value this block returns, will be stored in the cache
# If the value is already cached (and not expired), that value
# will be provided and this block won't even execute
end
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTTP Error 400. The request has an invalid header name
I have a Java application with the below code. I am trying to invoke a REST web service using HttpClient POST. I need to send a custom header "auth" for authentication. The value of the header is the encrypted credentials separated by a ":".
String strAuth = DoAESEncrypt("userid:pwd");
String strContent = DoAESEncrypt("{\"Name\":Tester,\"Id\":\"123\",\"NickName\":null,\"IsLocked\":false}");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://domainname/servicename");
post.addHeader("auth",strAuth);
post.addHeader("Content-Type", "application/json");
StringEntity input = new StringEntity(strContent);
post.setEntity(input);
HttpResponse response = client.execute(post);
The DoAESEncrypt is a function that encrypts the input string and returns the Cipher. However, when I run this code, I get the below error where I have the statement client.execute:
HTTP Error 400. The request has an invalid header name
However, if I hard-code the below header with the encrypted Cipher I generated using the same DoAESEncrypt function, it works fine:
post.addHeader("auth","5PE7vNMYVFJT/tgYo7TGuPO05lqMQx5w3BAJKDS567A73vM0TYFmWO5tP=");
A:
String strAuth = DoAESEncrypt("userid:pwd");
String strContent = DoAESEncrypt("{\"Name\":Tester,\"Id\":\"123\",\"NickName\":null,\"IsLocked\":false}");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://domainname/servicename");
post.addHeader("auth",strAuth.replace("\n","").replace("\r","");
post.addHeader("Content-Type", "application/json");
StringEntity input = new StringEntity(strContent);
post.setEntity(input);
HttpResponse response = client.execute(post);
Replace all \n and \r from your encrypted string which you passing to
header as follow
strAuth.replace("\n","").replace("\r","")
A:
For some reason, the DoAESEncrypt function was adding a carriage return "\r\n" to the Cipher text. This was removed and it worked fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove a trailing comma?
Given strings like:
Bob
Bob,
Bob
Bob Burns,
How can you return that w/o a comma?
Bob
Bob
Bob
Bob Burns
Also, I would want this method not to break if passed a nil, just to return a nil?
def remove_trailing_comma(str)
!str.nil? ? str.replace(",") :nil
end
A:
My thought would be to use string.chomp:
Returns a new String with the given record separator removed from the end of str (if present).
Does this do what you want?
def remove_trailing_comma(str)
str.nil? ? nil : str.chomp(",")
end
A:
use String#chomp
irb(main):005:0> "Bob".chomp(",")
=> "Bob"
irb(main):006:0> "Bob,".chomp(",")
=> "Bob"
irb(main):007:0> "Bob Burns,".chomp(",")
=> "Bob Burns"
UPDATE:
def awesome_chomp(str)
str.is_a?(String) ? str.chomp(",") : nil
end
p awesome_chomp "asd," #=> "asd"
p awesome_chomp nil #=> nil
p awesome_chomp Object.new #=> nil
A:
You could do something like this:
str && str.sub(/,$/, '')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calculating Running Time of Recurrence Relations
I had to calculate the Running Time of the following Algorithm.
function Fib(n)
if n == 0 or n == 1 then
return 1
else
return Fib(n-1) + Fib(n-2)
Now I calculate it's running time to be about $O(2^n)$ I'm new to this subject so correct be if it's not $O(2^n)$. Now the questions asks if one wanted to calculate Fib(50) how many times would Fib(10) be called. I'm stumped at this part. I tried to make a diagram and calculate it through brute-force but I'm pretty sure there must be a much easier method to it.
A:
If you draw the recursion tree for a few levels, you will find the pattern so you don't need to draw the whole tree and count the answer in a brute-force fashion:
From here, you know that $Fib(50)$ is called $1$ time, $Fib(49)$ is called $1$ time, $Fib(48)$ is called $2$ times, $Fib(47)$ is called $3$ times, $Fib(46)$ is called $5$ times. For $Fib(45)$, you can see $7$ occurrences here, but there will be an $8$th call, just below the lowest level that we have drawn (under the $Fib(46)$ in the bottom left corner). So $Fib(45)$ is called $8$ times. Let $T(n)$ be the number of times $Fib(n)$ is called, now you can see the pattern and generalize this relation:
$T(49) = T(50) = 1$
$T(n - 2) = T(n) + T(n - 1)$ for $1 \le n \le 48$
In other words, $T(n)$ is the $(51-n)$-th Fibonacci number. So you can now find $T(10)$.
Added: In fact, the recursion tree diagram can also help understand why the overall complexity is $O(2^n)$. $Fib(n)$ only appears on or above Level $(50-n)$ of the tree (assume the root is Level $0$), so when $n$ increases by $1$, the height of the tree increases by $1$ as well. And this causes the number of calls to be approximately doubled. Hence the overall time complexity is $O(2^n)$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
remove characters between 2 character in notepad++
i want remove characters between ", R.drawable and ); in notepad++
case : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f31e);
case : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f320);
case : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f330);
case : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f331);
case : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f332);
and want change case to case number like this :
case 10 : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f31e);
case 11 : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f320);
case 12 : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f330);
case 13 : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f331);
case 14 : ed.getText().insert(ed.getSelectionStart(), getSmiledText(getBaseContext(), "", R.drawable.em_1f332);
begin from 10 to * . this possible ?
A:
For the first part of your question select Regular Expression in the Find Replace and Find:
(R.drawable).+(\);)
and Replace with:
\1\2
The second part can be done by holding alt and selecting the column then going Edit->Column Editor and playing with Number to Insert.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Functor in Ocaml
I have a problem with functor in Ocaml. I have this situation:
module type EveryType =
sig
type t
val str : t -> string
end;;
module type StackInterface =
functor (El : EveryType) ->
sig
type el = El.t
type stack
exception EmptyStackException
val empty : stack
val pop : stack -> stack
val top : stack -> el
val push : stack -> el -> stack
val str : stack -> string
end;;
module StackImpl (El : EveryType) =
struct
type el = El.t
type stack = Empty | Node of el * stack
exception EmptyStackException
let empty = Empty
let pop s =
match s with
| Empty -> raise EmptyStackException
| Node(_, t) -> t
let top s =
match s with
| Empty -> raise EmptyStackException
| Node(h, _) -> h
let push s el = Node(el, s)
let str s =
let rec str s =
match s with
| Node(h, Empty) -> El.str h ^ ")"
| Node(h, t) -> El.str h ^ ", " ^ str t
| _ -> ""
in
if s == Empty then
"Stack()"
else
"Stack(" ^ str s
end;;
module Stack = (StackImpl : StackInterface);;
module TypeChar =
struct
type t = char
let str c = Printf.sprintf "%c" c
end;;
module StackChar = Stack(TypeChar);;
module CheckExp(St : module type of StackChar) =
struct
let checkExp str =
let rec checkExp str stk =
try
match str with
| [] -> true
| '(' :: t -> checkExp t (St.push stk '(')
| ')' :: t -> checkExp t (St.pop stk)
| _ :: t -> checkExp t stk
with St.EmptyStackException -> false
in checkExp (explode str) St.empty
end;;
I create a Stack with functor to have a stack of every type. Now I want to use this stack (with type char) in a function that check parantesis into an expression. But compiler gives me this error: Unbound module type StackChar refered to line module CheckExp(St : StackChar) =
What have I wrong???
A:
StackChar is a module, but what you need for a functor is a module type. It wouldn't be much of a functor if you always pass it the same module. The simplest fix for this is to replace it with module type of StackChar:
module CheckExp(St : module type of StackChar) =
struct
...
end
But are you sure you actually need a functor here?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
in Android, when a service and activity use the same static class, is the class 'created' twice?
this is just a general knowledge question - out of curiosity...
In Android, when an activity and a service use the same static class (i.e. singleton) does the service end up getting its own 'version' of the class ?
For example, I put all of my global constants into a static class. Are these memory locations created once for activities and again for separate processes such as a service ?
A:
No. A single process with a single, unified memory space is created for your activities and services so there will only be one instance of your static class. Note that this is the default behavior and there are ways to, for instance, have your service run in a different process. Then all bets are off and static variables are almost certainly not the best path forward for your implementation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My sql getting empty value in table using join table
How to select all data in first table join with second table print null if dont have table
table 1
|---------------------|------------------|------------------|------------------|
| id . | name | success_img | unsuccess_img
|---------------------|------------------|------------------|------------------|
| 1 | name1 . | success | unsuccess
|---------------------|------------------|------------------|------------------| |---------------------|------------------|------------------|------------------|
| 2 | name2 . | success | unsuccess
|---------------------|------------------|------------------|------------------|
table 2
|---------------------|------------------|------------------|------------------|
| id . | condition_id | member_id | add_by
|---------------------|------------------|------------------|------------------|
| 1 | 1 . . | 10 | admin
|---------------------|------------------|------------------|------------------|
I want to out put
table1.id name success_img unsuccess_img member_id add_by
1 name1 success unsuccess 10 admin
2 name2 success unsuccess null null
I try to use
select * from table1
left join table2 on table1.id = table2.id
where member_id = 10
this query it's printing out only name 1 which have member_id = 10
A:
Move the where condition to the on clause:
SELECT *
FROM table1 t1
LEFT JOIN table2 t2
ON t1.id = t2.id AND
t2.member_id = 10;
Having the check on the member_id in the WHERE clause was causing the missing record to be filtered off.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Measure theory problem concerning convergence of integrals
Let $X$ be a measure space. Let $S_j$, $j \in \mathbb N$ be an increasing sequence of $\sigma$-algebras on $X$ such that $S := \bigcup_{j \geq 0} S_j$ is a $\sigma$-algebra. For every $j$, let $\mu_j$ be a probability measure on $S_j$.
Let $f_{ij}$ $(i, j \in \mathbb N)$ be a double indexed sequence of functions such that that for every $j$, $f_{ij}$ converges $\mu_j$-a.e. to a $S_j$ measurable function $f_j$.
Suppose there exists some probability measure $\mu$ on $S$ such that $f_j$ converges $\mu$-a.e. to a function $f$.
Suppose further that:
the restriction of $\mu$ to $S_j$ is absolutely continuous with respect to $\mu_j$ for every $j$
$f_{ij}, f_j, f$ are $\mu$-integrable, and $f_{ij}$ is $\mu_j$-integrable for every $i, j$
$\int f_{ij} \, d \mu_j \to \int f_j \, d \mu_j$ for every $j$
$\int f_j \, d \mu \to \int f \, d \mu$
Is it true that there exists a increasing function $b: \mathbb N \to \mathbb N$ such that $\int f_{n, b(n)} \, d \mu$ converges to $\int f \, d \mu$?
A:
Following Iosif's comment: the family $\sum_j S_j$ virtually never is a $\sigma$-algebra.
But this does not matter: even if $S = S_j$ for all $j$, the claim is clearly false without further restrictions. Indeed, consider $[-1,1]$ with the usual Borel $\sigma$-algebra $S = S_j$, and
$$
\begin{gathered}
\mu(dx) = \tfrac{1}{2} (1 + x) dx , & \mu_j(dx) = \tfrac{1}{2} dx , \\
f(x) = f_j(x) = 0 , & f_{ij}(x) = 2 i x^{2 i - 1} .
\end{gathered}
$$
Then:
$$
\begin{gathered}
\lim_{i \to \infty} f_{ij}(x) = f_j(x) \text{ except when $x = \pm 1$,} \\
f_j(x) = f(x) \text{ for all $x$,} \\
\int f_{ij}(x) \mu_j(dx) = 0 = \int f_j(x) \mu_j(dx) , \\
\int f_j(x) \mu(dx) = 0 = \int f(x) \mu(dx) ,
\end{gathered}
$$
but neither of:
$$
\begin{gathered}
\int f_{i,j(i)}(x) \mu(dx) = \frac{2 i}{2 i + 1} \, , \\
\int f_{i(j),j}(x) \mu(dx) = \frac{2 i(j)}{2 i(j) + 1}
\end{gathered}
$$
can converge to $0 = \int f(x) \mu(dx)$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Confused as to why these pictures and text aren't lining up
I have a div with 2 different divs in it. Each of these 3 have a picture in (60%) of the width and some text in them (40%) however it isn't lining up at all. The text is in the right place and the pictures are in the right organization but they are too far down the page. I'm newish to CSS and I don't know how to fix this
Here's a picture of what it looks like
HTML:
<div class="section 1">
<p id="section1text">
<b>ME</b><br>Hello! My name is Max Jordan. I am a student living in the UK currently doing A-Levels in Maths, Engineering, Physics and computer science. I then want to do a degree in computer science and work as a Software Engineer/Developer. I currently live in Nottingham in the UK. I love programming and creating elegant soloutions for problems.
</p>
<img src="section1.jpg" id="section1pic">
</div>
<div class="section 2">
<p id="section2text">
<b>WORK</b><br>
</p>
<img src="section2.jpg" id="section2pic">
</div>
<div class="section 3">
<p id="section3text">
</p>
<img src="section3.jpg" id="section3pic">
</div>
CSS:
.aboutSection{
width: 100%;
height:100%;
}
.section{
text-align: center;
display: inline-block;
width: 90%;
height: 20%;
margin-left: 5%;
}
#section1text{
float: left;
display: inline-block;
height: 100%;
width:40%;
background-color: #3399ff;
color: white;
font-size: 20;
padding: 10px;
}
#section2text{
float: right;
height: 100%;
width:40%;
float: right;
background-color: #3399ff;
color: white;
font-size: 20;
display: inline-block;
padding: 10px;
}
#section3text{
float: left;
height: 100%;
width:40%;
background-color: #3399ff;
color: white;
font-size: 20;
display: inline-block;
padding: 10px;
}
#section1pic{
float: right;
position:relative;
display: inline-block;
height: 100%;
width: 60%;
}
#section2pic{
float: left;
position:relative;
display: inline-block;
height: 100%;
width: 60%;
}
#section3pic{
float: right;
position:relative;
display: inline-block;
height: 100%;
width: 60%;
}
I know the CSS is very bad but im just trying to get it working.
A:
Instead of fiddling around with floats and positioning. I guess display:flex is a good option for such layouts
check this snippet
.imgContainer {
display: flex;
flex-wrap: wrap;
}
.section {
display: flex;
border: 1px solid;
}
#section1text {
border: 1px solid;
width: 40%;
background-color: #3399ff;
border-right: 1px solid red;
px solid;
}
.div1 img {
width: 60%;
height: 100%;
}
.div2 img {
width: 60%;
height: 100%;
border-right: 1px solid red;
padding: 10px;
}
.div3 img {
width: 60%;
height: 100%;
}
#section2text {
width: 40%;
background-color: #3399ff;
color: white;
font-size: 20;
padding: 10px;
}
#section3text {
background-color: #3399ff;
color: white;
width: 60%;
}
<div class="imgContainer">
<div class="section div1">
<p id="section1text">
<b>ME</b>
<br>Hello! My name is Max Jordan. I am a student living in the UK currently doing A-Levels in Maths, Engineering, Physics and computer science. I then want to do a degree in computer science and work as a Software Engineer/Developer. I currently live
in Nottingham in the UK. I love programming and creating elegant soloutions for problems.
</p>
<img src="https://exoticcars.enterprise.com/etc/designs/exotics/clientlibs/dist/img/homepage/Homepage-Hero-Car.png" id="section1pic">
</div>
<div class="section div2">
<img src="https://exoticcars.enterprise.com/etc/designs/exotics/clientlibs/dist/img/homepage/Homepage-Hero-Car.png" id="section2pic">
<p id="section2text">
<b>WORK</b>
<br>
</p>
</div>
<div class="section div3">
<p id="section3text">
skfshfk
</p>
<img src="https://exoticcars.enterprise.com/etc/designs/exotics/clientlibs/dist/img/homepage/Homepage-Hero-Car.png" id="section3pic">
</div>
</div>
I tried to create sample layout of your requirement
Hope it helps
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why are my squash shrivelling?
I put squash seeds in with my compost at the end of last year, and apparently it didn't get heated up enough to kill everything. I now have Delicata plants with dinner-plate sized leaves growing out of it.
One of the plants has nice, healthy, 4 and 6 inch squash hanging off of it.
Another of the plants has produced a 10-foot runner with a little squash every foot or so, but every one of those squash has shriveled up after the flower closed up. I had always thought they only did that when they didn't get pollinated, so I went as far as going out there with a small paintbrush and transferring pollen from the male flowers to the female flowers, and the squash still did that.
Could it still be a pollination issue, or would a nutrient imbalance cause the squash to shrivel up?
A:
If you were intentionally saving seed, you would have wanted 1/2 mile isolation distance (or bagging and hand-pollination) for the parent plants to be sure that you had seed that wasn't crossed with some other type of squash. If you grew a different variety of squash (C. pepo) last year, or if anyone in your neighborhood was growing any variety of C. pepo at the same time last year, your volunteers could be crossed with another variety -- possibly in strange ways.
So if you have a volunteer that looks and fruits like the parent, that one must not have been crossed. Consider yourself lucky and enjoy the squash.
It's possible that the unproductive volunteer is crossed in a way that makes it unable to produce fruit.
If both the healthy and unhealthy plant are growing in the same soil, a nutrient imbalance seems unlikely.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to customize name, length and value of a discriminator column with Entity Framework 6
I try to use EF6 with an existing database I must be compatible with.
The database has been generated by nHibernate and some tables use the table-per-hierarchy (TPH) inheritance model.
Discriminator columns are named Category (instead of Discriminator) and have an SQL length of 255 (instead of 128). Values are also different from what EF would generate.
How can I configure EF to use the existing columns (name, size and values)?
I tried to define a custom convention:
protected class DiscriminatorRenamingConvention : IStoreModelConvention<EdmProperty>
{
public void Apply(EdmProperty property, DbModel model)
{
if (property.Name == "Discriminator")
{
property.Name = "Category";
property.MaxLength = 255;
}
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntityA>().Map(x => x.Requires("Category").HasValue("CatA"));
modelBuilder.Entity<MyEntityB>().Map(x => x.Requires("Category").HasValue("CatB"));
modelBuilder.Conventions.Add<DiscriminatorRenamingConvention>();
base.OnModelCreating(modelBuilder);
}
This generates a column named Category but with a length of 128, whatever the order of instructions in the OnModelCreating method. Specifying category values seems to overwrite MaxLength.
A:
Here
modelBuilder.Entity<MyEntityA>().Map(x => x.Requires("Category").HasValue("CatA"));
you specify the name of the discriminator to be "Category", so this
if (property.Name == "Discriminator")
will evaluate to false, hence the MaxLength will be the EF default.
To get the desired behavior, use Requires("Discriminator") and let the convention do the rest.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use singleton class for get and Post the json values in xamarin forms?
I developing a xamarin application using singleton based to get the server values. Searched the example by StackOverflow in this site(Show List in Xamarin consuming REST API). but I have small doubts about this. no one reply to my comment to this question.
My Code:
public async Task<Response> GetList<T>(string urlBase, string servicePrefix, string controller)
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(urlBase);
var url = string.Format("{0}{1}", servicePrefix, controller);
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
return new Response
{
IsSuccess = false,
Message = result,
};
}
var list = JsonConvert.DeserializeObject<List<T>>(result);
return new Response
{
IsSuccess = true,
Message = "Ok",
Result = list,
};
}
catch (Exception ex)
{
return new Response
{
IsSuccess = false,
Message = ex.Message,
};
}
}
My doubt what is Response in this code. It is a separate class or HTTP response message. but I changed the HTTP response message, it gives an error in the above-declared variables(Success, Message).
A:
Response is a Custom class like following code,.It contails three properties.
public class Response
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
public object Result { get; set; }
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python Image Library fails with message "decoder JPEG not available" - PIL
PIL does support JPEG in my system.
Whenever I do an upload, my code is failing with:
File "PIL/Image.py", line 375, in _getdecoder
raise IOError("decoder %s not available" % decoder_name)
IOError: decoder jpeg not available
How can I resolve this?
A:
libjpeg-dev is required to be able to process jpegs with pillow (or PIL), so you need to install it and then recompile pillow. It also seems that libjpeg8-dev is needed on Ubuntu 14.04
If you're still using PIL then you should really be using pillow these days though, so first pip uninstall PIL before following these instructions to switch, or if you have a good reason for sticking with PIL then replace "pillow" with "PIL" in the below).
On Ubuntu:
# install libjpeg-dev with apt
sudo apt-get install libjpeg-dev
# if you're on Ubuntu 14.04, also install this
sudo apt-get install libjpeg8-dev
# reinstall pillow
pip install --no-cache-dir -I pillow
If that doesn't work, try one of the below, depending on whether you are on 64bit or 32bit Ubuntu.
For Ubuntu x64:
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib
Or for Ubuntu 32bit:
sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so.6 /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/
Then reinstall pillow:
pip install --no-cache-dir -I pillow
(Edits to include feedback from comments. Thanks Charles Offenbacher for pointing out this differs for 32bit, and t-mart for suggesting use of --no-cache-dir).
A:
For those on OSX, I used the following binary to get libpng and libjpeg installed systemwide:
libpng & libjpeg for OSX
Because I already had PIL installed (via pip on a virtualenv), I ran:
pip uninstall PIL
pip install PIL --upgrade
This resolved the decoder JPEG not available error for me.
UPDATE (4/24/14):
Newer versions of pip require additional flags to download libraries (including PIL) from external sources. Try the following:
pip install PIL --allow-external PIL --allow-unverified PIL
See the following answer for additional info: pip install PIL dont install into virtualenv
UPDATE 2:
If on OSX Mavericks, you'll want to set the ARCHFLAGS flag as @RicardoGonzales comments below:
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install PIL --allow-external PIL --allow-unverified PIL
A:
This is the only way that worked for me. Installing packages and reinstalling PIL didn't work.
On ubuntu, install the required package:
sudo apt-get install libjpeg-dev
(you may also want to install libfreetype6 libfreetype6-dev zlib1g-dev to enable other decoders).
Then replace PIL with pillow:
pip uninstall PIL
pip install pillow
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Explanation for a latex def
I came across this line in the awesome-cv document class
\def\@sectioncolor#1#2#3{%
\ifbool{acvSectionColorHighlight}{{\color{awesome}#1#2#3}}{#1#2#3}%
}
\newcommand*{\sectionstyle}[1]{{\fontsize{16pt}
{1em}\bodyfont\bfseries\color{text}\@sectioncolor #1}}
What it does is that you give it a word and it changes the colour of the first three letters of the word.
However, I don't understand how it works. Could someone please describe it to me?
A:
Without considering the definitions in their entirety, focus on the following:
\def\@sectioncolor#1#2#3{%
% <some definition>
}
\newcommand*{\sectionstyle}[1]{{%
% <some definition>
\@sectioncolor #1}}
It should be obvious that \sectionstyle takes a single, mandatory argument. This mandatory argument is the title of the section, as in \sectionstyle{Education} for example. This argument is passed to \@sectioncolor via
\@sectioncolor #1
However, note that there are no braces around #1, since \@sectioncolor expects three mandatory arguments. To that end, a call like \sectionstyle{Education} translates to
\@sectioncolor Education
where \@sectioncolor takes the first three tokens as its mandatory argument. That is, one can almost assume the following transferred input:
\@sectioncolor {E}{d}{u}cation
Within \@sectioncolor's definition, E would be #1, d would be #2 and u would be #3. They are set in sequence #1#2#3 if you don't want your sections highlighted by colour, or they're coloured using the colour awesome if you do.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flutter web visual studio
I've been using flutter web in visual studio code.
Today I tried upgrading to flutter 1.9.
After that, the option new flutter web project in visual studio is gone.
I tried installing it again, but it doesn't come back.
Are there other options?
A:
Checkout the latest dartcode release. "New Web Project command has been removed. To create web projects, you should now use the standard Flutter: New Project command."
https://dartcode.org/releases/v3-5/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is this downcasting undefined?
Consider this example, where the base class has some data members, while derived one only provides an additional method:
struct TestBase
{
int x;
TestBase() : x(5) {}
};
struct TestDerived : public TestBase
{
void myMethod()
{
x=8;
}
};
int main()
{
TestBase b;
TestDerived& d=static_cast<TestDerived&>(b);
d.myMethod();
}
This is downcasting to wrong type, so AFAIU it has undefined behavior. But are there maybe some exceptions to such cases as this, where the derived class' layout is identical to that of base class?
A:
From the standard (emphasis mine):
§5.2.9 Static cast [expr.static.cast] ...
(2) An lvalue of type “cv1 B,” where B is a class type,
can be cast to type “reference to cv2 D,” where
D is a class derived from B, if a valid
standard conversion from “pointer to D” to “pointer to B” exists, cv2 is
the same cv-qualification as, or greater cv-qualification than, cv1, and B
is neither a virtual base class of D nor a base class of a virtual base
class of D. The result has type “cv2 D.” An xvalue of type “cv1 B”may be
cast to type “rvalue reference to cv2 D” with the same constraints as for
an lvalue of type “cv1 B.”
If the object of type “cv1 B” is actually a subobject of an object of
type D, the result refers to the enclosing object of type D.
Otherwise, the behavior is undefined.
My first guess was that the cast should be valid in this case,
because I got confused by the term subobject.
Now (thanks to @T.C. and @M.M), it is obvious that the behavior is undefined in this case.
The cast would be valid in the following example:
int main()
{
TestDerived d;
TestBase &br = d; // reference to a subobject of d
TestDerived &dr = static_cast<TestDerived&>(br); // reference to the original d object
d.myMethod();
}
Here, an object of class TestDerived (d) will have a subobject of class TestBase (br is a reference to this object).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Setting an environment variable that launches Octave
I recently installed octave on macOS and I can launch octave fine by running Octave-cli in Applications or by running in terminal /usr/local/octave/3.8.0/bin/octave-3.8.0.
How can I set it so octave-cli runs in terminal when I type octave?
A:
Update your PATH variable to include the octave install location (folder). You can do this by editing your .bash_profile file in your home directory. Append the following to the file (create it if it doesn't exist) and start a new terminal session.
export PATH="$PATH:<path to your octave install directory>"
If want to test it in your current terminal session just run the command above. All putting it the profile does is ensure it is run every time you start a new terminal window.
Also, my install directory seems to be a bit different from yours so you may want to double check you installed it correctly. The octave executables are located in /usr/local/bin for me. This is already in my PATH so I didn't need to update my bash profile.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Connecting Eclipse to TFS From Behind a proxy server
I am having trouble connecting to the TFS Server using the eclipse tfs plugin from behind the proxy. I have configured my proxy settings correctly on the Eclipe->Preferences->Network Connections.
I read somewhere that I need to add my TFS credentials to the mac keychain ?. Could anyone explain me how to do that exactly ?.
A:
If you're having proxy configuration problems, it is recommend to check the "Override Default HTTP Proxy" option when configuring your Team Foundation Server in the plug-in for Eclipse.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Proving $\int _{-\pi }^{\pi }\int _{-\pi }^{\pi }\int _{-\pi }^{\pi }\log \left| 1+e^{i x}+e^{i y}+e^{i z}\right| dxdydz=28 \pi \zeta (3)$
It is known that:
$$\int _{-\pi }^{\pi }\log \left|1+e^{i x} \right| dx=0$$
$$\int _{-\pi }^{\pi }\int _{-\pi }^{\pi }\log \left|1+e^{i x}+e^{i y} \right| dxdy=\frac{\pi \left(\psi ^{(1)}\left(\frac{1}{3}\right)-\psi ^{(1)}\left(\frac{2}{3}\right)\right)}{\sqrt{3}}$$
The first formula can be shown using Cauchy theorem, while the second is a direct consequence of Poisson integral formula and fourier expansion. However, I have no idea how to solve the 3-dimensional case:
$$\int _{-\pi }^{\pi }\int _{-\pi }^{\pi }\int _{-\pi }^{\pi }\log \left| 1+e^{i x}+e^{i y}+e^{i z}\right| dxdydz=28 \pi \zeta (3)$$
I collected it from J.Borwein's review but it offered no proof. How can we solve this problem, and is there a deeper background of it, which may give insight on general cases? Any kind of help is appreciated.
A:
It turns out that J.Borwein's own article "Mahler measures, short walks and log-sine integrals" offers an elegant proof of this formula using hypergeometric method.
Denote $$W_n(s)=\int_{(0,1)^n}\left|\sum_{k=1}^n e^{2\pi i x_k}\right|^s dx_1\cdots dx_n$$
According to R.Crandall's article "Analytic representations for circle-jump moments", $W_4(s)$ has a Meijer-G representation, which is transformed into generalized hypergeometric functions via functional identities, that is:
$$W_4(s)=\binom{s}{\frac{s}{2}} \, _4F_3\left(\frac{1}{2},-\frac{s}{2},-\frac{s}{2},-\frac{s}{2};1,1,\frac{1-s}{2};1\right)+\frac{1}{4^s}{\binom{s}{\frac{s-1}{2}}^3 \tan \left(\frac{\pi s}{2}\right) \, _4F_3\left(\frac{1}{2},\frac{1}{2},\frac{1}{2},\frac{s}{2}+1;\frac{s+3}{2},\frac{s+3}{2},\frac{s+3}{2};1\right)}$$
Differentiating both sides w.r.t $s$ then let $s\rightarrow 0$, after simplification we have:
$$W_4^{'}(0)=\frac{4}{\pi ^2}{_4F_3\left(\frac{1}{2},\frac{1}{2},\frac{1}{2},1;\frac{3}{2},\frac{3}{2},\frac{3}{2};1\right)}=\frac{7 \zeta (3)}{2 \pi ^2}$$
On the other hand, by scaling, using symmetry and periodicity of the original integrand and noticing $\log\left|e^{i \phi}\right|=1$, it's clear that:
$$2\pi I=\int _{-\pi }^{\pi }\int _{-\pi }^{\pi }\int _{-\pi }^{\pi }\int _{-\pi }^{\pi }\log \left|e^{i w}+e^{i x}+e^{i y}+e^{i z}\right|dwdxdydz=16\pi^4 W_4^{'}(0)$$
From which we get the desired result $I=28\pi \zeta(3)$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Auto Gitpull Script?
I want to create a script for git which is triggered when there is an update to a repo and does "git pull" on our remote server.
I have a very basic version in which a POST message is set to the URL on our server which would have the content
<?php `git pull`;
In it, no problem there. However the dev domain is actually a fake domain which nginx redirects to on my server (url.dev) so I can't point to it this way. My idea was to point another live domain to a subfolder on the dev server, so the top level directory can't be accessed, but then of course running "git pull" from that directory won't work. Is there anyway in PHP to run the command so that it "CD"'s into the correct director and Gitpulls or is this not possible with php?
A:
If you add the public keys to the user that is running your scripts (usually www-data) you can do this
system("/path/to/executable/git pull;echo \"\nLast commit\"; /path/to/executable/git log -2;");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# code to change browser download options
I am trying to do following with c#.
1) Open Firefox Browser-->Tools-->Options-->General Tab--->Downloads--->Always ask me where to save file.
I want to do this whole process in my application with c#. I want that when download window opens, the radio button in "Always ask me where to save file" option gets checked automatically.
I have tried from various links, but all is in vain.
A:
Here is the full code, console application.
Summary: preferences file is located in application roaming folder, something like this on windows 7:
C:\Users\MYNAME\AppData\Roaming\Mozilla\Firefox\Profiles\d9i9jniz.default\prefs.js
We alter this file so that it includes "user_pref("browser.download.useDownloadDir", false);"
Restart firefox, and done. Only run this application when firefox is not running.
static void Main(string[] args)
{
if (isFireFoxOpen())
{
Console.WriteLine("Firefox is open, close it");
}
else
{
string pathOfPrefsFile = GetPathOfPrefsFile();
updateSettingsFile(pathOfPrefsFile);
Console.WriteLine("Done");
}
Console.ReadLine();
}
private static void updateSettingsFile(string pathOfPrefsFile)
{
string[] contentsOfFile = File.ReadAllLines(pathOfPrefsFile);
// We are looking for "user_pref("browser.download.useDownloadDir", true);"
// This needs to be set to:
// "user_pref("browser.download.useDownloadDir", false);"
List<String> outputLines = new List<string>();
foreach (string line in contentsOfFile)
{
if (line.StartsWith("user_pref(\"browser.download.useDownloadDir\""))
{
Console.WriteLine("Found it already in file, replacing");
}
else
{
outputLines.Add(line);
}
}
// Finally add the value we want to the end
outputLines.Add("user_pref(\"browser.download.useDownloadDir\", false);");
// Rename the old file preferences for safety...
File.Move(pathOfPrefsFile, Path.GetDirectoryName(pathOfPrefsFile) + @"\" + Path.GetFileName(pathOfPrefsFile) + ".OLD." + Guid.NewGuid().ToString());
// Write the new file.
File.WriteAllLines(pathOfPrefsFile, outputLines.ToArray());
}
private static string GetPathOfPrefsFile()
{
// Get roaming folder, and get the profiles.ini
string iniFilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Mozilla\Firefox\profiles.ini";
// Profiles.ini tells us what folder the preferences file is in.
string contentsOfIni = File.ReadAllText(iniFilePath);
int locOfPath = contentsOfIni.IndexOf("Path=Profiles");
int endOfPath = contentsOfIni.IndexOf(".default", locOfPath);
int startOfPath = locOfPath + "Path=Profiles".Length + 1;
int countofCopy = ((endOfPath + ".default".Length) - startOfPath);
string path = contentsOfIni.Substring(startOfPath, countofCopy);
string toReturn = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Mozilla\Firefox\Profiles\" + path + @"\prefs.js";
return toReturn;
}
public static bool isFireFoxOpen()
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName == "firefox")
{
return true;
}
}
return false;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If $H$ is a normal subgroup of $G$ then $Z(H)$ is normal in $G$
Let $G$ be a group and $H$ a normal subgroup of $G$. Let $Z(H)$ be the center of $H$. Show that $Z(H)$ is normal in $G$.
So I know that if $h' \in Z(H)$ then $h'h=hh'$ for all $h \in H$ and I tried proving that $gZ(H)=Z(H)g$. Let $h' \in Z(H)$, so $gh'=hg$ for some $h \in H$ since $H$ is normal and $Z(H)$ is a subgroup of $H$. In particular, $z(H)$ is normal in $H$, so $gh'g^{-1} \in Z(H)$. Therefore $h$ has to be in $Z(H)$. That proves that $gZ(H) \subseteq Z(H)g$. Similarly, we can prove the reverse inclusion. Did I do it correctly?
A:
The goal is to show that $Z(H)$ is normal in $G$. Take any element $z \in Z(H)$ and any $g \in G$. We need to show that $gzg^{-1} \in Z(H)$. First, note that $gzg^{-1} \in H$, since $z \in H$ and $H$ is normal in $G$. Now, given any element $h \in H$, we need to show that $h(gzg^{-1}) = (gzg^{-1})h$.
Since $H$ is normal in $G$, we have $hg = gk$ for some $k \in H$. Therefore:
$$h(gzg^{-1}) = (hg)zg^{-1} = (gk)zg^{-1} = g(kz)g^{-1} = g(zk)g^{-1} = gz(kg^{-1})$$
where we have used the fact that $kz = zk$ because $k \in H$ and $z \in Z(H)$. Now recall that $hg = gk$. Multiplying this equation on the left and right by $g^{-1}$ gives us $g^{-1}h = kg^{-1}$. Applying this to the rightmost expression in the chain of equalities above, we get $gz(kg^{-1}) = gz(g^{-1}h) = (gzg^{-1})h$, which is exactly what we want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Убрать помехи бинарное изображение C++
Превращаю изображение в бинарное(черно-белое):
image = image.convertToFormat(QImage::Format_Mono);
Получается вот такое изображение с помехами:
А необходимо, что получилось примерно вот такое:
Как убрать помехи, желательно без сторонних библиотек?
A:
image = image.convertToFormat(QImage::Format_Mono, Qt::ThresholdDither);
Фглаг Qt::ThresholdDither отключает дизеринг и применяет простой пороговый алгоритм для конвертации изображения.
см QImage::convertToFormat(), Qt::ImageConversionFlag
Полученное изображение:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to generate set of arrays when clicking button, without disappearing the first one?
Im trying to learn js. Im starting playing with array by generating 6 combination numbers. This is working but i dont know how to output another combinations when I click the button. Any comment is appreciated. THanks
function getRandomNumber() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var arr = [];
while(arr.length < 8){
var myrandomnumber = Math.floor(Math.random(x) * y + 1);
if(arr.indexOf(myrandomnumber) === -1) arr.push(myrandomnumber);
}
if (x==""){
alert("Please enter a number");
}
else if (y==""){
alert("Please enter a number");
}
else{
document.getElementById("ok").innerHTML = arr;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RANDOM NUMBER JS</title>
<meta name="" content="">
<link rel="stylesheet" href="css/css/bootstrap.css">
<link rel="stylesheet" href="css/cssextra/csse1.css">
<script src="customscript.js"></script>
</head>
<body class="bg-light">
<br>
<p id="demo">Random Number</p>
<br><br>
<input type="number" id="num1" name="one"/ >
<input type="number" id="num2" name="two"/ >
<button onclick="getRandomNumber();">Generate random number</button >
<p id="ok"></p><br>
<p id="okok"></p>
</body>
</html>
A:
Accumulate results
A easy yet crude solution would be appending the current text with <br> for line breaks:
const p = document.getElementById("ok");
p.innerHTML = p.innerHTML + (p.innerHTML === "" ? "" : "<br>") + arr.join(", ");
But this approach will notoriously perform badly as the text grows larger.
If you change the p elements into:
<div id="ok" class="text-container">
And replace the script's document.getElementById("ok").innerHTML = arr; into:
const p = document.createElement("p");
p.textContent = arr.join(", ");
document.getElementById("ok").appendChild(p);
And add css:
.text-container {
margin-top: 1em;
}
.text-container > p {
margin: 0;
}
Then you should have something working.
Also there are some things to address:
Math.random()
The function Math.random() does not take arguments, so your variable x does not have any effect.
If the intention is to x and y as a minimum and maximum value, try this from Math.random() - JavaScript | MDN:
function getRandomInt(min, max) {
var min = Math.ceil(min);
var max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
The min is inclusive and the max is exclusive. If x = 0 and y = 10, and you want the range to be [0-10], you can do getRandomInt(x, y + 1).
Make sure min is not greater than max.
Prevent infinite loop
Your loop will get stuck if the amount of possible unique integers is smaller than the number of array elements required for it to end.
More user input semantics
Variables x and y are tested before writing out the numbers, but after they have already been used to generate the numbers. In other words, the number creation process should be moved into the else block.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
trying to launch wpf application from visual studio setup project custom action. Error 1001: Assembly.GetEntryAssembly() returns null
I am preparing a setup project for my application. i need to construct database connection string and then run the script file based on the connection string and update the application config files as well.
i have this WPF Sql Connection User Control which enables me to construct the database connection string from user input.
The problem is that when i try to launch the WPF Sql Connection User Control from an installer class i get this exception.
Error 1001: Assembly.GetEntryAssembly() returns null. Set the Application.ResourceAssembly property or use the pack syntax to specify the assembly to load the resource from.
here is the App.xaml.cs code
Uri uri = new Uri(@"/WpfApplication1;component/MainWindow.xaml", UriKind.Relative);
var window = Application.LoadComponent(uri);
my installer class has this code to launch the application.
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
var thread = new System.Threading.Thread(StartDatabaseUserControl);
thread.SetApartmentState(System.Threading.ApartmentState.STA);
thread.Start();
thread.Join();
}
Thanks,
Implemented Solution
well i have got it working in a different way.
Changing the custom action property "Installer Class" to false in the visual studio setup project worked for me.
i had to add another entry point and set it as project startup object. don't even need to add any code in the App.xaml.cs file.
this is the new entry point
[STAThread]
private static void Main(string[] args)
{
TargetDirectory = args[0];
var app = new App();
app.InitializeComponent();
app.Run();
}
A:
The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.
MSDN
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does the form duplicates after removing one child div form?
I'm a student and new to JavaScript and JQuery. I took some time to understand and learn (by myself) how to write a program using both PHP and JQuery for the program I am working on.
I try to allow users to add multiple forms by using an Add button and remove as well. My question is, why does the child form group duplicates after user removes the added form and how do I ensure that the 'select2' plugin initializes properly?
I wrote a sample for you to try it out here.
HTML Code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body>
<div id="pointsTitleDiv" class="form-group">
<label for="pointsTitle" class="col-sm-3 control-label">PRODUCT</label>
<div class="col-sm-4">
<select class="form-control select2" id="pointsTitle" name="pointsTitle[]" style="width: 100%;">
<option value="">Select Product</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<span id="pointsTitleSpan" class="help-block" style="display:none"></span>
</div>
</div>
<div id="pointsQuantityDiv" class="form-group">
<label for="pointsQuantity" class="col-sm-3 control-label">QUANTITY</label>
<div class="date col-sm-4">
<input type="number" min="0" class="form-control pull-right" id="pointsQuantity" name="pointsQuantity[]">
<span id="pointsQuantitySpan" class="help-block" style="display:none"></span>
</div>
<div id="addButton" class="form-group-sm pull-right" style="padding-right: 15px; padding-top: 10px">
<button type="button" id="add" name="add" class="btn btn-info pull-right">ADD ORDER</button>
</div>
</div>
<div id="childFormGroup" class="form-group" style="padding-left: 10px">
</div>
<!-- /.form group -->
<script>
$(function () {
//Initialize Select2 Elements
$('.select2').select2()
})
</script>
</body>
</html>
JavaScript
$(document).ready(function (e) {
//Counter for form addition
var count = 1;
//Defining buttons
var addButton = document.getElementById("add");
var removeButton = document.getElementsByName("remove");
//VARIABLES
var divID = "#pointsTitle";
var html = '';
var selectData = '<option value = "">Select Product</option><option value = "1">Option 1</option><option value = "2">Option 2</option>';
var x = 0;
//Populate select box for first form. 'selectData' replicates the data coming from a Database to populate the select option.
$("#pointsTitle").html(selectData);
//Add button's behaviour
addButton.addEventListener('click', function (e) {
html += '<div id = "childFormGroup-internal' + count + '"><hr>';
html += '<div id = "childpointsTitleDiv' + count + '" class = "form-group" style = "padding-left: 5px">';
html += '<label for="childpointsTitle" class="col-sm-3 control-label"><p> PRODUCT</p></label>';
html += '<div class="date col-sm-4"><select class = "childselect' + count + ' form-control pull-right" id="pointsTitle' + count + '" name="pointsTitle[]" style="width: 100%;">';
html += '<option value="">Select Order</option>';
html += '</select><span id="childpointsTitleSpan' + count + '" class="help-block" style="display:none"></span>';
html += '</div></div>';
html += '<div id="childpointsQuantityDiv' + count + '" class="form-group" style = "padding-left: 5px"><label for="childpointsQuantity" class="col-sm-3 control-label"> QUANTITY</label><div class="date col-sm-4">';
html += '<input type="number" min="0" class="form-control pull-right" id="pointsQuantity" name="pointsQuantity[]"><span id="childpointsQuantitySpan' + count + '" class="help-block" style="display:none"></span>';
html += '</div><span class="pull-right" style = "padding-right: 40px; padding-top: 10px"><button type="button" id = "' + count + '" name="remove" class="btn btn-danger btn_remove">X</button></span></div></div>';
$("#childFormGroup").html(html);
for (x = 1; x <= count; x++) {
$(".childselect" + x).select2();
$(divID + x).html(selectData);
}
count++;
});
$(document).on('click', '.btn_remove', function () {
--count;
--x;
var button_id = $(this).attr("id");
$("#childFormGroup-internal" + button_id).remove();
});
});
I am out of ideas. I appreciate your time and help in guiding me through this problem, thanks!
A:
The reason that you forms are getting duplicated is that you keep appending the form html to your html variable every time the addButton is clicked.
What you need to fix that is to define the html variable inside the click handler function so that it is empty before you add a form.
Then, you loop through all your forms and initialize select2 on these. But you actually need to initialize select2 only on those forms where it has not been initialized. So get the id for the form that you just appended and initialize select2 only for this form.
Instead of counting groups, you can use the length property. For example,
$( '[id^="childFormGroup-internal"]' ).length
This will get you the number of your forms on the page. Even better if you add a class to these forms, for example, .childFormGroup-internal, then you will be able to select even easier:
var count = $( '.childFormGroup-internal' ).length // goes in the click handler to be up to date with the number of the forms on the page at the time of the click
It also makes it easier to generate IDs for new forms:
var newId = count + 1
And to initialize select2 on new forms (outside any loop):
$(".childselect" + newId).select2();
Hope this helps!
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.