text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Returning original post data if request fails
I know I could just do this with a global, but I'd like to be object oriented if I can. If my request response returns a false for that 'ok' value, I'd like to log the data that was originally posted. Is that data accessible by a listener function on the request object?
Thanks!
function reqListener () {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
//Here I want to log the data that I originally posted
console.log(__TheFormDataThatWasPassedtoSend__);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load",reqListener);
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
A:
So the problem you have is needing to use data known when you create the eventListener when the eventListener actually fires. Below is your code to do this with formData
function reqListener (formData) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
console.log(formData);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() { reqListener.call(this,formData) });
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
| {
"pile_set_name": "StackExchange"
} |
Q:
Display value from other table
I have a database with two tables.
The first table contains an foreign key from the second table.
In my MVC-project, i would like to display the value (stored in second table) instead
of only the ID from the first table..
In SSMS i could do this with a join. But how do I do this in c#?
rec.Title = item.Title + " - " + item.AppointmentLength.ToString() + " mins" + " BehandlingsID " + ***item.BehandlingarId***;
//
item.BehandlingarId contains the ID which i would like to change to its corresponding value.
These are my two tabeles:
public class AppointmentDiary
{
public int ID { get; set; }
public DateTime DateTimeScheduled { get; set; }
public Behandlingar Behandling { get; set; }
public int? BehandlingarId { get; set; }
}
public class Behandlingar
{
public int BehandlingarId { get; set; }
public string Namn { get; set; }
public int Pris { get; set; }
public int Tid { get; set; }
}
List<DiaryEvent> result = new List<DiaryEvent>();
foreach (var item in rslt)
{
DiaryEvent rec = new DiaryEvent();
rec.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("s");
rec.Title = item.Title + " - " + item.AppointmentLength.ToString() + " mins" + " BehandlingsID " + item.BehandlingarId;
}
A:
Are you expecting something like this?
var result=AppointmentDiary.Where(i=>i.BehandlingarId==BehandlingarId).ToList;
This will give you the records that matches the BehandlingarId in AppointmentDiary table
Edit :
If you want the other way around.
If DB is your datacontext
var result=DB.Behandlingar.Where(i=>i.BehandlingarId == BehandlingarId).FirstorDefault().Nam;
Note: BehandlingarId here is the foreign key from AppointmentDiary.
say you want to access the nam for BehandlingarId=1 then
var result=DB.Behandlingar.Where(i=>i.BehandlingarId == 1).FirstorDefault().Nam;
will give you the first record that matches the BehandlingarId==1 in the Behandlingar table
You can put this snippet any where you want to access the nam
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Composition of relations: A ∘ B
Solve: Composition of relations: A ∘ B
A = {(1, 1), (1, 2), (4, 1), (4, 2)}
B = {(1, 1), (2, 1), (1, 4), (2, 4)}
When I solve mentally I get A ∘ B = {(1, 1), (2,2)}
But when I draw an arrow-diagram I get A ∘ B = {(1, 1), (1, 2), (2, 1), (2,2)}
(1, 2) and (2, 1) from the the arrow-diagram since 4 points to 1 & 2, and 1 also points 1 & 2.
Which one is right?
A:
The diagram is correct.
$B$ maps both $1$ and $2$ to $1$ or $4$. $A$ maps both $1$ and $4$ to $1$ or $2$.
Thus $A\circ B$ maps both $1$ and $2$ to $1$ or $2$.
When you solved mentally, I guess you mistook the relations for inverses which would have meant the composition was an identity. However, as neither is one-to-one, then they are not invertible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Objective C - Box2d float type casting: multiplying * operand on float32
Please help me in removing the error with explanation
Error on the following line:
_Sprite.position.x = _Body->GetPosition().x * _PhysicsWorld->RATIO;
Error message: Invalid operands to binary expression ('float32 (aka 'float') and 'float32()())
_Body is a B2Body object
_Sprite is a CCSprite object
_PhysicsWorld->RATIO returns float32
If I change the line to:
_Sprite.position.x = _Body->GetPosition().x * (float) _PhysicsWorld->RATIO;
Another error message comes: C-style cast from float32(*)() to float is not allowed.
A:
You probably need to do:
_Sprite.position.x = _Body->GetPosition().x * _PhysicsWorld->RATIO();
Note the trailing '()' after RATIO.
You are multiplying a float (which parses into pointer dereferencing instead) by a function that returns a float (I believe).
| {
"pile_set_name": "StackExchange"
} |
Q:
Python performance vs PHP
I am an experienced PHP developer, and I would want to know what of both languages is better for web development.
I understand that there are a lot of factors to evaluate; but focusing in execution time, in your own experience making connections to a MySQL server, parsing and concatenating strings, and making several echoes (or prints), what language would you recommend me?
I cite this specific situations because are common for me, and I don´t calculate fibonacci sequences neither prime numbers, like are showed in several benchmarks.
A:
Even if things aren't specifically integer comparison or string comparison problems, looking at those computations is a decent indication of how the language will perform in more complex tasks. Keep in mind, though, that web development isn't all about computation speed. Unless you're doing some fancy backend data processing (in which case PHP is really not appropriate) when it comes to things like generating pages: it's still often worth the small sacrifice in terms of speed/memory to make it much, much easier to develop.
Also: Python+MySql is kind of a pain, in my experience. It can be done. But it's not nearly as nice.
Which is faster, python webpages or php webpages? <- lots of stuff here
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple inputs in C
I'm trying to create a function that gets multiple inputs for resistances value. In my main function the program asks the user to ask how many resistors are needed. The number of resistors needed by the user will become the number of times the program will ask the user to input for resistance value. The problem is what loop should i use to make an error statement and make the user input the value again. the input only accepts integer. here is the code:
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 500
int resistors(int rescount, int *val_res);
int validate ( char *a )
{
unsigned x;
for ( x = 0; x < strlen ( a ); x++ )
if ( !isdigit ( a[x] ) )
return 1;
return 0;
}
int main()
{
int numres;
int resistance[MAXSIZE];
char resist[MAXSIZE];
do
{
printf("How many resistors do you want to place in the circuit?\n");
if (fgets(resist, sizeof(resist), stdin) != NULL)
{
resist[strlen (resist) - 1] = '\0';
if(validate (resist) == 0)
{
numres = atoi(resist);
}
}
} while(numres < 1 || numres > 100);
resistors(numres, resistance);
return 0;
}
int resistors(int rescount, int *val_res)
{
char resistor_value[MAXSIZE];
int z;
printf("Please input the value of resistors:\n");
for(z = 1; z < (*val_res); z++)
{
printf("\tPlease input Resistor #%d: \n", z);
if (fgets(resistor_value, sizeof(resistor_value), stdin) != NULL)
{
resistor_value[strlen (resistor_value) - 1] = '\0';
if(validate (resistor_value) == 0)
{
val_res[z-1] = atof(resistor_value);
}
}
do{
printf("\tInvalid Resistance\n");
printf("\tRe-input Resistor #%d: \n", z);
if (fgets(resistor_value, sizeof(resistor_value), stdin) != NULL)
{
resistor_value[strlen (resistor_value) - 1] = '\0';
if(validate (resistor_value) == 0)
{
val_res[z-1] = atof(resistor_value);
}
}
}while(val_res[z-1] < 0);
}
}
the output should be like this:
How many resistors do you want to place in the circuit?
3
Please input the value of resistors:
Please input resistor #1:
abcd
Invalid resistance!
Re-input resistance #1:
5
Please input resistor #2:
6
...
etc
that does not happen on my code. please help thanks!
A:
Two changes in you code.
First One,
In loop , you have to mention the rescount not *val_res.
for(z = 1; z <= rescount; z++){
. . .
}
Then instead of do..while use while loop for checking the error.
while(val_res[z-1] <= 0){
printf("\tInvalid Resistance\n");
printf("\tRe-input Resistor #%d: \n", z);
if (fgets(resistor_value, sizeof(resistor_value), stdin) != NULL)
{
resistor_value[strlen (resistor_value) - 1] = '\0';
if(validate (resistor_value) == 0)
{
val_res[z-1] = atof(resistor_value);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Multithreading headache. Java. Return values
Hi guys I have the following.
class a extends Thread
{
public synchronized BigInteger getUniqueID()
{
BigInteger aUniqueID = new BigInteger(getUniqueKeyFromDatabase);
return aUniqueID;
}
}
class b extends a
{
public run()
{
BigInteger uniquieID = getUniqueID();
// store UniqueID in another database table with other stuff
}
}
And what I'm getting is duplicate unique id stored in the database table. I'm assuming because uniqieID is being changed in this multi threaded environment.
I'm obviously going horribly horribly wrong somewhere, I'm guessing I shouldn't be returning the value in this way. Or should be defining uniqueID as new BigInteger based on the response from the getUniqueID method.
Any help would be greatly appreciated, as my fragile mind has been warped right now!
Cheers
Alan
A:
BigInteger is an (from the JavaDocs)
Immutable arbitrary-precision integer
So that rules out anyone mutating the BigInteger object. I'd look into getUniqueKeyKeyFromDatabase
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue with apache/mod_php running rsync via exec()
I am having an issue with a php script running rsync on one of my servers, but only when run through apache/mod_php.
Here is a trimmed down version of the script:
<?php
exec("rsync -a /var/www/html/from/ /var/www/html/to");
?>
Pretty simple. The purpose of this command is to copy a folder structure (complete with appropriate permissions) to a new folder. But the issue is, this rsync command hangs and won't complete.
Doing a bit of investigating, I noticed that the script would spawn two rsync processes:
> ps aux | grep rsync
apache 20752 56.9 0.0 10400 656 ? R 11:29 1:37 rsync -a /var/www/html/from/ /var/www/html/to
apache 20753 0.0 0.0 10400 276 ? S 11:29 0:00 rsync -a /var/www/html/from/ /var/www/html/to
root 22305 0.0 0.0 61212 764 pts/1 S+ 11:32 0:00 grep rsync
I noticed that the first process was in the 'running' status. So I did an strace on it, but all I got for output was the following:
> strace -p 20752
<snip>
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
select(1037, [1026 1027 1028 1029], [], NULL, {60, 0}) = 4 (in [1026 1027 1028 1029], left {60, 0})
<snip>
Here is what I know so far:
The php script works fine when run from the cli. I enabled the ability to su apache and run the script > php myscript.php and it works fine. But running http://mydomain.com/myscript.php creates the 2 processes, with one of the first one in continual running state. This leads me to believe it's not a permission issue. As further proof, here is the ls -l output:
> ls -l /var/www | grep html
drwxr-xr-x 79 apache apacheftp 4096 Aug 17 12:07 html
> ls -l /var/www/html | grep from
drwxrwxr-x 2 apache apache 4096 Aug 22 11:27 from
So, apache has permission to write to the directory, and read from the from directory.
Running the same script on a different server of same specs works fine. The specs of both servers are:
Apache version: Apache/2.2.3
PHP version: 5.3.3
rsync version: 2.6.8 protocol version 29
OS: Red Hat Enterprise Linux Server release 5.6 (Tikanga)
What I don't know is why apache spawns two rsync processes (or why the first rsync spawns a second), and why the first rsync process seems to be stuck on select(1037...)
Can someone shed light on this?
A:
So after modifying my script to run strace directly through the exec() function like so:
/usr/bin/strace -fo /var/www/html/rsynce.log /usr/bin/rsync -a /var/www/html/from/ /var/www/html/to
and examining the difference in the file generated by running through a browser, and from the command line, I found this line (in the log generated from the browser-run script):
select(1034, [1026 1027 1028 1029], [], NULL, {60, 0}) = -1 EBADF (Bad file descriptor)
This got me researching file descriptors in apache. In my setup, I run many virtualhosts and each one was defining 3 unique logfiles. So while an apache process was using 1143 file descriptors (via lsof -p pid | wc -l ), only 124 of those were not logs.
I was able to remove the unique logfiles from the virtual host, restarted apache, and the script-run-through-the-browser worked fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
xlPasteAll is changing a fixed criteria
Using VBA, I've created a new column and populating it with VLOOKUP to a range in another worksheet.
H2 is a code, and 'Start!A2' is the code, and 'Start!B2' is the corresponding column/value I want.
Range("G2").Formula = "=VLOOKUP(H2,Start!A2:B9,2)"
Range("G2").Copy
Range("G2:G" & x).PasteSpecial (xlPasteAll)
My problem is that the range part of my formula adjusts along with the criteria.
I want the range (Start!A2:B9) to remain static when I paste the formula.
How do I do this?
Thanks.
A:
You can use $ in front of the row or column that should not change, and set all formulas at once:
Range("G2:G" & x).Formula = "=VLOOKUP(H2,Start!A$2:B$9,2)"
| {
"pile_set_name": "StackExchange"
} |
Q:
Searching for a value within an arbitrary range
I have a database where a user can search for addresses. However, some addresses in the databases are listed in a range. For example, 120-125 main st can be a record in the database. If the user searches for 123 Main St, is there a way to get the 120-125 record to show up? This needs to be rather dynamic to include all ranges so I'm not sure if the BETWEEN clause will work properly. Any ideas?
A:
Save yourself many, many headaches and make dedicated fields for this kind of data. You might even create a function that parses addresses and fills these fields with the help of a trigger (after insert, update):
create function rangeFrom( @address varchar(100) ) returns int as
begin
declare @pos int
set @address = replace(@address, ' ', '') + '.'
set @pos = patindex('%[0-9]%', @address)
if @pos > 0
begin
set @address = right(@address, len(@address) - @pos + 1)
set @pos = patindex('%[0-9][^0-9]%', @address)
return left(@address, @pos)
end
return null
end
-- ------------------------------------------------------------
create function rangeTo( @address varchar(100) ) returns int as
begin
declare @pos int
set @address = replace(@address, ' ', '') + '.'
set @pos = patindex('%[0-9]-[0-9]%', @address)
if @pos > 0
begin
set @address = right(@address, len(@address) - @pos - 1)
set @pos = patindex('%[0-9][^0-9]%', @address)
return left(@address, @pos)
end
return null
end
Later, you can call them (e.g. in your trigger):
select dbo.rangeFrom('120-125 main st') -- returns 120
select dbo.rangeTo('120-125 main st') -- returns 125
This way you have actual fields that you can use with the BETWEEN operator.
| {
"pile_set_name": "StackExchange"
} |
Q:
iPhone development with an Intel GMA 950
I am thinking about purchasing a used MacBook with an Intel GMA 950 graphics card for iPhone application development.
Will this card present any problems?
So far I have only been able to find this thread: http://forum.unity3d.com/viewtopic.php?t=17454 but I don't have enough experience to understand what they are talking about.
Any help would be appreciated!
A:
From the thread you posted.
A MacMini will serve you very well for iPhone development with the one exception that it cannot compute occlusion culling information. AFAIK that fact will not change in any coming updates/releases on our end.
Occlusion culling is when an object is behind other opaque objects, then it may be culled.
From Wikipedia:
This is a very popular mechanism to speed up the rendering of large scenes that have a moderate to high depth complexity
More detail on Occlusion Culling.
| {
"pile_set_name": "StackExchange"
} |
Q:
visual basic for applications classes Compile error: Expected: end of Statement
I am trying to rewrite some C++ into an excel macro, but can't seem to even get line 1 of any tutorial on classes in VBA to work.
I have tried the following:
Public Class gamepath
End Class
Sub Whatever()
End Sub
Then, when I run the Whatever() Macro I expect it to compile but I get the error:
Compile error:
Expected: end of Statement
And it highlights the word gamepath
I am not skilled enough in VB to know why this error occurs, and the error is too vague for my searches to pull up anything I can use. Can anyone tell me why this won't compile?
A:
the code you're using looks like it's vb.net, not VBA. The syntax is similar, but not the same. In VBA, you don't script a class, you insert a special type of code module that contains the class's code. Sub Whatever resides in that.
Insert a class module, name it "GameClass" (classes are typically proper-cased, not lower-cased). Add your methods and any properties (here is a good overview of property getters/setters) in that module:
Then you can instantiate your GameClass and call its methods from elsewhere:
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I develop Java servlet using eclipse ADT
I am currently using the Android developer Tools platform to develop android code, downloaded from http://developer.android.com/sdk/index.html. Now i want to develop Java servlets as well for my server side app and generate the WAR file. As i understand it, I can't use the ADT to develop servlets. Since i think it is basically an Eclipse IDE with the ADT plugin, can i simply install another plugin so that it supports servlet development? If yes, how do i do that exactly? Or do i need to install another eclipse? I am a complete newbie to Eclipse and Java, so please bear with me.
A:
Install the Web Tools Platform. Be sure to find out which version of the Eclipse Platform you're already using first. http://wiki.eclipse.org/WTP_FAQ#How_do_I_install_WTP.3F
| {
"pile_set_name": "StackExchange"
} |
Q:
Limit the multiplied amount result to 2 decimals
I made a simple javascript that multiplies an amount and shows the result. However, I want to limit the result to 2 decimals. I've tried using toFixed, but that doesn't seem to work.
Does anyone know how to make this work?
function MultiplyTheAmount() {
var multiplier = 0.75;
var roundedMultiplier = multiplier.toFixed(2);
document.getElementById('multiplyResult').innerHTML = document.getElementById('multiplyAmount').innerHTML * roundedMultiplier;
};
MultiplyTheAmount();
<ul style="list-style:none;">
<li>Amount:</li>
<li id="multiplyAmount">119.99</li>
<li><br/></li>
<li>Multiply by:</li>
<li>0.75</li>
<li><br/></li>
<li>Result:</li>
<li id="multiplyResult"></li>
</ul>
A:
Apply the toFixed method to the end result to eliminate the magnified floating point inaccuracy you are seeing:
function MultiplyTheAmount() {
var multiplier = 0.75;
var roundedMultiplier = multiplier.toFixed(2);
document.getElementById('multiplyResult').textContent = (
+document.getElementById('multiplyAmount').textContent * roundedMultiplier
).toFixed(2);
};
MultiplyTheAmount();
<ul style="list-style:none;">
<li>Amount:</li>
<li id="multiplyAmount">119.99</li>
<li><br/></li>
<li>Multiply by:</li>
<li>0.75</li>
<li><br/></li>
<li>Result:</li>
<li id="multiplyResult"></li>
</ul>
Not related to the question, but I would suggesting the use of textContent instead of innerHTML when not dealing with HTML content.
| {
"pile_set_name": "StackExchange"
} |
Q:
VB.NET: How can you activate the childform when only the control inside is clicked?
*edit: OK, so this is my real problem, below scenario happens only when the form is MDIChild.. thanks for anyone that could provide me with the code
I have a form with labels, panels, buttons etc. Where I'm having problem is, while form2 is my active window/form and I clicked on a control inside form1, the form1 does not activate itself. What I would like to happen is for form1 to activate even when it's not the form I clicked, only the control inside it (any control)..
I'm thinking that if I clicked a control on the form, there's an event fired on the form. If I could only know of that certain event, that would help - maybe (coz I could just add Me.activate on that event if it exists). I've tried searching for series of events when a control (ex. label) is clicked but to no avail. I hope that someone could help me with this one.
Thanks in advance.
*edit
i will just try to make my question more understandable..
How can I activate the form when only the control is clicked (say, label or textbox)? My forms does not activate or focused when I click inside it except the form itself..
I can do this on one control..
Private Sub Label1_Click - Handles Label1.Click
Me.Activate()
End Sub
But what if I have 20 controls (labels, buttons, textbox, combobox, etc)? See? =)
A:
In non-MDI forms, the form is automatically activated when you click any control inside it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Determining The Polarity of a FeedBack Circuit
In determining the polarity of such a circuit I used the following reasoning:
if Vin goes up ID1 goes up and ID2 goes down, ID4 goes down and VG3,VG4 go up because of PMOS, then Vout goes down, if Vout goes down then Vin will go up. So I ended up with positive feedback. Am I making a mistake? Sometimes when I try to understand a current source's relationship with its nodes polarities I get confused. Could you explain this point too?
A:
You are correct, the feedback is positive. To check whether a feedback is negative or positive just imagine breaking the loop at a certain point and applying some disturbance on the node. If the returned disturbance is of the same polarity as the applied one then it is positive otherwise it is a negative feedback.
So for the circuit you showed if, for instance, we break the loop at \$V_{out}\$ and imagine the gate potential of M2 going up by a small amount. This would increase its gate source potential and \$I_{dM2}\$ increases. Since more current now flows into ground, the drain potential of M2 will go down. This would reduce the gate potential of M3 causing \$I_{dM3}\$ to go up. Since there is more current through the resistor \$V_{out}\$ goes up (same way as the applied disturbance). So we see that the feedback tries to amplify any disturbance in the circuit so it is positive feedback.
An easier way to do the same thing is to notice that while traversing the loop we move from gate of M2 to its drain, kind of like a common source, which is an inverting stage. From drain of M2 we move to drain of M3 which is again an inverting stage. Since we go through even number of inversions, the output disturbance will be in phase with the applied disturbance and feedback will be positive.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sliding effect menu with JComponents
I'm trying to make some sliding effect with JLabels and timers.
I'd like to use only two timers (IN and OUT) to manage the effect for multiple components.
The problem is that everything works fine only if I don't move quickly from one JLabel to another and I don't know how to manage the thing.
Gif showing the problem
Here is my code:
public class Sliders extends JFrame {
private JPanel contentPane;
JLabel label,label_1;
static RainDrop frame;
javax.swing.Timer in,out;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new RainDrop();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sliders() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
label = new JLabel("");
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent a1) {
setIN(2,0,label);
System.out.println("ENTRATO");
checkloop_out_mag(-270,label);
}
@Override
public void mouseExited(MouseEvent a2) {
in.stop();
setOUT(-2,0,label);
System.out.println("USCITO");
}
});
label.setBackground(Color.ORANGE);
label.setOpaque(true);
label.setBounds(-270, 0, 337, 44);
contentPane.add(label);
label_1 = new JLabel("");
label_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent b1) {
setIN(2,44,label_1);
System.out.println("ENTRATO");
checkloop_out_mag(-270,label_1);
}
@Override
public void mouseExited(MouseEvent b2) {
in.stop();
setOUT(-2,44,label_1);
System.out.println("USCITO");
}
});
label_1.setOpaque(true);
label_1.setBackground(Color.GREEN);
label_1.setBounds(-270, 44, 337, 44);
contentPane.add(label_1);
}
public void setIN(int x,int y,JLabel label) {
in = new javax.swing.Timer(2, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getBounds().x+x,y);
System.out.println("SPOSTO");
System.out.println("CONTROLLO");
checkloop_in_magequals(0,label);
}
});
in.setRepeats(true);
in.start();
}
public void setOUT(int x,int y,JLabel label) {
out = new javax.swing.Timer(2, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getBounds().x+x,y);
System.out.println("SPOSTO");
System.out.println("CONTROLLO");
checkloop_out_equals(-270,label);
}
});
out.setRepeats(true);
out.start();
}
public void checkloop_out_equals(int z,JLabel label) {
if (label.getBounds().x==z){
out.stop();
System.out.println("STOP");
}
}
public void checkloop_out_mag(int z,JLabel label) {
if (label.getBounds().x>z){
out.stop();
System.out.println("STOP");
}
}
public void checkloop_in_magequals(int z,JLabel label) {
if (label.getBounds().x>=z){
in.stop();
System.out.println("STOP");
}
}
}
Is there a way to fix the code using only two timers? Or do I need two timers for each JComponent?
A:
First of all, go use a animation framework, like Trident or The Timing Framework or The Universal Tween Engine, they provide an awesome amount of functionality which would otherwise take an awful lot of coding to accomplish.
Animation is a complex subject, so I'm only going to cover some primary basics. Animation is the illusion of change over time (told you it was going to be basic).
The crust of your you problem comes down to two basic things:
You need a central "clock" which can provide "ticks" and (a relative) regular interval
A API which agnostic enough, decoupled enough, that it doesn't care "what" it's animating, only that, given a duration and range, it can calculate the required properties on each "tick"
One important concept to get your head around is, animation should played over a period of time, not between values. The main reason for this is flexibility. It's much easier to change the duration of the animation in order to change the speed and it allows the system to "drop" frames relatively simply. Remember when I said "Animation is the illusion of change over time" - this is what I'm talking about.
Simple ...
Let's start with some basics...
public class Range<T> {
private T from;
private T to;
public Range(T from, T to) {
this.from = from;
this.to = to;
}
public T getFrom() {
return from;
}
public T getTo() {
return to;
}
@Override
public String toString() {
return "From " + getFrom() + " to " + getTo();
}
}
Range describes something which can be measured in terms of a "start" (from) value and a "target" (to) value. This allows use to supply a number of important values, but most notably, the "range" of the animation we want to execute.
In the past I've used such a concept for all sorts of values, including Point, Rectangle and even Color
public interface AnimationPropertiesListener<T> {
public void stateChanged(AnimationProperties<T> animator);
}
public interface AnimationProperties<T> {
public Range<T> getRange();
public T getValue();
public boolean tick();
public void setDuration(Duration duration);
public Duration getDuration();
}
public abstract class AbstractAnimationProperties<T> implements AnimationProperties<T> {
private Range<T> range;
private LocalDateTime startTime;
private Duration duration = Duration.ofSeconds(5);
private T value;
private AnimationPropertiesListener<T> listener;
public AbstractAnimationProperties(Range<T> range, AnimationPropertiesListener<T> listener) {
this.range = range;
this.value = range.getFrom();
this.listener = listener;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Duration getDuration() {
return duration;
}
public Range<T> getRange() {
return range;
}
@Override
public T getValue() {
return value;
}
@Override
public boolean tick() {
if (startTime == null) {
startTime = LocalDateTime.now();
}
Duration duration = getDuration();
Duration runningTime = Duration.between(startTime, LocalDateTime.now());
Duration timeRemaining = duration.minus(runningTime);
if (timeRemaining.isNegative()) {
runningTime = duration;
}
double progress = (runningTime.toMillis() / (double) duration.toMillis());
value = calculateValue(progress);
listener.stateChanged(this);
return progress >= 1.0;
}
public abstract T calculateValue(double progress);
}
The "animation properties" is the underlying power of what we are trying to achieve. It's responsible for calculate the amount of time the animation wants to run for, the amount of time the animation has been running and provides a means to calculate the resulting value for the specified animation Range value. (note the calculateValue could be a property of the Range, but I just left it where it was)
Okay, that's all fine and good, but we actually need a central clock to provide all the ticks and notify the properties
public enum Animator {
INSTANCE;
private Timer timer;
private List<AnimationProperties> properies;
private Animator() {
properies = new ArrayList<>(5);
timer = new Timer(5, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Iterator<AnimationProperties> it = properies.iterator();
while (it.hasNext()) {
AnimationProperties ap = it.next();
if (ap.tick()) {
it.remove();
}
}
if (properies.isEmpty()) {
timer.stop();
}
}
});
}
public void add(AnimationProperties ap) {
properies.add(ap);
timer.start();
}
public void remove(AnimationProperties ap) {
properies.remove(ap);
if (properies.isEmpty()) {
timer.stop();
}
}
}
Okay, so this is a really simple implementation. It is just a Swing Timer which runs really fast. When there AnimationProperties available, it continues looping until all the AnimationProperties tick method return true (completed) at which time it stops (so it's not doing unless things in the background)
Okay, but how does this all help us?
Well, basically, all we want to do is calculate the new width of the component from a given value to a given value over a period of time. Since width is defined as a int, we can create a series of concrete classes based on the above abstract/generic class, for example...
public class IntRange extends Range<Integer> {
public IntRange(Integer from, Integer to) {
super(from, to);
}
public Integer getDistance() {
return getTo() - getFrom();
}
}
public class IntAnimationProperties extends AbstractAnimationProperties<Integer> {
public IntAnimationProperties(IntRange animationRange, IntRange maxRange, Duration duration, AnimationPropertiesListener<Integer> listener) {
super(animationRange, listener);
int maxDistance = maxRange.getDistance();
int aniDistance = animationRange.getDistance();
double progress = Math.min(100, Math.max(0, Math.abs(aniDistance/ (double)maxDistance)));
Duration remainingDuration = Duration.ofMillis((long)(duration.toMillis() * progress));
setDuration(remainingDuration);
}
@Override
public Integer calculateValue(double progress) {
IntRange range = (IntRange)getRange();
int distance = range.getDistance();
int value = (int) Math.round((double) distance * progress);
value += range.getFrom();
return value;
}
}
What's really important to note here is, the IntAnimationProperties also requires a "max range" value. This is the total available range that the animation would ever be expected to run over. This is used to calculate the current "progress" value that the "animation range" is at.
Consider what would happen if the one panel was half expanded when the user exited it? Normally it would have to use the whole duration to animate back that half range.
Instead, this implementation calculates the "remaining" duration required to move to the desired point, in the example above, that's half the normal duration.
Example...
So, based on the above, we could end up with something like...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(null);
Slider slider1 = new Slider();
slider1.setBackground(Color.BLUE);
slider1.setLocation(0, 44);
add(slider1);
Slider slider2 = new Slider();
slider2.setBackground(Color.MAGENTA);
slider2.setLocation(0, 88);
add(slider2);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class Slider extends JPanel {
private AnimationProperties<Integer> ap;
private IntRange maxRange = new IntRange(44, 150);
private Duration duration = Duration.ofSeconds(5);
public Slider() {
setSize(44, 44);
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
animateTo(150);
}
@Override
public void mouseExited(MouseEvent e) {
animateTo(44);
}
public void animateTo(int to) {
if (ap != null) {
Animator.INSTANCE.remove(ap);
}
IntRange animationRange = new IntRange(getWidth(), to);
ap = new IntAnimationProperties(animationRange, maxRange, duration, new AnimationPropertiesListener<Integer>() {
@Override
public void stateChanged(AnimationProperties<Integer> animator) {
setSize(animator.getValue(), 44);
repaint();
}
});
Animator.INSTANCE.add(ap);
}
});
}
}
public enum Animator {
INSTANCE;
private Timer timer;
private List<AnimationProperties> properies;
private Animator() {
properies = new ArrayList<>(5);
timer = new Timer(5, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Iterator<AnimationProperties> it = properies.iterator();
while (it.hasNext()) {
AnimationProperties ap = it.next();
if (ap.tick()) {
it.remove();
}
}
if (properies.isEmpty()) {
timer.stop();
}
}
});
}
public void add(AnimationProperties ap) {
properies.add(ap);
timer.start();
}
public void remove(AnimationProperties ap) {
properies.remove(ap);
if (properies.isEmpty()) {
timer.stop();
}
}
}
public interface AnimationProperties<T> {
public Range<T> getRange();
public T getValue();
public boolean tick();
public void setDuration(Duration duration);
public Duration getDuration();
}
public interface AnimationPropertiesListener<T> {
public void stateChanged(AnimationProperties<T> animator);
}
public class Range<T> {
private T from;
private T to;
public Range(T from, T to) {
this.from = from;
this.to = to;
}
public T getFrom() {
return from;
}
public T getTo() {
return to;
}
@Override
public String toString() {
return "From " + getFrom() + " to " + getTo();
}
}
public abstract class AbstractAnimationProperties<T> implements AnimationProperties<T> {
private Range<T> range;
private LocalDateTime startTime;
private Duration duration = Duration.ofSeconds(5);
private T value;
private AnimationPropertiesListener<T> listener;
public AbstractAnimationProperties(Range<T> range, AnimationPropertiesListener<T> listener) {
this.range = range;
this.value = range.getFrom();
this.listener = listener;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Duration getDuration() {
return duration;
}
public Range<T> getRange() {
return range;
}
@Override
public T getValue() {
return value;
}
@Override
public boolean tick() {
if (startTime == null) {
startTime = LocalDateTime.now();
}
Duration duration = getDuration();
Duration runningTime = Duration.between(startTime, LocalDateTime.now());
Duration timeRemaining = duration.minus(runningTime);
if (timeRemaining.isNegative()) {
runningTime = duration;
}
double progress = (runningTime.toMillis() / (double) duration.toMillis());
value = calculateValue(progress);
listener.stateChanged(this);
return progress >= 1.0;
}
public abstract T calculateValue(double progress);
}
public class IntRange extends Range<Integer> {
public IntRange(Integer from, Integer to) {
super(from, to);
}
public Integer getDistance() {
return getTo() - getFrom();
}
}
public class IntAnimationProperties extends AbstractAnimationProperties<Integer> {
public IntAnimationProperties(IntRange animationRange, IntRange maxRange, Duration duration, AnimationPropertiesListener<Integer> listener) {
super(animationRange, listener);
int maxDistance = maxRange.getDistance();
int aniDistance = animationRange.getDistance();
double progress = Math.min(100, Math.max(0, Math.abs(aniDistance/ (double)maxDistance)));
Duration remainingDuration = Duration.ofMillis((long)(duration.toMillis() * progress));
setDuration(remainingDuration);
}
@Override
public Integer calculateValue(double progress) {
IntRange range = (IntRange)getRange();
int distance = range.getDistance();
int value = (int) Math.round((double) distance * progress);
value += range.getFrom();
return value;
}
}
}
But that's really slow ☹️
Okay, two places you change the duration. AbstractAnimationProperties has a default Duration of 5 seconds and Slider has a default Duration of 5 seconds. In your case, changing the Sliders Duration is probably where you want to start
Oh, wait, you want "easement" (slow in/slow out) to? Well, go have a look at How can I implement easing functions with a thread and then go have a look at the animation frameworks I linked earlier, because they already do this
Now if you're really intent on doing this by hand - you could have a look at this gist which is a "time line" based implementation which supports easement
| {
"pile_set_name": "StackExchange"
} |
Q:
meaning of parameter $1 in sql Function
absoulte rookie question. In a course we use Postgressql functions, eg.:
CREATE FUNCTION Raptor_lastSurveyDate1(bigint) RETURNS date As $$
SELECT max(date) FROM raptor_surveys WHERE nest=$1;
$$ LANGUAGE SQL
or:
CREATE FUNCTION Raptor_lastSurveyDate2(bigint) RETURNS date As $$
SELECT date FROM raptor_surveys WHERE nest=$1 ORDER BY date DESC LIMIT 1;
$$ LANGUAGE SQL
what does this $1 parameter mean??
addendum:
select * from raptor_surveys delivers this table:
A:
$1 references the first parameter passed to the function, $2 would refer to the second and so on.
The use of $1 as a parameter "name" predates the introduction of named parameters for SQL functions in Postgres 9.2
With any modern Postgres version, I would rewrite that to use a named parameter:
CREATE FUNCTION Raptor_lastSurveyDate1(p_some_value bigint)
RETURNS date
As $$
SELECT max(date)
FROM raptor_surveys
WHERE nest = p_some_value;
$$ LANGUAGE SQL
A:
$1 is a reference to the first argument of the function. Your functions both have a single argument of type bigint. Inside the function body, this argument can be referenced by $1.
See the documentation for more details: https://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-FUNCTION-ARGUMENTS
| {
"pile_set_name": "StackExchange"
} |
Q:
Use jQuery to construct "Tweet" button
I know how to use the "Tweet" button and to put default text into it but has anyone got anyideas how to do something like this: I have a div on my website in which i load dynamic movie quotes into, so i'd like a tweet button underneath which would tweet "(The current movie quote) and i found it here (my site URL)". Is this going to be possible or not? Could i use jQuery or have to use PHP?
A:
I would use jQuery to find the text within the movie quote div. Then construct the URL with that text before you either open a new window or change the current browser window to go to that Twitter URL.
I think the URL format to pre-fill the tweet is: http://twitter.com/home?status=here+is+my+tweet
| {
"pile_set_name": "StackExchange"
} |
Q:
primary datasource is not fetching data from jpaRepository in the spring boot
https://github.com/vikramsinghsengar007/SpringbootMultiDataSource
please check the above project as I am not getting any error for the primary dataSource but it's not fetching the records from the db. I have checked the log and getting proper sql.
Hibernate:
select product0_.id as id1_1_, product0_.brand as brand2_1_, product0_.madein as madein3_1_, product0_.name as name4_1_, product0_.price as price5_1_
from Product product0_
But the same configuration is working for the secondary DataSource.
A:
This issue got fixed. Actually, I forgot to use proper naming conventions.The problem was spring was overriding the primary datasource with the secondary as all the configurations was in the same package. And the second problem was I was providing wrong persistenceUnit while creating entitymanagefactory. It should be same as Mysql database.
Hope this will help someone.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proper use of Beans in Java MVC
I'm trying to make a deliberate effort to write code that follows proper convention, even when it might add complexity, and so far I've succeeded but I'm noticing a trend in my programs.
My project is small, a javaee webapp with only a handful of servlets, follows MVC design, and makes use of beans as the model. My problem is that my beans are more often just 'a place to stick something so I can get a decent view coded'. I got the impression that beans were of course just containers for data, but also meant to have some portability and usefulness beyond a single servlet.
Is my problem just the result of relatively simple code or am I likely misusing the concept of a bean ?
A:
Beans are supposed for data storage. We are talking about Pojo Beans. If collections are not enough to handle data model the app works with, class is created that fits the needs. BEAN should be considered just an object for temporary state preservation having setters and getters that might have light additional functionality.
There is nothing wrong when your application operates with a lot of beans, if you adhere to paradigms like inheritance and polymorphism.
Pojo Beans also captures data model (domain model) of your application if it runs on a database ... database tables and beans corresponds to each other. That's how ORM works (persisting the state of a bean in time and the other way around). Even without ORM, Domain Access Objects layer operates well on a domain model compound of many beans.
They are also the best way for view presentation. Mixing them with collections. Implementing comparators.
The term "bean" started to be used in Spring framework for instance, where it is just a class that is part of application context / Spring container not a getter/setter JavaBean at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery .html() does not copy contents of textareas or inputs
I'm trying to copy the contents of an element using elem.html() but it's not including the contents of inputs or textareas.
Here's an example (try writting in the boxes then click "Copy"): http://jsfiddle.net/gAMmr/2/
Is there a way of copying all info?
These are the approaches I have tried so far:
elem.clone() - not suitable for my task because it copies the
element itself
elem.children().clone() - misses out text nodes
elem.contents().clone() - doesn't include the textarea contents
EDIT: The results seem to be different in each browser. I'm using Chrome.
A:
$("button").click(function () {
$("#2").html($("#1").html());
$("#1").find("input").each(function(idx) {
$("#2").find("input").eq(idx).val($(this).val());
});
$("#1").find("textarea").each(function(idx) {
$("#2").find("textarea").eq(idx).val($(this).val());
});
});
http://jsfiddle.net/gAMmr/5/
A:
As Šime Vidas pointed out earlier, this is a 4-year old bug which hasn't been corrected, though a fix exists which is quite simple to apply:
-Download jquery.fix.clone.js
-Include it in your page: <script src='path/to/jquery.fix.clone.js'></script>
From then on cloned textarea elements should include the text of their source (note: you need to use the .clone() method to create your new textarea, not .html()).
| {
"pile_set_name": "StackExchange"
} |
Q:
word-break within words
I have this html
<div class="externalWidth">
<div class="container">
<div class="element">this_is_a_really_long_text_without_spaces</div>
<div class="element noWrap">:-)</div>
</div>
</div>
<div class="externalWidth">
<div class="container">
<div class="element ">this is a really long text without spaces</div>
<div class="element noWrap">:-)</div>
</div>
</div>
and this css
.externalWidth { width: 200px; }
.container { margin-bottom:10px; display:inline-table; height:40px; width:100%; }
.element { display:table-cell; }
.noWrap { white-space:nowrap; }
I have made an jsfiddle to demonstrate it. The texts in both .elements are read from a server and bound via knockout. I want this to look as follows:
the second .element should have as much space as it needs
the first .elementshould have the remaining space. It should break into multiple lines if possible.
Everything works fine but long words causes the whole table to expand. Is it possible to break within words if necessary?
I've also tried table-layout:fixed; but that made two 100px colums.
Edit: Thanks. word-break: break-all; did exactly what I needed.
A:
Use CSS word-break Property
try this DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Constructor Implementation Error
C++ Constructor Implementation Error
I have 2 class
Map2D(parent) & Map3D(child)
So this is what happen...
class Map3D : public Map2D
{
private:
int z;
public:
Map3D();
Map3D(int,int,int);
int getZ();
}
And below is my Map2D
class Map2D
{
friend ifstream& operator>>(ifstream&, Map2D&);
protected:
int x;
int y;
public:
Map2D();
Map2D(int,int);
};
Map2D::Map2D()
{
x=0;
y=0;
}
Map2D::Map2D(int xIn,int yIn)
{
x = xIn;
y = yIn;
}
The problem now is i try to implement Map3D but got issue.. which what i try is below
Back on Map3D.cpp
Map3D::Map3D()
{
x=0;
y=0;
z=0;
}
Map3D::Map3D(int xIn,int yIn,int zIn)
{
x=xIn;
y=yIn;
z=zIn;
}
map3d.cpp:18:1: error: extra qualification ‘map3D::’ on member ‘map3D’ [-fpermissive]
map3d.cpp:18:1: error: ‘map3D::map3D()’ cannot be overloaded
map3d.cpp:14:1: error: with ‘map3D::map3D()’
map3d.cpp:25:1: error: extra qualification ‘map3D::’ on member ‘map3D’ [-fpermissive]
map3d.cpp:25:1: error: ‘map3D::map3D(int, int, int)’ cannot be overloaded
map3d.cpp:15:1: error: with ‘map3D::map3D(int, int, int)’
What should i change to make my implementation correct. Thanks for all help.
A:
Looks like a missing semi-colon at the end of the Map3D declaration
class Map3D : public Map2D
{
private:
int z;
public:
Map3D();
Map3D(int,int,int);
int getZ();
}; // SEMI-COLON HERE!!!!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to limit user text input and disable send button in JSQMessagesViewController
I am building a messaging app using JSQMessagesViewController and I was wondering if there would be a way for me to require a user's text input to be between 10 and 140 characters in length.
I have put this following piece of code
if (text.characters.count <= 10 || text.characters.count >= 140) {
self.inputToolbar.sendButtonOnRight = false
}
else {
self.inputToolbar.sendButtonOnRight = true
}
in several key spots such as the function didPressSendButton:
override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!,
senderDisplayName: String!, date: NSDate!) {
let itemRef = messageRef.childByAutoId() // 1
let messageItem = [ // 2
"text": text,
"senderId": senderId,
"location": getLocation()
]
itemRef.setValue(messageItem) // 3
// 4
JSQSystemSoundPlayer.jsq_playMessageSentSound()
// 5
finishSendingMessage()
Answers.logCustomEventWithName("Message sent", customAttributes: nil)
}
and my addMessages function:
func addMessage(id: String, text: String, displayName: String) {
let message = JSQMessage(senderId: id, displayName: displayName, text: text)
messages.append(message)
}
like such:
func addMessage(id: String, text: String, displayName: String) {
if (text.characters.count <= 10 || text.characters.count >= 140) {
self.inputToolbar.sendButtonOnRight = false
}
else {
self.inputToolbar.sendButtonOnRight = true
let message = JSQMessage(senderId: id, displayName: displayName, text: text)
messages.append(message)
}
}
However that does not work.
What kind of works for me is doing this in my addMessages function:
if (text.characters.count <= 10 || text.characters.count >= 140) {
// pass
}
else {
let message = JSQMessage(senderId: id, displayName: displayName, text: text)
messages.append(message)
}
In this case, the character filter works but the send button is still enabled, so the data is sent to my database, which I do not want. It would work a lot better for me if the send button was just disabled entirely if the text input is not long enough or too long.
If anybody would be able to help me with this, that would be great. Thanks!
A:
You should not remove the button from the bar but instead just disable it. I would first suggest setting a disabled state for the button with something like this.
let sendButton = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 35)) //You can change these values to fit your needs
sendButton.setTitle("Send", forState: .Normal)
sendButton.setTitleColor(UIColor.grayColor(), forState: .Disabled)
sendButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
sendButton.contentMode = .Center
self.inputToolbar?.contentView?.rightBarButtonItem = sendButton
Then you want to set the userInteractionEnabled property on that button based on the length of the string in the input field. We can accomplish this by setting an observer on that.
First get a reference to the inputField.
let inputField = self.inputToolbar.contentView.inputView
Then set up a observer on that field and change the sendButtons state.
NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: inputField, queue: NSOperationQueue.mainQueue()) { (notification) in
let text = self.inputField.text
You do not need parentheses () around if statements.
Also I would swap your logic around
if text.characters.count >= 10 && text.characters.count <= 140 {
if text == self.verifyPasswordField.text {
self.sendButton.enabled = true
} else {
self.sendButton.enabled = false
}
}
if you want to be a swift ninja you can do shorthand for this with.
self.sendButton.enabled = (text.characters.count >= 10 && text.characters.count <= 140)
just throw that in a function and make sure you call it and you should be good to go. The Button should update its color if the input text does not meet the criteria. But you also may want to tell your users that, that is the reason the button is disabled but that is just my opinion. I hope this helped let me know if you have any more questions.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to bulk-amend the job step command in ALL sql server agent jobs
I have many jobs that have a step to send 1 specific email out to a list of people. That list of reciepients is hardcoded in the step command and I need to remove one person from that list, in all jobs.
How do I loop through ALL the jobs in the Sql Server Agent and modify the command text to find+replace a specific piece of text.
I am using sql server 2005 and have already looked at sp_update_jobStep but doesn't appear to be exactly what i want.
Cheers.
A:
You could try to update the System tables that hold the information on jobs of the SQL server directly. The relevant ones for you would be:
msdb.dbo.SysJobs
msdb.dbo.SysJobSteps
If you have a specific email address to remove, you could update the Command field in the SysJobSteps table with a single UPDATE statement.
UPDATE SJS SET
Command = REPLACE(Command, 'EmailAddress&TestDomain.Com', '')
FROM msdb.dbo.SysJobs SJ
INNER JOIN msdb.dbo.SysJobSteps SJS
ON SJS.Job_Id = SJ.Job_Id
WHERE SJ.Originating_server = ..... -- Your server here
AND SJS.Command LIKE '%[email protected]%'
It would be advisable to run the above query as a SELECT statement first, to test it returns only the job steps your are expecting to update.
| {
"pile_set_name": "StackExchange"
} |
Q:
Casting struct to int in c++
I have a structure to represent the 29 bit CAN identifier with bit fields as following.
struct canId
{
u8 priority :3;
u8 reserved :1;
u8 dataPage :1;
u8 pduFormat :8;
u8 pduSpecific :8;
u8 sourceAddress :8;
} iD;
in my code I want to copy this structure to an integer variable. Something like:
int newId = iD;
However I am not sure if this is correct. Can somebody comment on it?
Edit: I can do this using shift operator on each field and then with bitwise OR to have them in the right place. But that makes the use of structure with bit fields useless in the first place.
A:
The safest way I can imagine is doing it manually:
int canIdToInt(canId id) {
int temp = 0;
int offset = 0;
temp |= id.sourceAddress << offset; offset += 8;
temp |= id.pduSpecific << offset; offset += 8;
temp |= id.pduFormat << offset; offset += 8;
temp |= id.dataPage << offset; offset += 1;
temp |= id.reserved << offset; offset += 1;
temp |= id.priority << offset; // offset += 3; redundant
return temp;
}
Of course you could hide the whole offset thing behind a macro to make it a bit cleaner.
#define START_WRITE int temp=0,offset=0
#define RESULT temp
#define ADD_VALUE(X) temp |= X << offset; offset += sizeof(X)
Actually, sizeof won't behave as expected here, but there's another macro that will.
A:
For a truly portable solution, you shouldn't be using a struct of bitfields at all, as the field layout is undefined. Instead, use an integer and explicit bitwise arithmetic.
But for a more relaxed solution, a uniont of an int with the bitfield struct is good enough.
To combine safety and convenience, you can also consider integrating a test function that toggles the fields one at a time and checks the match with the desired integers.
union
{
uint32_t packed;
struct canId
{
u8 priority :3;
u8 reserved :1;
u8 dataPage :1;
u8 pduFormat :8;
u8 pduSpecific :8;
u8 sourceAddress :8;
} split;
} iD;
iD.packed= 0; iD.split.priority= 7; if (iD.packed != 0x7) ...
| {
"pile_set_name": "StackExchange"
} |
Q:
content at after youtube iframe not shown
I want to show youtube video in html. For that i am using iframe. But the content at after iframe is not showing.
this is my html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<p>Content of the document......</p>
<h3>1 Microsoft And Google Collaborate On Angular 2 Framework, TypeScript Language</h3><div><p><span class="embed-youtube"><iframe class="youtube-player" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/videoseries?list=PLOETEcp3DkCoNnlhE-7fovYvqwVPrRiY7&hl=en_US" frameborder="0" allowfullscreen="true"/></span></p></div>
<p>END END</p>
</body>
</html>
In this code "END END" not showing at after the youtube iframe
A:
You need to close the iframe tag properly. Currently you close it
inline, but this is not the correct way. Do:
<iframe ..></iframe>
| {
"pile_set_name": "StackExchange"
} |
Q:
Type hinting in PHP constructors?
Is there anything to stop me from type hinting like this within the __construct() parentheses?
<?php
class SomeClass extends BaseClass {
public function __construct(array $someArray) {
parent::__construct($someArray);
}
Or can I only do it like this?
<?php
class SomeClass extends BaseClass {
public function __construct($someArray = array()) {
parent::__construct($someArray);
}
Edit:
This is what works: (Thanks @hakra and @Leigh)
<?php
class SomeClass extends BaseClass {
public function __construct( array $someArray = NULL ) {
parent::__construct( (array) $someArray);
}
To me it looks nice and clean and I know exactly what it supposed to mean.
A:
This is type hinting with no default, stating that a parameter must be given, and it's type must be an array
public function __construct(array $someArray) {
This is providing the default value for the argument if no parameter is passed, without a typehint.
public function __construct($someArray = array()) {
They are two different things.
In the second instance you can call the function with no parameters and it will work, but the first will not.
If you want, you can combine the two, to specify an default and specify the required type.
public function __construct(array $someArray = array()) {
Or as @hakre has stated, you can do:
public function __construct(array $someArray = NULL) {
A:
You can do so:
public function __construct(array $someArray = NULL)
{
$someArray = (array) $someArray;
parent::__construct($someArray);
...
The case here is to make use of the = NULL exception of the rule. The next line:
$someArray = (array) $someArray;
is just some shorthand to convert NULL into an empty array and otherwise leave the array an array as-is (a so called castDocs to array):
Converting NULL to an array results in an empty array.
(from: Converting to arrayDocs)
Sure you could write it even shorter:
public function __construct(array $someArray = NULL)
{
parent::__construct((array) $someArray);
}
but it does not explain it that well.
| {
"pile_set_name": "StackExchange"
} |
Q:
discord.js - bot timing out
I recently created a discord.js bot with node.js. However, I can't start my bot, because its timing out.
Error: Something took too long to do.
at timeout.client.setTimeout (C:\Users\User\Desktop\tntbot\node_modules\discord.js\src\client\ClientManager.js:40:57)
at Timeout.setTimeout (C:\Users\User\Desktop\tntbot\node_modules\discord.js\src\client\Client.js:422:7)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
That's what I get on every start.
I checked the code, it has no problem.
Please help.
A:
Okay, I found the problem.
For some strange reasons, Discord generated a new token, and I used the old one.
Sorry for the misunderstanding.
Have a great day!
| {
"pile_set_name": "StackExchange"
} |
Q:
Typescript - Code fails to build from error TS1128: Declaration or Statement expected, but runs as expected when I serve the code
I am developing an Angular2 project, and I created a class that serves as my main Component class:
import { Component, OnInit} from '@angular/core';
import { submitService } from './Common-functions/submit.service';
@Component({
selector: 'my-app',
template: `htmlCode`
})
export class AppComponent implements OnInit{
hideTable = true;
lengthOfRecords = 0;
lowerLimit = 0;
upperLimit = 5;
prevButtonDisabled = true;
nextButtonDisabled = false;
//User inputs
constructor(private sService:submitService) { }
ngOnInit() {
public submitToJSON() {
//SumbitJSON Object
var submitJSON = {
//inputData
};
this.sService.POST(submitJSON);
}
public returnDetails() {
this.listOfIDs = {//ListData};
this.hideTable = false;
var keys = Object.keys(this.listOfIDs);
var len = keys.length;
this.lengthOfRecords = len;
}
public prev() {
if(this.lowerLimit <= 0) {
;
}
else {
this.lowerLimit = this.lowerLimit - 6;
this.upperLimit = this.upperLimit - 5;
this.nextButtonDisabled = false;
if(this.lowerLimit <= 0) {
this.prevButtonDisabled = true;
}
}
}
public next() {
if(this.upperLimit >= this.lengthOfRecords) {
;
}
else {
this.lowerLimit = this.lowerLimit + 6;
this.upperLimit = this.upperLimit + 5;
this.prevButtonDisabled = false;
if(this.upperLimit >= this.lengthOfRecords) {
this.nextButtonDisabled = true;
}
}
}
getEntries(obj, from, to) {
if(obj!=null) {
var entries = [];
for(var key in obj) {
// extract index after `app`
var index = key.substring(3);
if(index >= from && index <= to) {
entries.push( obj[key]);
}
}
return entries;
}
}
}
When I run npm start (which will run tsc -p ./), I get the following two errors:
app.appComponent.ts: error TS1128:Declaration or statement expected
app.appComponent.ts: error TS1128:Declaration or statement expected
At the following lines of code
---> public submitToJSON() {
//SumbitJSON Object
var submitJSON = {
//inputData };
this.sService.POST(submitJSON);
}
And at the last line of the code. I have been modifying the code the whole day, and only removing the OnInit related code fixes it. What am I doing wrong? I'm new to Angular2, so any information would be helpful. I am also running tsc version 3.1
A:
You have commented
//inputData };
I think the curly brace should be on the next line...
//inputData
};
Edit
Your ngOnInit function should not contain other functions:
import { Component, OnInit} from '@angular/core';
import { submitService } from './Common-functions/submit.service';
@Component({
selector: 'my-app',
template: `htmlCode`
})
export class AppComponent implements OnInit{
hideTable = true;
lengthOfRecords = 0;
lowerLimit = 0;
upperLimit = 5;
prevButtonDisabled = true;
nextButtonDisabled = false;
//User inputs
constructor(private sService:submitService) { }
ngOnInit() {
// Add any initialization code here
}
submitToJSON() {
//SumbitJSON Object
var submitJSON = {
//inputData
};
this.sService.POST(submitJSON);
}
returnDetails() {
this.listOfIDs = {//ListData};
this.hideTable = false;
var keys = Object.keys(this.listOfIDs);
var len = keys.length;
this.lengthOfRecords = len;
}
prev() {
if(this.lowerLimit <= 0) {
;
}
else {
this.lowerLimit = this.lowerLimit - 6;
this.upperLimit = this.upperLimit - 5;
this.nextButtonDisabled = false;
if(this.lowerLimit <= 0) {
this.prevButtonDisabled = true;
}
}
}
next() {
if(this.upperLimit >= this.lengthOfRecords) {
;
}
else {
this.lowerLimit = this.lowerLimit + 6;
this.upperLimit = this.upperLimit + 5;
this.prevButtonDisabled = false;
if(this.upperLimit >= this.lengthOfRecords) {
this.nextButtonDisabled = true;
}
}
}
getEntries(obj, from, to) {
if(obj!=null) {
var entries = [];
for(var key in obj) {
// extract index after `app`
var index = key.substring(3);
if(index >= from && index <= to) {
entries.push( obj[key]);
}
}
return entries;
}
}
A:
In my case was just necessary to compile again the project
| {
"pile_set_name": "StackExchange"
} |
Q:
Meteor collection.update permisions
Hi i dont understand why is this not working?
Notifications.update({'userId':Meteor.userId(), 'notifyUserId':notifyFriendId}, {$set: {read: 1}});
I have update allow method as well
Notifications = new Meteor.Collection('Notifications');
Notifications.allow({
update: function(userId, doc) {
return true;
}
});
Error appear:
Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]
A:
To update a collection you can only use the document's _id. So you need to query for it first
var docid = Notifications.findOne({'userId':Meteor.userId(), 'notifyUserId':notifyFriendId});
Notifications.update({_id:docid._id}, {$set: {read: 1}});
This is only for code that runs on the client. On the server you can run the code as you had it.
| {
"pile_set_name": "StackExchange"
} |
Q:
NodeJS/V8/JavaScript on Linux: Upredictable ramp-up to full performance
Following is a stitch-up of the CPU consumption graphs over multiple runs of a simple script. I am intrigued by the variability of the CPU consumption graphs over short periods of time. Does anybody have an idea what may be causing these curves to change so dramatically within few minutes' span?
The driver script to make the node process hog one CPU at a time:
$ for (( i = 0; i < 8; ++i )) ; do echo CPU: $i; taskset -c $i node ticks_per_second.js; done
The script: Node Ticks per Second
Node version: 0.10.8 (installed using NVM)
OS: Ubuntu 12.04
Hardware: MacBook Pro 9,1
This was an exercise to see the theoretical limit of how many events I can generate/process from a single NodeJS process.
PS: I understand what kinds of tasks NodeJS is good at (I/O) and which it is not good at (CPU), so please suppress the urge to discuss those aspects. I am looking for advice to make NodeJS perform predictably.
A:
Turns out that the Gnome System Monitor is retarded!!
(Note: In the following screenshots, the upper graph is made by the KSysGuard, and the lower graph is from Gnome System Monitor.)
The update interval has to be set to '10' seconds, just so that System Monitor will move the graph every 1 second. (see screenshot 1)
When the update interval is set to 1 second, the graph moves just too fast!! (See screenshot 2)
The KSysGuard is much more responsive, and updates the graph at precisely 1 second when asked to do so. (see screenshot 1).
Thankfully, the KSysGuard package does not have any dependency on the rest of the KDE system, so installing it installed just the GUI and the ksysguardd daemon, and caused no unnecessary bloat.
Bottom-line: Don't use Gnome System Monitor, and use KSysGuard as it does the right thing, and is very flexible.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to redirect output of Python script to terminal
How can I redirect my Python script output to one of the open terminal windows under Ubuntu? The script is spawned by KMail filtering rule.
A:
Creating a simple socket server would be one method… But I'd probably use fifos:
$ mkfifo /tmp/my_fifo
$ cat producer.py
f = open("/tmp/my_fifo", "w")
f.write("hello, world!\n")
f.close()
Then you could read from it using cat /tmp/my_fifo
Or a simple log file:
$ cat producer.py
f = open("/tmp/my_log", "a")
f.write("hello, world!\n")
f.close()
Then you could read from it using tail -f /tmp/my_log
| {
"pile_set_name": "StackExchange"
} |
Q:
"server sockets closed" when duplicate tabs are opened
I'm having trouble figuring out this issue.
I have a Node/Express server and I'm using MongoDB. Everything is working fine and normally. It has user accounts and the system for login and signup is working normally. I even tested signing up and logging in on my phone (I use Gulp as my build tool).
The problem I'm having now is that whenever I try to signup in the a duplicate tab (as in another tab on the same signup/login page) I get an error:
Server code:
//check for existing account using the given email
User.findOne({ "email" : email }, function(err, doc) {
if(err) throw err;
//if no email is found proceed with account creation
if(!doc) {
//snip
} else {
//if an account is found re-render the page with the error message
//and close the db
res.render(...);
dbase.close();
}
});
But when I have the same tab open I get this error:
MongoError: server localhost:27017 socket closed.
I've tested this multiple times. It works fine when there are no duplicate tabs. It works on my phone when the tab's still open on the computer. I checked and quadruple-checked to make sure I wasn't closing the DB too soon. This error literally only happens when I have the same tab open. when I submit the form they both start Loading (or attempting to, rather). Here's a screenshot to be very clear:
Again, I've checked multiple times that I'm not closing the DB before receiving a response from the DB, and not outside of that response handle.
Am I missing something in my requests handling? how can I keep it from sending data to both tabs and (seemingly) performing the same operation twice?
Thanks in advance.
A:
Thanks to Louis93 I have better clarity on how to construct my server an database queries.
The connection must be reused! More information here: https://stackoverflow.com/a/14607887/765409
i.e. Don't close it
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting data to long format -- other variables inserted between observations
I have the following dataframe in R:
ID Count
31/10/2019 15
01 1
02 2
03 5
04 7
01/11/2019 14
01 1
02 4
03 5
04 5
02/11/2019 10
01 1
02 2
03 3
04 4
I would like to change it to:
ID Count Date
01 1 31/10/2019
02 2 31/10/2019
03 5 31/10/2019
04 7 31/10/2019
01 1 01/11/2019
02 4 01/11/2019
03 5 01/11/2019
04 5 01/11/2019
01 1 02/11/2019
02 2 02/11/2019
03 3 02/11/2019
04 4 02/11/2019
I was thinking of using gather but I'm not sure how. Can someone help me out please? Thank you!
A:
We can create a new column Date where the value is ID if Color column is empty else NA, fill the Date Column and remove empty values from Color column.
library(dplyr)
df %>%
mutate(Date = ifelse(Color == "", ID, NA)) %>%
tidyr::fill(Date) %>%
filter(Color != "")
# ID Color Date
#1 01 blue 31/10/2019
#2 02 cyan 31/10/2019
#3 03 red 31/10/2019
#4 04 black 31/10/2019
#5 01 blue 01/11/2019
#6 02 cyan 01/11/2019
#7 03 red 01/11/2019
#8 04 black 01/11/2019
#9 01 blue 02/11/2019
#10 02 cyan 02/11/2019
#11 03 red 02/11/2019
#12 04 black 02/11/2019
| {
"pile_set_name": "StackExchange"
} |
Q:
Client => Server communication with Vaadin + GWT
I'm developing a GWT widget for an existing vaadin application and so far everything has worked out fine,
until I needed to call a server-side function from the client and get a value from it to the client.
more detailed issue:
There is a server-side function that gets certain values from a connected database.
Now I want to get access this function from the client-side,
since I need the values to update something in the widget.
According to Vaadin and GWT documentations you're supposed to use RPC for this,
and I already implemented multiple functions on the server-side that bascially do the opposite
(send something from the server to the client, initiate a call of a client function from server code etc.)
From my understanding I'm supposed to call a void return function on the server by using rpc (the part I can't get to work)
then I could make that function on the server use a server=>client rpc to send that value back to the client (already working)
Is this the definite solution and if so how do I properly implement the client=>server part
and if not, what would be a good solution?
I've already tried something like https://vaadin.com/wiki/-/wiki/Main/Sending+events+from+the+client+to+the+server+using+RPC
but somehow can't figure out how to call the method while in the widget class and not in the connector class
There just seems to be something missing? and is this even the right approach?
parts of the current code:
DrawwServerRPC
public interface DrawwServerRPC extends ServerRpc {
public void updateE(String e);
}
relevant part of Draww.java on server
protected DrawwServerRPC = new DrawwServerRPC () {
public void updateE(String e){
// gets some values from a db and then sends them back to the client
// via rpc (both points working fine)
}
};
public Draww() {
registerRpc(rpc);
}
part of the connector class, this is supposed to be called when a specific method in the DrawwWidget class (client) is called, instead of on a click
getWidget().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
final MouseEventDetails mouseDetails = MouseEventDetailsBuilder
.buildMouseEventDetails(event.getNativeEvent(),
getWidget().getElement());
rpc.updateE("test");
}
});
So my main issue is, how do I now properly access this method (most likely over the connector method) when a specific function in the DrawwWidget class on the Client is called?
And how do I then pass the value from the client method to the connector (or even server side) method? => need to somehow call the updateE method on the server from client side code (by using connector/rpc)
edit:
so here is a bit longer explanation of how I solved it in the end according to the idea I got from Mika's answer and this
added an Interface
public interface customListener {
void customEvent (String s);
}
adjusted the DrawwWidget:
public class DrawwWidget extends Label{
private customListener MyListener;
//...
private void someFunction() {
String something = ...;
if (myListener != null) myListener.customEvent(something);
}
public void setMyListener(customListener listener) {
this.myListener = listener;
}
}
and finally implemented the listener in the connector class:
public class DrawwConnector extends AbstractComponentConnector implements customListener {
DrawwServerRpc rpc = RpcProxy.create(DrawwServerRpc.class, this);
public DrawwConnector () {
//lots of irrelevant Server => Client rpc things
getWidget().setMyListener(this);
}
@Override
public void customEvent(String s) {
rpc.doSomething(s);
}
Now I can call the server side "doSomething" method from wherever I want in the widget by using the "customEvent (String s)" Method
A:
You can interact with client side with custom widgets or javascript extensions. For visible components custom widget is usually suitable solution.
You can follow similar convention in client side as Vaadin generally follows in server side and register a listener from connector to your widget. For example:
@Override
protected Widget createWidget() {
MyWidget widget = GWT.create(MyWidget.class);
widget.addMyListener(new MyListener() {
@Override
public void onSomeEvent(ClientData data) {
rpc.onEventFromClient(data);
}
});
return widget;
}
Widget is a GWT component and usually you can find some existing GWT component that you can extend. If not, then it is possible to create plain HTML elements from the widget, good reference for this is the source code for existing GWT components.
Here is an example of a widget that has a text and you can click on the widget.
import com.google.gwt.user.client.ui.Label;
// ... only relevant imports included
public class MyWidget extends Label {
private List<MyListener> listeners = new ArrayList<MyListener>();
public MyWidget() {
addStyleName("m-my-label");
// Add GWT event listeners for events that you want to capture.
addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
notifyListeners();
}
});
}
private void notifyListeners() {
for (MyListener listener : listeners) {
listener.onSomeEvent(new ClientData("Hello from widget"));
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
if a test case throws an exception (@expectedException) how to finish that method correctly?
I have a test case:
/**
* @expectedException Exception
*/
public function testDie()
{
saveSomething();
doOp();
doOp(); // here the exception triggers
restoreSomething(); // this line wont be executed, still I need it
}
something needs to be set and restore, but I cant restore because of the exception. How to dodge it?
A:
Catch the expected exception, and fail the test if no exception is caught.
However, having a necessary state restoration within a test function is bad practice. Put the save in a setUp() function and the restore in a tearDown() function instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como configurar idiomas em Asp.net Core
Estou a configurar o AddLocalization
Então o problema é que os Resources estão numa biblioteca de classes em separado do projecto e eu não sei configurar.
services.AddLocalization(options => options.ResourcesPath = "Resources");
A:
Para configurar os idiomas em asp.net core utilizei a seguinte configuração:
No ficheiro Startup
public void ConfigureServices(IServiceCollection services) {
services.AddLocalization(opts => {
opts.ResourcesPath = "Resources";
});
services.AddMvc()
.AddViewLocalization(
LanguageViewLocationExpanderFormat.SubFolder,
opts => {
opts.ResourcesPath = "Resources";
})
.AddDataAnnotationsLocalization()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Coloquei os ficheiros de tradução aqui como mostra na imagem
Para no controlador acessar a tradução utilizei
private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(IStringLocalizer<HomeController> localizer)
{
_localizer = localizer;
}
Seguidamente para aceder a um texto especifico utilizei
ViewData["Contact"] = _localizer.GetString("Contact").Value;
Passo para a ViewData["Contact"] o campo com o nome Contact que se encontram nos ficheiros:
Controllers.HomeController.en.resx
Controllers.HomeController.pt-PT.resx
Estes ficheiro por sua ordem:
Views.Shared._Layout.pt-PT.resx
Views.Shared._Layout.en.resx
Afectam o ficheiro _Layout.cshtml
Dentro do ficheiro _Layout.cshtml podemos para traduzir-mos dentro desse ficheiro sem existir controlador utilizamos razor
@inject IViewLocalizer Localizer
E para colocarmos uma variavel de tradução utilizamos por exemplo:
@Localizer["MenuHome"]
sendo que "MenuHome" é o nome da variável declarada no ficheiro Views.Shared._Layout.en.resx e Views.Shared._Layout.pt-PT.resx
Depois para ver as paginas nos diferentes idiomas basta acessar o link do seu site:
https://linkdosite/NomeControlador/NomeAction?culture=en
Para mostrar a tradução neste caso em ingles
| {
"pile_set_name": "StackExchange"
} |
Q:
Make textbox in UserControl become readonly
I have a couple of textbox in the UserControl. How am I going to change them into readOnly = true/false depending on the conditions?
In my content page, I have the following codes:
<%@ Register TagPrefix="uc1" TagName="item" Src="~/User_Controls/itemDetails.ascx" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent_1" runat="server">
<uc1:item id="ItemList" runat="server"></uc1:item><br />
</asp:Content>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (//Some Conditions)
{
//turn ItemList.txtItemName = enable read Only
}
if (//Some other Conditions)
{
//turn ItemList.txtItemPrice = disable read Only
}
}
In the ItemDetails.ascx.cs:
protected void Page_Load(object sender, EventArgs e)
{
}
public string itemName
{
get { return txtItemName.Text; }
set { txtItemName.Text = value; }
}
public string itemPrice
{
get { return txtItemPrice.Text; }
set { txtItemPrice.Text = value; }
}
//and get...set... for other controls
A:
Create property in User control ItemDetails.ascx. and assign the property to the textbox enable property.
User control
public bool EnabledtxtItemName { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
txtItemName.Enabled = EnabledtxtItemName;
}
Now you can access the property from respective page you have added the user control.
Web page
protected void Page_Load(object sender, EventArgs e)
{
ItemList.EnabledtxtItemName = false;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Should we add screenshots?
At least for game-rec and identify-this-game answers this would help a lot... I'll put this to vote (edited following Oak's advice)
A:
Screenshots are awesome, especially for the type of questions listed in the question. I'm not sure there is a need to actively encourage them, though, because I think people have a tendency to upvote answers with screenshots anyway.
Also, I do not think we should edit other people's answers just to add screenshots... unless it's a community wiki answer, at least.
| {
"pile_set_name": "StackExchange"
} |
Q:
Declaring an int value outside of inner class
How do i get the value of the int count to be declare in a setText outside of its inner class?
model.getSearch().observe(this, new Observer<List<Sight>>() {
@Override
public void onChanged(@Nullable List<Sight> searchList) {
adaptersearch = new SearchAdapter(SearchResults.this, searchList);
searchhList.setAdapter(adaptersearch);
int count = 0;
if (adaptersearch != null) {
count = adaptersearch.getItemCount();
}
}
});
apptxt.setText(count +name+ "items");
At the minute it just comes up with the error cannot resolve count.
A:
You can't write to a variable (change the value of the variable ) that has been initialized in outer class from an inner class.
there is a workaround to do it is to create a final array of int with one value, then you can access it in your inner class.
keep in mind that this is not the best way to do it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mocking Files In Python Unittest In Imported Modules
I readily admit to going a bit overboard with unit testing.
While I have passing tests, I find my solution to be inelegant, and I'm curious if anyone has a cleaner solution.
The class being tested:
class Config():
def __init__(self):
config_parser = ConfigParser()
try:
self._read_config_file(config_parser)
except FileNotFoundError as e:
pass
self.token = config_parser.get('Tokens', 'Token', )
@staticmethod
def _read_config_file(config):
if not config.read(os.path.abspath(os.path.join(BASE_DIR, ROOT_DIR, CONFIG_FILE))):
raise FileNotFoundError(f'File {CONFIG_FILE} not found at path {BASE_DIR}{ROOT_DIR}')
The ugly test:
class TestConfiguration(unittest.TestCase):
@mock.patch('config.os.path.abspath')
def test_config_init_sets_token(self, mockFilePath: mock.MagicMock):
with open('mock_file.ini', 'w') as file: #here's where it gets ugly
file.write('[Tokens]\nToken: token')
mockFilePath.return_value = 'mock_file.ini'
config = Config()
self.assertEqual(config.token, 'token')
os.remove('mock_file.ini') #quite ugly
EDIT: What I mean is I'm creating a file instead of mocking one.
Does anyone know how to mock a file object, while having its data set so that it reads ascii text? The class is deeply buried.
Other than that, the way ConfigParser sets data with .read() is throwing me off. Granted, the test "works", it doesn't do it nicely.
For those asking about other testing behaviors, here's an example of another test in this class:
@mock.patch('config.os.path.abspath')
def test_warning_when_file_not_found(self, mockFilePath: mock.MagicMock):
mockFilePath.return_value = 'mock_no_file.ini'
with self.assertRaises(FileNotFoundError):
config.Config._read_config_file(ConfigParser())
Thank you for your time.
A:
I've found it!
I had to start off with a few imports:from io import TextIOWrapper, BytesIO
This allows a file object to be created: TextIOWrapper(BytesIO(b'<StringContentHere>'))
The next part involved digging into the configparser module to see that it calls open(), in order to mock.patch the behavior, and, here we have it, an isolated unittest!
@mock.patch('configparser.open')
def test_bot_init_sets_token(self, mockFileOpen: mock.MagicMock):
mockFileOpen.return_value = TextIOWrapper(BytesIO(b'[Tokens]\nToken: token'))
config = Config()
self.assertEqual(config.token, 'token')
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues with arrays
I am fetching some of the datas from my database and one of my column has multiple entries from one user say col(col1) values(a,b,c). Now when I am selecting data from this database, my array looks like this,
Array
(
[0] => srt
[1] => qwe
[2] => xyz
[3] => abc
[4] => 1
)
Array
(
[0] => srt
[1] => qwe
[2] => xyz
[3] => abc
[4] => 2
)
Array
(
[0] => srt
[1] => qwe
[2] => xyz
[3] => abc
[4] => 3
)
Now as my array shows only fourth element of array is different.
I want to insert this data into another table which has different columns for different values means only one row corresponding to one user. Thus
col(col1) turns in to col(cola,colb,colc).
Now I want to insert like
cola -> 1,colb -> 2,colc -> 3.
But I am not able to access these values. If I select array[4] then it selects all four elements if I try this $array=array($result[4]); then it create an array of result but with same index value
Array ( [0] => 1 )
Array ( [0] => 2 )
Array ( [0] => 3 )
Array ( [0] => 4 )
I hope I am able to clarify my question.
So please suggest me some way so that I can access these values in some way.
Thanks !
EDIT
my code
while($result= mysql_fetch_array($select))
{
echo "<pre>";
print_r($result);
$array=array($result[4]);
echo "</pre>";
print_r($array);
my result
Array
(
[0] => [email protected]
[email] => [email protected]
[1] => 2011-01-06 13:00:36
[date_joined] => 2011-01-06 13:00:36
[2] => 1
[is_active] => 1
[3] => 1
[attribute_id] => 1
[4] => suresh
[info] => suresh
)
Array ( [0] => suresh )
Array
(
[0] => [email protected]
[email] => [email protected]
[1] => 2011-01-06 13:00:36
[date_joined] => 2011-01-06 13:00:36
[2] => 1
[is_active] => 1
[3] => 2
[attribute_id] => 2
[4] => patidar
[info] => patidar
)
Array ( [0] => patidar )
Array
(
[0] => [email protected]
[email] => [email protected]
[1] => 2011-01-06 13:00:36
[date_joined] => 2011-01-06 13:00:36
[2] => 1
[is_active] => 1
[3] => 4
[attribute_id] => 4
[4] => e5c59af60000c8dff51e4e9a315ab152:vN
[info] => e5c59af60000c8dff51e4e9a315ab152:vN
)
Array ( [0] => e5c59af60000c8dff51e4e9a315ab152:vN )
A:
You could make a loop first, then from there you could slice the array after the loop
<?php
$arr = array();
while($result= mysql_fetch_array($select))
{
$arr[] = $result;
}
print_r($arr);
echo $arr[0][4] ;
| {
"pile_set_name": "StackExchange"
} |
Q:
Positive slope of BER with a greater frequency deviation?
I am trying to implement a frequency-modulated communication channel on MatLab. However, there is something I don't understand about the sensitivity of the frequency modulator (or the frequency deviation as my signal has an amplitude equal to 1). My message has a 500Hz frequency and is sampled at 20kHz. I added white gaussian noise to my bandpass signal (carrier of 6kHz).
Why does the BER of the demodulated message have a positive slope after 250Hz ?
NB : it is written [dB] for the BER on the graph but it is not, I forgot to remove it
A:
This could happen as discriminator gain is increased with a filter discriminator approach since in many of those approaches the gain would be maximum and linear for small signals only and then the slope of the discriminator slowly goes down coinciding with the results in your plot (such that you no longer get a perfect sine wave out for a sine wave in—- so you can also look at it as converting some of your signal components to other harmonics at the discriminator output due to that non-linearity). Ultimately as you increase the gain further your signal will start to saturate and then even invert depending on the wider bandwidth shape of your discriminator.
Plot the derivative of your frequency discriminator to see this more clearly as to its usable range for a given frequency deviation- the ideal for no distortion is to have a constant slope.
I see from the link you provided that the slope is indeed constant over a limited usable range. So specifically in your case I assume as $k_f$ was increased, it would cause a proportionate amount of the signal to go beyond the discriminator range (where your response is 0).
| {
"pile_set_name": "StackExchange"
} |
Q:
macOS update closed all my applications?
At exactly 4 a.m., macOS gave a popup saying, “Update Available,” then abruptly closed all my applications. I don’t remember receiving any earlier popups or warnings about updates being available.
Is this normal behaviour? Can I prevent it from happening again somehow?
Having this happen at exactly 4 a.m. seems significant. Maybe it assumes I’m not active at that time?
A:
You will normally be prompted to install updates as they are detected. However if you were away from your computer you may not see those notifications. Also if you delay them enough times they will eventually be installed for you. Lastly if the updates are detected overnight they may be installed right then as well. This is usually done sometime after 3 a.m.
You can go to → System Preferences → App Store and uncheck the following:
Install app updates
Install macOS updates
Install system data files and security updates
This will keep macOS from installing updates, quitting apps and/or restarting your system without asking you first.
You will still be notified when updates become available, and offered the choice to install them.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to make "i+=x" works as "i++"?
The following code
int i=0;
while(i<10) {
printf("%d\n", i++);
}
is equivalent to
int i=0;
while(i<10) {
printf("%d\n", i); i++;
}
But the following code
int i=0;
while(i<10) {
printf("%d\n", i+=2);
}
is equivalent to
int i=0;
while(i<10) {
i+=2; printf("%d\n", i);
}
How to make it equivalent to
int i=0;
while(i<10) {
printf("%d\n", i); i+=2;
}
the same as i++
A:
You can write a macro to do this too. Like this:
#define POSTINC(var, val) ((var) += (val), (var) - (val))
printf("%d\n", POSTINC(i,2));
But better use either for or just increase the value in the next statement.
A:
Curious as to how hard I'll be hit for suggesting something as obvious as:
for(int i = 0; i < 10; i += 2) {
printf("%d\n", i);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
The "right" way to use my pinky.
Ever since I've been playing, I've always fretted a B chord like this:
Using my pinky to cover the D, G, & B string. However, while it works, it's never felt quite right. I've tried to use three fingers to do the same thing, but I've never seemed to be able to move them in to position fast enough for the chord to sound good.
Is this the "right" way to fret the chord, or should I be trying to use a three-fingered approach?
A:
Wherever possible you should be trying to use a finger per fret, in the case of the B chord in your picture your fingering is wrong.
Your index finger should be barring from the A string on the second fret (B note), with your ring finger covering the D,G,B strings on the 4th fret.
The you should strum the chord from the A string, if you are having trouble with the strength of your ring finger then as previously mentioned, the three finger fingering is an option.
Its really mostly about hand strength; if you play these types of chord more often using both fingering then you will build up your hand strength to cope better with this and other types of chord.
Failing all of the above; you could always find and use a different and less stressful voicing for the chord, check this link out
A:
In my opinion, if something doesn't feel right, try not do it. I would try either the 3 finger method, or using your fourth/ring finger in the same way as your pinky. Your ring finger is usually stronger than your pinky, so it will be a little easier.
Using three fingers is great, because it means you can play variations on those chords, such as minors, 7th's or sus4's. With this, I'm afraid, it is just a case of practice, practice, practice! For me, it was like learning playing F-shaped barre chords. I could not get to that shape and position fast enough, but eventually I got there. It's just a case of learning to get in that position and making a clean sound.
If you are finding it tricky to learn that, try not barring your first finger fully across the fretboard, just fretting the 1st string. That certainly helped me learn them.
Hope this helps! :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Question concerning h-cobordisms
Suppose we have a cobordism $W$ of manifolds $M_0$ and $M_1$ and suppose the inclusion of $M_0$ into $W$ is a homotopy equivalence. Is the same true for the inclusion of $M_1$ (ie. is $W$ already an h-cobordism)?
Using Poincare Lefschetz duality one can show that this map induces isomorphisms on homology.
Hence it suffices to show that the inclusion $M_1\rightarrow W$ induces an isomorphism on $\pi_1$.
A:
For a counterexample take a non-simply connected homology sphere bounding a contractible manifold and remove the interior of a small ball from the contractible manifold. Such homology spheres exist in abundance.
A:
I think the answer should be no, since people study so-called semi-s-cobordisms, which (if they exist) give counter-examples.
A:
However, the answer is "yes" after stabilizing three times: The product $W \times J^3$ (where $J^3$ is a $3$-cube) is an $h$-cobordism from $M_0 \times J^3$ to the closure of the remaining part of the boundary. There are details in Remark 1.1.3 of my book project "Spaces of PL manifolds and categories of simple maps" with Jahren and Waldhausen.
| {
"pile_set_name": "StackExchange"
} |
Q:
add lib to intelliJ project but dont include the lib in artifacts
I included my lib in several ways i found online.
The last one i used is based on this:
Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project
However, i don't want the library to be included on export (building artifacts).
At the moment it is which gives problems.
How can i include a library in such a way that it doesn't get included when building artifacts?
A:
Change the library scope to Provided or exclude it from Artifacts by editing artifact layout.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python getting values from class
im trying to make an app that runs few files to make it organized, however im kinda lurker in python and got stuck trying to import values from settings.py in main.py.
The error type im getting looks like this depending on how im trying to get the object's value:
self.code = sets.run().self.code
AttributeError: 'NoneType' object has no attribute 'self'
or
self.code = sets.code
AttributeError: 'settings' object has no attribute 'code'
The whole idea is to make get self. values in the other file not using the return but simply specifying the element.
Simple sample code:
Main file:
import settings
def run():
sets = settings.settings()
code = sets.code
run()
Settings file:
class settings():
def run(self):
self.code = somevalue
so basicaly that is the minimum extension of what im trying to do, i could return the self.code in run however that is not what i want because i have many settings_values and id like to access them in different files.
help much appreciated.
Edit:
So how should i approach this if i need to import settings in main but only run() settings whenever i start running the main_run() and than just get the variables?
I dont want to complicate it with saving to file and than reading a list() i need to just access them and only run
basicaly: my settings gets a long list from pickle and than makes some operations that return the code combination and lots of other self.settings that need to be initiated when the program(main) starts and than for the whole While True inside run() the values are fixed unless i start refresh_settings() and change the settings than the data is recompiled and the program returns to while true
A:
You need and __init__ function, your class should look like this:
class settings():
def __init__(self,code):
self.code = code
Now you can make a variable like this
sets = settings(“something”)
And Access the code in the variable in this way:
code = sets.code
Or if you really want to do the run() bit then your code would be:
class settings():
def __init__(self,code):
self.code = code
def run(self):
return self.code
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to access the Class object in a static method?
Consider the following Java class:
public class Foo
{
public static void doStuff()
{
// boring stuff here
}
}
Is it possible to access either the class literal Foo.class, or just the class name "Foo" from within a static method such as doStuff()? In a non-static method I would just call this.getClass(), but there is no this to use in a static method.
Edit: sorry this wasn't clear - I want to do this with explicitly using the class literal Foo.class.
A:
Unfortunately Java doesn't give you a good way to do this. You just have to reference Foo.class. This is something that is a regular annoyance for me.
For logging I solved it (the idea for the solution came from Log5j) by reading the stack, because it got really annoying to restate the class for every logger every time. Fortunately modern IDEs make it relatively painless, so that refactoring isn't really negatively impacted if you have to change the name of the class.
EDIT: Some code:
private static StackTraceElement getCallerStackTraceElement(StackTraceElement[] elements) {
for (int i = 0; i < elements.length; i++) {
if (elements[i].getClassName().equals(MyLogger.class.getName())) {
return elements[i + 1];
}
}
return null;
}
MyLogger in this case is the class where this method exists. It finds itself in the stacktrace and goes one earlier, and then extracts the class from the StackTraceElement.
The StackTraceElement[] array can be retrieved by either new Exception().getStackTrace(), or Thread.currentThread().getStackTrace(); The way this method is written it assumes the stacktrace is created on the first method call into MyLogger.
| {
"pile_set_name": "StackExchange"
} |
Q:
Closing ServerSocket - how to properly check if client socket is closed?
I create a new thread that runs the following code:
public static void startServer() throws IOException {
serverSocket = new ServerSocket(55000);
Socket clientSocket = serverSocket.accept();
}
The above code is run in a thread. Now, in my main class, I successfully create a socket
connection to the server and I have checked it's integrity which is fine. here is the code:
Socket testServerSocket = new Socket("127.0.0.1", 55000);
assertEquals("/127.0.0.1", testServerSocket.getInetAddress().toString());
assertEquals(55000, testServerSocket.getPort());
This runs perfect. Then, again from my main, I kill the server connection that closes the connection on the server side. However the following code keeps failing:
assertEquals(false, testServerSocket.isBound());
It keeps returning true. Likewise, if I check the remote IP address for the connection, it doesn't return null, but rather '/127.0.0.1'. Any ideas why this might be happening? Many thanks for your help
A:
I'm not an expert on sockets (I know what they are, but haven't ever used sockets on Java, only with C on Linux), but like JavaDoc for java.net.Socket states, 'A socket is an endpoint for communication between two machines'. So while closing server-side socket does destroy the connection between the two sockets (server- and client-side), your client-side socket is still bound, hence the isBound() is returning true. Maybe you meant to call isConnected() or isClosed()?
| {
"pile_set_name": "StackExchange"
} |
Q:
Qt - remove menu from bottom?
How in the world do I get rid of these buttons?
A:
Call showFullScreen() on your QMainWindow.
| {
"pile_set_name": "StackExchange"
} |
Q:
Open file with terminal and close terminal afterwards
I want to open a file using the terminal on ubuntu.
To have it independent from the terminal, I use gnome-open:
gnome-open text.pdf
And since I'm lazy, I also have this alias in my .bashrc:
alias g='gnome-open'
So when I type g text.pdf the file opens in evince but here is my problem:
The terminal is still open! I often don't need the terminal at that moment and since I'm using a tiling window manager it's wasting space so I close it manually which is annoying.
Is there a way to automatically close the terminal after the file was opened?
A:
Maybe I'm not understanding the question but I would use something like [program] [file-to-be-opened] & exit. So, if I have a file called something.txt and I wanted to open it from a terminal with a GUI-based text editor, Leafpad, and close the terminal, I'd open a terminal and run:
leafpad something.txt & exit
where exit is used to close the terminal.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I draw a image with circular border in canvas?
I am currently working with canvas in Flutter for the first time. I have to do an market for google maps (its just possible to do it using canvas or raw images for now), using a custom image taken from the internet. I got something working with the image and it looks like this:
But my expected result should have the image with a circular shape. It looks like this:
Does someone know how to do it?
Here some code
Painter
class ImageEditor extends CustomPainter {
ImageEditor({
this.image,
});
ui.Image image;
@override
void paint(Canvas canvas, Size size) async{
canvas.drawImage(image, new Offset(0, -size.height*0.8), new Paint()..style=PaintingStyle.fill);
final radius = math.min(size.width, size.height) / 8;
final center = Offset(50, 50);
Paint paintCircle = Paint()..color = Colors.black;
Paint paintBorder = Paint()
..color = Colors.white
..strokeWidth = size.width/36
..style = PaintingStyle.stroke;
canvas.drawCircle(center, radius, paintCircle);
canvas.drawCircle(center, radius, paintBorder);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
Main class
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'canvas_test.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ui.Image image;
bool isImageloaded = false;
void initState() {
super.initState();
init();
}
Future <Null> init() async {
image = await _loadImage("https://<link>");
}
Future<ui.Image> _loadImage(String photoUrl) async {
final cache = DefaultCacheManager();
final file = await cache.getSingleFile(photoUrl);
final bytes = new Uint8List.fromList(await file.readAsBytes());
final Completer<ui.Image> completer = new Completer();
ui.decodeImageFromList(bytes, (ui.Image img) {
setState(() {
isImageloaded = true;
});
return completer.complete(img);
});
return completer.future;
}
Widget _buildImage() {
if (this.isImageloaded) {
return new CustomPaint(
painter: new ImageEditor(image: image),
);
} else {
return new Center(child: new Text('loading'));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("First Canvas"),
),
body: Container(
color: Colors.blueGrey,
child: Center(
child: Container(
width: 80,
height: 90.0,
child: _buildImage(),
),
),
),
);
}
}
A:
@override
void paint(Canvas canvas, Size size) async{
final center = Offset(50, 50);
final radius = math.min(size.width, size.height) / 8;
// The circle should be paint before or it will be hidden by the path
Paint paintCircle = Paint()..color = Colors.black;
Paint paintBorder = Paint()
..color = Colors.white
..strokeWidth = size.width/36
..style = PaintingStyle.stroke;
canvas.drawCircle(center, radius, paintCircle);
canvas.drawCircle(center, radius, paintBorder);
var drawImageWidth = 0;
var drawImageHeight = -size.height*0.8;
Path path = Path()
..addOval(Rect.fromLTWH(drawImageWidth, drawImageHeight, image.width, image.height));
canvas.clipPath(path);
canvas.drawImage(image, new Offset(drawImageWidth, drawImageHeight), new Paint());
}
This solution allows you to make round image on the canvas.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cancel Shipment Creation Magento 2
How to Cancel Shipment Creation for an Order in Magento2?
I have a condition where If the condition is false I need to stop Shipment Creation and Cancel the order. How can I manage this? Any help will be appreciated.
A:
For this requirement, you have to work on Magento\Sales\Model\Order\Shipment::register() .
Create a plugin on Magento\Sales\Model\Order\Shipment::register(
Then using around plugin on register() implement your logic.
Create di.xml at your module and defined the plugin class of Magento\Sales\Model\Order\Shipment
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Sales\Model\Order\Shipment">
<plugin disabled="false" name="Devbera_PreventInvoice_Plugin_Magento_Sales_Model_Order_Shipment" sortOrder="10" type="{Vendorname}\{ModuleName}\Plugin\Magento\Sales\Model\Order\Shipment"/>
</type>
</config>
And after that create a plugin class on app\code\{Vendorname}\{ModuleName}\Plugin\Plugin\Magento\Sales\Model\Order\Shipment.php,prevent the shipment create or cancel order or etc.
But note if you created any invoice of that order then you cannot cancel that order and you have to create a credit memo instead of cancel.
| {
"pile_set_name": "StackExchange"
} |
Q:
C Tic tac toe beginner
I'm getting a segmentation fault error — any suggestions? I'm trying to create a tic tac toe game, and I just started programming in C. Any suggestions would be helpful. I just want it to print to the terminal no graphics for now.
#include <stdio.h>
int main()
{
int Board[9];
char row1[3];
char row2[3];
char row3[3];
int j = 0;
int turns = 0;
char x;
x = 'x';
char o;
o='o';
int spot;
printf("Hello, and welcome to Christian's Tic Tac Toe game\n");
printf("Here's how it works: X goes first and chooses a place(1-9 corresponding to a place on the board)\n");
printf("First to get 3 in a row wins. Have fun!\n");
printf("X goes first where do you want to go?");
scanf("%d", &spot);
Board[spot-1] = 1;
turns = 1;
if (spot <=3)
{
row1[spot-1] = x;
for (j =0; j<3; j++)
{
printf("%c", row1[j]);
}
for (j =0; j<3; j++)
{
printf("%c", row2[j]);
}
for (j=0; j<3; j++)
{
printf("%c", row3[j]);
}
}
else if(spot >3 && spot <=6)
{
row2[spot - 4] = x;
for (j =0; j<3; j++)
{
printf("%c", row1[j]);
}
for (j =0; j<3; j++)
{
printf("%c", row2[j]);
}
for (j=0; j<3; j++)
{
printf("%c", row3[j]);
}
}
else
{
row3[spot - 7] = x;
for (j =0; j<3; j++)
{
printf("\n%c", row1[j]);
}
for (j =0; j<3; j++)
{
printf("%c", row2[j]);
}
for (j=0; j<3; j++)
{
printf("%c", row3[j]);
}
}
}
A:
You invoked undefined behavior by passing data having wrong type to printf(). The format specifier to print one character is %c, not %s.
Your usage of for statement is wrong, so j will be too big and undefined behavior will be invoked by accessing out-of-range of an array.
Example of wrong code:
for (j<3; j++;)
{
printf("%s", row1[j]);
}
Corrected code:
for (j=0; j<3; j++)
{
printf("%c", row1[j]);
}
The same correction is required for loops using row2 and row3.
More mistakes:
scanf("%s", &spot); will invoke undefined behavior: wrong specifier is used again. %d should be used to read integers.
char x ="x"; and char o = "o"; are bad because the values converted from the pointers converted from the string literals should be meaningless. You should use character constants instead like char x ='x'; and char o = 'o';.
Array indexes in C will begin with 0, not 1. row1[3] is not a valid object and you mustn't write something there when it is declared as char row1[3];. You should correct like
row1[spot] = x; -> row1[spot - 1] = x;
row2[spot - 3] = x; -> row2[spot - 4] = x;
row3[spot - 6] = x; -> row3[spot - 7] = x;
Using values of uninitialized variables having automatic storage duration, which is indeterminate, invokes undefined behavior. You have to initialized variables before using their values like char row1[3] = " ";. Also initialize row2 and row3 like this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Go error handling, what's the idiomatic way for making things DRY
Consider the following example program which is primitive stack implementation in Go:
package main
import "fmt"
import "errors"
const MAX_SIZE = 10
var a [10]int
var top int = -1
func main() {
printStack()
push(1)
printStack()
push(23)
printStack()
pop()
push(2)
push(24)
push(56)
push(87)
push(97)
push(47)
push(37)
push(31)
push(69)
printStack()
push(75)
println("Top element is", getTop())
}
func push(x int) (int, error) {
if top >= (MAX_SIZE - 1) {
return 0, errors.New("Error: Prevented Stackoverflow. Stack full")
}
top += 1
a[top] = x
return 0, nil
}
func pop() {
top -= 1
}
func getTop() int {
return a[top]
}
func printStack() {
fmt.Println(top+1, "Stack: ", a, "Top", top)
}
Now, I read Error handling and Go & it seems the above way of returning multiple values is the way to handle errors in go.
But what I don't understand is that does do gophers check of errors on every statement? Coming from other languages this concept it bit hard for me to grok. So the question is
What is the idiomatic way of handling errors in above problem?
Is considered a bad practice if I don't check for errors? if yes, then I am supposed to check the output of push() everytime I call it?
Basically what I want to know if how would a experienced gopher do error handling in the above program?
Play URL: https://play.golang.org/p/_AnZLvY-28
[Update]
Added a real-world program where I fetch data from database & output to json. http://play.golang.org/p/dDApCYprjU
A:
Yes, the idiomatic way to produce errors is to return multiple values. The idiomatic way to handle errors is this:
val, err := myFunc()
if err != nil {
// do something with err
}
// do something with val
At the end of the day it's a judgement call, but it's almost always good practice to handle errors. The code you're writing is also a bit unusual, you normally don't have 10 calls to the same function back-to-back, so the verbose error handling you'd have to do is more a result of the original code. For instance, you could use a loop:
for _, num := range []int{2, 24, 56, 87, 97, 47, 37, 31, 69} {
_, err := push(num)
if err != nil {
panic(err)
}
}
You have some other things that are more problematic than not handling the push errors though. One minor thing is there is no reason for push to always return 0, why not only have it return an error, instead of an int and an error? The bigger problem is that pop keeps decrementing top, and getTop just accesses a[top], so you can easily get a runtime panic if top becomes negative from having popped too much. You probably want some error handling or other safeguards in your pop and getTop functions.
| {
"pile_set_name": "StackExchange"
} |
Q:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint sql
I have this code that creates a foreign key to the table P that has to reference to table Ss. At the moment the column that I want to be a fk is bigint, not null and its default is to 0. Is this the impediment? And the StoredFile column id is not null and is filled with bigint data.
alter table P add constraint fk_fileId_p foreign key (fileID)
references Ss(id)
A:
In order to add the FK, you have to make sure that storefileID 0 is present in the table StoredFile (e.g. by adding a dummy record) - otherwise the FK validation fails and the constraint can not be created.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql master to master replication with one slave
I have 3 servers
Server A master to Server B
Server B master to Server A and Server C
Server C slave to Server B
When I add table to Server A, it replicated on server B but not in Server C
When I add table to Server B, it replicated to server A and Server C
Why is this happening, is there any configuration to make sure when I add table in Server A, it replicate on both Server B and Server C
Thank you
A:
You need to enable log-slave-updates in configuration of server B. This option allow server B to save updates received from server A to its binlog, so server C can see it as new transaction and will replicate it. If this option is disallowed, server B just apply changes received from server A but not propagate it into server C. More info you can find in mysql documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Maps Utility extra functionality (Clustering)
I am reading the Google Maps Android API Utility Library and in order to initialise the clustering manager I need to put this line of code:
getMap().setOnCameraChangeListener(mClusterManager);
My question is what I need to do if I have more things to do when the camera changes position (for example bringing more items/markers from server)?
For marker click event, the documentation states the following:
If you want to add specific functionality in response to a marker
click event, set the map's OnMarkerClickListener() to the
ClusterManager, since ClusterManager implements the listener.
I am not sure I understand what is said in this sentence and if it will work for the camera change event.
Thanks.
A:
You can manually call onCameraChange:
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
mClusterManager.onCameraChange(cameraPosition);
// Your custom code here
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Data stored in Spring (HTTP) Session is not removed from Redis during destroy
i am doing a PoC with the newly released Spring Session component. This is backed-up by Redis repository, where both the Session and the objects/data stored in session are persisted to.
Session got created in the application
ran the "Keys *" command in Redis CLI and saw a new entry (like "spring:session:sessions:6b55103a-baf5-4a05-a127-3a9cfa15c164")
From the application, Added a custom bean to the session
ran the "Keys *" command in Redis CLI and saw one more new entry for
this bean (like "\xac\xed\x00\x05t\x00\tcustomer1" , because the
bean had a string with value 'customer1')
I had configured an auto expiry of 30 seconds and left the application unused for that time
The sessionDestroyEvent got triggered and was captured in the Listener implementing ApplicationListener
ran the "Keys *" command in Redis CLI and now the first created
entry for the session was gone but, the custom bean object
(customer1) was still left over in Redis
Question:
Is it the user responsibility to clean-up the Redis Store ? If i had
many data elements stored in my session, should i have to manually
clean them up from the redis store during session destroy (logout and
timeout events).
Update:
While i posted this question and went back (probably after 3/4 mins)
to Redis-CLI to list the Keys, now i do not find the Customer1 object.
So does that mean the clean-up is performed by Redis on some regular
interval, like the Garbage collection ?
A:
The Session Expiration section Spring Session reference describes in detail how sessions are cleaned up.
From the documentation:
One problem with this approach is that Redis makes no guarantee of
when the expired event will be fired if they key has not been
accessed. Specifically the background task that Redis uses to clean up
expired keys is a low priority task and may not trigger the key
expiration. For additional details see Timing of expired events
section in the Redis documentation.
...
For this reason, each session expiration is also tracked to the
nearest minute. This allows a background task to access the
potentially expired sessions to ensure that Redis expired events are
fired in a more deterministic fashion.
| {
"pile_set_name": "StackExchange"
} |
Q:
UIPickerView change/reverse scroll direction
I have a UIPickerView that contains values 0-100. When I scroll up, it ascends accordingly (0, 1, 2, etc.) (see attached image)
Is it possible to scroll down and have the numbers ascend that way?
Essentially I want to reverse scroll for the UIPickerView so in the provided image, the numbers would be reversed and as I scroll down the numbers will increase up to 100.
On viewDidLoad I tried
[self.pickerView selectRow:100 inComponent:0 animated:YES];
However that just goes straight to 100 in the same manner.
A:
I suggest you reverse the order of the numbers in the data source and then set the initial selection to the last row. That combination gives you what you want.
I also recommend implementing (or finding a 3rd party implementation) a "circular" picker view. See the minute column of the picker view used on the Timer tab of the standard Clock app for an example of what I mean.
| {
"pile_set_name": "StackExchange"
} |
Q:
non build files of eclipse project in git repository
I have files that are associated with my Android project, that are not needed for the build. For example .svg files to generate icons, README file, apk files etc.
Since i would like these files to be part of my project's local git repository(and GitHub), where can i place them? If i place them inside the project folder, it shows up in the Project Explorer in Eclipse. I wonder if it then becomes part of the build and therefore the apk. Is there a convention for this?
A:
Placing them in a subfolder in the project folder should work.
I have tested this by placing a subfolder svg with 19 .svg files totalling 100 kb in my project folder. The resulting .apk was the exact same size as before. So ADT's building process is intelligent enough to ignore miscellaneous folders.
| {
"pile_set_name": "StackExchange"
} |
Q:
What happened to the original crew of Destiny?
After watching the series again, I still can't find the answer to the question, what happened to the original crew of Destiny?
A:
There was no original crew of the Destiny. It would seem that the Ancients set it (and its counterparts) off unmanned with the firm intention of boarding later, then never got around to it after they discovered how to ascend to a higher plane of existence.
GLORIA: This is what you wanted.
RUSH: You know, the Ancients never intended Destiny to operate on its own. They were supposed to come here, in person.
SGU: Aftermath - Transcript
and
RUSH: Look, if Destiny was ever capable of dialing back to Earth, it was thousands of years ago when the Ancients originally intended to come here. But not now.
SGU: Water - Transcript
and
RUSH: The name of the ship, translated from Ancient. I've also discovered that they were never here.
ELI: I thought this was an Ancient ship?
RUSH: It is. But they sent it out unmanned, planning to use the 'gate to get here when it was far enough out into the universe. But…they probably learned to ascend before that time.
SGU: Air, Part 2 - Transcript
As a side note, ascending would have also answered the question that the Ancients designed the Destiny to answer.
A:
An engineering team was trapped aboard Destiny, and the planned expedition team never arrived
In Stargate Universe: Back to Destiny (a canon comic book followup to Season 2), issue 1 shows Eli traveling to an unexplored section of the ship where there are stasis pods containing Ancients.
In issue 2, these Ancients explain that they were engineers preparing Destiny for launch, and that there was another team designated for the actual expedition mission.
Vasi. My name is Vasi. It was not our mission. We are engineers, not explorers.
She later recounts what happened, explaining that there was a last minute malfunction before Destiny launched that trapped them aboard and unable to leave through the Stargate. They were ordered to go into the stasis pods and await rescue from the expedition team, but they never arrived and they don't know why.
Vasi (flashback): Then what are we supposed to do?
Superior (flashback, via audio): Repair the power systems in your section and take refuge in hibernation pods. When the expedition team arrives, you will return through the Astria Porta [Stargate].
Eli: So what did you do?
Vasi: We followed orders. Now, as rescue would seem to be a million years in the past, we are trapped here with no way home.
Eli: For what it's worth, that's something we have in common.
So we know from someone with firsthand knowledge that Destiny was intended to have an expedition team for accomplishing the ship's mission, but we don't know why they didn't arrive to rescue the Ancient engineers who were trapped aboard.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't upload file in PHP using $ajax()
I was trying to upload file on server using php with jQuery's ajax() function. Below is the code which I was trying. Things worked fine when I wrote PHP code on same page without jQuery, so there is no doubt that file upload is working.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$("form").submit(function(e){
e.preventDefault();
var fd = new FormData();
fd.append("files", $("#fileinput").prop("files"));
$.ajax({
url: "imgupload_.php",
type:"POST",
processData: false,
contentType: false,
data: fd,
success: function(result){
alert(result);
}
});
});
});
</script>
<form method="POST" action="#" enctype="multipart/form-data">
<input type='file' name='files' id="fileinput"/>
<input type='submit' value='Submit' name='submit'/>
</form>
imgupload_.php
if(isset($_POST["submit"])) {
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["files"]["name"]);
if (move_uploaded_file($_FILES["files"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["files"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
If you want any other info please comment below.
A:
You're checking if(isset($_POST["submit"])) but this is not set.
Instead of just this:
var fd = new FormData();
Use this to pull in any non-file input values (such as your submit button.)
var fd = new FormData(this);
| {
"pile_set_name": "StackExchange"
} |
Q:
Why it is throwing compile time error?
Why this program throwing compile time error even though I have declared Ari class which extends Exception class.It is giving me output like "unreported exception Ari; must be caught or declared to be thrown".
class Ari extends Exception{ }
public class Main
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C ");
}
System.out.print("D");
}
public static void badMethod()
{
throw new Ari(); /* Line 22 */
}
}
A:
This looks like Java, which uses "checked exceptions". Since your method can throw an Ari exception (in fact, it's guaranteed to), the method signature must declare this:
public static void badMethod() throws Ari {
throw new Ari();
}
This advises consuming code of the possibility of this specific exception so that it can be written to handle that exception.
| {
"pile_set_name": "StackExchange"
} |
Q:
Yii2: Error Not allowed to load local resource
Im trying to display images from backend of my app
<?php foreach ($img as $key=>$row): ?>
<div class="products_inside_wrapper intro_wrapper">
<div class="classes_inside_item bordered_wht_border">
<?php
foreach (explode(';',rtrim($row['images'],';')) as $key_img => $value_img)
{
?>
<?php echo Html::img('@backend/web'.'/'.$value_img);?>
<?php
}
?>
</div>
</div>
<?php endforeach; ?>
Tried with above code to display all images, but getting error Not allowed to load local resource when I open Google Chrome Inspect Element
A:
As stig-js answered you can't load local saved image directly, If you're really interested into loading resources from a local path, you can open image as a binary file with fopen and echo the content of it with a proper header to output. In general way, you can add a method to your model like this:
public function getImage($imageName)
{
$imagePath = '@backend/web' . '/' . $imageName;
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($fileInfo, $imagePath);
finfo_close($fileInfo);
$fp = fopen($imagePath, 'r');
header("Content-Type: " . $contentType);
header("Content-Length: " . filesize($imagePath));
ob_end_clean();
fpassthru($fp);
}
P.S: Also you can use combination of this answer with showing image as base64 on HTML. See How to display Base64 images in HTML?
| {
"pile_set_name": "StackExchange"
} |
Q:
Confusion about data alignment
suppose a struct defined like this:
struct S{
char a[3];
char b[3];
char c[3];
};
then what will be the output of printf("%d", sizeof(S)) ? On My compiler of Vc++ 2008 expression, the output is 9. And I got confused... I suppose the result be 12, but it is not. Shouldn't the compiler align the structure to 4 or 8 ?
A:
The value of the sizeof-expression is implementation-dependent; the only thing guaranteed by the C++ standard is that it must be at least nine since you're storing nine char's in the struct.
The new C++11 standard has an alignas keyword, but this may not be implemented in VC++08. Check your compiler's manual (see e.g. __declspec(align(#))).
| {
"pile_set_name": "StackExchange"
} |
Q:
issue in updating the page after file upload
I am having a strange issue associated with AsyncFileUpload control. after the upload, I am updating the page by calling__doPostBack function from ClientUploadComplete event handler. it works fine first time, but next time I try to upload the file, it refreshes the page first before uploading, then does the upload and refreshes the page again. not sure why refresh page is being called twice once before the upload and once after the upload. I have a simplified version of this code which has this bug. any clues please why it is happening?
Markup:
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnClientUploadComplete="AsyncFileUpload1_ClientUploadComplete"
OnUploadedComplete="AsyncFileUpload1_UploadedComplete" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Refresh Data" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" EnableViewState="false"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Javascript:
<script type="text/javascript">
function AsyncFileUpload1_ClientUploadComplete() {
var btnRefreshData = $get("<%=Button1.ClientID%>").name;
__doPostBack(btnRefreshData, "");
}
</script>
Code-Behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Upload complete";
}
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
System.Threading.Thread.Sleep(3000);
}
A:
looks like no one can answer this question. I still haven't figured out why this happens, but I put a workaround by adding a flag in session when the upload is complete and check that flag before refreshing the data on the page. this way the data refresh won't happen before the upload. thanks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prepared statement with PHP and MySQL without using mysqli
I'd like to know if it is possible to create a prepared statement with PHP and MySQL using the mysql library rather than the mysqli library.
I can't find anything on the PHP documentation.
Thanks.
A:
The PHP documentation quite clearly states (at the end of that page) that the mysql extension does not support prepared statements. An alternative to mysqli that supports prepared statements would be PDO_MYSQL.
A:
what about PDO ?
http://php.net/manual/en/book.pdo.php
| {
"pile_set_name": "StackExchange"
} |
Q:
Align Labels in Grid WPF
I'm having an alignment issue, I'm trying to position the labels from start to end but they're starting in the middle. Can someone shed some light on what I need to do to change it and get it aligned how I want.
<Grid Height="23.3" Margin="169,0,8,8.199" VerticalAlignment="Bottom" Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Rectangle Grid.ColumnSpan="6" Fill="#FFDDDDDD" Stroke="#FFD7D7D7" RadiusX="2" RadiusY="2"/>
<Label Grid.Column="1" Grid.Row="1" x:Name="lblAbout" Content="{Binding Source={StaticResource localisation}, Mode=OneWay, Path=.[Language.about]}" HorizontalAlignment="Left" Foreground="#FF585858" FontSize="10" Cursor="Hand" d:LayoutOverrides="Height" MouseLeftButtonUp="lblAbout_MouseLeftButtonUp"/>
<Label Grid.Column="2" Grid.Row="1" Content="{Binding Source={StaticResource localisation}, Mode=OneWay, Path=.[Language.settings]}" HorizontalAlignment="Left" Foreground="#FF585858" FontSize="10" Cursor="Hand" d:LayoutOverrides="Height"/>
<Label Grid.Column="3" Grid.Row="1" Content="{Binding Source={StaticResource localisation}, Mode=OneWay, Path=.[Language.feedback]}" Foreground="#FF585858" FontSize="10" Cursor="Hand" HorizontalAlignment="Left" Width="Auto" d:LayoutOverrides="Height"/>
<Label Grid.Column="4" Grid.Row="1" Content="{Binding Source={StaticResource localisation}, Mode=OneWay, Path=.[Language.help]}" Foreground="#FF585858" FontSize="10" Cursor="Hand" HorizontalAlignment="Left" Width="Auto" d:LayoutOverrides="Height"/>
<Label Grid.Column="1" Grid.Row="1" Content="{Binding Source={StaticResource localisation}, Mode=OneWay, Path=.[Language.checkingUpdates]}" Foreground="#FF585858" FontSize="10" Cursor="Hand" d:LayoutOverrides="Height" Visibility="Collapsed"/>
</Grid>
A:
Right now, since all of your columns are using star sizing, they will all be even sized and stretched across the width.
I believe you want:
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
This will cause them to stack left to right, and "fill" at the end.
| {
"pile_set_name": "StackExchange"
} |
Q:
Google App Scripts and FusionTable
I am working on my first Google App Script (Script as Webapp) and trying to access a fusion table, but each time I try to access the fusion table I get back insufficient privileges. I am logged in as the owner of the app, so I am not sure why this is happening.
function getReports(){
var authToken = ScriptApp.getOAuthToken();
Logger.log(authToken);
var query = encodeURIComponent("Select * from " + tableId);
queryFusionTables(authToken, query);
}
function queryFusionTables(authToken, query) {
var URL = "https://www.googleapis.com/fusiontables/v1/query?sql="+query+"&key={myKey}";
Logger.log(query);
//Logger.log(authToken);
var response = UrlFetchApp.fetch(URL, {
method: "post",
headers: {
"Authorization": "Bearer " + authToken,
"X-JavaScript-User-Agent": "Google APIs Explorer",
},
});
Logger.log(response.getContentText());
return response.getContentText();
}
Does Anyone have any ideas as to why this is happening?
A:
The OAuth token returned by ScriptApp.getOAuthToken() is only authorized for the scopes required by your script, which is determined by the Apps Script services you use. For instance, if you were to use DriveApp the Google Drive API scope would be requested.
The Apps Script code doesn't know you are attempting to use the Fusion Tables API, so it didn't request that scope. However, you are in luck! Apps Script has a built-in integration with Fusion Tables, using the Fusion Tables advanced service. Simply enable the service and Apps Script will take care of the authorization for you, plus provide you with auto-complete.
| {
"pile_set_name": "StackExchange"
} |
Q:
Question about KKT conditions and strong duality
I am confused about the KKT conditions. I have seen similar questions asked here, but I think none of the questions/answers cleared up my confusion.
In Boyd and Vandenberghe's Convex Optimization [Sec 5.5.3] , KKT is explained in the following way.
I-For any differentiable (potentially non-convex) problem:
If strong duality holds, then any primal/dual (global) optimal pair must satisfy the KKT conditions (i.e., gradient of Lagrangian must vanish, points must be primal/dual feasible, and they must satisfy complementary slackness).
II-For convex problems:
If the problem is convex, then (a) any (primal/dual) points that satisfy the KTT conditions (same as above) are (global) primal/dual optimal pairs and (b) strong duality holds.
Using I and II, Boyd and Vandenberghe conclude that for convex problems that satisfy the Slater's condition (hence strong duality holds), KKT conditions are both necessary and sufficient for (global) primal/dual optimality.
Now in traditional Nonlinear Programming textbooks, the same KKT conditions are presented as first-order necessary condition for local optimality for any (differentiable, but potentially non-convex) problem. In those references, there is no discussion of dual points (instead, we treat them as Lagrange multipliers) or strong duality: (III) for any regular locally optimal (primal) point, there must exist Lagrange multipliers such that jointly they satisfy the KKT conditions (same as above).
I have three related questions:
(Q1) does III imply that the strong duality requirement in I was unnecessary? (edit: I realized that III is a necessary condition for regular local optima - but still, it would be great to hear about the relation between I and III)
(Q2) What can be said in general about the KKT conditions in differentiable nonlinear programs that do not satisfy strong duality?
(Q3) Consider a general nonlinear program (primal) with differentiable cost and constraints where strong duality does not hold. Now imagine I have found all KKT pairs for the primal. The Lagrange multipliers in my KKT pairs are clearly feasible for the dual problem. But is it also guaranteed that every regular local optima of the dual problem appears in my KKT pairs of the primal?
My guess: I guess the answer to Q1 is negative - if strong duality does not hold, regular primal (global/local) optimal points must still satisfy the KKT conditions with some Lagrange multipliers that may not have anything to do with (optimal) dual points (?).
A:
I think that your guess in (Q1) is correct.
Consider the following optimization problem:
\begin{align}
&\min_{x\in \mathbb{R}^n}\ f_0(x)\\
&\mathrm{s.t.}\ \ f_i(x) \le 0, \ i=1,2, \cdots,m\\
&\qquad h_j(x) = 0, \ j=1,2,\cdots, p
\end{align}
where $f_0$, $f_i, \forall i$ and $h_j, \forall j$ are all differentiable.
The KKT conditions are the following
\begin{align}
\nabla f_0(x^\ast) + \sum_{i=1}^m \lambda_i^\ast \nabla f_i(x^\ast) +
\sum_{j=1}^p \mu_j^\ast \nabla h_j(x^\ast) &= 0, \\
f_i(x^\ast) &\le 0, \ i = 1, 2, \cdots, m\\
h_j(x^\ast) &= 0, \ j=1, 2, \cdots, p\\
\lambda_i^\ast &\ge 0, \ i=1, 2, \cdots, m\\
\lambda_i^\ast f_i(x^\ast) &= 0, \ i = 1, 2, \cdots, m.
\end{align}
See: [1], and [2], page 356, Ch. 9.
1) If $x^\ast$ is locally optimal and $x^\ast$ is regular (regularity conditions,
or constraint qualifications), then there exists $(\lambda^\ast, \mu^\ast)$
such that the KKT conditions hold.
2) If strong duality holds, the KKT conditions are necessary optimality conditions:
if $x^\ast$ and $(\lambda^\ast, \mu^\ast)$ are primal and dual optimal,
then the KKT conditions hold.
3) For convex problems with strong duality (e.g., when Slater's condition is satisfied),
the KKT conditions are sufficient and necessary optimality conditions, i.e.,
$x^\ast$ and $(\lambda^\ast, \mu^\ast)$ are primal and dual optimal
if and only if the KKT conditions hold.
Reference
[1] https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions
[2] Chong-Yung Chi, Wei-Chiang Li, Chia-Hsiang Lin, "Convex Optimization for Signal Processing and Communications: From Fundamentals to Applications", 2017.
| {
"pile_set_name": "StackExchange"
} |
Q:
Specify a deadline with Go gRPC for peer to peer connections.
According to the gRPC documentation, deadlines can be specified by clients to determine how long the client will wait on the server before exiting with a DEADLINE_EXCEEDED error. The documentation mentions that different languages have different implementations and that some languages do not have default values.
Indeed, a quick CTRL+F for "deadline" on the Go gRPC documentation reveals no results. What I did discover was a WithTimeout on the dialer for the TCP connection.
Implemented as follows (from the helloworld example):
package main
import (
"log"
"os"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)
const (
address = "localhost:50051"
defaultName = "world"
deadline = 20
)
func main() {
// Set up a connection to the server with a timeout
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithTimeout(time.Duration(deadline)*time.Second)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)
// Contact the server and print out its response.
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
}
The code will raise an error only if the client cannot connect after 20 seconds. The output will be something as follows:
2016/05/24 09:02:54 grpc: Conn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::1]:3265: getsockopt: connection refused"; Reconnecting to "localhost:3265"
2016/05/24 09:02:54 Failed to dial localhost:3265: grpc: timed out trying to connect; please retry.
2016/05/24 09:02:54 could not greet: rpc error: code = 2 desc = grpc: the client connection is closing
As noted in the question title, the system I'm working with is peer to peer, so there is no central, always up server and therefore the retry system that gRPC implements is wonderful. However, I'm actually looking for deadlines because if the remote does connect, but the server takes > 20 seconds to respond, no exception will be raised in the WithTimeout context.
A complete win for me would be a timeout/deadline system where:
if the client cannot connect, an error is returned after timeout
if the client connects, but the server doesn't respond before timeout, an error is returned.
if the client connects, but the connection drops before timeout, an error is returned.
My feeling though is that I will need some combination of connection management plus gRPC deadline management. Does anyone know how to implement deadlines in Go?
A:
According to the WithTimeout example of context
package main
import (
"context"
"fmt"
"time"
)
func main() {
// Pass a context with a timeout to tell a blocking function that it
// should abandon its work after the timeout elapses.
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err()) // prints "context deadline exceeded"
}
}
You can change the helloworld example client code for 100ms timeout:
ctx, _ := context.WithTimeout(context.Background(), 100 * time.Millisecond)
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
| {
"pile_set_name": "StackExchange"
} |
Q:
Configure tests and coverage to run at setup
I'm supposed to configure a python package with tests and coverage.
Now, I can successfully run tests (with nosetest) and coverage (through coverage.py), but I'm a little confused on how to make them run automatically, when the package is installed or updated.
I've searched online and I edited my setup.py file so it looks something like this:
...
test_suite='nose.collector',
setup_requires=['nose>=1.0','coverage>=1.0'],
tests_require=['nose'],
...
My confusion is such that I cannot even understand if this is enough to make it work. Any help will be appreciated.
A:
My guess is that you are after a Continuous integration solution like Travis CI (or any other) that installs and runs your package against the test suite in every branch (including master).
You can take a look in GitHub at how other open source projects are doing it, for example aiohttp:
aiohttp is running their CI pipeline in Travis CI:
The configuration is at .travis.yml
As you can see there, it is
executing the test suite through the Makefile
Another project doing something similar is flask
| {
"pile_set_name": "StackExchange"
} |
Q:
VBA, Userform to alter keyword in code
Never did any userform before, but is there a way to create a form/button/cells, as you fill them in, it replaces/changes a search term in my vba code?
' Find the Node column
intColNode = 0
On Error Resume Next
intColNode = WorksheetFunction.Match("Node", .Rows(1), 0)
On Error GoTo 0
Example would be to replace the word "Node" with what the user inputs. How can I create a form where a user of spreadsheet can alter keyword to desired taste.
Any help would be appreciated
A:
Declare a variable for the user input. In this case a textbox should do the trick, then have a Submit button (Command Button in UserForm toolbox) that runs your code like the following:
Private Sub CommandButton1_Click()
Dim uVal as String
uVal = Userform1.Textbox1.Value
intColNode = 0
On Error Resume Next
intColNode = WorksheetFunction.Match(uVal, .Rows(1), 0)
On Error GoTo 0
Unload Me
End Sub
Good page for learning how to create a UserForm
| {
"pile_set_name": "StackExchange"
} |
Q:
Select query from mysql database
Hello I am having a hard time trying to SELECT all of the information I need from two tables, the following two tables are:
Person: |id|fname|mname|lname| and Related: |id1|id2|relationship|
and I want the following to be displayed back from the SELECT query:
|id1|fname(of id1)|id2|fname(of id2)|relationship|
SO the Related table has two id's that are FOREIGN KEYS to Person(id), and I need to
SELECT id1, (id1's first name), id2, (id2's firstname), and the relationship.
I've tried something like this and a few other SELECT queries but I can't seem to get it to work:
SELECT p.fname, r.id1, r.id2, r.relationship
FROM Person p, Related r
INNER JOIN Related ON first.id = r.id1
INNER JOIN Related ON second.id = r.id2;
Any help will be greatly appreciated! Thank you!
A:
You're joining on Related thrice. You only need to join once, and you need to join on Person again.
SELECT id1, p1.fname, id2, p2.fname, relationship
FROM Person p1
JOIN Related ON (p1.id = id1)
JOIN Person p2 ON (id2 = p2.id)
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Development: How to set a timer to multiple checkboxes when they're unchecked?
How do I set a timer on all of the checkboxes at the same time if I were to uncheck them all at once? If I uncheck "checkbox1" and set up a timer for that checkbox, wouldn't unchecking "checkbox2" override that timer?
I have 3 checkboxes and 1 textview,
All checkboxes in the state of checked.
I want to create a timer when any of them is unchecked.
I wish to have a independent timer for each checkbox
For example, when "checkbox1" is unchecked, I wish to create a timer that lasts for 5 minutes and when it only has 1 minute left, I want it to change the textview's text to "you have 1 minute left" as a reminder that the timer is ending soon.
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (!buttonView.isChecked()) {
new CountDownTimer(300000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
if (millisUntilFinished < 60000) {
map.get(buttonView).setText("1 min left!");
} else if (millisUntilFinished < 30000) {
map.get(buttonView).setText("30 sec left!");
} else {
map.get(buttonView).setText(millisUntilFinished/60000 + ":" + (millisUntilFinished%60000)/1000);
}
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
map.get(buttonView).setText("Spawned!");
}
}.start();
} else if (buttonView.isChecked()) {
// cancel the timer basically
}
}
Unlike what i originally wanted to do, i've created a textview for each checkbox, so it wouldn't be confusing to the user. I've created a map which contains (Checkbox, TextView). How do i cancel the timer when the checkbox is unchecked? do i make an arraylist? if so, where would i add the timer into the arraylist?
A:
My main concern is...how do i set a timer on all of them at the same time if i were to uncheck them all at once?
You can use CountdownTimer. Set an onCheckedChangeListener on your CheckBoxesand create a new instance of your CountdownTimer each time.
if i uncheck "checkbox1" and set up a timer for that checkbox, wouldn't unchecking "checkbox2" override that timer?
Not if you create separate instances of the CountdownTimer for each one it shouldn't give you a problem.
You could store these instances of CountdownTimer in an Array if you needed to so you could iterate over them and cancel and restart each one if you needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get jackson to find my key deserializer?
Here's my class (getters and setters omitted):
public class ClassWithAMap {
@JsonProperty("map")
@JsonDeserialize(keyUsing = RangeDeserializer.class)
private Map<Range<Instant>, String> map;
@JsonCreator
public ClassWithAMap(Map<Range<Instant>, String> map) {
this.map = map;
}
}
The RangeSerializer looks like this:
public class RangeDeserializer extends KeyDeserializer {
public ObjectMapper objectMapper() {
return new ObjectMapper()
.registerModules(
new JavaTimeModule(),
new Jdk8Module(),
new GuavaModule(),
new ParameterNamesModule());
}
@Override
public Range<Instant> deserializeKey(String key, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
TypeReference<Range<Instant>> typeRef = new TypeReference<Range<Instant>>() {
};
Range<Instant> range = objectMapper().readValue(key, typeRef);
return range;
}
}
And the main code that uses these is this:
Map<Range<Instant>,String> map = new HashMap<>();
Range<Instant> key = Range.greaterThan(Instant.now());
map.put(key, "some value");
ClassWithAMap classWithAMap = new ClassWithAMap(map);
String jsonInput = objectMapper()
.writerWithDefaultPrettyPrinter()
.writeValueAsString(classWithAMap);
ClassWithAMap classWithMap = objectMapper()
.readValue(jsonInput,
ClassWithAMap.class);
The last statement gives me this error:
InvalidDefinitionException: Cannot find a (Map) Key deserializer for type [simple type, class com.google.common.collect.Range<java.time.Instant>]
and, sure enough, it never calls my deserializer. I've missed some step registering the deserializer, though I've compared it to a similar setup with a custom class instead of Range<Instant> which works fine, an I can't see the difference. Anyone know what I did wrong? I'm guessing something to do with the generic but I haven't got further.
I'm using jackson 2.9.9 and Java 1.8.
A:
You need to move all annotations to constructor:
class ClassWithAMap {
private Map<Range<Instant>, String> map;
@JsonCreator
public ClassWithAMap(
@JsonProperty("map")
@JsonDeserialize(keyUsing = RangeDeserializer.class)
Map<Range<Instant>, String> map) {
this.map = map;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof by Induction Question including Rational Numbers
I just recently covered 'rational numbers' in class and was assigned the following question to solve using induction for n, so that for all $q \in \mathbb{Q}$ \ {1}:
$$\sum_{k=0}^n q^k = \frac{q^{n+1}-1}{q-1}$$
I am not entirely sure on where to start, since up to this point I've only done proofs by induction involving natural numbers only. I've thought about leaving the variable q as it is, and doing
n = 1
then assuming statement is true for n, solve for n + 1
where $n \in \mathbb{N}$, but it leaves me with a dead end, since there are too many unknown variables involved.
I hope someone can help me with this question and explain to me what the best approach would be and why!
Thank you!!
A:
Your attempt is right! You do not have to change the $q$; leave it as it is and do the standard induction regarding to $n$.
Therefore lets start with our basis case $n=0$:
$$\begin{align}
\sum_{k=0}^0q^k&=\frac{q^{0+1}-1}{q-1}\\
1&=1
\end{align}$$
Next consider the new values $n=m$ and $n=m+1$ which corresponde to the two equations
$$\begin{align}
\sum_{k=0}^{m}q^k&=\frac{q^{m+1}-1}{q-1}\\
\sum_{k=0}^{m+1}q^k&=\frac{q^{m+2}-1}{q-1}
\end{align}$$
Here the first one is our assumption the second one our hypothesis. Howsoever lets split up the second sum as the following
$$\sum_{k=0}^{m+1}q^k=\underbrace{\sum_{k=0}^{m}q^k}_{=\text{assumption}}+q^{m+1}$$
As we can see the remaining sum equals our assumption. Therefore we can replace it by the given fraction from above. This yields to
$$\sum_{k=0}^{m}q^k+q^{m+1}=\frac{q^{m+1}-1}{q-1}+q^{m+1}=\frac{q^{m+1}-1+q^{m+2}-q^{m+1}}{q-1}=\frac{q^{m+2}-1}{q-1}$$
And thus we have shown that from our assumption the hypothesis follows and therefore we are done.
| {
"pile_set_name": "StackExchange"
} |
Q:
"The most rude" or "the rudest"?
Rude comparative ruder superlative rudest
But the most rude is applied in the following title:
The Most Rude, ill-Mannered, and Humiliating Plays in NBA History!
Can we use both forms for any circumstance?
A:
The Most Rude, ill-Mannered, and Humiliating Plays in NBA History!
If we use rudest here, we would have to still use "most" for the other adjectives:
The Rudest, Most ill-Mannered, and Most Humiliating Plays in NBA History!
The title uses "most" to apply to all three adjectives, because "ill-Manneredest" is a word I've never seen nor would wish to see in a title, unless written in jest, and there's no "humiliatingest".
Hence, the most logical, or logicalest, way is just to attach "most" at the start of the title.
| {
"pile_set_name": "StackExchange"
} |
Q:
What to use for Python string.find?
The documentation for Python 2.7 lists string.find as a deprecated function but does not (unlike atoi and atol) provide an alternative.
I'm coding in 2.7 at the moment so I'm happy to use it but I would like to know:
what is it going to be replaced with?
is that usable in 2.7 (if so, I'll use it now so as to avoid recoding later)?
A:
A lot of methods in string have been replaced by the str class. Here is str.find.
A:
Almost the entire string module has been moved to the str type as method functions.
Why are you using the string module, when almost everything you need is already part of the string type?
http://docs.python.org/library/stdtypes.html#str.find
The string type -- and it's methods -- is not deprecated. Indeed, it will me morphed to include Unicode in Python 3.
| {
"pile_set_name": "StackExchange"
} |
Q:
New closure on scriptblock
Consider this code:
PS> $timer = New-Object Timers.Timer
PS> $timer.Interval = 1000
PS> $i = 1;
PS> Register-ObjectEvent $timer Elapsed -Action { write-host 'i: ' $i }.GetNewClosure()
PS> $timer.Enabled = 1
i: 1
i: 1
i: 1
...
# wait a couple of seconds and change $i
PS> $i = 2
i: 2
i: 2
i: 2
I assumed that when I create new closure ({ write-host 'i: ' $i }.GetNewClosure()) value of $i will be tied to this closure. But not in this case. Afer I change the value, write-host takes the new value.
On the other side, this works:
PS> $i = 1;
PS> $action = { write-host 'i: ' $i }.GetNewClosure()
PS> &$action
i: 1
PS> $i = 2
PS> &$action
i: 1
Why it doesn't work with the Register-ObjectEvent?
A:
Jobs are executed in a dynamic module; modules have isolated sessionstate, and share access to globals. PowerShell closures only work within the same sessionstate / scope chain. Annoying, yes.
-Oisin
p.s. I say "jobs" because event handlers are effectively local jobs, no different than script being run with start-job (local machine only, implicit, not using -computer localhost)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I know if I'm abstracting graphics APIs too tightly?
When making a renderer that supports multiple graphics APIs, you would typically want to abstract your code in some sort of low level library that is tied with some graphics API like OpenGL, Vulkan, D3D11 and so on;
They work very differently from each other, so making a good generic API becomes essential;
I've read that you would typically want to use a "back-end" that implements the basic functionality for each API you want to support, and a "front-end" which is what is used by the programmer to draw stuff on the screen.
How do I know if I'm making too much of a tight abstraction?
A:
First of all, consider if it is actually worth it to support more than one graphics API. Just using OpenGL will cover most platforms and will be "good enough" for all but the most graphically ambitious projects. Unless you work for a very large game studio which can afford to sink several thousand person-hours into implementing and testing multiple rendering backends and unless there are some DirectX or Vulcan specific features you really want to show off, it is usually not worth the hassle. Especially considering that you can save a lot of work by using an abstraction layer someone else created (a 3rd party library or game engine).
But let's assume that you already evaluated your options and came to the conclusion that it is both viable and worth the time to roll your own.
Then the main judge of your abstraction layer's software architecture are your front-end programmers.
Are they able to implement the game systems they want to implement without having to wonder about any low-level details?
Are they able to completely ignore that there is more than one graphics API?
Would it theoretically be possible to add yet another rendering backend without changing any of the front-end code?
If so, you succeeded.
A:
Start by identifying what you actually need out of the "wrapper" part of the API. It's generally very, very simple: you need the basic resources (buffers, shaders, textures, pipeline state) and a way to use those resources to construct a frame by submitting some draw calls.
Try to keep any high-level logic out of the wrapper portion of the API. If you implement a clever scene culling technique in this portion of the API, well now you are on the hook to duplicate that logic in all of the backend implementations. That's a lot of extra effort, so keep it simple. Scene management should be part of a higher-level portion of the API that uses the wrapper rather than being part of the wrapper itself.
Choose the targets you will support and understand them. It's hard to write decent wrappers for "everything," and you probably don't need to (arguably you don't need to write a single wrapper, either, as noted in Philipp's answer). It's almost impossible to write a decent wrapper if you don't know the APIs you're going to wrap already.
Evaluate the state of your API regularly. It should in general have a smaller surface area than the underlying wrapped APIs; if you find yourself creating one-to-one wrapper types for every D3D structure or every OpenGL function call you are probably veering off course.
Look at what work has gone before. Sokol and BGFX are APIs that provide levels of agnosticism that may be useful to you, and are relatively easy to understand (the former especially).
A:
Another point not yet mentioned which you should consider is what your performance goals are. If your goal is to have a graphics library that will yield good performance out of a cheap hardware platform, but also be usable on a variety of platforms that are vastly more powerful but use a different API, it may make sense to design your API around whatever abstractions are used natively on the platform where performance is an issue. Even if this causes a 50% speed degradation on the more powerful platforms, it may be worth it if it allows a 20% speed improvement on the platform where performance matters most.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSFileManager - Swift - File Browser
I am new at ios development and I am trying to create an app in swift that will list all the files in the directory (all the files are PDF) and the user to be able to open them.
I have googling this for a the past two days and I am super confused. Can anyone suggest a tutorial or steps I would need to get this to work.
I have started with this in my ViewController.swift file:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
class func defaultManager()->NSFileManager{
}
}
I just don't know what to do next, very sad I know. I would appreciate any or all help.
Thanks,
J
A:
let manager = NSFileManager.defaultManager()
var array = manager.contentsOfDirectoryAtPath(_ path: String,
error error: NSErrorPointer) -> [AnyObject]?
Swift 3.0 version
let manager = FileManager.default
let installed_files = try manager.contentsOfDirectory(atPath: "/Applications/")
| {
"pile_set_name": "StackExchange"
} |
Q:
How to wrap text when inporting from MySQL database, not before?
I have a problem related with linebreaks of an inported text, previously inserted in MySQL using the classic PHP - HTML form method.
The problem is the following. I want to load the text saved in MySQL databe into a "news" section in my web page. The thing is that my web page has a PC version and a mobil version, each one with different widths.
So, I don't want to insert linebreaks when I submit the text to MySQL (I mean the line-breaks the form will submit if the text line width excedes a hipotethical "cols" width, assuming I'd do a "physhical" or "hard" wrap; the manually inserted line-breaks to separate parragraphs I want to keep of course) because, as far as I know, you have to specify "cols", which is a parameter that will tell the width of the lines before doing the linebreaks.
This is not interesting, because the text fields on my "news" sections will have different widths, as I've told you, so importing text with linebreaks from MySQL won't adjust the the two different "news" sizes in my web.
What I need is to upload text to MySQL with no linebreaks, and then, let the two "news" sections in my web do the formatting of the text.
I though this would be easy, as I'm just parsing the saved text in MySQL databse into a <div> tag with a specified width. But the thing is that the text overflows the <div> container width every time.
This is what I'm using as the text input in the HTML form:
<textarea name="STORY" wrap="physical">EXAMPLE</textarea>
To inject the news in MySQL I use the typical PHP:
$var = "INSERT INTO exampleTable ('story') VALUE ($_POST['STORY']);
To load the saved text, I just echo the value of a variable that imports the text from the story field of MySQL database between div tags:
echo "<div>".$story."</div>";
As you can see, because I don't wan´t to use a "hard" wrap when I insert the text from the from in MySQL to avoid inserting line-breaks in the lines that otherwise would exced the "cols" width, I use a "phisycal" wrap, but I don't specify "cols", so I think that should prevent the form from inserting line-breaks other than the ones I do manually (presing "enter" key).
But the resulting text, when I echo it, will overflow my div width, as I've told you before.
Shouldn't the div width wrap the text inside of itself?
Should I delete the wrap="physhical" attribute from the form?
A:
First, please note that you're insertion into the database is very likely to be insecure, and will probably result in SQL Injections.
To remove every linebreak, you can do things like that:
echo "<div>".str_replace("\n", "", $story)."</div>";
| {
"pile_set_name": "StackExchange"
} |
Q:
Clojure load-file on repl and call -main with arguments
I've done some coding in clojure inside core.clj which have a -main method that can take 0 or more arguments:
(defn -main
"dequeue function"
[& args]
I'm loading this clj file with:
(load-file "src/exercise/core.clj")
And then i'm trying to learn how to call this within repl in order to develop core_test.clj (if there is any tips about how to develop this auto tests, please give me some hints as well). What I'm trying to do now is:
(-main "resources\\sample-input.json" "a")
But this is printing "Arguments 0" which is a message that I told the code to print just to see how many arguments are being passed with
(println "Arguments" (count *command-line-args*))
How am I suposed to do this?
Thanks!
A:
i'm trying to learn how to call this within repl in order to develop core_test.clj
Usually you'd write other functions that are called from -main and test those rather than the app's entry point -main.
But you should be able to call -main like any other function. I have a src/sandbox/main.clj file:
(ns sandbox.main)
(defn -main [& args]
(prn args))
Starting a REPL in the project folder, I can call -main like this:
(use 'sandbox.main) ;; (load-file "src/sandbox/main.clj") also works
=> nil
(in-ns 'sandbox.main)
=> #object[clojure.lang.Namespace 0x67ccce04 "sandbox.main"]
(-main "some" "args")
;; ("some" "args")
=> nil
There's a key difference in my example though: it's printing -main's args binding; *command-line-args* is nil because you're not running the code from the command line with args, you're running it from a REPL.
Regardless, it's probably a better idea to use an existing library to work with CLI args rather than *command-line-args* directly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pinning a pointer to a managed variable
Currently, I have this code:
class SO
{
public SO()
{
var ptrManager = new PointerManager();
int i = 1;
ptrManager.SavePointer(ref i);
Console.WriteLine(i); // prints 1
i = 2; //change value to 2 within the current scope
Console.WriteLine(i); // prints 2
ptrManager.SetValue(3); // change value to 3 in another (unsafe) scope
Console.WriteLine(i); // prints 3
}
}
unsafe class PointerManager
{
private int* ptr;
public void SavePointer(ref int i)
{
fixed (int* p = &i)
{
ptr = p;
}
}
public void SetValue(int i)
{
*ptr = i;
}
}
First, I tell the PointerManager to create a pointer pointing to my int i.
This way, later, i'll be able to tell the PointerManager to change the value of i, without having to pass i in again.
This seems to work well so far. However, I've read that if the GC decides to move i around in memory, then my pointer ptr will become invalid, and subsequent calls to SetValue will have unpredictable behaviour.
So, how do I prevent GC from moving i around? Or, alternatively, is there a better way of accomplishing my goal?
I've also been told that simply adding GCHandle.Alloc(i, GCHandleType.Pinned); will work, but that doesn't seem right...
Edit: To be more specific, GCHandle.Alloc would be called at the beginning of the SavePointer method.
A:
Generally you do not want to prevent the GC from moving around anything - especially in your case (transactional objects), where I would rather consider options like:
making objects savable+restorable=serializable
doing it with some sort of manager (maybe this fits well to the idea you had with pointers) that you can pass closures!
Second option explained:
class VariableManager
{
private Action<int> setter;
public void VariableManager(Action<int> setter)
{
this.setter = setter;
}
public void SetValue(int i)
{
setter(i);
}
}
Simply create the manager via new VariableManager(i => yourInt = i) and viola - there you have your desired semantics without pointers!
| {
"pile_set_name": "StackExchange"
} |
Q:
unable to filter on a specific string pattern and unable to change the index in pandas
I have a dataframe as below:
customer_data =
Account ID Account Name Account Status gb
1-ABC ABC Customer Active 90
2-XYZ XYZ Customer Inactive 100
1-CBA CBA Indirect - Active 50
2-GHC GHC Direct - Inactive 67
For
print(customer_data.dtypes)
Output is
gb int64
dtype: object
For
print(customer_data.columns)
Output is
Index(['gb'], dtype='object')
I am trying to have two dataframes, one with those accounts which have text Active in Account Statusand other those which have string Inactive in Account Status
I tried this
only_active = customer_data[customer_data['Account Status'].str.contains("Active")]
and
only_inactive = customer_data[customer_data['Account Status'].str.contains('Inactive')]
getting error like this
KeyError: 'Account Status'
Please help me on this, I want two dataframes, one with those accounts which have text Active in Account Statusand other those which have string Inactive in Account Status
A:
If your dataframe looks like
Account ID | Account Name | Account Status | gb
but customer_data.columns only contains ['gb'], then your other columns are in a MultiIndex from some groupby or similar earlier in the code. To get those indices back as columns, you can use customer_data.reset_index(), then your columns will be usable in filtering without using index or multiindex methods
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a faster way to get the colors in a screen-shot?
I have piece of code, and what it does is find the colors of an image (or section of the screen) and if the R G and B color's are greater than 127 it put's a 1 in the corresponding position of a 2D int array. Here is the segment I have now, but it is obviously extremely slow. Is there a better way to do this?
private void traceImage(){
try{
Robot r = new Robot();
b = new int[470][338];
for(int y = 597; y < 597+469; y++)
{
for(int x = 570; x < 570+337; x++)
{
if(r.getPixelColor(x,y).getRed() > 127 &&
r.getPixelColor(x,y).getGreen() > 127 &&
r.getPixelColor(x,y).getBlue() > 127)
{
b[y-597][x-570] = 1;
}
else
{
b[y-597][x-570] = 0;
}
}
}
}
catch(Exception ex){System.out.println(ex.toString());}
}
There must be a faster way to do this using the values above. b is the int array and it is initialized in this segment. r is a robot that I use to find the color of the pixel on the screen. x and y should be self explanatory.
Thanks Mikera! This is the end result I got based on your answer:
private void traceActionPerformed(java.awt.event.ActionEvent evt) {
try{
Robot r = new Robot();
BufferedImage image = r.createScreenCapture(new Rectangle(597,570,470,337));
b = new int[image.getWidth()][image.getHeight()];
for(int y=0;y<image.getWidth();y++){
for(int x=0;x<image.getHeight();x++){
if(image.getRGB(y,x)==-1){
b[y][x]=0;
}
else{
b[y][x]=1;
}
}
}
System.out.println("Done");
}
catch(Exception ex){System.out.println(ex.toString());}
}
The -1 in the if else statement apparently finds the value of black pixels like I wanted.
A:
You should use Robot.createScreenCapture() to capture the entire subimage in one go.
Then you will be able to query the individual pixels in the subimage much faster, e.g. using BufferedImage.getRGB(x,y)
Interestingly your specific operation has a very fast bitwise implementation: just do ((rgb & 0x808080) == 0x808080)
| {
"pile_set_name": "StackExchange"
} |
Q:
Nested options doesn't print all path
When I click on an option, the select only shows the option value. Is there a way in angular to show the full path of a select with nested options?
<select>
<optgroup label="A">
<option>1</option>
<option>2</option>
<option>3</option>
</optgroup>
<optgroup label="B">
<option>4</option>
<option>5</option>
<option>6</option>
</optgroup>
</select>
For example if I select option 5, the standard select will show only value "5". I want "B / 5".
A:
You can achieve it by directive,
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myapp', []);
app.directive('getVal', function () {
return function (scope, ele) {
var element = angular.element(ele);
element.change(function (e) {
var y = element.val();
var selected = angular.element(':selected', element);
var optionLabel = selected.closest('optgroup').attr('label');
angular.element('#output').text(optionLabel + ' / ' + y);
});
};
});
</script>
<body ng-app="myapp">
<select get-val>
<optgroup label="A">
<option>1</option>
<option>2</option>
<option>3</option>
</optgroup>
<optgroup label="B">
<option>4</option>
<option>5</option>
<option>6</option>
</optgroup>
</select>
<div id="output"></div>
</body>
</html>
This will output "B / 5" if you select 5.
| {
"pile_set_name": "StackExchange"
} |
Q:
The structure $(\mathbb N, <, f)_{f\in \mathcal F}$ seems to have no elementary extension
This is exercise 2.3.1 (2) from Tent/Ziegler, A Course in Model Theory.
Let $\mathcal F$ be the set of all functions $\mathbb N \to \mathbb N$. Show that $(\mathbb N, <, f)_{f\in \mathcal F}$ has no countable proper elementary extension.
My approach was to assume we have some proper elementary extension $\mathfrak A$ with $\mathbb N \subsetneq A$. Choose $a \in A \setminus \mathbb N$. As we have a first order sentences true in $\mathbb N$ stating that there is no maximal element, either $a$ is between two natural numbers $n,m$ with $m = n+1$, or comes before every natural number. In the first case let $\overline n, \overline m : \mathbb N \to \mathbb N$ the constant function giving $n$ and $m$. Then in $(\mathbb N, <, f)_{f\in \mathcal F}$ the sentence $\exists x \forall y ( \overline n(y) < x < \overline m(y) )$ is false, but in $\mathfrak A$ it is true. Hence this case could not arise. Similar if $a$ comes before every natural number, using $\overline 0 : \mathbb N \to \mathbb N$ I can give a sentence true in this extension, but not true in $\mathbb N$.
So, in consequence there would be no elementary extension at all. But this contradicts the Theorem stated on these slides (see slide number 7), that every infinite model has a proper elementary extension.
So what is wrong with my above reasoning? Why this contradiction?
A:
There seems to be some confusion here. Let $\mathcal{M} = (\mathbb{N}, < f)_{f \in \mathcal{F}}$. We want to show that if $\mathcal{M} \prec \mathcal{N}$, then $|\mathcal{N}| > \aleph_0$ (by upward Löwenheim–Skolem/Ultrapower construction, we know such $\mathcal{N}$ exists). Any element in $a \in \mathcal{N} \backslash \mathcal{M}$ will be greater than any natural number (in above, you say that it must be less than any natural number or inbetween two of them).
Now, one has to show that $|\mathcal{N}| > \aleph_0$. Choose $a \in \mathcal{N} \backslash \mathcal{M}$. We know that $M \models \forall x \exists y f(x) = y$ for every $f \in \mathcal{F}$. Since $M \prec \mathcal{N}$, we know that for every $f \in \mathcal{F}$, $f(a) \in \mathcal{N}$. Now, it's your job to show that $|\mathcal{N}| > \aleph_0$.
(As a hint, you need to somehow incorporate the ordering.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Using layered rendering with default framebuffer
I know that we can attach a layered texture which is:
A mipmap level of a 1D/2D texture array
A mipmap levevl of a 3D texture
A mipmap levevl of a Cube Texture/ Cube Texture Array
to a FBO and do layered rendering.
The OpenGL wiki also says "Layered rendering is the process of having the GS send specific primitives to different layers of a layered framebuffer."
Can default framebuffer be a layered framebuffer? i.e Can I bind a 3d texture to the default FB and use a geometry shader to render to different layers of this texture?
I tried writing such a program but the screen is blank and I am not sure if this is right.
If it is not, what is possibly happening when I bind default FB for layered rendering?
A:
If you use the default framebuffer for layered rendering, then everything you draw will go straight to the default framebuffer. They will behave as if everything were in the same layer.
OpenGL 4.4 Core Specification - 9.8 Layered Framebuffers - pp. 296
A framebuffer is considered to be layered if it is complete and all of its populated attachments are layered. When rendering to a layered framebuffer, each fragment generated by the GL is assigned a layer number.
[...]
A layer number written by a geometry shader has no effect if the framebuffer is not layered.
| {
"pile_set_name": "StackExchange"
} |
Q:
Each model Ember not listing the models in template
I am using Ember.RSVP.hash to create different models in the same route, i successfully create the model records in the store, i can see the data in the console.
The problem is that i can only list one the two models in my template. ( repos name but not the commit message ).
Here the code
Route
var gitrepositoriesPromise = function() {
return Ember.$.ajax(reposUrl, {
success: function(repos) {
return repos.map(function(repo) {
return store.createRecord('repo', {
name: repo.name,
description: repo.description
});
});
},
error: function(reason) {
reject(reason);
}});
};
var gitactivitiesPromise = function() {
return Ember.$.ajax(eventsAct, {
success: function(events) {
return events.filter(function(event) {
return event.type == 'PushEvent';
}).forEach(function(item){
return item.payload.commits.map(function(commit){
return store.createRecord('commit', {
message: commit.message,
});
});
});
},
error: function(reason) {
reject(reason);
}});
};
return Ember.RSVP.hash({
commits: gitactivitiesPromise(),
repos: gitrepositoriesPromise()
});
Template
<ul>
{{#each model.repos}}
<li>{{name}}</li>
{{/each}}
</ul>
<ul>
{{#each model.commits}}
<li>{{message}}</li>
{{/each}}
</ul>
So the problem must be here in
{{#each model.commits}}
<li>{{message}}</li>
{{/each}}
What am i doing wrong? here the jsbin reproducing the issue.
A:
Ok, so problem was in your gitactivitesPromise function. I've modified your approach to use Ember.RSVP.hash:
var gitactivitiesPromise = function() {
return new Ember.RSVP.Promise(function (resolve) {
Ember.$.ajax(eventsAct, {
success: function(events) {
var result = [];
events.filter(function(event) {
return event.type == 'PushEvent';
}).forEach(function(item){
item.payload.commits.map(function(commit){
result.push(store.createRecord('commit', {
message: commit.message,
}));
});
});
resolve(result);
},
error: function(reason) {
reject(reason);
}
});
});
};
This lets you to access message this way in template:
Commits:
<ul>
{{#each model.commits}}
<li>{{this.message}}</li>
{{/each}}
</ul>
Result:
Working demo.
| {
"pile_set_name": "StackExchange"
} |
Q:
tclhttpd.3.5.1 shows page source (Windows)
I am playing with tclhttpd web server and found a strange error
I start tclhttpd at default port 8015
Open firefox and navigate to http://localhost:8015
I see source of my index.html file instead of web page.
index.html is simple ( < and > are skipped ):
html
head
title
TEST
/title
/head
body
H1 TEST HEADER /H1
/body
/html
Any ideas?
I have checked with the curl:
* About to connect() to localhost port 8015 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8015 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.21.3 (i386-pc-win32) libcurl/7.21.3
OpenSSL/0.9.8q zlib/1.2.5
> Host: localhost:8015
> Accept: */*
Server Response
HTTP/1.1 200 Data follows
Date: Thu, 12 Apr 2012 14:16:47 GMT
Server: Tcl-Webserver/3.5.1 May 27, 2004
Content-Type: text/plain
Content-Length: 130
Last-Modified: Thu, 12 Apr 2012 14:14:30 GMT
So, tclhttpd returns text/plain instead of text/html
Linux case
I have tried to check what would happened with Linux.
As tclkttpd is wrapped in kit I made the same test under Linux.
It looks like everything works fine.
curl -G -v localhost:8015
* About to connect() to localhost port 8015 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8015 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.21.7 (i686-pc-linux-gnu) libcurl/7.21.7
OpenSSL/1.0.0d zlib/1.2.5 libssh2/1.2.7
> Host: localhost:8015
> Accept: */*
Server response
HTTP/1.1 200 Data follows
Date: Thu, 12 Apr 2012 17:25:29 GMT
Server: Tcl-Webserver/3.5.1 May 27, 2004
Content-Type: text/html
Content-Length: 125
Last-Modified: Thu, 12 Apr 2012 17:14:04 GMT
Deep research
I have modified some of the source files, to dump more information:
proc Mtype {path} {
global MimeType
set ext [string tolower [file extension $path]]
Stderr "Mtype: path $path ext $ext"
if {[info exist MimeType($ext)]} {
Stderr "MimeType($ext) exists."
Stderr "Print MimeType "
set lst [lsort [array names MimeType]]
foreach {i} $lst {
Stderr " $i $MimeType($i)"
}
return $MimeType($ext)
} else {
Stderr "Mimetype not found. ext $ext"
Stderr "Print MimeType "
set lst [lsort [array names MimeType]]
foreach {i} $lst {
Stderr " $i $MimeType($i)"
}
return text/plain
}
}
When I query http://localhost:8015
I got following output:
Linux
Mtype: path /home/a2/src/tcl/tcl_www/doc/index.html ext .html
MimeType(.html) exists.
Print MimeType
text/plain
.ai application/postscript
.aif audio/x-aiff
.aifc audio/x-aiff
....
.hqx application/mac-binhex40
.htm text/html
.html text/html
.i86pc application/octet-stream
...
Default cmd Doc_text/html
Windows
Look for Tcl proc whos name match the MIME Content-Type
Mtype: path M:/apr/tcl_www/doc/index.html ext .html
Mimetype not found. ext .html
Print MimeType
.man application/x-doctool
Mtype M:/apr/tcl_www/doc/index.html returns Doc_text/plain
So it look like there are troubles with reading mime.types
A:
I have checked with the fresh tclkitsh and tclhttpd
tclkitsh-8.5.9-win32.upx.exe ( http://code.google.com/p/tclkit/downloads/list )
tclhttpd5.3.1.kit
Everything works.
If I use my "old" version of tclkitsh-win32.upx.exe
I receive text/plain instead of text/html
So it looks like there is a bug in my old wrapped interpretor, that leads to the problem with not reading mime.types.
| {
"pile_set_name": "StackExchange"
} |
Q:
sorting as well as removing duplicacy
<?xml version="1.0"?>
<project name="sortlist11" default="sortlist11">
<taskdef resource="net/sf/antcontrib/antcontrib.properties" />
<property name="my.list" value="z,y,x,w,v,u,t" />
<property name="my.list1" `value="5,3,6,1,8,4,6" `/>
<target name="sortlist11">
<sortlist property="my.sorted.list" value="${my.list}" delimiter="," />
<sortlist property="my.sorted.list1" value="${my.list1}" delimiter="," />
<echo message="${my.sorted.list}" />
<echo message="${my.sorted.list1}" />
</target>
</project>
here second echo print 1,3,4,5,6,6,8 but how can i remove redundancy?
A:
Every language running in JVM via Bean Scripting Framework may be used in ant with full access to the ant api. Here's a solution with Groovy for your problem =
<project>
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
<property name="my.list" value="z,y,x,w,v,u,t"/>
<property name="my.list1" value="5,3,6,1,8,4,6"/>
<groovy>
properties.'my.sorted.list' = properties.'my.list'.split(',').sort().toString()
properties.'my.sorted.list1' = properties.'my.list1'.split(',').toList().unique().sort().toString()
</groovy>
<echo>
$${my.sorted.list} => ${my.sorted.list}
$${my.sorted.list1} => ${my.sorted.list1}
</echo>
</project>
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating Query on statement (TSQL)
I've got a log file with different functions and steps:
What I need is the Duration of the whole function.
This is my Statement so far:
SELECT [Id]
,[Func]
,[Step]
,[Timestamp]
,CAST((SELECT [Timestamp]
FROM [LiPimDb].[dbo].[Log_Export_Catalog]
WHERE [Id] = [Log].[Id]+1)-[Timestamp]AS TIME(3)) AS Duration
FROM [LiPimDb].[dbo].[Log_Export_Catalog] AS [Log]
WHERE Func = 'SP_Create_Export_Catalog'
Do I Need to get a subquery and then get the sum of Duration?
A:
It looks like simple GROUP BY is all you need:
SELECT
Func
,DATEDIFF(second, MAX(Timestamp), MIN(Timestamp)) AS DurationSeconds
FROM [LiPimDb].[dbo].[Log_Export_Catalog] AS [Log]
WHERE Func = 'SP_Create_Export_Catalog'
GROUP BY Func
Remove the WHERE filter to see the duration for each function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java - check if date format is acceptable and compare dates based on it
I want to create a simple function that gets 2 params - date format(dd/mm/yyyy, dd-mm-yyyy etc...) and a string that in this format(1/4/2015, 1-4-2015).
First of all is there a way to check if the format is acceptable by SimpleDateFormat and the next step if the dateInString is today, here is my code:
public boolean checkDate(String dateInString, String format){
boolean result = false;
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
//parse the string to date
Date inputDate = dateFormat.parse(dateInString);
//check if the date is today using the format
//if the date is today then
result = true;
return result;
}
A:
You could use this Utility class (DateUtils) with this implementation:
public boolean checkDate(String dateInString, String format){
try {
return DateUtils.isToday(new SimpleDateFormat(format).parse(dateInString));
} catch (ParseException e) {
return false;
}
}
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.