id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23534700
|
from abc import ABCMeta
class MyClass(metaclass=ABCMeta):
pass
x = MyClass()
A: From the docs (https://docs.python.org/3/library/abc.html#abc.ABCMeta):
A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden
As you have no abstract methods or properties in MyClass, it can be instantiated.
| |
doc_23534701
|
Req:
1) Player should have built in controller.
2) Should be able to show the video loading symbol
3) Video should have the video image with play button.
Can anyone help me pls?
A: This is the one that I use and it supports Video source from file as well as stream source. So far, this is the best I found for Xamarin forms.
https://components.xamarin.com/gettingstarted/video-player
A: Have a look at LibVLCSharp. Official VLC bindings for Xamarin/.NET.
Samples here: https://code.videolan.org/mfkl/libvlcsharp-samples
Disclaimer: I am the maintainer.
| |
doc_23534702
|
cur = con.cursor()
for item in self.button_array:
if item.isChecked():
productName = item.text()
custCommand = '''SELECT COUNT(*) FROM Customers''' # counts the number of rows in the table Customers
cur.execute(custCommand)
newCustomerID = cur.fetchall()[0][0] + 1000 # gives the order an CustomerID that is +1
print(newCustomerID)
con.close()
print(productName)
con = lite.connect(db)
cur = con.cursor()
findProductID = '''SELECT ProductID FROM Products WHERE ProductName = ''' + productName #searches for ProductID from the database and compares it to the product name
cur.execute(findProductID)
resultProductID = cur.fetchall()
print(resultProductID)
con.close()
I'm trying to get it so it compares the column ProductName (just a column with flower names in it) in the table to the text of the labels for the flowers but it keeps coming up with this:
<class 'sqlite3.OperationalError'> no such column: Tulips <traceback object at 0x03FAA4E0>
(Tulips is just an example of a flower available)
So it seems to think that the text is meant to be a column name instead of an item in a column and I'm not too sure how to get it to work, I'm sorry for explaining it poorly but I don't really know what else to do since I'm not that experienced with this.
Edit:
So I tried putting the statement in the execution and using 'LIKE ?' instead
con = lite.connect(db)
cur = con.cursor()
findProductID = '''SELECT ProductID FROM Products WHERE ProductName = LIKE ?''' #searches for ProductID from the database and compares it to the product name
cur.execute('''SELECT ProductID FROM Products WHERE ProductName = LIKE ?''',(productName))
resultProductID = cur.fetchall()
print(resultProductID)
con.close()
But that ended up coming up with this:
<class 'sqlite3.OperationalError'> near "?": syntax error <traceback object at 0x0356A2D8>
A: findProductID = '''SELECT ProductID FROM Products WHERE ProductName = "{}"'''.format(productName)
cur.execute(findProductID)
resultProductID = cur.fetchall()
print(resultProductID)
con.close()
#the final part of inserting into the table
con = lite.connect(db)
cur = con.cursor()
command = '''INSERT INTO Entries(entryID, ProductID, CustomerID) VALUES ("{}", "{}", "{}")'''.format(newOrderID,resultProductID,newCustomerID)
so I did this to the code and it seems to work, it does save like this "[('9003',)]" but that probably will not be too hard to fix
| |
doc_23534703
|
// some code here
foo.aVeryLongMethodNameWhichCausesLineWraps(
param1,
param2);
// and some other code here
But what I'd like to have is the following:
// some code here
foo.aVeryLongMethodNameWhichCausesLineWraps(
param1,
param2
);
// and some other code here
For nested invocations it should look like the following:
// some code here
foo.bar(
nested(
param1,
param2
)
);
// and some other code here
Is this possible? If not, is there any chance to extend the formatter to provide such feature?
A: But you see, why it's a not that obvious idea?
How would it behave for methods without parameters?
foo.aVeryLongMethodNameWhichCausesLineWraps(
);
It doesn't look that good, does it?
There are of course pros and cons for each code formatting, but if you use not that good API of some guy from your office and that guy wanted to have 10 parameters in his methods it would mean that you'd have something like this:
foo.bar(
nested(
param1,
param2,
param3,
param4,
param5,
param6,
param7,
param8,
param9
),
param1,
param2,
param3,
param4,
param5,
param6,
param7,
param8,
param9
);
You can ease your pain of improper formatting by using Editbox plugin:
http://editbox.sourceforge.net
| |
doc_23534704
|
A: None of your users are going to expect that to be the behavior because nothing else they work with on the web utilizes double-click. Since it's counter intuitive, you'll need to provide instructions to users on what to do. You should take this as a sign that you are going about it the wrong way and should follow the normal conventions for web UI.
| |
doc_23534705
|
Abort: precommit.whitelist hook failed, and the file is right since I diff'd with the file from another repo which is working fine and they have equal binary.
What should I do to fix this problem?
A: The precommit hook is set only on your repo, and may not be on every repository just yet. That may explain why you have the same identical file elsewhere. Or maybe it existed before the hook was added.
Nonetheless, for the problem at hand, you have few options. Either contact your admin to see why the file is not on the whitelist, and add it to the list, or disable the hook on your repo. If you do the latter, you may still get rejected at the push, if the same hook is present there, too.
| |
doc_23534706
|
class A {
public:
typedef int A_t;
};
template<class T>
class IB {
public:
typedef typename T::A_t B_t;
virtual B_t get() = 0;
protected:
B_t v;
IB(B_t in) : v(in) { }
};
template<class T>
class B : public IB<T> {
public:
B(B_t in) : IB<T>(in) { } // error: expected ')' before 'in'
B_t get() { return B_t(); } // error: B_t does not name a type
};
int main() {
B<A> a(3); // Errors here since int can't be converted to const B& or const B&&
// Also because A is virtual, since A::get() doesn't compile
return 0;
}
As far as I can understand the error messages, the main problem is that the typedef in IB for some reason isn't available in B.
If I add a line typedef IB<T>::B_t B_t; above the B constructor, the code compiles OK, but I don't understand why I need this. Shouldn't B_t be available through inheritance?
Also, the following doesn't work either:
B(IB<T>::B_t in) : IB<T>(in) { }
// etc, with qualified references to B_t
yields the same error messages.
What is the mechanism here that prevents me from using B_t it in B without the extra typedef?
| |
doc_23534707
|
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public ArrayList aList;
public String correctAnswer;
public static void main (String [] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
textField.addActionListener(new startTextFieldListener(aList));
JButton startButton = new JButton ("Start!");
startButton.addActionListener(new startButtonListener(aList));
text = new JTextArea (30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener(ArrayList passedInList)
{
aList = passedInList;
}
@Override
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
ArrayList aList = new ArrayList();
try {
try (BufferedReader input = new BufferedReader (new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}}
} catch (IOException e) {
System.out.println(e);
}
int sz = aList.size();
for (int k = 0; k< sz; k++) {
String correctAnswer = aList.get(k).toString();
text.append(aList.get(k).toString());
text.append("\n");
}
}
}
class startTextFieldListener implements ActionListener {
startTextFieldListener(ArrayList passedInList)
{
aList = passedInList;
}
@Override
public void actionPerformed(ActionEvent event) {
text.getText();
if (text.getText().equals(correctAnswer)) {
JOptionPane.showMessageDialog(null, "Hooray!");
}
else if (!text.getText().equals(correctAnswer)) {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}
A: You could attempt to do this by trying to make the variables accessible to the entire class.
To implement this, you can add the variable declaration where you have declared your User Interface items, after the class declaration.
You could then access this variable in another class.
Example Code:
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int sampleIntToBeUsed;
You could also implement this with various get/set methods.
How to Make a Constructor: (Put the name of the class with no return type)
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener(ArrayList passedInList)
{
aList = passedInList;
}
New Second ActionListener
class startTextFieldListener implements ActionListener {
String correctAnswer;
startTextFieldListener(String answer)
{
correctAnswer = answer;
}
@Override
public void actionPerformed(ActionEvent event) {
if (text.getText().equals(correctAnswer)) {
JOptionPane.showMessageDialog(null, "Hooray!");
}
else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}
| |
doc_23534708
|
You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the 'app' database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
Error: Database app couldn't be flushed. Possible reasons:
* The database isn't running or isn't configured correctly.
* At least one of the expected database tables doesn't exist.
* The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "taskapp_taskrequest" references "taskapp_task".
HINT: Truncate table "taskapp_taskrequest" at the same time, or use TRUNCATE ... CASCADE.
This is the corresponding output for sqlflush command
BEGIN;
TRUNCATE "auth_permission", "auth_group", "tagging_taggeditem", "auth_user_user_permissions", "taskapp_task_reviewers", "taskapp_task", "django_site", "profile_profile", "django_content_type", "profile_notification", "django_session", "auth_user_groups", "taskapp_pyntrequest", "profile_rolerequest", "tagging_tag", "taskapp_textbook_chapters", "registration_registrationprofile", "taskapp_textbook", "django_admin_log", "auth_group_permissions", "taskapp_task_selected_users", "taskapp_taskcomment", "south_migrationhistory", "taskapp_task_claimed_users", "taskapp_taskclaim", "taskapp_workreport", "auth_message", "taskapp_reportcomment", "auth_user";
SELECT setval(pg_get_serial_sequence('"registration_registrationprofile"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"tagging_tag"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"tagging_taggeditem"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"south_migrationhistory"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"auth_permission"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"auth_group"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"auth_user"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"auth_message"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"django_content_type"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"django_site"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"django_admin_log"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"profile_profile"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"profile_notification"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"profile_rolerequest"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"taskapp_task"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"taskapp_taskcomment"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"taskapp_taskclaim"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"taskapp_workreport"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"taskapp_reportcomment"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"taskapp_pyntrequest"','id'), 1, false);
SELECT setval(pg_get_serial_sequence('"taskapp_textbook"','id'), 1, false);
COMMIT;
I have a database with multiple models and many foreign key relations among them. From what I read over the internet, I understand that Truncate should used to drop tables which are dependent on. I can't quite figure the exact syntax for using it in the dbshell.
I also accessing the postgresql shell as the sudo user and tried to drop the database using
DROP DATABASE DBNAME
command. But the database persists.
Edit:
Thanks to stevejalim's comment I was able to drop the database and created a new one. I ran syncdb command again and created the db again. But trying to load the db using loaddata command throws the error
IntegrityError: duplicate key value violates unique constraint
Any help on this would be much appreciated.
A: The reason you could not drop the database is probably that you were connected to it. I have to guess because you are holding back on the actual error message. Connect to the default maintenance database postgres instead (as superuser or owner of the db):
psql postgres
And launch the command from there:
DROP DATABASE dbname;
Check out this related question od dba.SE for a robust way to drop a database that doesn't want to go.
Concerning the new error you get: you have a UNIQUE or PRIMARY index or constraint defined on one of your tables but try to insert duplicate values. In modern versions of PostgreSQL you get more information in the error message. Like:
ERROR: duplicate key value violates unique constraint "tbl_pkey"
DETAIL: Key (tbl_id)=(10) already exists.
Raises the question: which version of PostgreSQL do you use?
In any case: check your database log file for those details and fix the duplicate values in your source (or remove the UNIQUE constraint).
A: You could try droping the database using the postgres dropdb command line tool.
dropdb dbname
| |
doc_23534709
|
set-webconfigurationproperty /system.webServer/security/authentication/anonymousAuthentication -name UserName -value "domain\user" -Location "iis:\Sites\$NewApp"
I'm also trying to set a binding after I create a site, but the binding isn't being applied correctly, and I can't see why. I've looked at many examples online and tried to mimic what they have. I'm sure I just have a formatting error or something small like that. This is my binding line:
New-Item IIS:\Sites\$NewApp -bindings @{protocol="http";bindingInformation=$NewIP+":80"} -physicalPath "E:\Physicalpath"
I've spent 2 hours on this tonight, and it's driving me crazy. I just broke down and configured the servers manually for those couple items, but I really want to get this working so I can use it for other site creation scripts.
Thanks in advance for any assistance.
A: I was able to set the user, needed to add -PSPath. You should be able to combine -PSPath and -Location as per the Link: Enable authentication for IIS app in Powershell
set-webconfigurationproperty /system.webServer/security/authentication/anonymousAuthentication -name userName -value "domain\user" -pspath iis:\ -Location "iis:\Sites\pwa"
Further, you second doubt is clarified here: Examples of IIS Powershell cmdlets
From the above link:
COMMAND Examples: When -Value parameter is used by IIS powershell cmdlet, it usually set with a single string value (NOTE: if
the value contains space, it should be quoted with " or ')
The value can be hash table object if it is used to set a collection item
add-webconfiguration
'/system.applicationHost/sites/site[@name="Default Web
Site"]/bindings'-value @{protocol="http";bindingInformation="*:80:"}
-pspath iis:\
You can use Add-WebConfiguration for setting bindings, like so:
Add-WebConfiguration '/system.applicationHost/sites/site[@name="pwa"]/bindings' -Value @{protocol="ftp";bindingInformation="10.0.0.100:21:pwa.fabrikam.local"} -PSPath iis:\
Or, you can use Set-WebConfiguration for modifying:
set-WebConfiguration '/system.applicationHost/sites/site[@name="pwa"]/bindings' -Value @{protocol="https";bindingInformation="*:443:pwa.fabrikam.local";sslFlags=0} -PSPath iis:\
Adding everything via variables. You can manage your variables it suites your needs, I've separated every components of bindings into various variables. Putting variables inside bracket helps evaluating expressions.
$siteName = "pwa"
$appFilter = "//system.applicationHost/sites/site[@name='$($sitename)']/bindings"
$newIP = "*"
$port = 80
$hostName = "pwa.fabrikam.local"
$bindings = @{
protocol = "http"
bindingInformation="$($newIP):$($port):$($hostName)"
}
set-WebConfiguration -Filter $appFilter -Value $bindings -PSPath iis:\
If you now change only variables, the commands should continue to function. I tried changing IP and ports via variables $newIP and $port. Let us know how it goes.
| |
doc_23534710
|
I've an entity A that has one-to-many relationship with entities B, C, D, E, F, G, H, I, J.
When I want to create new data of A I need to put text in some inputs, upload a file and create new data in B, C, D, E, F, G, H, I and J because of the relationship.
In addition, some of the data of the other entities that are not A, proceed from other entities related to B, C, D... like K, L, M, N, O.
I want to construct only one form to collect all data, and I've seen that it can be done through collections and embedded forms, but it seems so complicated with this amount of entities.
My question is: is there an easy way to do that?
Thanks.
| |
doc_23534711
|
Following is the error:
Multiple markers at this line
- Syntax error on token ".", @ expected after this token
- Syntax error, insert "SimpleName" to complete
QualifiedName
- Syntax error, insert "Identifier (" to complete
MethodHeaderName
- Syntax error, insert ")" to complete MethodDeclaration
- Syntax error on token ",", < expected
I have already correctly set Build path and JARs. Still I am getting this error.
package testing;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Login {
WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.gecko.driver", "G:\\JARs\\geckodriver.exe");
}
A: It seems your code does not include a main method.
It should be something like this:
package testing;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Login {
public static final main(String[] args) {
WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.gecko.driver", "G:\\JARs\\geckodriver.exe");
}
}
| |
doc_23534712
|
class Base {
public:
class Nested {
virtual void display() {
std::cout << "Not overridden" << std::endl;
}
};
Nested N;
};
And I have another class named Derived that inherits from the class Base.
Is it possible to override the display() method declared inside the Nested so that in the Derived class it does this instead:
void display() {
std::cout << "Overridden" << std::endl;
}
If so, how?
If not, what other options do I have?
A: Nested class (from cppreference):
The name of the nested class exists in the scope of the enclosing class, and name lookup from a member function of a nested class visits the scope of the enclosing class after examining the scope of the nested class. Like any member of its enclosing class, the nested class has access to all names (private, protected, etc) to which the enclosing class has access, but it is otherwise independent and has no special access to the this pointer of the enclosing class.
and since c++11
Declarations in a nested class can use any members of the enclosing class, following the usual usage rules for the non-static members.
So sloppy speaking, nesting classes is about names and accessing members. Thats it.
A class deriving from Base does not inherit a method display, because Base has no method display. Concerning inheriting from Base there is little difference to:
class Nested {
virtual void display() {
std::cout << "Not overridden" << std::endl;
}
};
class Base {
public:
Nested N;
};
class Derived : public Base {};
Derived inherits the member N, but no methods, because Base has no methods (apart from the special compiler generated ones).
| |
doc_23534713
|
I'd expect this to resolve as true, which it does. But what happens when I do
if(strpos("abcdefghijklmnop","http://www.")==0){// do work}
This also passes on php 5 because as far as I can work out the strpos returns false which translates as 0.
Is this correct thinking/behaviour? If so what is the workaround for testing for that a substring is at the beginning of another string?
A: Yes, this is correct / expected behavior :
*
*strpos can return 0 when there is a match at the beginning of the string
*and it will return false when there is no match
The thing is you should not use == to compare 0 and false ; you should use ===, like this :
if(strpos("abcdefghijklmnop","http://www.") === 0) {
}
Or :
if(strpos("abcdefghijklmnop","http://www.") === false) {
}
For more informations, see Comparison Operators :
*
*$a == $b will be TRUE if $a is equal to $b.
*$a === $b will be TRUE if $a is equal to $b, and they are of the same type.
And, quoting the manual page of strpos :
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please
read the section on Booleans for
more information. Use the ===
operator for testing the return
value of this function.
A: strpos returns an int or boolean false. the == operator also evaluates 0 to mean false, you want to use the === operator (three equals signs) that also checks that the types being compared are the same instead of just seeing if they can be evaluated to mean the same.
so
if (strpos($hastack, $needle) === 0)
{
// the $needle is found at position 0 in the $haystack
}
A: === and !== compare type and value as shown below:
if (strpos("abcdefghijklmnop", "http://www.") !== false) {
// do work
}
A: 0 is a possible return value from strpos when it finds a match at the very beginning. In case if the match is not found it returns false(boolean). So you need to check the return value of strpos using the === operator which check the value and the type rather than using == which just checks value.
A: I personally tend to use this way :
if(!strpos($v,'ttp:'))$v='http://'.$v;
or
if(strpos(' '.$v,'http'))
to avoid the "0" position then always make it a number more than 0
cheers
| |
doc_23534714
|
Say I have one Google Analytics account with one created property (tied to abc.com). Depending on your login information, it will send you to abc.com/red, abc.com/blue or abc.com/yellow.
Is it possible to create separate views for /red, /blue and /yellow? How do you implement a custom filter for it?
Using Google Data Studio, how would you add a filter control to filter between /red, /blue and /yellow?
A: In your GA filter for the view choose :
predefined -> include only traffic to the subdirectories -> that are equal to -> /red/
| |
doc_23534715
|
Code as follows:
$a = array ("Rama", "Seetha", "Kannan", "Shiva");
$b = array ("12", "10", "15", "17");
$c = array ("11", "b1", "d2", "10");
Expected output as follows:
Sno Name Age Id
1 Rama 12 11
2 Seetha 10 b1
3 Kannan 15 d2
4 Shiva 17 10
A:
$a = array ("Rama", "Seetha", "Kannan", "Shiva");
$b = array ("12", "10", "15", "17");
$c = array ("11", "b1", "d2", "10");
$count = count($a);
?>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Sno</th>
</tr>
</thead>
<tbody>
<?php
$j = 1;
for ($i=0; $i < $count ; $i++)
{
$name = $a[$i];
$age = $b[$i];
$id = $c[$i];
?>
<tr>
<td><?php echo $j ?></td>
<td><?php echo $name ?></td>
<td><?php echo $age ?></td>
<td><?php echo $id ?></td>
</tr>
<?php
$j++;
}
?>
</tbody>
</table>
| |
doc_23534716
|
I have Eclipse with android SDK 15 i.e. android 4.0.3 and Tablet with OS Android 4.0.3.
A: There should be no problem. Two notes:
*
*For some devices you need to install appropriate drivers, and they may usually be found in the vendor's site.
*You need to enable the devices for debugging, take a look here.
A: install the drivers for your tablet or the one from google..enable usb debugging mode in you settings>development>enble usb debugging
your ready to go..just debug your code and it will run on the tablet
A: I faced the same issue ,
Actually my laptop is too slow to use emulator so i decided to debug on tab.
steps i follow
1) Let eclipse have usb debugging software
http://developer.android.com/sdk/win-usb.html
2) get and install the driver for my windows 7 os, from asus as I am using fonepad 7. from here
http://developer.android.com/tools/extras/oem-usb.html#InstallingDriver
3) Turn usb debugging in android, you will find out in google how to do that. Need to tap on build version several times will turn it on. Then enable usb debugging
HW/SW list I am using
a) Windows 7
b) Asus fonepad 7 android 4.4.2
Key is you need to find correct driver for your android device.
| |
doc_23534717
|
I think the problem is with this line:
echo 'document.getElementById("CreditContent_ID").style.display="block"';
Here is my code:
<style>
.CreditContent{
display:none;
}
.BillContent{
display:none;
}
</style>
<body>
<?php
if($_POST['cc_owner']=='personal'){
echo '<script language="javascript">';
echo 'document.getElementById("CreditContent_ID").style.display="block"';
echo '</script>';
}else{
echo '<script language="javascript">';
echo 'document.getElementById("BillContent_ID").style.display="block"';
echo '</script>';
}
?>
<div class=CreditContent id="CreditContent_ID">
//I have other code here.
</div>
<div class=BillContent id="BillContent_ID">
//more code here
</div>
</body>
A: <style>
.hideContent {
display: none;
}
</style>
<body>
<div class="CreditContent <?php echo $_POST['cc_owner'] != 'personal'? 'hideContent': ''; ?>"
id="CreditContent_ID">
//I have other code here.
</div>
<div class="BillContent <?php echo $_POST['cc_owner'] == 'personal'? 'hideContent': ''; ?>"
id="BillContent_ID">
//more code here
</div>
</body>
Add css class hideContent to div based on cc_owner value.
| |
doc_23534718
|
But I had to write the client-side code with AngularJs and javascript, Is there a way that I coding in Intellij AngularJs and JS like Java, in fact, I would like to autocomplete my code for functions and services and etc in Intellij.
A: I'm using Intellij for both Java and AngularJs.
You just have to install the AngularJs plugin :
In File → Settings, click on Plugins and search for AngularJs
Then you'll have autocompletion.
| |
doc_23534719
|
NullPointerException at: mAdView.loadAd(new AdRequest.Builder().build());
My app build version 26.0.1 and using Android Studio 3.0 Beta 2.
my code:
public class B1 extends Fragment {
public B1() {
// Required empty public constructor
}
private AdView mAdView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_b1, container, false);
//Banner
mAdView = rootView.findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
@Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
});
return rootView;
}
}
A: The banner is ready. Your findViewById is returning null. Make sure rootView actually contains the AdView R.id.adView
| |
doc_23534720
|
I am trying to group the table by columns "Portfolio" and "Date" and sum up Net Discrepancy. Also, I would like to add a new column named "Gross Discrepancy".
The "Gross Discrepancy" would be the same as NET Discrepancy if NET Discrepancy is a positive number. If Net Discrepancy is a negative number, then it should be multiplied by -1 in order to get a positive number. In short, I am looking for the result like below:
I have been written the code below, which correctly calculates the aggregate NET_discrepancy but I am not able to figure out how to get the GROSS_discrepancy:
SELECT
date_long, portfolio,
SUM(ISNULL(CAST(NET_Discrepancy AS float), 0))
FROM
My_Table
GROUP BY
date_long, Portfolio
ORDER BY
date_long
A: You have to use the ABS function to get an absolute value
Result here
select
portfolio,
date_long,
sum(coalesce(net_discrepancy,0)) as "NET discrepancy",
abs(sum(coalesce(net_discrepancy,0))) as "GROSS discrepancy"
from my_table
group by portfolio,date_long
order by 1 desc,2 desc
| |
doc_23534721
|
CREATE TRIGGER biblioitems_after_marcxml_update
AFTER UPDATE ON biblioitems
FOR EACH ROW BEGIN
INSERT IGNORE INTO X_BIBLIONUMBER_BIBID VALUES (NEW.biblionumber, EXTRACTVALUE(NEW.marcxml, '//controlfield[@tag="001"]' ));
END
Any ideas what is going wrong here are very welcome.
A: Are you using DELIMITER?
Try:
DELIMITER //
CREATE TRIGGER biblioitems_after_marcxml_update AFTER UPDATE ON biblioitems
FOR EACH ROW
BEGIN
INSERT IGNORE INTO X_BIBLIONUMBER_BIBID
VALUES
(NEW.biblionumber, EXTRACTVALUE(NEW.marcxml, '//controlfield[@tag="001"]'));
END//
DELIMITER ;
| |
doc_23534722
|
my code :
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice ="rock"
} else if(computerChoice <= 0.67) {
computerChoice ="paper";
} else {
computerChoice ="scissors";
} console.log("Computer: " + computerChoice);
var compare=function(choice1, choice2){
if(choice1 === choice2) {
return("The result is a tie!");
}
else if(choice1 ==="rock"){
if(choice2 ==="scissors")
return("rock wins");
}
else{
return"paper wins";
}
else if(choice1 ==="paper");{
if(choice2 ==="rock")
return("paper wins");
}
else{
return"scissors wins";
}
}
A: else if(choice1 ==="paper");{
if(choice2 ==="rock")
return("paper wins");
}
you're terminating you're else if after the condition with ;
it should be:
else if(choice1 ==="paper"){
if(choice2 ==="rock")
return("paper wins");
}
A: var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice ="rock"
} else if(computerChoice <= 0.67) {
computerChoice ="paper";
} else {
computerChoice ="scissors";
} console.log("Computer: " + computerChoice);
var compare=function(choice1, choice2){
if(choice1 === choice2) {
return("The result is a tie!");
}
else if(choice1 ==="rock"){
if(choice2 ==="scissors")
return("rock wins");
}
else{
return"paper wins";
}
else if(choice1 ==="paper");{ -- on this there is semicolon after elseif block.. and how come else if is there after else block..
if(choice2 ==="rock")
return("paper wins");
}
else{
return"scissors wins";
}
}
A: I am assuming you are a beginner. Write a very clean code, take care of spaces and tabs, it is the best way to solve your debugging problems. there is indeed problem on line 22, you have put a semi-colon after a conditional statement.
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if(computerChoice < 0.34) {
computerChoice = "rock"
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice);
var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return("The result is a tie!");
} else if(choice1 === "rock") {
if(choice2 === "scissors")
return("rock wins");
} else {
return "paper wins";
} else if(choice1 === "paper"){//here the error was.
if(choice2 === "rock")
return("paper wins");
} else {
return "scissors wins";
}
}
A: I'm seeing several syntax errors in your code. It should look like the following:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice);
var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return("The result is a tie!");
} else if(choice1 === "rock") {
if(choice2 === "scissors") {
return("rock wins");
} else {
return "paper wins";
}
} else if(choice1 ==="paper") {
if(choice2 ==="rock") {
return("paper wins");
} else {
return"scissors wins";
}
}
}
A: You cant have an else if after an else statement, thats what is causing your error message error(Expected an identifier and instead saw 'else')
And of course no semicolorn before the line really ends
https://jsfiddle.net/8hcpfnhw/
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice ="rock"
} else if(computerChoice <= 0.67) {
computerChoice ="paper";
} else {
computerChoice ="scissors";
} console.log("Computer: " + computerChoice);
var compare=function(choice1, choice2){
if(choice1 === choice2) {
return("The result is a tie!");
}
else if(choice1 ==="rock"){
if(choice2 ==="scissors")
return("rock wins");
}
else if(choice1 === "paper"){ // I changed this to else if instead of else
return "paper wins";
}
else if(choice1 ==="paper") {
if(choice2 ==="rock")
return("paper wins");
}
else{ // only else as last check
return"scissors wins";
}
}
| |
doc_23534723
|
<action method="addJs"><script>nav/navigation.js</script></action>
navigation.js
$sub = $('div.col-md-2.right-content');
$('div.col-md-10').on({
mouseenter: function() {
var i = $(this).index();
$sub.addClass('li-'+i);
}, mouseleave: function() {
$sub.removeClass().addClass('col-md-2.right-content');
}
})
style.css
li.level2.nav-2-1-1.first{
background-color: green;
}
li.level2.nav-2-1-2.last{
background-color: red;
}
The purpose of this is that whenever a user hover over a link inside my submenu, the right-content will change accordingly. The problem is that my navigation.js file is targeting objects that does not exist until after the menu is loaded. These being 'div.col-md-2.right-content' and 'div.col-md-10'.
Is there a way to load the javascript after the menu has loaded? Or is there another way to accomplish this? Or am I just approaching this completely wrong.
A: You can use the $(function() { ... } ) syntax to have that code run only after all of your DOM is loaded:
$(function() {
$sub = $('div.col-md-2.right-content');
$('div.col-md-10').on({
mouseenter: function() {
var i = $(this).index();
$sub.addClass('li-'+i);
}, mouseleave: function() {
$sub.removeClass().addClass('col-md-2.right-content');
}
})
})
Note that this will work only if the menu is part of your original DOM (part of the HTML code) and not created dynamically.
In case the menu is generated dynamically you can use:
$('body').on('mouseenter', 'div.col-md-10', function() { ... });
Here is a working example:
$(function() {
$sub = $('.subject');
$('body')
.on('mouseenter', '.yeah', function() {
var i = $(this).index();
$sub.addClass('li-'+i);
})
.on('mouseleave', '.yeah', function() {
$sub.removeClass().addClass('subject');
})
$('.test').append($(' <ul> <li class="yeah"><a href="#">Link 1</a></li> <li class="yeah"><a href="#">Link 1</a></li> <li class="yeah"><a href="#">Link 1</a></li> </ul>'));
});
.li-0{
background-color:green;
}
.li-1{
background-color:red;
}
.li-2{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
</div>
<div class="subject">
<p>hello</p>
</div>
A: I think the problem is within the routing in local.xml
<default>
<reference name="head">
<action method="addItem">
<type>skin_js</type><name>js/navigation.js</name><params/>
</action>
</reference>
</default>
Where the navigation.js is in: Note (developer/template) is your template within the skin folder
site.com/skin/frontend/developer/template/js/navigation.js
The default Tag means that it will be loaded thru the entire site.
| |
doc_23534724
|
I don't know what is the issue. I tried different solutions from here but none of them helped me.
Here is my rating bar xml code
<RatingBar
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:maxHeight="30dp"
android:numStars="5"
android:progressDrawable="@drawable/ratingbar_custom"
android:rating="4"
android:stepSize="1" />
here is drawable xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@android:id/background"
android:drawable="@drawable/star_empty" />
<item
android:id="@android:id/secondaryProgress"
android:drawable="@drawable/star_empty" />
<item
android:id="@android:id/progress"
android:drawable="@drawable/star_filled" />
</layer-list>
And these are 2 images star_empty and star_filled
| |
doc_23534725
|
First step is to generate a webcam container:
var bandwidth:int = 0;
var quality:int = 100;
var camera:Camera = Camera.getCamera();
camera.setQuality(bandwidth, quality);
camera.setMode(885,575,30,true);
var video:Video = new Video(885,575);
video.attachCamera(camera);
video.name = "camara";
webcam.addChild(video);
It works ok, the problem is that I want to apply to it a custom filter
It works ok if I write it this way:
MovieClip(parent).contenedor_postal.postal.webcam.filters = [filter];
But I want to affect only the child inside the clip "webcam" without affecting other MC's, so I write it like this:
MovieClip(parent).contenedor_postal.postal.webcam.camara.filters = [filter];
and does not work. I used to program in AS2, so maybe the trick is very simple but I can't find anything that works. Thanks in advance!
A: If the video has a name property "camara" then this should work:
MovieClip(parent).contenedor_postal.postal.webcam.getChildByName("camara").filters = [filter];
| |
doc_23534726
|
I am getting:
Uncaught ReferenceError: google is not defined
However, if I look at the Google object in the console, it shows up just fine.
Is the script for the API not completely loaded yet before I try to use it?
Also, I have this main script (below) loading with the 'defer' attribute, though I don't think that should be an issue.
What am I missing?
Thanks in advance.
var inrMap = {
map : null,
markers : [],
addCoords : function(){
var regex1 = /\s/;
var regex2 = /\./;
for(var i in inrMap.locations){
var address = inrMap.locations[i].address;
address = address.replace(regex1, '+');
address = address.replace(regex2, '');
$.ajax({
data : 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false',
dataType : 'json',
type : 'get',
success : function(data, textStatus, xhr){
inrMap.locations[i].lat = data.geometry.location.lat;
inrMap.locations[i].lng = data.geometry.location.lng;
},
error : function(xhr, textStatus, errorThrown){
//console.error('problem with geocoding service...');
}
});
}
},
generateMap : function(){
var map_options = { center : new google.maps.LatLng(-34.397, 150.644), zoom : 8, mapTypeId : google.maps.MapTypeId.ROADMAP };
inrMap.map = new google.maps.Map(document.getElementById("map_canvas"), map_options);
//load markers
for(var i in inrMap.locations){
var position = new google.maps.LatLng(inrMap.locations[i].lat, inrMap.locations[i].lng);
inrMap.markers[i] = new google.maps.marker(position, inrMap.locations[i].title);
inrMap.markers[i].setMap( { map : inrMap.map, draggable : false, animation : google.maps.Animation.DROP } );
}
},
bindMarkers : function(){
// $(inrMap.markers).each(function(){
// this.bind('click', function(){
// //create new info window
// var location_name = this.id; // ***** this needs to be fixed ******
// var iw = new google.maps.InfoWindow( { content : this.id.title, maxWidth : '300' } );
// })
// });
},
bindForm : function(){
}
}
inrMap.locations = {
jacksonville : {
title : 'jacksonville',
address : '4651 Salisbury Rd. Suite 170, Jacksonville FL 32256',
phone : '(904) 398-0155',
link : '/location/florida-regional-office',
marker : null
},
miami : {
title : 'Miami',
address : '15050 NW 79 Court Suite 104, Miami Lakes FL 33016',
phone : '(305) 403-0594',
link : '/location/florida-regional-office',
marker : null
}
etc...
}
//load google maps js
var gmaps_script = document.createElement('script');
gmaps_script.type = 'text/javascript';
gmaps_script.src = 'http://maps.googleapis.com/maps/api/js?key=*****&sensor=false';
$('body').append(gmaps_script);
$(function(){
for(var i = 0; i < 4000; i++){
var foo = Math.sin(i);
}
//check if locations object is not in local storage (and thus does not have coordinates)
if(!localStorage.getItem('inr_locations')){
//get lat & long, add to locations obj
inrMap.addCoords();
//save object
//localStorage.setItem('inr_locations', inrMap.locations);
}
else{
//pull locations object from local storage
//inrMap.locations = localStorage.getItem('inrMap.locations');
}
//create element to place map in
var map_canvas = document.createElement('div');
$(map_canvas).attr('id', 'map_canvas').appendTo('#content');
//generate map
inrMap.generateMap();
//bind events to map markers
//inrMap.bindMarkers();
//bind events to form / links
//inrMap.bindForm();
});
A:
Is the script for the API not completely loaded yet before I try to
use it?
Yes, that is the problem.
Instead of:
var gmaps_script = document.createElement('script');
gmaps_script.type = 'text/javascript';
gmaps_script.src = 'http://maps.googleapis.com/maps/api/js?key=*****&sensor=false';
$('body').append(gmaps_script);
Use jQuery.getScript() and try something like this:
//Temporary creating global function,for handling loading of the Google Maps Library
window.__googlemapscallback = function(){
delete window.__googlemapscallback;
//do your map initialization here
};
$.getScript('http://maps.googleapis.com/maps/api/js?key=*****&sensor=false&&callback=__googlemapscallback');
The main problem of loading Google Maps V3 API, is that script is loaded partially.By http://maps.googleapis.com/maps/api/js?key=*****&sensor=false url, you load the first chunk of the library,which then loads the other chunks.After the all chunks is fully loaded, library calls callback function provided in the url.
| |
doc_23534727
|
Library used for GUI and embedded browser: PyQT
A: If you're using QWebView.title to get the title of the current web-page, then it will either return a QString or a python unicode string. Which one you get depends on the PyQt API version in use. For version 1 (which is the default for Python2), it will be a QString; for version 2 (which is the default for Python3), it will be a python unicode string. Whichever it is, in order to display it correctly in the line-edit, just set it directly:
lineEdit.setText(webview.title())
Since you appear to be using Python2, I'll assume that webview.title() is returning a QString. If you want to convert this to a python unicode string (e.g. in order to use it with sqlite), then you can do the following:
title = unicode(webview.title())
Note that you should not pass an encoding (such as "utf-8") as the second argument to unicode, as this is used for decoding byte strings to unicode strings.
If you do need to get a "utf-8" encoded byte string from a QString, then you can either do:
data = unicode(webview.title()).encode('utf-8')
or:
data = webview.title().toUtf8().data()
A: What are you using to parse the websites? I would recommend Beautiful Soup. It will try and determine the encoding of the web page and give you back unicode. Beautiful Soup's Parsing HTML section. Edit: Also take a look at the "Beautiful Soup Gives You Unicode, Dammit" section
| |
doc_23534728
|
In [24]: pd.set_option('display.max_rows', 10)
In [25]: df = pd.DataFrame(np.random.randn(100, 2), columns=['x', 'y'])
In [26]: df = df.sort('x')
In [27]: df
Out[27]:
x y
13 -3.403818 0.717744
49 -2.688876 1.936267
74 -2.388332 -0.121599
52 -2.185848 0.617896
90 -2.155343 -1.132673
.. ... ...
65 1.736506 -0.170502
0 1.770901 0.520490
60 1.878376 0.206113
63 2.263602 1.112115
33 2.384195 -1.877502
[100 rows x 2 columns]
Now, I want to kind of "window" it or "discretize" it and get statistics on each window. But I don't want to do the Pandas moving-window functions because they define windows by rows. I want to define windows by a span of x-values, thus "x-value-window". Specifically, let's define each x-value-window with 2 parameters:
*
*center x-value of each window
*
*in this example, let's say I want x = 0.0 + 0.4 * k for all positive or negative k
*thus -3.2, -2.8, -2.4, ..., 1.6, 2.0, 2.4
*width of each window
*
*in this example, let's say I want W = 0.5
*thus, the example windows will be [-3.2-0.25, -3.2+0.25], [-2.8-0.25, -2.8+0.25], ..., [2.4-0.25, 2.4+0.25]
*note that the windows overlap, which is intended
Having thus defined the windows, I would like to ask if there's a function that will produce the following data frame (or numpy array):
x y
-3.2 mean of y-values in x-value-window centered at -3.2
-2.8 mean of y-values in x-value-window centered at -2.8
-2.4 mean of y-values in x-value-window centered at -2.4
... ...
1.6 mean of y-values in x-value-window centered at 1.6
2.0 mean of y-values in x-value-window centered at 2.0
2.4 mean of y-values in x-value-window centered at 2.4
Is there anything that will do this for me? Or do I have to totally roll my own (and probably in a very slow python loop instead of fast numpy or pandas code)?
Extra 1: It would be even better if there's support for weighted windows (such as supported by Pandas's rolling_window function) but of course the weights in this case would not be based on how far the sample's row is from the center row of the window, but rather, how far the sample's x-value is from the center of the x-value-window.
Extra 2: It would be nice if there's support for statistics other than mean on the x-value-windows, e.g. (a) variance of the y-values in each x-value-window or (b) count of the number of samples falling within each x-value-window.
A: I first create a range of x values centered at zero. This range is wide enough so that then min value minus the width and the max value plus the width will capture all x values.
I then iterate through this range of x values which have k as the step size. At each point, I use loc to capture y values located at the selected x value plus and minus the width. The mean of these selected values are then calculated. These values are used to create the result dataframe.
import math
import numpy as np
import pandas as pd
k = .4
w = .5
np.random.seed(0)
df = pd.DataFrame(np.random.randn(100, 2), columns=['x', 'y'])
x_range = np.arange(math.floor((df.x.min() + w) / k) * k,
k * (math.ceil((df.x.max() - w) / k) + 1), k)
result = pd.DataFrame((df.loc[df.x.between(x - w, x + w), 'y'].mean() for x in x_range),
index=x_range, columns=['y_mean'])
result.index.name = 'centered_x'
>>> result
y_mean
centered_x
-2.400000e+00 0.653619
-2.000000e+00 0.733606
-1.600000e+00 0.576594
-1.200000e+00 0.150462
-8.000000e-01 0.065884
-4.000000e-01 0.022925
-8.881784e-16 0.211693
4.000000e-01 0.057527
8.000000e-01 -0.141970
1.200000e+00 0.233695
1.600000e+00 0.203570
2.000000e+00 0.306409
2.400000e+00 0.576789
| |
doc_23534729
|
print(final)
'Prod': Timestamp Flag group
0 2019-10-21 07:39:28.052763 begin Prod
1 2019-10-21 07:39:58.332252 end Prod
2 2019-10-21 07:40:00.279654 begin Prod
3 2019-10-21 07:41:58.631835 end Prod
4 2019-10-21 07:42:54.243338 begin Prod
[5354 rows x 3 columns],
'Clean': Timestamp Flag group
0 2019-10-21 07:48:26.740378 begin Clean
1 2019-10-21 07:48:28.272688 end Clean
2 2019-10-21 07:48:37.306045 begin Clean
3 2019-10-21 07:48:41.689466 end Clean
4 2019-10-21 08:32:46.240015 begin Clean
So I tried this, but it doesn't work, I think the problem is in the line "filename =..."
for key in final.keys():
filename = [key]+"/*.csv"
final[key].to_csv(filename, sep = ',' , encoding = 'utf-8', index = False)
I need this for datascience purpose. Thanks for your help.
| |
doc_23534730
|
mousecatdog.txt
dogcowfox.gif
dogmousecat.txt
dogmousepig.txt
So I'd like to get only dogmousepig.txt from this list.
I tried to use negative lookaheads, but I am getting an error:
syntax error near unexpected token `('
Of course looked at other threads on the forum, and tried to fix the problem by adding parentheses () or enabling shopt -s extglob, but to no avail.
I'm using mac and the script is in bash.
#!/bin/bash
for FILE in ^((?!cat).)*.txt
do
printf "\$FILE\n"
done
A: You can't use regular expressions after in, but you can use glob patterns. With shopt -s extglob, you can use the extended patterns:
#! /bin/bash
shopt -s extglob
for f in !(*cat*).txt ; do
printf "$f\n"
done
To prevent the pattern from expanding to itself when there are no matching files, you need to enable nullglob, too.
A: Bash uses wildcard expansion, not regular expressions in your example.
I see two fairly easy solutions:
1- use a wildcard for the positive selection and an RE for the negative selection, just like @Wiktor Stribizew said in his comment:
for FILE in *.txt; do
if [[ ! $FILE =~ cat ]]; then
printf "$FILE\n"
fi
done
2- grep out the output of the wildcard expansion (although this won't work correctly if there are spaces in your file names):
for FILE in `\ls -1 *.txt | grep -v cat`; do
printf "$FILE\n"
done
| |
doc_23534731
|
Where should I look into to find it? driver, kernel, a user space code? I know I can use cp /dev/fb0 fb0 to copy the framebuffer and compare it to a previously copied framebuffer. But this is not efficient I think.
| |
doc_23534732
|
I am already using Firebase Storage and Firebase Real time database.
Which Firebase service should I use? I am familiar with PHP so should I use Firebase Hosting to upload there some php script?
Sorry if this is a newbie question.
A: Firebase does not offer any options for running PHP code for your app's backend. You can use Cloud Functions for Firebase, which runs nodejs. Or if you must run PHP, you can use Google App Engine.
| |
doc_23534733
|
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
sql = """SELECT url FROM domain_sold WHERE url = %s;"""
try:
cursor = spider.db_connection.cursor()
cursor.execute(sql, (request.url,))
is_seen = cursor.fetchone()
cursor.close()
if is_seen:
raise IgnoreRequest('duplicate url {}'.format(request.url))
except (Exception, psycopg2.DatabaseError) as error:
self.logger.error(error)
return None
if IgnoreRequest is raised I expect the spider would continue onto another request but in my case the spider would still continue scraping that request and pipe through the item through my custom pipeline.
I currently have my setting for the dl mw as below
'DOWNLOADER_MIDDLEWARES' : {
'realestate.middlewares.RealestateDownloaderMiddleware': 99
could anyone suggest to why this is happening. Thanks
A: IgnoreRequest inherits from the base Exception class which you're then immediately catching in your except and logging so it never propagates enough to actually ignore the request...
Change:
except (Exception, psycopg2.DatabaseError) as error:
To:
except psycopg2.DatabaseError as error:
| |
doc_23534734
|
In the demo example provided by Microsoft, they create a logger and then pass this into the Startup class:
public class Program
{
public static async Task Main(string[] args)
{
var logger = CreateLogger(); // <--- HERE !!!!
var host = Host.CreateDefaultBuilder()
.ConfigureWebHost(builder =>
{
builder.UseStartup(context => new Startup(logger)); // Logger passed into the ctor
})
.Build();
await host.RunAsync();
}
}
However, I am not sure how the author created the Logger (ie. the code in that method), which hopefully will be an ILogger.
A:
However, I am not sure how the author created the Logger (ie. the code in that method), which hopefully will be an ILogger.
It's the same as always (fortunately). First, create and configure a logger factory:
var loggerFactory = LoggerFactory.Create(builder => { /*configure*/ });
Then, get a logger out of it:
var startupLogger = loggerFactory.CreateLogger<Startup>();
The above is just one way and there are multiple, both built-in and with the several third-party logging frameworks. Read more in the main Logging in .NET Core and ASP.NET Core document.
A: You need to wire it up in ConfigureLogging (Namespace: Microsoft.Extensions.Hosting) extension:
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(builder =>
{
builder.AddNLog(); //<-I used Nlog for demonstration purposes. This will take care things for you.
//builder.AddConsole();
//builder.AddDebug();
})
.ConfigureWebHostDefaults(builder =>
{
builder.UseStartup<Startup>(); //<Startup class
});
Use dependency injection via your constructor:
private readonly ILoggerFactory loggerFactory;
public Class1(ILoggerFactory loggerFactory)
{
this.loggerFactory = loggerFactory;
}
public SomeMethod(){
var logger = loggerFactory.CreateLogger("Exception logger"); //<-You can call create logger here
}
*
*I would suggest you decide first, which logging framework you want to use, popular loggers provides rich documentations that will help you hit the ground running.
| |
doc_23534735
|
*
*Have a system wide callback for every mouse and keyboard press.
*Sleep for a 100ms and see if there is a keydown or mousemovent
*Use a system call that actually tells me when the last userinput was and use a combo of the above for efficiently. (sleep until user is away, then use callback to track arrival)
A: Try looking at this.
You shouldn't need to do the tracking yourself, it looks like you can do system calls to get the idle time.
A: http://www.geekpedia.com/tutorial210_Retrieving-the-Operating-System-Idle-Time-Uptime-and-Last-Input-Time.html might also help you
bit late :P :P
| |
doc_23534736
|
$mpdf = new mPDF('UTF-8', array(224, 500));
The length of 500 is not constant because it will change according to the content. May be less than or more than 500.
To set the automatic height. Make changes according to the content. What to do?
A: This may help you: https://mpdf.github.io/paging/different-page-sizes.html
The functions AddPage() and TOCpagebreak() both have parameters to
select sheet size.
Accepted values - same options as the original mPDF() - are:
"A4", "A3", "Letter" etc "A4-L", "A3-L", "Letter-L" etc. for landscape
an array of 2 numbers which are the width then height in mm e.g.
array(210,297)
| |
doc_23534737
|
<p style="text-align: center;"><iframe src="myurl&quality=flv" width="560" height="315" frameborder="0" allowfullscreen=""></iframe></p>
Thank you!
EDIT: it is a jwplayer video
A: You should activate autostart feature in jwplayer. Instead of using iframe use a div with id and then configure the features with js in a short script.
Example:
<div id="myVideo"></div>
<script>
var playerInstance = jwplayer("myVideo");
playerInstance.setup({
file: "/videoURL/video.mp4",
width: 560,
height: 315,
autostart: true
});
</script>
if you need to mute the video at autostart then just add mute: true
To get more info you can check here: https://support.jwplayer.com/customer/portal/articles/1428525-autostarting-on-page-load
A: If you are using youtube there is an autoplay parameter
<iframe width="640" height="360" src="[YouTube Video URL]?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
| |
doc_23534738
|
Thanks,
A: You can do this in mxml when you define your state like so:
<mx:State name="someState" enterState="someFunction()"/>
| |
doc_23534739
|
I am currently looking at a combobox (the drop down box). I used the "showdropdown" command to have it drop down, and it worked successfully.
I then tried to use "SelectString", but it didn't go to the string that I specified. How does the "SelectString" ControlCommand option work?
I have also tried "SetCurrentSelection".
This is the statement I used:
ControlCommand($windowName, "", "[Name:myComboBox]", "SelectString", "a")
I have also tried searching for it first with:
ControlCommand($windowName, "", "[Name:myComboBox]", "FindString", "a")
but it didn't find it either. Strange, the single character "a" is there.
If it helps, this is the control class: WindowsForms10.COMBOBOX
A: _GUICtrlComboBox_xxx functions also work on external controls. For example, _GUICtrlComboBox_FindString, _GUICtrlComboBox_SelectString, _GUICtrlComboBox_SetCurSel. Try those instead.
Call ControlGetHandle first, then use this handle to call the functions above.
Remember to include the GuiComboBox library, otherwise you will get an error message "Error: Unknown function name":
#include <GuiComboBox.au3>
A: You can send key presses to this control, like this:
ControlSend("Window title", "", "[NAME:comboBoxName]", "ComboBox value")
It works because ComboBox interprets input as a search string and selects the first item starting with this string.
Note: Because it searches the matching item as you type, there's no need to send a complete value, only the shortest substring.
| |
doc_23534740
|
This is like it should look:
I tried it with a surrounding <div class='heading'> tag and the following CSS code:
.heading {
width: 100%;
}
.heading div, form {
float: left;
clear: none;
}
But this ends up looking like this:
The sliders at the bottom are also too narrow. They should expand from the left to the right and be ordered one below the other (like depicted in the first image).
Here's my JSFiddle: https://jsfiddle.net/salocinx/rub5jLhn/
Requirements:
*
*entire page width max 420px
*heading inline ("Manual Control" and "Back")
*remaining page as "block"
*sliders full length of page
HTML:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'/>
<title>Menu Test</title>
<link href='style.css' rel='stylesheet' type='text/css'>
<script src='websocket.js' type='text/javascript'></script>
</head>
<body>
<div class='frame'>
<div class='heading'>
<div class='title'>
Manual Control
</div>
<form method='post' action='/' class='back'>
Back
</form>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor.</p>
</div>
<div class='title'>
Gadget
</div>
<div>
<input class='enabled_red' id='r0' type='range' min='0' max='1023' step='1' oninput='sendRGB(0);' value='0'>
<input class='enabled_green' id='g0' type='range' min='0' max='1023' step='1' oninput='sendRGB(0);' value='0'>
<input class='enabled_blue' id='b0' type='range' min='0' max='1023' step='1' oninput='sendRGB(0);' value='0'>
</div>
</div>
</body>
</html>
CSS:
body {
text-align: center;
font-family: verdana;
}
p {
font-size: 1em;
text-align: center;
}
div {
font-size:1em;
border-radius: 0.2rem;
box-sizing: border-box;
}
div.frame {
max-width: 420px;
margin: auto;
color: #444;
text-align: left;
border-style: solid;
border-width: 1px;
border-color: #d1d1d1;
display: block;
}
.heading {
width: 100%;
}
.heading div, form {
float: left;
clear: none;
}
div.title {
border: 0;
font-size:1.25em;
font-weight: bold;
text-align: center;
color: white;
background-color: #4C6DAF;
padding: 18px;
}
form.back {
border: 0;
border-radius: 0.2rem;
font-size:1.25em;
font-weight: bold;
text-align: center;
color: white;
background-color: #CB4C4C;
cursor: pointer;
padding: 18px;
}
div.logo {
border: 0;
text-align: center;
padding: 24px;
}
/*input {
width:100%;
font-size:1em;
border-style: solid;
border-width: 1px;
border-radius: 0.2rem;
border-color: #d1d1d1;
margin: 12px 0px;
padding: 12px 0px 12px 12px;
box-sizing: border-box;
display: block;
} */
button {
width: 100%;
border: 0;
color: white;
border-radius: 0.2rem;
line-height: 2.4rem;
font-size: 1.2rem;
cursor: pointer;
padding: 12px 0px;
}
button:hover {
opacity: 0.75;
}
form.back:hover {
opacity: 0.75;
}
/* ___________________________________ COLOURS __________________________________ */
.red {
background-color: #CB4C4C;
}
.green {
background-color: #4DB248;
}
.blue {
background-color: #5591E3;
}
/* ____________________________________ SLIDER ___________________________________ */
input[type=range] {
-webkit-appearance: none;
border: 0px;
outline: none;
padding: 16px 16px;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: 0px;
height: 36px;
width: 36px;
margin-top: -16px;
border-radius: 5px;
cursor: pointer;
}
input.enabled_red[type=range]::-webkit-slider-thumb {
background: #CB4C4C;
cursor: pointer;
}
input.enabled_green[type=range]::-webkit-slider-thumb {
background: #4DB248;
cursor: pointer;
}
input.enabled_blue[type=range]::-webkit-slider-thumb {
background: #5591E3;
cursor: pointer;
}
input.disabled[type=range]::-webkit-slider-thumb {
background: #999999;
}
input[type=range]::-webkit-slider-runnable-track {
width: inherit;
height: 4px;
border-radius: 1px;
background: #CCCCCC;
}
input.enabled[type=range]::-webkit-slider-runnable-track {
cursor: pointer;
}
Tried lots of different approaches, but I am really out of luck. Could somebody point me to the right direction?
A: You are using some unecessary floating. You can use flex for the heading like this :
.heading {
width: 100%;
display: flex;
}
.heading>div {
flex: 4;
}
.heading>form {
flex: 1;
}
Also wrap the input ranges inside a container and use flex like this :
.container-input {
display:flex;
flex-direction:column;
}
Full code :
body {
text-align: center;
font-family: verdana;
}
p {
font-size: 1em;
text-align: center;
}
div {
font-size: 1em;
border-radius: 0.2rem;
box-sizing: border-box;
}
div.frame {
max-width: 420px;
margin: auto;
color: #444;
text-align: left;
border-style: solid;
border-width: 1px;
border-color: #d1d1d1;
display: inline-block;
}
.heading {
width: 100%;
display: flex;
}
.heading>div {
flex: 4;
}
.heading>form {
flex: 1;
}
div.title {
border: 0;
font-size: 1.25em;
font-weight: bold;
text-align: center;
color: white;
background-color: #4C6DAF;
padding: 18px;
}
form.back {
border: 0;
border-radius: 0.2rem;
font-size: 1.25em;
font-weight: bold;
text-align: center;
color: white;
background-color: #CB4C4C;
cursor: pointer;
padding: 18px;
}
div.logo {
border: 0;
text-align: center;
padding: 24px;
}
.container-input {
display: flex;
flex-direction: column;
padding:10px 0;
}
button {
width: 100%;
border: 0;
color: white;
border-radius: 0.2rem;
line-height: 2.4rem;
font-size: 1.2rem;
cursor: pointer;
padding: 12px 0px;
}
button:hover {
opacity: 0.75;
}
form.back:hover {
opacity: 0.75;
}
/* ___________________________________ COLOURS __________________________________ */
.red {
background-color: #CB4C4C;
}
.green {
background-color: #4DB248;
}
.blue {
background-color: #5591E3;
}
/* ____________________________________ SLIDER ___________________________________ */
input[type=range] {
-webkit-appearance: none;
border: 0px;
outline: none;
padding: 16px 16px;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: 0px;
height: 36px;
width: 36px;
margin-top: -16px;
border-radius: 5px;
cursor: pointer;
}
input.enabled_red[type=range]::-webkit-slider-thumb {
background: #CB4C4C;
cursor: pointer;
}
input.enabled_green[type=range]::-webkit-slider-thumb {
background: #4DB248;
cursor: pointer;
}
input.enabled_blue[type=range]::-webkit-slider-thumb {
background: #5591E3;
cursor: pointer;
}
input.disabled[type=range]::-webkit-slider-thumb {
background: #999999;
}
input[type=range]::-webkit-slider-runnable-track {
width: inherit;
height: 4px;
border-radius: 1px;
background: #CCCCCC;
}
input.enabled[type=range]::-webkit-slider-runnable-track {
cursor: pointer;
}
<body>
<div class='frame'>
<div class='heading'>
<div class='title'>
Manual Control
</div>
<form method='post' action='/' class='back'>
Back
</form>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor.</p>
</div>
<div class='title'>
Gadget
</div>
<div class='container-input'>
<input class='enabled_red' id='r0' type='range' min='0' max='1023' step='1' oninput='sendRGB(0);' value='0'>
<input class='enabled_green' id='g0' type='range' min='0' max='1023' step='1' oninput='sendRGB(0);' value='0'>
<input class='enabled_blue' id='b0' type='range' min='0' max='1023' step='1' oninput='sendRGB(0);' value='0'>
</div>
</div>
</body>
</html>
A: Hi Please add below CSS
.header-back{
width:25%;
}
form.back{
width:100%;
padding-left:0px !important;
padding-right:0px !important;
}
.heading .title{
width:75%;
}
then change your heading div html to below
<div class='heading'>
<div class='title'>
Manual Control
</div>
<div class="header-back">
<form method='post' action='/' class='back'>
Back
</form>
</div>
</div>
then it will look like
A: Try this
.heading div,
.heading form{
float:left;
}
.heading div{
width:75%;
}
.heading form{
width:25%;
}
| |
doc_23534741
|
.contactInformation {
background-color: $Ice;
height: 100vh;
.contactInfo {
border: 2px solid red;
width: 25%;
display: inline-block;
p {
line-height: 15px;
}
h4 {
font-size: 1.625;
letter-spacing: 1.1px;
margin-bottom: 30px;
}
i {
padding: 0 10px;
}
}
}
.container {
display: inline-block;
padding-top: 50px;
border: 2px solid red;
}
.right-side {
width: 50%;
background: $White;
.top {
width: 600px;
display: flex;
justify-content: flex-start;
margin-bottom: 30px;
input {
width: 45%;
font-size: 20px;
padding: 10px;
border-radius: 5px;
}
}
textarea {
width: 100%;
font-size: 20px;
height: 100px;
padding: 10px;
border-radius: 5px;
margin-bottom: 30px;
resize: none;
}
.button {
width: 100%;
padding: 2px auto;
}
}
<main class="contact contactInformation">
<div class="container">
<div class="right-side">
<form action="" method="post">
<div class="top">
<input type="text" placeholder="Name">
<input type="text" placeholder="Email">
</div>
<textarea name="name" placeholder="Message"></textarea>
<button type="submit" class="button">Submit</button>
</form>
</div>
</div>
<div class="contactInfo">
<i class="fa-brands fa-facebook-f"></i>
<i class="fa-brands fa-instagram"></i>
<i class="fa-brands fa-twitter"></i>
<i class="fa-brands fa-whatsapp"></i>
<h4>INFO@EMAIL.COM</h4>
<p>123 - 456 - 7890</p>
<p>123 Queen Street West, Unit 10</p>
<p>Toronto, Ontario</p>
<P>M5V2D5</P>
</div>
</main>
A: You can do this by using flexbox with the order command:
.wrapper {
display: flex;
flex-flow: row wrap;
width: 100%;
height: 500px;
}
.wrapper .wrapper__child1 {
flex: 0 0 50%;
height: 100%;
width: 50%;
order: 2;
background: red;
}
.wrapper .wrapper__child2 {
flex: 0 0 50%;
height: 100%;
width: 50%;
order: 1;
background: blue;
}
<div class="wrapper">
<div class="wrapper__child1"></div>
<div class="wrapper__child2"></div>
</div>
A: you can use flex and then set flex-direction to reverse-row. so your CSS would be:
.wrapper {
display: flex;
flex-direction: reverse-row;
}
| |
doc_23534742
|
My HTML:
<!DOCTYPE html>
<html lang="nl">
<head>
<title>Test</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="test.css" />
</head>
<body>
<header>
</header>
<a id="photo">Photo</a>
<footer>
</footer>
</body>
</html>
My css:
#photo {
content: url('right-button.png');
}
A: Try this:
#photo {
background: url("right-button.png") no-repeat;
}
For more informations read here some articles i found for content attribute:
content property,W3c
| |
doc_23534743
|
So when I am doing :
for (i in 1:length(df[,1]))
(df[,i]<-df[,i][!is.na(df[,i])])
It answers :
Error in `[<-.data.frame`(`*tmp*`, , i, value = c(2696L, 2696L, 2640L, :
Do anyone has an idea how to do it ?
A: You cannot do what you're attempting in the code in your question because a data.frame is a list structure with a single key restriction: all vectors (or variables) in the list must have the same length. Your code is attempting to create vectors with different lengths, which is not allowed.
You probably just need the complete.cases function:
complete.cases(df)
This removes all rows that have any NA value in any column.
| |
doc_23534744
|
A: Have a look at ExtJs. It has the best Grid i've seen so far. It supports XML and JSON and conversion from basic HTML tables.
A: Take a look at Dojo Grid:
*
*Good write up in Dojo 1.2 Grid and in New Features in Dojo Grid 1.2.
*Tons of code examples in dojox.grid.tests (warning: this link points directly to the nightlies ⇒ the Dojo code is packaged for debugging purposes, not for performance).
| |
doc_23534745
|
As I understand Rust's module system, in order to do this, I have to also create src/handlers/mod.rs wherein I include mod get_foo; and also pub use get_foo::get_foo_handler;.
Then, from src/main.rs I have to mod handlers; and access my handler as handlers::get_foo_handler when I boot up the application.
Is there a way to include each of the nested modules under src/handlers/*.rs without having boilerplate mod.rs to include the child modules and re-export the handlers?
| |
doc_23534746
|
"Time Series (5min)": {
"2018-11-21 16:00:00": {
"1. open": "103.3300",
"2. high": "103.4300",
"3. low": "103.0800",
"4. close": "103.0800",
"5. volume": "1430557"
},
Obviously I can specify the exact entry by referencing the
['2018-11-21 16:00:00']
using square bracket notation and similarly
['4. close']
in order to retrieve the data I need, but given that the latest entry is constantly switching date and time, the reference is always changing.
How do I ensure I am always retrieving the latest value?
A: You can just convert the keys to Date and sort the keys in descending order. Then select the first one. Here's a snippet for that:
[This works even if the keys are not ordered when fetched initially]
var obj = {
"Time Series (5min)": {
"2018-11-21 16:00:00": {
"1. open": "103.3300",
"2. high": "103.4300",
"3. low": "103.0800",
"4. close": "103.0800",
"5. volume": "1430557"
},
"2018-11-21 16:00:20": {
"1. open": "104.3300",
"2. high": "104.4300",
"3. low": "104.0800",
"4. close": "104.0800",
"5. volume": "1430557"
},
}
}
var keys = Object.keys(obj['Time Series (5min)']);
//now sort the dates in descending order
keys.sort(function(a, b) {
a = new Date(a);
b = new Date(b);
return a>b ? -1 : a<b ? 1 : 0;
});
var latestKey = keys[0];
var getVal = obj['Time Series (5min)'][latestKey]; //this is your latest data
console.log(getVal);
A: You can convert the Time Series (5min) object in to an array using Object.values method. Then access the first index of the array for latest entry
Here's how you get the latest entry using Fetch api
const url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo';
fetch(url)
.then(response => response.json())
.then(data => {
const obj = data['Time Series (5min)'];
const arr = Object.values(obj);
const latestEntry = arr[0];
console.log(latestEntry);
})
.catch(error => console.log(error));
A: You can use Object.keys.It will give an array , then use the index, here 0 to get the first element
let obj = {
"Time Series (5min)": {
"2018-11-21 16:00:00": {
"1. open": "103.3300",
"2. high": "103.4300",
"3. low": "103.0800",
"4. close": "103.0800",
"5. volume": "1430557"
},
}
}
let getKeys = Object.keys(obj['Time Series (5min)'])[0];
let getVal = obj['Time Series (5min)'][getKeys];
console.log(getVal)
A: You can't guarantee order in an object, so I don't think this is possible.
| |
doc_23534747
|
The string it will be set, for example as 1.png but on the where I call this method the string it will be as "" rly don't understand why this is happening.
On the GerirDoc.cs I define the string as String _imgFile = "" at the beginning of the Form and have this code:
DocImg docImg = new DocImg();
docImg.selectImage(_imgFile, this.pictureBoxDoc);
The class DocImg
class DocImg
{
public int Hwnd { get; private set; }
public void selectImage(String imgFile, PictureBox imgBox)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Escolher imagem";
openFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png";
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
imgFile = openFileDialog.SafeFileName;
DialogResult dialogResult = MessageBox.Show("Deseja passar a imagem para o aparelho se tiver ligado ao computador?", "Informação", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
imgBox.Image = Image.FromFile(openFileDialog.FileName);
switch (dialogResult)
{
case DialogResult.Yes:
Shell shell = new Shell();
Folder folder = shell.BrowseForFolder((int)Hwnd, "Selecione o caminho para a pasta \"Imagens\"", 0, 0);
if (folder != null)
{
FolderItem _destinationDir = (folder as Folder3).Self;
if (String.Equals(_destinationDir.Name, "Imagens"))
{
try
{
folder.CopyHere(openFileDialog.FileName, null);
MessageBox.Show("Imagem guardada com sucesso", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
MessageBox.Show("A pasta de destino tem que ser a pasta \"Imagens\" que se está dentro de adbRetail");
}
}
break;
case DialogResult.No:
MessageBox.Show("De lembrar que a imagem só ira aparecer correctamente se tiver na pasta correcta do aparelho", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
break;
}
}
}
}
I did put a breakpoint just after imgFile = openFileDialog.SafeFileName; and the variable imgFile as the value of the filename, ex 1.png, but on GerirDoc.cs after choosing the file of the image, _imgFile doesn't have any value.
On GerirDoc.cs I only put _imgFile = "" when the form is created. Why is this happening ? Since I send the string inside it and since in DocImg if the user chose a image it should have the filename, ex 1.png and not be empty
A: As I can understand you want method to change your local variable. You should change it to:
public void selectImage(out string imgFile, PictureBox imgBox)
notice the parameter modifier out. And then call this method like this:
docImg.selectImage(out _imgFile, this.pictureBoxDoc);
The out keyword causes arguments to be passed by reference. It is like the ref keyword, except that ref requires that the variable be initialized before it is passed.
More reference here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
| |
doc_23534748
|
<div id="question_content" class="row question-main-content question-item"></div>
<!-- END QUESTION-MAIN-CONTENT -->
<div class="row question-main-content question-item answer-item"></div>
<!-- END ANSWER-CONTENT -->
and each question container and answer contain has a button
<a class="action vote vote-up img-circle"></a>
The js for capturing the click action is defined as
Views.PostListItem = Backbone.View.extend({
tagName: 'div',
className: 'row question-main-content question-item answer-item',
model: [],
events: {
'click a.action': 'doAction',
}
doAction: function(event) {
# mycode
}
});
I notice that the className includes answer-item. When I clicked the button in the question container, it executes the code the stops at the line where I placed a debugger. I wonder why this works? Shouldn't only the buttons in the answer container be executed because their class attributes exactly match className in js.
Also, I am trying to add a vote button on the other page. Do I just simply copy the js code and change the classname attribute to that of my container in new page?
| |
doc_23534749
|
file 1:
abc 123
def 456
ghi 789
file 2:
abc 321
ghi 987
I've heard awk is what I need, but how can I use it to make this desired output?
abc 321
def 456
ghi 987
You can assume all data has been de-duplicated within the files. So the only thing it needs to do is iterate through the files, and if there's a match between files 1 and 2 on column 1, the output should be the information in file 2.
Thanks in advance!
A: With GNU sort:
sort -k1,1 -u file2 file1
Output:
abc 321
def 456
ghi 987
A: Assuming the keys in file2 are strictly a subset of what appears in file1
awk 'NR==FNR {f2[$1] = $2; next} $1 in f2 {$2 = f2[$1]} 1' file2 file1
| |
doc_23534750
|
A: None that I'am aware of.
But it should not be to hard to write one. You can use ObjectContainer.Ext().KnownClasses() method.
| |
doc_23534751
|
['ManagementForm data is missing or has been tampered with']
Views:
def employedit(request, pk, id):
employ_academic_forms = EmployAcademicUpdateFormSet(queryset=EmployAcademicInfo.objects.filter(employ_id=pk))
if request.method == 'POST':
employ_academic_forms = EmployAcademicUpdateFormSet(request.POST)
if employ_academic_forms.is_valid():
employ_academic_forms.save()
return redirect('employ-list')
context = {
'employ_academic_forms':employ_academic_forms,
}
return render(request, 'admins/employ/edit_employ.html', context)
form:
EmployAcademicUpdateFormSet = modelformset_factory(
EmployAcademicInfo,
exclude = ['employ_id'],
extra=0,
labels = {
'degree': 'Enter Employ Degree',
'last_passing_institution_name': 'Enter Employ Passing Institution',
'last_passing_year': 'Enter Employ Passing Year',
},
widgets = {
'degree' : forms.Select(attrs={'class':'form-control form-control-lg', 'placeholder':'Enter degree'}),
'last_passing_institution_name' : forms.TextInput(attrs={'class':'form-control form-control-lg', 'placeholder':'Enter institution name'}),
'last_passing_year' : forms.DateInput(attrs={'class':'form-control form-control-lg', 'type':'date'}),
},
)
Html:
{% extends 'base/base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="card">
<form class="form-horizontal" action="" method="post">
{% csrf_token %}
<div class="card-body">
<div class="card-body">
<div class="form-horizontal">
{{ employAcademicFormSet.management_form }}
{% for form in employ_academic_forms %}
{% for field in form.visible_fields %}
<div class="form-group row">
<label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label>
<div class="col-md-9">{{ field }}</div>
</div>
{% endfor %}
{% endfor %}
</div>
</div>
</div>
<div class="card-footer">
<button class="btn btn-lg btn-primary" type="submit">Submit</button>
</div>
</form>
</div>
{% endblock %}
Does anyone know what is causing this? Please help me!!!
A: I think you might be using the wrong name when calling management_form.
Can you try replacing
{{ employAcademicFormSet.management_form }}
with
{{ employ_academic_forms.management_form }}
and see if that helps.
| |
doc_23534752
|
Do classes in namespaces have to ever be declared?
using System;
public class myprogram
{
void main()
{
// The console class does not have to be declared?
Console.WriteLine("Hello World");
}
}
If I'm not using a namespace then I have to declare a class
class mathstuff
{
private int numberone = 2;
private int numbertwo = 3;
public int addhere()
{
return numberone + numbertwo;
}
using System;
public class myprogram
{
void main()
{
// the class here needs to be declared.
mathstuff mymath = new mathstuff();
Console.WriteLine(mymath.addhere());
}
}
Am I understanding this correctly?
A: I think what you mean is "can you declare a class without a namespace?". Yes you can, it's referred to as the global namespace.
class BaseClass
{
}
class SubClass : global::BaseClass
{
}
However, this is very bad practice, and you should never do this in a production application.
A: A namespace is simply a way to make clear in which context the class is living in. Think of your own name, Ralph. We have many Ralphs in this world, but one of that is you. An extra way to get rid of the ambiguity is to add your surname. So that if we have 2 Ralphs, we have a bigger chance of talking about you.
The same works for classes. If you define class AClass and you would have the need of define another class AClass there would be no way to distinguish between the two. A namespace would be that 'surname'. A way of having to classes, but still able to distinguish between the two different classes, with the same name.
To answer your question, it has nothing to do with "not having to declare". It would only be easier to write code.
For example:
using System;
public class myprogram
{
void main()
{
// the class here needs to be declared.
Console.WriteLine("blah");
}
}
Because of the using System; you don't have to declare the namespace of Console. There is only one Console available, which lives in the System namespace. If you wouldn't declare your using System; namespace then you'd need to explain where Console can be found. Like this.
System.Console.WriteLine("blah");
From MSDN:
The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types.
For more info check MSDN for namespace.
| |
doc_23534753
|
I directly add a UIView in UICollectionReusableView, and I got the error:
The bannerView outlet from the CollectionViewController to the GADBannerView is invalid. Outlets cannot be connected to repeating content.
I used the UIView to get AdMob like this:
https://developers.google.com/mobile-ads-sdk/docs/admob/ios/quick-start
Are there others way to add google AdMob in CollectionView "footer"?
Thank you very much!
A: The error is telling you the problem: "Outlets cannot be connected to repeating content".
Advertising is not allowed to be placed in repeating content views, like collection views, table views, etc.
This is because some ads pay by impression, and in a repeating view the ad may be loaded multiple times causing an impression each time. Ad companies don't like it when you do that because they then have to pay you for false impressions (it's the same as having a webpage with an ad that refreshes itself to try and get more ad revenue).
I know this from my own experience where I placed an ad in a place where it was accidentally clickable by users - I didn't get any complaints from users about its placement, but after Admob noticed how much revenue it generated they limited my earnings rate to 5% of normal and told me it would not be increased again until I moved the advert. So there you have it. Don't place your ads in collection views or table views.
| |
doc_23534754
|
When I tried to post open graph story, logcat says: GraphRequest﹕ Warning: Request without access token missing application ID or client token and story is not being post.
My onCreate method code is:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {//@Overridden method});
}
And Later I called following code from button's onClickListener
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_action"));
I have also handled callback as:
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
The code I used for open graph post is:
Bundle params = new Bundle();
params.putString("match", "http://samples.ogp.me/413385652011237");
GraphRequest request = new GraphRequest(
AccessToken.getCurrentAccessToken(),
"me/tigertraptest:complete",
params,
HttpMethod.POST
);
GraphResponse response = request.executeAndWait();
Also I have tried all solution suggested in this link: failed solution.
I'm new to Facebook Integration. Please help.
Edit I have posted all codes that I used in my activity to enable Facebook open graph post.
A: You have to use accesstokentracker to track your accesstoken since it changes after some time. You also have to add the method onCurrentAccessTokenChanged. You can refer to
Getting null response in android fb graph api
for the code. Although in that code, group feeds are being fetched but you cam see the part related to access token.
A: You need to pass access token also.
params.putString("access_token", "YOUR_ACCESS_TOKEN");
| |
doc_23534755
|
User.add_to_class('new_field', models.BooleanField(default=False))
and in admin.py I've got the following (with fieldsets basically just copied from django/contrib/auth/admin.py)
class AdjUserAdmin(UserAdmin):
list_display = UserAdmin.list_display + ('new_field',)
list_filter = UserAdmin.list_filter + ('new_field',)
fieldsets = UserAdmin.fieldsets
fieldsets[1][1]['fields'] = ('first_name','last_name','email','new_field')
The problem is, when I do this I get the error:
AdjUserAdmin.fieldsets[4][1]['fields']' refers to field 'new_field' that is missing from the form.
I've looked at UserChangeForm, but it looks like it's already correctly pulling in User as the model. I'm not sure as to why new_field is missing from the form.
Thanks
In regards to this being smelly code
I know this is a smelly monkey patching way to go about doing this, but subclassing gives me issues mainly for these reasons.. if I could get it to work the way stated above, I'd be happy.. and maybe smelly.
In regards to the recommended way
I'm aware of the recommended way of creating a user profile, just that in particular situations, I don't see the merit in creating an entire new table and having an additional call to the database when all I want to store is an extra bit of information such as is_private or some such. If I'm storing lots more info, then I agree, setting up a user profile is preferable.
A: Just figured this out, perhaps this could help you as well.
Since you don't mention that you have a separate profile, if you want to simply add a column to the existing User admin, you can do the following in admin.py:
First you create a custom admin by subclassing UserAdmin:
class CustomUserAdmin(UserAdmin):
list_display = UserAdmin.list_display + ('is_complete',)
def is_complete(self, obj):
# Example here, you can use any expression.
return SomeOtherClass.objects.get(my_field=obj).is_complete()
# Not required, but this gives you a nice boolean field:
is_complete.boolean = True
Then unregister the existing UserAdmin and register your own:
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
A: It is preferred to write your own user profile class, and attach it to the User model. Then you can use the get_profile() method to retrieve the profile from the user.
Subclassing the profile admin from an Inline Admin should also allow you to edit the profile on the user's page, which is almost what you're trying to do.
This post has a really good write-up on the issue: http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/
A: First the "is it plugged in?" question -- Have you manually added new_field to the users table in the database? Syncdb wouldn't have taken care of that, of course.
After that, I would try appending the fields onto the existing UserAdmin rather than rebuilding it from scratch:
from django.contrib.auth.admin import UserAdmin
UserAdmin.list_display += ('new_field',) # don't forget the commas
UserAdmin.list_filter += ('new_field',)
UserAdmin.fieldsets += ('new_field',)
A: Despite your DB look up concerns for having a UserProfile, that is really the way you should go for this problem. There are two main reasons for this:
*
*The User Model is pretty tightly coupled to Django's authentication system and to many other plugins. Monkey patching it isn't a good idea.
*Django has built-in support for creating User Profiles and many extensions know how to play nicely with these. By using User Profiles (see http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users for the main discussion on this) you can benefit from that.
If you're looking to add functionality to the Admin interface for users, then this note may be helpful:
http://www.thenestedfloat.com/articles/displaying-custom-user-profile-fields-in-djangos-admin/index.html
Regards,
Ian
A: Based on @anschauung response, what worked for me in Django 3.2 is:
from django.contrib.auth.admin import UserAdmin
# don't forget the commas
UserAdmin.list_filter += ('new_field',)
UserAdmin.fieldsets += (('Extra Fields', {'fields': ('new_field', )}),)
A: I got the 'that is missing from the form' error, and discovered that it was due to my field being marked as 'editable=False' in the model.
| |
doc_23534756
|
My issue is with the Highlighting of the result.
I want to only have the first match highlighted.
I use the very basics as described here : https://ng-bootstrap.github.io/#/components/typeahead/examples
Code: https://ng-bootstrap.github.io/stackblitzes/typeahead/http/stackblitz.html
List : ['ABCD AAAA ABCD', 'BBBB ABCD BBBB', 'CCCC CCCC CCCC'];
Search : 'ABCD'
The output I want :
'**ABCD** AAAA ABCD'
'BBBB **ABCD** BBBB'
The output I get :
'**ABCD** AAAA **ABCD**'
'BBBB **ABCD** BBBB'
What should I do to limit the highlight to the first part ?
Example:
HTML
<div class="form-group">
<label for="typeahead-http">Search for a wiki page:</label>
<input id="typeahead-http" type="text" class="form-control" [class.is-invalid]="searchFailed" [(ngModel)]="model" [ngbTypeahead]="search" placeholder="Wikipedia search" />
<span *ngIf="searching">searching...</span>
<div class="invalid-feedback" *ngIf="searchFailed">Sorry, suggestions could not be loaded.</div>
</div>
TypeScript
import {Component, Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {catchError, debounceTime, distinctUntilChanged, map, tap, switchMap} from 'rxjs/operators';
const WIKI_URL = 'https://en.wikipedia.org/w/api.php';
const PARAMS = new HttpParams({
fromObject: {
action: 'opensearch',
format: 'json',
origin: '*'
}
});
@Injectable()
export class WikipediaService {
constructor(private http: HttpClient) {}
search(term: string) {
if (term === '') {
return of([]);
}
return this.http
.get(WIKI_URL, {params: PARAMS.set('search', term)}).pipe(
map(response => response[1])
);
}
}
@Component({
selector: 'ngbd-typeahead-http',
templateUrl: './typeahead-http.html',
providers: [WikipediaService],
styles: [`.form-control { width: 300px; display: inline; }`]
})
export class NgbdTypeaheadHttp {
model: any;
searching = false;
searchFailed = false;
constructor(private _service: WikipediaService) {}
search = (text$: Observable<string>) =>
text$.pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => this.searching = true),
switchMap(term =>
this._service.search(term).pipe(
tap(() => this.searchFailed = false),
catchError(() => {
this.searchFailed = true;
return of([]);
}))
),
tap(() => this.searching = false)
)
}
A: As to avoid touching the code of ngb-typeahead I've made a "fix" on my CSS.
Not the pretiest solution, but at least it's working visually.
Here is the generated HTML by ngb-typeahead (untouched, I just removed the comments).
Search term : 'ABCD'
<ngb-highlight ng-reflect-result="'ABCD AAAA ABCD" ng-reflect-term="act">
<span class="ngb-highlight">ABCD</span>
AAAA
<span class="ngb-highlight">ABCD</span>
</ngb-highlight>
So my solution :
.ngb-highlight {
font-weight: normal !important;
}
ngb-highlight .ngb-highlight:first-child {
font-weight: bold !important;
}
As you can see, not the prettiest but at least I don't have to modify anything that could be override in the futur.
Anyway, thx for your help everyone !
A: NgbHighlight cannot do it. You can easily implement the component you need based on NgbHighlight source code. It's a tiny component and a small change. You just need to change regex a bit to split only on the first occurrence of a term
ngOnChanges(changes: SimpleChanges) {
const result = toString(this.result);
const terms = Array.isArray(this.term) ? this.term : [this.term];
const escapedTerms = terms.map(term => regExpEscape(toString(term)))
.map(term => `${term}(.+)`)
.filter(term => term);
this.parts = escapedTerms.length ? result.split(new RegExp(`(${escapedTerms.join('|')})`, 'gmi')) : [result];
}
the code was never tested (: not sure if it will work with several terms
| |
doc_23534757
|
Computer IP
-------- --
IMPPRD1 172.22.30.33
IMPPRD2 172.22.30.31
IMPPRD3 172.22.30.32
IMPSR1 172.22.30.12
IMPPRD5 172.22.30.17
I would like it to be a normal CSV, so something like this :
Computer,IP
IMPPRD1,172.22.30.33
IMPPRD2,172.22.30.31
IMPPRD3,172.22.30.32
IMPSR1,172.22.30.12
How could I manage to do this using powershell?
Thanks !
A: Using > outputs as normal text - including the spaces between columns. Basically the same as Write-Output. You are looking for Export-Csv which outputs in CSV format.
| |
doc_23534758
|
To me it seems like the "Cover as.." attempt to run the tests with the wrong persistence.xml, eg not using the one in src/test/resources/META-INF but rather src/main/resources/META-INF (or no one at all).
Is there a way to tell cobertura that it needs the files in src/test/resources to run the tests?
Should I report a bug to the eCobertura-developers?
| |
doc_23534759
|
For example:
If I set a header like "access-control-allow-credentials", it will be sent as "Access-Control-Allow-Credentials", which the consumer does not recognize.
I know these headers should be case insensitive, but because I cannot modify the consumer, I'm hoping there is a way to pass them through without modifying the case.
Any help is greatly appreciated!
Best regards,
Royce
| |
doc_23534760
|
If i report an int score from the same viewcontroller, it seems to work fine. I can send that number to the leaderboard set up in game center.
When I report an int score that is from another viewcontroller, it doesn't work. At first I thought it was because the numbers weren't in int64_t. I'm not sure if that is really the issue though.
I'm fairly new to ios programming. If this is a duplicate question, please direct me in the right direction. I really appreciate any help.
-(IBAction)report:(id)sender{
[self reportScore]; //just calling the method
}
-(void)reportScore{
GKScore *score = [[GKScore alloc] initWithLeaderboardIdentifier:_leaderboardIdentifier];
score.value = HighScore; //HighScore is the int I want from another viewcontroller.
[GKScore reportScores:@[score] withCompletionHandler:^(NSError *error) {
if (error != nil) {
NSLog(@"%@", [error localizedDescription]);
}
}];
}
A: I guess
GKScore *score = [[GKScore alloc] initWithLeaderboardIdentifier:_leaderboardIdentifier];
This line creating the object each time. And thats the reason you are getting the wrong result.
Try to create GKScore *score object only once which will be global and then access it.
| |
doc_23534761
|
val buffer = ByteBuffer.allocate(Packet.MAX_PACKET_SIZE)
while (continueRunning) {
buffer.clear()
val address = socket.receive(buffer) // DatagramChannel in non-blocking mode
buffer.flip()
// No packets received, always null
if (address != null) {
val data = ByteArray(buffer.limit())
buffer.get(data, 0, buffer.limit())
val packet = DatagramPacket(data, data.size, address)
// threadPool is created with Executors.newCachedThreadPool()
threadPool.submit { packetProcessor.processPacket(packet) }
}
val answer = answerQueue.poll() // ConcurrentLinkedQueue
// Answer queue is always empty, so this is always null as well
if (answer != null) socket.send(ByteBuffer.wrap(answer.data), answer.socketAddress)
}
After calling start() function for this thread the application's CPU usage jumps to 15 - 25% and stays at this value while the thread is not stopped. I am actually okay with it. But I wonder if it is a normal situation when the server takes a lot of CPU time while doing nothing except of running an infinite loop? Or should I use some tricks to lower the CPU usage? And if I should, what should I do?
| |
doc_23534762
| ||
doc_23534763
|
Parent Side:
<!DOCTYPE html>
<html>
<head>
<title>Parent</title>
</head>
<body>
<script type="text/javascript">
window.onload = function() {
let el_win = window.open("https://www.example.com/child/", "_blank", "toolbar=no, scrollbars=no, resizable=no, top=0, left=0, width="+screen.availWidth+", height="+screen.availHeight);
el_win.focus();
el_win.postMessage("hello","*");
}
</script>
</body>
</html>
Child Side:
<!DOCTYPE html>
<html>
<head>
<title>child</title>
</head>
<body>
<script type="text/javascript">
window.addEventListener("message", function(e) {
alert("Message Recieved");
console.log(e.data);
}, false);
</script>
</body>
</html>
Even alert() is not called in child window and also no data in console.log()
| |
doc_23534764
|
, just trying to create a simple linked list
here is the code
class node:
def __init__(self, data = None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
def length(self):
cur = self.head
total = 0
while cur.next != None:
total += 1
cur = cur.next
return total
@property
def display(self):
elems = []
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
elems.append(cur_node.data)
print(elems)
def get(self, index):
if index >= self.length():
print('index out of range')
return None
cur_idx = 0
cur_node= self.head
while True:
cur_node = cur_node.next
if cur_idx == index: return cur_node.data
cur_idx+= 1
def erase(self, index):
if index >= self.length():
print('index out of range')
return None
cur_idx = 0
cur_node = self.head
while True:
last_node = cur_node
cur_node = cur_node.next
if cur_idx == index:
last_node.next = cur_node.next
return
cur_idx+= 1
l1 = linked_list()
l1.append(8)
l1.append(7)
l1.append(6)
l1.append(5)
print(l1.get(0))
print(l1.get(1))
print(l1.get(2))
print(l1.get(3))
everything went well except when I tried to put node class into linked list class as an inner class like below:
class linked_list:
class node:
def __init__(self, data = None):
self.data = data
self.next = None
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
......
(the rest are the same as the code above)
I got this error :
Traceback (most recent call last):
File "c:\blahblah\Basic_exercise.py", line 65, in <module>
l1 = linked_list()
File "c:\blahblah\Basic_exercise.py", line 11, in __init__
self.head = node()
NameError: name 'node' is not defined
1.what logic did I miss here?
2.Is there any way that I can treat node class as an inner class without getting errors?
A: The error you are seeing is due to the way you are referencing your innner class - it is a namespace issue. To disambiguate your inner node class from other node classes, you need to reference it by first using the outer class: linked_list.node.
Example:
class linked_list:
class node:
def __init__(self, data = None):
self.data = data
self.next = None
def __init__(self):
self.head = linked_list.node()
def append(self, data):
new_node = linked_list.node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
A: If you want to keep the node class inside the linked_list class then you need to call the node class from the linked list class. So to do that you must do new_node = linked_list.node(data) . Rest all should be the same
| |
doc_23534765
|
Following is my nginx.conf
charset utf-8;
server {
listen 80;
server_name localhost;
root /usr/nginx/html;
}
server {
listen 443;
server_name localhost;
root /usr/nginx/html;
}
I have added the SSL self-signed certificate in the /usr/nginx folder and exposed port 443 via Dockerfile
The following is my Dockerfile
FROM nginx
COPY dist /usr/nginx/html
RUN chmod -R 777 /usr/nginx/html/*
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY domain.crt /usr/nginx
EXPOSE 80:443
ENTRYPOINT nginx -g 'daemon off;'
Can anyone please explain me is port 443 not allowing any access
A: For nginx server to allow SSL encryption you need to provide ssl flag while listening in nginx.conf
and only ssl certificate will not be sufficient, you will need the ssl certificate key and password as well and they must be configured.
charset utf-8;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
}
server {
listen 443 ssl;
ssl_certificate /usr/nginx/ssl.crt;
ssl_certificate_key /usr/nginx/ssl.key;
ssl_password_file /usr/nginx/ssl.pass;
server_name localhost;
root /usr/nginx/html;
}
And you need to put the ssl certificate, key and password via volumes or via embedding in docker container. If you are running container over kubernetes cluster, adding them via kubernetes secrets will be better option.
For Dockerfile you can add like
FROM nginx
COPY dist /usr/nginx/html
RUN chmod -R 777 /usr/nginx/html/*
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY ssl.crt /usr/nginx/
COPY ssl.pass /usr/nginx/
COPY ssl.key /usr/nginx/
EXPOSE 80:443
ENTRYPOINT nginx -g 'daemon off;'
For further info you can refer the Nginx Docker article https://medium.com/@agusnavce/nginx-server-with-ssl-certificates-with-lets-encrypt-in-docker-670caefc2e31
| |
doc_23534766
|
although all data is saved. And which operator has a null value, I can’t understand, after all, everything is saved. How can I remove this error or warning?
text_field
class PriceCounter extends StatefulWidget {
PriceCounter({Key? key, required this.price, this.onChanged})
: super(key: key);
double price;
final Function(double)? onChanged;
@override
State<PriceCounter> createState() => _PriceCounterState();
}
class _PriceCounterState extends State<PriceCounter> {
final _priceController = TextEditingController();
@override
void dispose() {
_priceController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final FilterPriceCubit cubit = BlocProvider.of<FilterPriceCubit>(context);
return BlocBuilder<FilterPriceCubit, FilterPriceState>(
builder: (context, state) {
_priceController.text = state.fitlerPrice.toStringAsFixed(2).toString();
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 21),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: () => cubit.priceFilterDecrement(state.fitlerPrice),
icon: SvgPicture.asset(constants.Assets.minus),
constraints: const BoxConstraints(),
padding: EdgeInsets.zero,
),
const SizedBox(width: 20),
SizedBox(
width: 100,
child: TextFormField(
keyboardType: TextInputType.number,
// controller: _priceController
// ..text = widget.price.toStringAsFixed(2),
controller: _priceController,
style: constants.Styles.normalBookTextStyleWhite,
textAlign: TextAlign.center,
decoration: const InputDecoration(
prefix: Text('JC',
style: constants.Styles.normalBookTextStyleWhite),
suffix: Text(
'KWh',
style: constants.Styles.smallerBookTextStyleWhite,
),
contentPadding: EdgeInsets.zero,
border: InputBorder.none,
),
onFieldSubmitted: (value) {
cubit.setPrice(value);
widget.onChanged!(double.parse(value));
},
error
A: An error occurs at this point:
widget.onChanged!(double.parse(value));
You have to be sure that widget.onChanged isn't null.
The best way is:
if (widget.onChanged != null) {
widget.onChanged!(double.parse(value));
}
or
widget.onChanged?.call(double.parse(value));
| |
doc_23534767
|
I have been able to retrieve video Ids with the code below,
however, I cannot retrieve the insights. I'm hoping that
by using the video ID I can do a Get on the following URL:
https://insight.youtube.com/video-analytics/csvreports?query=VIDEO_ID&type=v&starttime=1330727299&endtime=1331677699®ion=world&hl=en_US&userName=USERNAME&password=PASSWORD&token=DEV_TOKEN
Though this URL doesn't seem to work.
Any ideas? A specific C# code example would be invaluable.
public class UnixTime
{
public static string ToUnixTime(DateTime dateTime)
{
return (Math.Round((dateTime - new DateTime(1970, 1, 1, 0, 0, 0).ToLocalTime()).TotalSeconds, 0)).ToString() ;
}
}
public void PrepareAndDownloadFile(string username, string password, string token,
string channel, string destination)
{
YouTubeRequestSettings settings = new YouTubeRequestSettings(channel, token, username, password);
YouTubeRequest request = new YouTubeRequest(settings);
string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads?v=2", channel);
Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
foreach (Video video in videoFeed.Entries)
{
StringBuilder url = new StringBuilder();
url.Append("https://insight.youtube.com/video-analytics/csvreports");
url.Append(String.Format("?query={0}", video.VideoId));
url.Append("&type=v");
url.Append(String.Format("&starttime={0}", UnixTime.ToUnixTime(DateTime.Now.AddDays(SINCE_OFFSET))));
url.Append(String.Format("&endtime={0}", UnixTime.ToUnixTime(DateTime.Now.AddDays(UNTIL_OFFSET))));
url.Append("®ion=world");
url.Append("&hl=en_US");
url.Append(String.Format("&userName={0}", username));
url.Append(String.Format("&password={0}", password));
url.Append(string.Format("&token={0}", token));
// make Http Request here given the new url.
dynamic rows = GetPath(url.ToString());
processor.WriteRows(destination, rows);
}
}
A: Jeffrey Posnick Post reply
10:53 AM (1 hour ago)
Hello,
I don't have any C# code readily available, but I can tell you what
you're doing wrong. You should not be manually creating YouTube
Insight URLs. You can't do it. You seem to be using your YouTube
authentication token as the value of the "token=" URL parameter, and
sticking your username and password in the URL for good measure, but
that's completely the wrong approach. The Insight URL is uniquely
generated by the API and exposed in an authenticated request for a
video entry by that entry's owner, in a element. This is
explained at
https://developers.google.com/youtube/2.0/developers_guide_protocol_insight
Again, you can't manually create the URL. The only time you need to
modify the automatically generated URL at all is if you want to modify
the user_starttime or user_endtime parameters, which is also covered
in the docs.
Cheers,
-Jeff Posnick, YouTube API Team
groups.google.com/group/youtube-api-gdata | apiblog.youtube.com |
@YouTubeDev
| |
doc_23534768
|
public class RankingEntity
{
public string Tournament { get; set; }
public IList<SelectListItem> Years { get; set; }
}
public class Years
{
public int Year { get; set; }
public string YearDisplay { get; set; }
}
Controller's code:
public ActionResult Index()
{
var years = _rankingService.GetAllYears().ToList();
var model = new RankingEntity();
if (years != null)
{
foreach (var y in years)
{
model.Years.Add(new SelectListItem
{
Text = y.Year.ToString(),
Value = y.Year.ToString()
});
}
}
return View(model);
}
I am getting error on model.Years.Add(new SelectListItem i.e. "Object reference"
please correct me,
| |
doc_23534769
|
function getPropImplicitAny<T, K extends keyof T>(p: K, buffer: T): T[K] {
const { [p]: value } = buffer; // element implicitly has an 'any' type
// because T has not index signature
return value;
}
function getPropTyped<T, K extends keyof T>(p: K, buffer: T): T[K] {
const value = buffer[p]; // value:T[K]
return value;
}
In my view both functions know the same about the structure of the T type and its relations with the K. Both of them access member of T by index syntax. Yet the first one fails to compile in strict mode.
Why?
A: The issue you are describing has been fixed in typescript 3.2. This issue describes your exact problem and it was included in typescript 3.2
| |
doc_23534770
|
public enum MyEnum = {A=0, B=1, C=3};
and get an error invalid type in Eclipse.
A: That's not how they are used. See examples at http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html, such as
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Java enums are much more powerful than in, say, C#. They're (almost) full-blown objects, and thus cannot be represented with just a number. They can however contain a number, and they do have an ordinal number value.
You could have the number value with
public enum MyEnum {
A(0), B(1), C(3);
private final int number;
MyEnum(int number) {
this.number = number;
}
}
A: Java enums are quite different to C and C++ enums. The biggest difference is that the enum constants are full-blown objects rather than compile-time integer constants.
In your example, A, B and C are objects. Therefore constructs like A=0, B=1, C=3 are not allowed.
I recommend taking a look at the tutorial.
If you have to associate numeric values with enum constants, you can achieve a similar effect like so:
public enum MyEnum {
A(0), B(1), C(3);
public final int val;
private MyEnum(int val) {
this.val = val;
}
}
Having done this, you can access the values using MyEnum.A.val etc.
A: In Java, enum is a type, but it is incompatible with integers. Enum objects are closer to classes than to primitives, in that they can have methods, member variables, and so on.
Java lets you get the effect that you wanted by adding an int member to your enumeration, and initializing it differently for different enumeration members, like this:
public enum MyEnum {
A(1), B(2), C(3);
int val;
private MyEnum (int v) {
val = v;
}
public int value() {
return val;
}
};
Now each member of your enum has a public method value() that returns the integer value associated with the corresponding element of the enumeration.
A: you can't do this as you do. enum define in java in the following way
enum myenum{a,b,c,d}
A: public enum ModuleType {A,B,C}
A: To answer your question: enum is technically not a type. Therefore you cannot define a variable of type enum as you have tried.
enum is a keyword to define an enumerated (abbreviated to enum) type which is a special data type.
Once an enum type is defined (very much like how you would define a class), you refer to it using the name of the enum type. Please check the enum types documentation.
| |
doc_23534771
|
A: Microsoft Ads use an algorithm designed for targeted advertising based off of information they receive from the users of a given application. Sometimes the advertising targets a specific user, sometimes it targets a specific app's demographic.
There are quite a few possible reasons that your app is displaying primarily Microsoft ads. It could be that you and your friend are both prime targets for Microsoft products. It could be that your app's demographic or genre is targeted for Microsoft ads.
It could also be that Microsoft's own ads are the default (likely, I'd think). It may take a bit for the demographics information to be received by Microsoft ads, or any other numerous reasons that the default ads are currently being displayed.
Basically, as of right now, there is nothing pointing at this being your fault. With more datapoints over more time, we could possibly begin to eliminate unlikely causes (such as sync time on a specific device).
I don't think you have anything to worry about now. If your ad revenue is particularly low or otherwise anomalous, then maybe there is some need for concern, but until there is some more information, we can only speculate.
| |
doc_23534772
|
keyword param1 param2 ... paramN : cc eth usd 1
that will be mapped into https://currencio.co/%s/%s/%s/ or https://currencio.co/%1/%2/%3/ using relative or absolute references respectively.
It's similar to what searchEngines do, but they are limited to only one substitution.
The query url is: http://www.wolframalpha.com/input/?i=%s
Is that possible or might there be an extension that does that?
| |
doc_23534773
|
https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/table-view.htm
This class creates TextField for edit purposes. Clicking on another row launches cancel() method. And there is this code line:
setText((String( getItem());
that blocks edit. I replaced it with:
setText((String) textField.getText());
and edit works now. But after editing this cell again old value is loaded to TextField. I guess that ObservableList is not updated after first edit.
Here is FXML code:
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<TableView GridPane.columnIndex="0" GridPane.rowIndex="1" items="${controller.data}" editable="true">
<columns>
<TableColumn fx:id="colName" text="name">
<cellValueFactory>
<PropertyValueFactory property="Name"/>
</cellValueFactory>
</TableColumn>
<TableColumn fx:id="colSurname" text="surname">
<cellValueFactory>
<PropertyValueFactory property="Surname"/>
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
</GridPane>
In controller I declare ObservableList:
public class Controller {
@FXML
private TableColumn<Person, String> colName;
@FXML
private TableColumn<Person, String> colSurname;
@FXML
private ObservableList<Person> data;
public Controller(){
data = FXCollections.observableArrayList(
new Person("John", "S."),
new Person("Jane", "S.")
);
}
public TableColumn<Person, String> getColName() {
return colName;
}
public void setColName(TableColumn<Person, String> colName) {
this.colName = colName;
}
public TableColumn<Person, String> getColSurname() {
return colSurname;
}
public void setColSurname(TableColumn<Person, String> colSurname) {
this.colSurname = colSurname;
}
public ObservableList<Person> getData() {
return data;
}
public void setData(ObservableList<Person> data) {
this.data = data;
}
}
Person.java code:
public class Person {
private final SimpleStringProperty name;
private final SimpleStringProperty surname;
public Person(String name, String surname){
this.name = new SimpleStringProperty(name);
this.surname = new SimpleStringProperty(surname);
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public String getSurname() {
return surname.get();
}
public SimpleStringProperty surnameProperty() {
return surname;
}
public void setSurname(String surname) {
this.surname.set(surname);
}
}
In Main I declare controller and editable column:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = (Parent) loader.load();
primaryStage.setScene(new Scene(root, 300, 275));
Controller controller = loader.getController();
TableColumn<Person, String> colName = controller.getColName();
Callback<TableColumn<Person, String>, TableCell<Person, String>> cellFactory =
(TableColumn<Person, String> p) -> new sample.EditCell();
colName.setCellFactory(cellFactory);
colName.setOnEditCommit(
(TableColumn.CellEditEvent<Person, String> t) -> {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setName(t.getNewValue());
});
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Do I need bind cell with ObservableList? Or refresh it? How to update data to have TextField always filled with actual value?
Here is whole EditCell class:
class EditCell extends TableCell<Person, String> {
private TextField textField;
public EditCell() {
}
@Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
//setText((String) textField.getText());
//This line updates cell, but textField keeps old value after next edit.
setGraphic(null);
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) -> {
if (!arg2) {
commitEdit(textField.getText());
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
A: Editing
When editing, the onEditCommit handler is notified when an edit has been committed (unsurprisingly). This handler is responsible for writing the new value to the model (in your case, Person). When this happens the TableView will automatically update to display the new value.
Your solution to set the text of the Cell to the value of the TextField when the edit is cancelled won't work. Eventually, once an update is triggered somehow, the Cell will refresh to display the real data provided by the model (obtained by the cellValueFactory). Besides that, you haven't actually updated the model and so the supposed edit is just a visual thing.
About the Tutorial
The tutorial you link to has issues. The biggest of which is that it assumes when the TextField loses focus you can successfully commit the new value. As you are experiencing, this is not the case. You can see many others have experienced this problem by looking the this question: TableView doesn't commit values on focus lost event. The answers to that question provide many ways to hack around the problem. Some also point to bug reports, indicating the no-commit-on-lost-focus behavior is actually unintended; however, those bugs have not been fixed as of JavaFX 11.0.2.
What this means is that:
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) -> {
if (!arg2) {
commitEdit(textField.getText());
}
});
Won't ever commit the edit. You (but really the tutorial) provide no working means to commit the new value because the edit is cancelled by the time if (!arg2) { commitEdit(...); } is invoked. Since the edit is cancelled there is no commit edit event fired and your TableColumn can't write the new value to the model item. What you can do, though this won't fix the no-commit-on-lost-focus problem, is add an onAction handler to your TextField that commits the edit. You'll probably want to provide a means to cancel the edit via the keyboard as well. This would look something like:
textField.setOnAction(event -> {
commitEdit(textField.getText());
event.consume();
}
textField.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ESCAPE) {
cancelEdit();
event.consume();
}
}
This will commit the edit when the Enter key is pressed and cancel the edit when the Esc key is pressed.
Note that TextFieldTableCell already provides this behavior out of the box, no need to roll your own EditCell implementation. However, if you want to commit the edit when the focus is lost then you'll have to look at the answers to TableView doesn't commit values on focus lost event (or its linked/related questions) and attempt to use one of the given solutions (hacks).
Also, as noted in the below documentation, you don't have to provide your own onEditCommit handler in order to write the new value to the model—TableColumn does that by default (assuming cellValueFactory returns a WritableValue).
Documentation
Perhaps reading the documentation of TableView will be more beneficial than, or at least complimentary to, the tutorial you're reading:
Editing
This control supports inline editing of values, and this section attempts to give an overview of the available APIs and how you should use them.
Firstly, cell editing most commonly requires a different user interface than when a cell is not being edited. This is the responsibility of the Cell implementation being used. For TableView, it is highly recommended that editing be per-TableColumn, rather than per row, as more often than not you want users to edit each column value differently, and this approach allows for editors specific to each column. It is your choice whether the cell is permanently in an editing state (e.g. this is common for CheckBox cells), or to switch to a different UI when editing begins (e.g. when a double-click is received on a cell).
To know when editing has been requested on a cell, simply override the Cell.startEdit() method, and update the cell text and graphic properties as appropriate (e.g. set the text to null and set the graphic to be a TextField). Additionally, you should also override Cell.cancelEdit() to reset the UI back to its original visual state when the editing concludes. In both cases it is important that you also ensure that you call the super method to have the cell perform all duties it must do to enter or exit its editing mode.
Once your cell is in an editing state, the next thing you are most probably interested in is how to commit or cancel the editing that is taking place. This is your responsibility as the cell factory provider. Your cell implementation will know when the editing is over, based on the user input (e.g. when the user presses the Enter or ESC keys on their keyboard). When this happens, it is your responsibility to call Cell.commitEdit(Object) or Cell.cancelEdit(), as appropriate.
When you call Cell.commitEdit(Object) an event is fired to the TableView, which you can observe by adding an EventHandler via TableColumn.setOnEditCommit(javafx.event.EventHandler). Similarly, you can also observe edit events for edit start and edit cancel.
By default the TableColumn edit commit handler is non-null, with a default handler that attempts to overwrite the property value for the item in the currently-being-edited row. It is able to do this as the Cell.commitEdit(Object) method is passed in the new value, and this is passed along to the edit commit handler via the CellEditEvent that is fired. It is simply a matter of calling TableColumn.CellEditEvent.getNewValue() to retrieve this value.
It is very important to note that if you call TableColumn.setOnEditCommit(javafx.event.EventHandler) with your own EventHandler, then you will be removing the default handler. Unless you then handle the writeback to the property (or the relevant data source), nothing will happen. You can work around this by using the TableColumnBase.addEventHandler(javafx.event.EventType, javafx.event.EventHandler) method to add a TableColumn.editCommitEvent() EventType with your desired EventHandler as the second argument. Using this method, you will not replace the default implementation, but you will be notified when an edit commit has occurred.
| |
doc_23534774
|
Use case: I would like to create a common interface to call the subclasses from the base class.
Example:
#basemodule.py
class BaseClass(object):
@abstractmethod
def method(self, inputs=None):
pass
def get_subclasses():
#I want derived class information here
for cls in list(BaseClass.__subclasses__):
# call subclasses here
# module1.py
import BaseClass
class derivedClass1(BaseClass):
def __init__(self):
super().__init__()
def method(self, inputs):
# method implemented in derivedClass1
# module2.py
import BaseClass
class derivedClass2(BaseClass):
def __init__(self):
super().__init__()
def method(self, inputs):
# method implemented in derivedClass2
Any suggestions are appreciated! Thanks :)
A: Your question is a little bit vague, and lacks important details, like the error you're getting, and a bit more context regarding your actual goals here. Having said that, I've noticed a couple of things that might be the cause of the problems you're having:
*
*BaseClass.__subclasses__ is a method, therefore, you need to call it instead of accessing it, like you access a class property, or attribute. To do so, use BaseClass.__subclasses__() instead.
*In order to your get_subclasses() function to work, you need to first import the subclasses. Otherwise python won't know which classes inherit from BaseClass.
Corrected code
Here's the correct implementation of get_subclasses() function, as mentioned above:
from basemodule import BaseClass
def get_subclasses():
"""Get subclasses from `basemodule.BaseClass`."""
for cls in list(BaseClass.__subclasses__()):
# call subclasses here
print(cls.__name__) # Added print statement to test the solution.
Example
Without importing module1, and module2
Here's an example of the output from get_subclasses() I receive, when I don't import the modules that host the subclasses:
Importing module1, and module2
When I import both modules that host the subclasses, you then get the output I think you're expecting:
Full-code
Here's the full code of the examples:
# my_pckg/basemodule.py
from abc import ABCMeta, abstractmethod
class BaseClass(object):
@abstractmethod
def method(self, inputs=None):
pass
# ================================================
# my_pckg/module1.py
from my_pckg.basemodule import BaseClass
class derivedClass1(BaseClass):
def __init__(self):
super().__init__()
def method(self, inputs):
# method implemented in derivedClass1
pass
# ================================================
# my_pckg/module2.py
from my_pckg.basemodule import BaseClass
class derivedClass2(BaseClass):
def __init__(self):
super().__init__()
def method(self, inputs):
# method implemented in derivedClass2
pass
# ================================================
# my_pckg/test.ipynb
from basemodule import BaseClass
from module1 import *
from module2 import *
def get_subclasses():
"""Get subclasses from `basemodule.BaseClass`."""
for cls in list(BaseClass.__subclasses__()):
# call subclasses here
print(cls.__name__) # Added print statement to test the solution.
get_subclasses()
# Prints:
# derivedClass1
# derivedClass2
Important notes
The imports as shown in the example pictures won't work, if you're trying to use them from outside the parent module. In the example I just gave, here's the complete tree view of the entire package structure:
my_pckg
|______init__.py # <-- Needed to make my_pckg submodules "importable".
|____basemodule.py # <-- Hosts the BaseClass class.
|____module1.py # <-- Hosts the derivedClass1 subclass.
|____module2.py # <-- Hosts the derivedClass2 subclass.
|____Test.ipynb # <-- Where the test from the screenshots took place.
If you want to import these modules from outside the package you have two options:
*
*Create a setup for you package, and pip install it (use the -e flag to install it in development mode).
*Import sys, and add my_pckg path to the known paths.
import sys
sys.path.insert(0, './my_pckg')
from basemodule import BaseClass
from module1 import *
from module2 import *
def get_subclasses():
"""Get subclasses from `basemodule.BaseClass`."""
for cls in list(BaseClass.__subclasses__()):
# call subclasses here
print(cls.__name__) # Added print statement to test the solution.
get_subclasses()
# Prints:
# derivedClass1
# derivedClass2
For example:
Circular Imports
Do NOT import module1, and module2 inside basemodule, as this leads to a circular import. This happens because when you import basemodule, python will see that the module needs to import module1, and module2 and therefore goes to these modules. There, it finds out that both actually require basemodule themselves, so it goes back to basemodule. You can see that this becomes an infinite circle, where no module is able to be imported. To overcome this, place get_subclasses() function in a separate module, alongside all your necessary imports, like the example pictures.
| |
doc_23534775
|
echo "ÇŞİĞÖÜ, çşıüğö";
There is no problem:
http://i.hizliresim.com/kj9kov.png
But when I encode this string in a JSON array, and put the encoded string in mysql db, it shows like:
{"otherComments":"u00c7u015eu0130u011eu00d6u00dc, u00e7u015fu0131u00fcu011fu00f6"}
and when I do not encode it in a JSON array, it just shows "?" instead of Turkish characters.
I already have this code in my php file:
header('Content-Type: text/html; charset=utf8');
I have no idea what else to do.
This is the code in my dbconnect file:
mysql_query("SET NAMES 'utf8'", $this->con);
mysql_query("SET CHARACTER SET utf8", $this->con);
mysql_query("SET COLLATION_COLLECTION='utf8_turkish_ci'", $this->con);
mysql_select_db("mehmeta3_team6", $this->con);
The settings for the selected schema:
http://i.hizliresim.com/gkrAZN.png
The settings for the table and the column:
http://i.hizliresim.com/YvQlrE.png
A: its not the db side problem
when you convert it to json format echo that string
you will see it converts it to some different format may be to ascii values of those special characters. even if you decode that result it will produce a different result not the strin you encode.
i think try to insert in the database without encodin i mean simple string like ÇŞİĞÖÜ
may be that can work
| |
doc_23534776
|
A: This is quite involved due to the complexity of the several stages of the development process. This link may help you get started that guides you through the processes involved. Hope it helps!
| |
doc_23534777
|
this is the problem code:
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:@"ShowPhoto"])
{
DetailsViewController *dvc = [segue
destinationViewController];
NSIndexPath *path = [[self tableView] indexPathsForSelectedRows];
Photo *pic = [photosArray objectAtIndex:[path row]];
[dvc setCureentPic: pic];
}
}
the problem is the line with NSIndexPath... I think that the reason is that I try insert array into NSIndex.
xcode warning: Incompatible pointer types initializing 'NSIndexPath *__strong' with an expression of type 'NSArray.
the crush message: unrecognized selector sent to instance [__NSArrayI row].
how can I solve the problem?
A: Please do read the documentation (here) of the methods you call instead of making assumptions about what they do...
[[self tableView] indexPathsForSelectedRows]
returns an NSArray and not an NSIndexPath (by the way, you could know this even without reading the docs - in Cocoa naming convention, if something is in plural, then it accepts or returns an NSArray), so sending it the messages of NSIndexPath will crash. Write
NSIndexPath *path = [[[self tableView] indexPathsForSelectedRows] objectAtIndex:0];
instead, and it will work (if there is at least one selected row - if not, you have to check for the array being empty, else it will crash again...)
By the way, the compiler even warns you about what the problem is... Please try to develop some common sense before trying to do programming, because if not, you will shoot yourself and others in the foot.
| |
doc_23534778
|
This only happens when you use a transition to change page, if you change page without a transition the header remains and the footer is correctly positioned at the end of the content.
Thanks
A: I've been troubleshooting this issue all morning because I was having the same one. I don't exactly know what is wrong with the jQuery mobile script, but for some reason it is failing to hide the x-axis overflow for the inactive windows after a page transition effect. I fixed the problem by putting the following CSS inside the page div of the page being transitioned to.
.ui-mobile, .ui-page {
overflow-x: hidden!important;
}
| |
doc_23534779
|
I am sending an Outbound Message from Salesforce and attempting to consume it within Mulesoft. I can receive the message, and process it through CXF as JAX-WS Service.
I would like to do this CXF >> JAVA >> GET RELEVENT VALUE FROM PAYLOAD >> DO MORE STUFF.
This is the issue I am having, I can reference the values from within the Java class, but after that I am lost. Also the Java class implements a interface which returns a boolean based on the WSDL.
What can I do? Should I use a Proxy Service and just work off the XML String?
A: Choose only body in CXF component and transform the XML to Java using transformer as a java collection and use the java class.
A: Use Payload annotation in Java component to access the payload, but prior transformation is required. please check
https://dzone.com/articles/mulesoft-payload-annotation-usage-in-java-componen
| |
doc_23534780
|
public class MyData2Server implements Serializable
{
private String myDataStr;
public String getMyDataStr() { return myDataStr; }
public void setMyDataStr(String newVal) { myDataStr = newVal; }
}
On the client side, I constrain the field myDataStr to be say 20 character max.
I have been reading on web-application security. If I learned something it is client data should not be trusted. Server should then check the data. So I feel like I ought to check on the server that my field is indeed not longer than 20 characters otherwise I would abort the request since I know it must be an attack attempt (assuming no bug on the client side of course).
So my questions are:
*
*How important is it to actually check on the server side my field is not longer than 20 characters? I mean what are the chances/risks of an attack and how bad could the consequences be? From what I have read, it looks like it could go as far as bringing the server down through overflow and denial of service, but not being a security expert, I could be mis-interpreting.
*Assuming I would not be wasting my time doing the field-size check on the server, how should one accomplish it? I seem to recall reading (sorry I no longer have the reference) that a naive check like
if (myData2ServerObject.getMyDataStr().length() > 20) throw new MyException();
is not the right way. Instead one would need to define (or override?) the method readObject(), something like in here. If so, again how should one do it within the context of an RPC call?
Thank you in advance.
A:
How important is it to actually check on the server side my field is not longer than 20 characters?
It's 100% important, except maybe if you can trust the end-user 100% (e. g. some internal apps).
I mean what are the chances
Generally: Increasing. The exact proability can only be answered for your concrete scenario individually (i. e. no one here will be able to tell you, though I would also be interested in general statistics). What I can say is, that tampering is trivially easy. It can be done in the JavaScript code (e. g. using Chrome's built-in dev tools debugger) or by editing the clearly visible HTTP request data.
/risks of an attack and how bad could the consequences be?
The risks can vary. The most direct risk can be evaluated by thinking: "What could you store and do, if you can set any field of any GWT-serializable object to any value?" This is not only about exceeding the size, but maybe tampering with the user ID etc.
From what I have read, it looks like it could go as far as bringing the server down through overflow and denial of service, but not being a security expert, I could be mis-interpreting.
This is yet another level to deal with, and cannot be addressed with server side validation within the GWT RPC method implementation.
Instead one would need to define (or override?) the method readObject(), something like in here.
I don't think that's a good approach. It tries to accomplish two things, but can do neither of them very well. There are two kinds of checks on the server side that must be done:
*
*On a low level, when the bytes come in (before they are converted by RemoteServiceServlet to a Java Object). This needs to be dealt with on every server, not only with GWT, and would need to be answered in a separate question (the answer could simply be a server setting for the maximum request size).
*On a logical level, after you have the data in the Java Object. For this, I would recommend a validation/authorization layer. One of the awesome features of GWT is, that you can use JSR 303 validation both on the server and client side now. It doesn't cover every aspect (you would still have to test for user permissions), but it can cover your "@Size(max = 20)" use case.
| |
doc_23534781
|
When I execute spark.conf.get("spark.task.maxFailures"), I get below error
java.util.NoSuchElementException: spark.task.maxFailures
Has anyone set this on databricks before?
I understand I can set it up using
spark.conf.set("spark.task.maxFailures", 10)
however not sure whether this has to be set up at cluster start time or can be set after that?
A: You can update required spark conf set in clusters advanced section .
| |
doc_23534782
|
void MyFunction(double function(double));
My question is what it means to have a variable of function type, since you can't declare one in any other context. Semantically, how is it different from a function pointer or reference to a function? Is there an important difference between function pointers and variables of function type that I should be aware of?
A: Just like void f(int x[]) is the same as void f(int* x), the following two are identical:
void MyFunction(double function(double));
void MyFunction(double (*function)(double));
Or, in official language (C++03 8.3.5/3), when determining the type of a function,
After determining the type of each parameter, any parameter of type "array of T" or "function returning T" is adjusted to be "pointer to T" or "pointer to function returning T," respectively.
| |
doc_23534783
|
If the "things that run in the background", encounter an error, my view controller catches it, and at this time I want to change UI elements, like bgcolor or add a new label.
But any changes I make are not showing up. This is what I'm trying:
[self performSelectorOnMainThread:@selector(onCompleteFail) withObject:nil waitUntilDone:YES];
- (void)onCompleteFail
{
NSLog(@"Error: Device Init Failed");
mLiveViewerView.backgroundColor= [UIColor whiteColor];
//self.view.backgroundColor = [UIColor whiteColor];
UILabel *tmpLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 200, 30)];
tmpLabel.text = @"Failed to init";
[self.view addSubview:tmpLabel];
}
A: You need to make any UI-related calls on the main thread: UIKit is not thread-safe and you’ll see all kinds of weird behavior from acting as if it is. That could be as simple as switching something from
[self onCompleteFail];
to
[self performSelectorOnMainThread:@selector(onCompleteFail) withObject:nil waitUntilDone:NO];
…or if -onCompleteFail has to be called on the background thread for other reasons, you can wrap your UI calls in a dispatch to the main queue, like this:
- (void)onCompleteFail
{
NSLog(@"Error: Device Init Failed");
dispatch_async(dispatch_get_main_queue(), ^{
mLiveViewerView.backgroundColor= [UIColor whiteColor];
//self.view.backgroundColor = [UIColor whiteColor];
UILabel *tmpLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 200, 30)];
tmpLabel.text = @"Failed to init";
[self.view addSubview:tmpLabel];
});
}
| |
doc_23534784
|
CREATE TABLE 2012_03_09 (
guid_key integer,
property_key integer,
instance_id_key integer,
time_stamp timestamp without time zone,
"value" double precision
)
with these indexes:
CREATE INDEX 2012_03_09_a
ON 2012_03_09
USING btree
(guid_key, property_key, time_stamp);
CREATE INDEX 2012_03_09_b
ON 2012_03_09
USING btree
(time_stamp, property_key);
When I analyze my queries, total amount of time for Append operations bothers me. Can you explain me, why query is running too long? Is there any way how to optimize such query?
Sort (cost=262.50..262.61 rows=47 width=20) (actual time=1918.237..1918.246 rows=100 loops=1)
Output: 2012_04_26.time_stamp, 2012_04_26.value, 2012_04_26.instance_id_key
Sort Key: 2012_04_26.instance_id_key, 2012_04_26.time_stamp
Sort Method: quicksort Memory: 32kB
-> Append (cost=0.00..261.19 rows=47 width=20) (actual time=69.817..1917.848 rows=100 loops=1)
-> Index Scan using 2012_04_26_a on 2012_04_26 (cost=0.00..8.28 rows=1 width=20) (actual time=14.909..14.909 rows=0 loops=1)
Output: 2012_04_26.time_stamp, 2012_04_26.value, 2012_04_26.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_04_27_a on 2012_04_27 (cost=0.00..8.28 rows=1 width=20) (actual time=1.535..1.535 rows=0 loops=1)
Output: 2012_04_27.time_stamp, 2012_04_27.value, 2012_04_27.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_02_a on 2012_05_02 (cost=0.00..12.50 rows=2 width=20) (actual time=53.370..121.894 rows=6 loops=1)
Output: 2012_05_02.time_stamp, 2012_05_02.value, 2012_05_02.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_03_a on 2012_05_03 (cost=0.00..24.74 rows=5 width=20) (actual time=59.136..170.215 rows=11 loops=1)
Output: 2012_05_03.time_stamp, 2012_05_03.value, 2012_05_03.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_04_a on 2012_05_04 (cost=0.00..12.47 rows=2 width=20) (actual time=67.458..125.172 rows=5 loops=1)
Output: 2012_05_04.time_stamp, 2012_05_04.value, 2012_05_04.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_05_a on 2012_05_05 (cost=0.00..8.28 rows=1 width=20) (actual time=14.112..14.112 rows=0 loops=1)
Output: 2012_05_05.time_stamp, 2012_05_05.value, 2012_05_05.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_07_a on 2012_05_07 (cost=0.00..12.46 rows=2 width=20) (actual time=60.549..99.999 rows=4 loops=1)
Output: 2012_05_07.time_stamp, 2012_05_07.value, 2012_05_07.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_08_a on 2012_05_08 (cost=0.00..24.71 rows=5 width=20) (actual time=63.367..197.296 rows=12 loops=1)
Output: 2012_05_08.time_stamp, 2012_05_08.value, 2012_05_08.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_09_a on 2012_05_09 (cost=0.00..28.87 rows=6 width=20) (actual time=59.596..224.685 rows=15 loops=1)
Output: 2012_05_09.time_stamp, 2012_05_09.value, 2012_05_09.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_10_a on 2012_05_10 (cost=0.00..28.85 rows=6 width=20) (actual time=56.995..196.590 rows=13 loops=1)
Output: 2012_05_10.time_stamp, 2012_05_10.value, 2012_05_10.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_11_a on 2012_05_11 (cost=0.00..20.59 rows=4 width=20) (actual time=62.761..134.313 rows=8 loops=1)
Output: 2012_05_11.time_stamp, 2012_05_11.value, 2012_05_11.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_12_a on 2012_05_12 (cost=0.00..8.28 rows=1 width=20) (actual time=12.018..12.018 rows=0 loops=1)
Output: 2012_05_12.time_stamp, 2012_05_12.value, 2012_05_12.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_13_a on 2012_05_13 (cost=0.00..8.28 rows=1 width=20) (actual time=12.286..12.286 rows=0 loops=1)
Output: 2012_05_13.time_stamp, 2012_05_13.value, 2012_05_13.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_14_a on 2012_05_14 (cost=0.00..16.58 rows=3 width=20) (actual time=92.161..156.802 rows=6 loops=1)
Output: 2012_05_14.time_stamp, 2012_05_14.value, 2012_05_14.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_15_a on 2012_05_15 (cost=0.00..25.03 rows=5 width=20) (actual time=73.636..263.537 rows=14 loops=1)
Output: 2012_05_15.time_stamp, 2012_05_15.value, 2012_05_15.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
-> Index Scan using 2012_05_16_a on 2012_05_16 (cost=0.00..12.56 rows=2 width=20) (actual time=100.893..172.404 rows=6 loops=1)
Output: 2012_05_16.time_stamp, 2012_05_16.value, 2012_05_16.instance_id_key
Index Cond: ((guid_key = 2105) AND (property_key = 67) AND (time_stamp >= '2012-04-16 00:00:00'::timestamp without time zone) AND (time_stamp <= '2012-05-16 06:25:50.172'::timestamp without time zone))
Total runtime: 1918.745 ms
UPDATE:
Posting also SQL query:
select time_stamp, value, instance_id_key as segment from perf_hourly_2012_04_26 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_04_27 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_02 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_03 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_04 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_05 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_07 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_08 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_09 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_10 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_11 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_12 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_13 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_14 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_15 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
UNION ALL
select time_stamp, value, instance_id_key as segment from 2012_05_16 where guid_key = 2105 and property_key=67 and time_stamp between '2012-04-16 00:00:00.0'::timestamp without time zone and '2012-05-16 06:25:50.172'::timestamp without time zone
ORDER BY 3 ASC, 1 ASC
A: It looks like you should check Postgresql Partitioning. Your query will be simpler and it may perform better (not 100% sure, but I think it's worth a try)
A: Besides the append, all the rows appear to be obtained index scans of the first type. I'd have to wonder if that's the best index for this. As you seem to be selecting significant time ranges, the only other choices are guid_key and property_key. Which is more selective? The more selective column should be first (that is, if you aren't worried about sorting, which I don't think you should be for 100 rows) Secondly, did you add those indexes for the purposes of this query or other queries? It may make sense to drop them if they aren't useful anywhere else. Indexes can actually slow performance, especially if the table records are already in memory most of the time, as they might require the database to unload the records from memory to load the index (and then load the table records back up once you're finished with the index scan).
The only real suggestion here I can give is to play with it.
Edit:
(of course there's the other issues of why do these records not have some sort of primary key and there is/isn't clustering on the table itself that I ignored but they also come into play here.)
A: The UNION isn't your timing problem, its reported elapsed time is basically the sum of each partition's index scan time. Your _a indexes look to be appropriately selective for your query predicate. The real time culprit I see in the explain analyze is that it's taking a long time to retrieve just a few rows with an index scan on each partition. eg: 125ms for 5 rows on 2012_05_04. The index scan should invoke maybe 0-5 seeks depending on cache state and table size, and if the data isn't clustered, there would then be one seek per data row. A slow single spindle disk should be able to do a seek and block fetch in ~10ms, so worst case for that scan with a crappy storage system is around 100ms, but with more common 7200 or 10K rpm disks, and multiple spindles, the worst case assuming no cache hits should be under 50ms. With decent cache retention, I would expect no more than a few tens of milliseconds for each partition's index scan.
Does this query run faster on a second try immediately after the first? If so, that points to slow storage with a cold cache as the issue. What sort of storage is the database running on? If we're talking about slow laptop drive, or a high latency network mount, that would explain the poor IO perf. Index scan can also be impacted by extreme index bloat. If you have dozens or hundreds of dead index entries because of update/delete churn on the data with improper vacuum regimen, then that could be the culprit. Are these tables regularly vacummed and analyzed?
As Adrian Serafin suggested, you should look into Pg's table partitioning features.
| |
doc_23534785
|
I can start and stop using the spacebar, but I have a problem after I click any button with the mouse: then the focus is on a different button, which I then accidentally press with the space bar.
I want the focus to be on the stop button after I clicked the start button, so I can press the stop button with the space bar. How should I do that?
public void Grid_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Space)
{
if(!isPlaying)
{
StartButton_Click(sender, null);
}
else
{
StopButton_Click(sender, null);
}
}
}
Regards
A: In StartButton_Click call
StopButton.Focus(Focus.Programmatic);
| |
doc_23534786
|
whats the function of the semicolon right after the open brackets of the for-loop below?
if (nCount > 0){
for(; nCount > 0; nCount--){
if (mBitmaplist[nCount - 1] != null){
mBitmaplist[nCount - 1].recycle();
mBitmaplist[nCount - 1] = null;
}
}
}
A: that means there is no statement for initializer part of for loop
similarly if you want to skip the increment portion of for loop it would look like
for( ; nCount > 0; ){
// some code
}
// which is like while loop
From JLS this is the format of for loop
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
you can see that all 3 are optional
A: The statement for (PART1; PART2; PART3) { BODY } works something like this:
PART1;
<<TOP OF LOOP>>
if PART2 is false then go to <<END OF LOOP>>;
do the BODY;
PART3;
go to <<TOP OF LOOP>>;
<<END OF LOOP>>
If you say for (; PART2; PART3) that just means PART1 does nothing. (Same thing for PART3. If you leave out PART2, then nothing is tested, and the go to <<END OF LOOP>> never happens. So the only way to get to the end of the loop is with a break or return or something.)
A: Hope this example helps you understand better:
public static void main(String[] args) {
int i = 0; // you normally put this before the first semicolon in next line
for (;;) {
if (i > 5) {
break; // this "if" normally goes between the 2 semicolons
}
System.out.println("printing:" + i);
i++; // this is what you put after the second semi-colon
}
}
Have fun with Java and keep coding on!
| |
doc_23534787
|
The code of the discriminator (very similar to the MNIST CNN tutorial) is:
def discriminator(x):
"""Compute discriminator score for a batch of input images.
Inputs:
- x: TensorFlow Tensor of flattened input images, shape [batch_size, 784]
Returns:
TensorFlow Tensor with shape [batch_size, 1], containing the score
for an image being real for each input image.
"""
with tf.variable_scope("discriminator"):
x = tf.reshape(x, [tf.shape(x)[0], 28, 28, 1])
h_1 = leaky_relu(tf.layers.conv2d(x, 32, 5))
m_1 = tf.layers.max_pooling2d(h_1, 2, 2)
h_2 = leaky_relu(tf.layers.conv2d(m_1, 64, 5))
m_2 = tf.layers.max_pooling2d(h_2, 2, 2)
m_2 = tf.contrib.layers.flatten(m_2)
h_3 = leaky_relu(tf.layers.dense(m_2, 4*4*64))
logits = tf.layers.dense(h_3, 1)
return logits
while the code for the generator (architecture of InfoGAN paper) is:
def generator(z):
"""Generate images from a random noise vector.
Inputs:
- z: TensorFlow Tensor of random noise with shape [batch_size, noise_dim]
Returns:
TensorFlow Tensor of generated images, with shape [batch_size, 784].
"""
with tf.variable_scope("generator"):
batch_size = tf.shape(z)[0]
fc = tf.nn.relu(tf.layers.dense(z, 1024))
bn_1 = tf.layers.batch_normalization(fc)
fc_2 = tf.nn.relu(tf.layers.dense(bn_1, 7*7*128))
bn_2 = tf.layers.batch_normalization(fc_2)
bn_2 = tf.reshape(bn_2, [batch_size, 7, 7, 128])
c_1 = tf.nn.relu(tf.contrib.layers.convolution2d_transpose(bn_2, 64, 4, 2, padding='valid'))
bn_3 = tf.layers.batch_normalization(c_1)
c_2 = tf.tanh(tf.contrib.layers.convolution2d_transpose(bn_3, 1, 4, 2, padding='valid'))
So far, so good. The number of parameters is correct (checked it). However, I am having some problems in the next block of code:
tf.reset_default_graph()
# number of images for each batch
batch_size = 128
# our noise dimension
noise_dim = 96
# placeholder for images from the training dataset
x = tf.placeholder(tf.float32, [None, 784])
# random noise fed into our generator
z = sample_noise(batch_size, noise_dim)
# generated images
G_sample = generator(z)
with tf.variable_scope("") as scope:
#scale images to be -1 to 1
logits_real = discriminator(preprocess_img(x))
# Re-use discriminator weights on new inputs
scope.reuse_variables()
logits_fake = discriminator(G_sample)
# Get the list of variables for the discriminator and generator
D_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'discriminator')
G_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'generator')
# get our solver
D_solver, G_solver = get_solvers()
# get our loss
D_loss, G_loss = gan_loss(logits_real, logits_fake)
# setup training steps
D_train_step = D_solver.minimize(D_loss, var_list=D_vars)
G_train_step = G_solver.minimize(G_loss, var_list=G_vars)
D_extra_step = tf.get_collection(tf.GraphKeys.UPDATE_OPS, 'discriminator')
G_extra_step = tf.get_collection(tf.GraphKeys.UPDATE_OPS, 'generator')
The problem I am getting is where I am doing the reshape in the discriminator, and the error says:
ValueError: None values not supported.
Sure, the value for the batch_size is None (btw, the same error I am getting even where I am changing it to some number), but shape function (as far as I understand) should get the dynamic shape, not the static one. I think that I am a bit lost here.
For what is worth, I am giving here the link to the entire notebook I am working: https://github.com/TheRevanchist/GANs/blob/master/GANs-TensorFlow.ipynb if someone wants to look at it.
NB: The code here is part of the Stanford CS231n assignment. I have no affiliation with Stanford though, so it isn't homework cheating (proof: the course is finished months ago).
A: The generator seems to be the problem. The output size should match the discriminator. And the other issues are batch norm should be applied before the activation unit. I have modified the code:
with tf.variable_scope("generator"):
fc = tf.layers.dense(z, 4*4*128)
bn_1 = leaky_relu(tf.layers.batch_normalization(fc))
bn_1 = tf.reshape(bn_1, [-1, 4, 4, 128])
c_1 = tf.layers.conv2d_transpose(bn_1, 64, 5, strides=2, padding='same')
bn_2 = leaky_relu(tf.layers.batch_normalization(c_1))
c_2 = tf.layers.conv2d_transpose(bn_2, 32, 5, strides=2, padding='same')
bn_3 = leaky_relu(tf.layers.batch_normalization(c_2))
c_3 = tf.layers.conv2d_transpose(bn_3, 1, 5, strides=2, padding='same')
c_3 = tf.layers.batch_normalization(c_3)
c_3 = tf.image.resize_images(c_3, (28, 28))
c_3 = tf.contrib.layers.flatten(c_3)
c_3 = tf.tanh(c_3)
return c_3
Your code gives the below output when run with the above changes
A: Instead of passing None to reshape you must pass -1.
So this:
x = tf.reshape(x, [tf.shape(x)[0], 28, 28, 1])
becomes
x = tf.reshape(x, [-1, 28, 28, 1])
and this:
bn_2 = tf.reshape(bn_2, [batch_size, 7, 7, 128])
becomes:
bn_2 = tf.reshape(bn_2, [-1, 7, 7, 128])
It will infer the batch size from the rest of the shape you provided.
| |
doc_23534788
|
I found a post about XMLSlurper that says that finding the new Node requires calling parseText again and/or StreaMarkupBuilder (see below). Really?! That seems so kludgy that I thought I'd verify on SO.
Here is a code snippet. The "find" gets NoChildren even though the Node was just added.
codeNode.appendNode {
'lab:vendorData'() {}
}
vendorNode = codeNode.children().find { it.name() == "vendorData" }
"appendNode doea not modify the slurped document directly. The edit is applied "on the fly" when the document is written out using StreamingMarkupBuilder."
http://markmail.org/message/5nmxbhwna7hr5zcq#query:related%3A5nmxbhwna7hr5zcq+page:1+mid:bkdesettsnfnieno+state:results
Why can't I find my new Node?!
A: This is what I got to work. Is not elegant, but got past "update" problem:
...
codeNode.appendNode {
'lab:vendorData'() {}
}
//-- must re-slurp to see appended node
labDoc = new XmlSlurper().parseText(serializeXml(labDoc))
codeNode = getResultNodeFor( nextResult.getCode() );
vendorNode = codeNode.children().find { it.name() == "vendorData" }
...
def String serializeXml(GPathResult xml){
XmlUtil.serialize(new StreamingMarkupBuilder().bind {
mkp.declareNamespace("lab", "www.myco.com/LabDocument")
mkp.yield labDoc
} )
}
| |
doc_23534789
|
How do I detect that with jquery ajax. It hangs on connecting and there is no HTTP Status Code, and no ajax error detected because the file exists.
I have tried using this answer and using error: function(XMLHttpRequest, status, message){ } and using statusCode: { } feature of jquery ajax it doesn't work.
A: There is a similar question with good answer here:
JQuery Ajax - How to Detect Network Connection error when making Ajax call
In short, you can check the "readyState" like:
error: function(XMLHttpRequest) {
if (XMLHttpRequest.readyState == 0) {
// Network error (Connection refused, Access denied, etc.)
}
else {
// some other error (HTTP error, etc...)
}
}
Here is a full working example for my cases:
var params = {name: 'John doe', age: 23};
// Make POST request to the server
$.post('/some/url/to/post', params, function (response) {
if (!response.result) {
// I have custom response format - contains validation errors, etc... Sample below:
//var content = $.isPlainObject(response) ? response.message : response;
//alert(content, 'Error saving data: Details' + content);
}
else {
// All is fine and data is saved
}
}).fail(function(jqXHR) {
var errorMessage = jqXHR.readyState == 0 || !jqXHR.responseText
? 'Network error - please check your internet connection or firewalls'
: jqXHR.responseText;
alert('Error saving data: Details' + errorMessage + );
});
| |
doc_23534790
|
- @theLinks.each_index do |x|
%br
%form{:action=>'/Download', :method=>"post",:enctype=>"multipart/form-data"}
%input{:type=>"submit", :name=>"#{@theLinks[x].url}", :value=>"Name: #{@theLinks[x].Name} Study Time: #{@theLinks[x].studyTime} Comments: #{@theLinks[x].comments}"}
Basically, for each person, list the time they participated in a study and the comments on the study. Right now, this renders as a set of buttons. I'd like to render it as a table, with each row clickable in the same way (ie, using the 'post' method, so that only the haml file has to be edited without touching the rest of the files).
Ideally, I'd also like to be able to sort the table by name, time, or comments, but that might be getting ahead of myself.
So how can I change this list of buttons into a table with clickable rows?
A: Okay, how about this code? This makes a table with three columns, one for the name(clickable buttons like what you did), one for the time spent, and one for comments. Time and comments are just plain text, so only the name is clickable. In the future, if you want to add sorting, just convert the table headers to links that have ajax functions in them for sorting. I think jQuery has a function/plugin for sorting tables so you can just look into their doc(if you use jquery)
%table
%tr
%th Name
%th Time spent
%th Comments
- @theLinks.each do |link|
%tr
%td
%form{:action=>'/Download', :method=>"post",:enctype=>"multipart/form-data"}
%input{:type=>"submit", :name=>"#{link.url}", :value=>"Name: #{link.Name}}"
%td= "Study Time: #{link.studyTime}"
%td= "Comments: #{link.comments}"
| |
doc_23534791
|
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
init = tf.initialize_all_variables()
# Tensorflow run
sess = tf.Session()
sess.run(init)
However, I am getting the following error:
InvalidArgumentError: dims must be a vector of int32.
Can you please help me fixing this problem?
Thanks
A: It works for me if you do this
W = tf.zeros([784, 10])
b = tf.zeros([10])
init = tf.initialize_all_variables()
# Tensorflow run
sess = tf.Session()
sess.run(init)
Also if you do it the way you're doing it. You'd still need to initialize W and b later on anyways as W below won't be initialized by the zeros tensor.
W = tf.Variable(tf.zeros([3,4]), name='x')
b = tf.Variable(x + 6, name='y')
model = tf.initialize_all_variables()
with tf.Session() as session:
session.run(model)
#Error: Attempting to use uninitialized value b
The example above will give an error but the one below won't and will give the correct answer.
W = tf.zeros([3,4], name='x')
b = tf.Variable(x + 6, name='y')
model = tf.initialize_all_variables()
with tf.Session() as session:
session.run(model)
If you want to do it the way you're with weights and biases (I'm guessing W and b stand for) I suggest looking here.
https://www.tensorflow.org/versions/r0.9/how_tos/variable_scope/index.html#variable-scope-example
Let me know if you still have any questions.
| |
doc_23534792
|
I'm trying to scrape http://utahcritseries.com/RawResults.aspx, using:
from BeautifulSoup import BeautifulSoup
import urllib2
base_url = "http://www.utahcritseries.com/RawResults.aspx"
data=urllib2.urlopen(base_url)
soup=BeautifulSoup(data)
i = 0
table=soup.find("table",id='ctl00_ContentPlaceHolder1_gridEvents')
#table=soup.table
print "begin table"
for row in table.findAll('tr')[1:10]:
i=i + 1
col = row.findAll('td')
date = col[0].string
event = col[1].a.string
confirmed = col[2].string
print '%s - %s' % (date, event)
print "end table"
print "%s rows processed" % i
On my windows machine,I get the correct result, which is a list of dates and event names. On my mac, I don't. instead, I get
3/2/2002 - Rocky Mtn Raceway Criterium
None - Rocky Mtn Raceway Criterium
3/23/2002 - Rocky Mtn Raceway Criterium
None - Rocky Mtn Raceway Criterium
4/2/2002 - Rocky Mtn Raceway Criterium
None - Saltair Time Trial
4/9/2002 - Rocky Mtn Raceway Criterium
None - DMV Criterium
4/16/2002 - Rocky Mtn Raceway Criterium
What I'm noticing is that when I
print row
on my windows machine, the tr data looks exactly the same as the source html. Note the style tag on the second table row. Here's the first two rows:
<tr>
<td>
3/2/2002
</td>
<td>
<a href="Event.aspx?id=226">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=226">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
<tr style="color:#333333;background-color:#EFEFEF;">
<td>
3/16/2002
</td>
<td>
<a href="Event.aspx?id=227">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=227">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
On my mac when I print the first two rows, the style information is removed from the tr tag and it's moved into each td field. I don't understand why this is happening. I'm getting None for every other date value, because BeautifulSoup is putting a font tag around every other date. Here's the mac's output:
<tr>
<td>
3/2/2002
</td>
<td>
<a href="Event.aspx?id=226">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=226">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
<tr bgcolor="#EFEFEF">
<td>
<font color="#333333">
3/16/2002
</font>
</td>
<td>
<font color="#333333">
<a href="Event.aspx?id=227">
Rocky Mtn Raceway Criterium
</a>
</font>
</td>
<td>
<font color="#333333">
Confirmed
</font>
</td>
<td>
<font color="#333333">
<a href="Event.aspx?id=227">
Points
</a>
</font>
</td>
<td>
<font color="#333333">
<a disabled="disabled">
Results
</a>
</font>
</td>
</tr>
My script is displaying the correct result under windows-what do I need to do in order to get my Mac to work correctly?
A: There are documented problems with version 3.1 of BeautifulSoup.
You might want to double check that is the version you in fact are using, and if so downgrade.
A: I suspect the problem is in the urlib2 request, not BeautifulSoup:
It might help if you show us the same section of the raw data as returned by this command on both machines:
urllib2.urlopen(base_url)
This page looks like it might help:
http://bytes.com/groups/python/635923-building-browser-like-get-request
The simplest solution is probably just to detect which environment the script is running in and change the parsing logic accordingly.
>>> import os
>>> os.uname()
('Darwin', 'skom.local', '9.6.0', 'Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386', 'i386')
Or get microsoft to use web standards :)
Also, didn't you use mechanize to fetch the pages? If so, the problem may be there.
| |
doc_23534793
|
Table1 data consists of schematics(dwg) along with a list of parts required to build the item depicted in the drawing. Table2 consists of data about the actual parts ordered to build the schematic. Some parts in table2 are a combination of parts in table1 (ex: foo and bar in table1 were ordered as foobar in table2).
I can display all rows in both tables with UNION ALL, but this doesn't join on both the dwg and part fields. I looked at FULL OUTER JOIN also, but I haven't figured out how to join first by dwg, then by part. Here is an example of the data.
table1 table2
dwg part qty order dwg part qty
----- ----- ----- ----- ----- ----- -----
123 foo 1 ord1 123 foobar 1
123 bar 1 ord1 123 bracket 2
123 widget 2 ord2 123 screw 4
123 bracket 4 ord2 123 nut 4
456 foo 1 ord2 123 widget 2
ord2 123 bracket 2
ord3 456 foo 1
Desired output:
The goal is to create a view that provides visibility to all parts in table1 and the associated orders in table2 (including those parts that appear in one but not the other table) so that I can see all the drawing parts in table1 and the associated records in table2 along with records in table2 where the part wasn't in table1.
part_request_order_report
dwg part qty order part qty
----- ----- ----- ------ ----- -----
123 foo 1
123 bar 1
123 widget 2 ord2 widget 2
123 bracket 4 ord1 bracket 2
123 bracket 4 ord2 bracket 2
123 ord1 foobar 1
123 ord1 screw 4
123 ord1 nut 4
456 foo 1 ord3 foo 1
Is this possible? Or am I better off iterating through the data to build the report table? Thanks in advance.
A: This should give you the right result :
select
coalesce(table1.dwg,table2.dwg),
table1.part,
table1.qty,
table2.order,
table2.part,
table2.qty,
from table1
full outer join table2 on
table1.dwg = table2.dwg and
table1.part = table2.part
A: It looks like a FULL JOIN is the right way to go. Try this:
SELECT A.dwg, A.part, A.qty, B.order, B.part, B.qty
FROM table1 A
FULL JOIN table2 B
ON A.dwg = B.dwg AND A.part = B.part
| |
doc_23534794
|
VALUE = list(map(int, VALUE))
print(name, VALUE)
with open("data.csv", "a") as out_file:
out_string = ""
out_string += "" + name
out_string += "," + str(VALUE)
out_string += "\n"
out_file.write(out_string)
The output file is:
I need to remove the [ and ] generated in column 2 and 17. I am not sure how to do it.
A: You're printing an array of integers, which looks like this:
>>> x = [1,2,3]
>>> print(str(x))
[1, 2, 3]
>>>
The square brackets are Python's way to print an array. To print them as CSV lines, convert the elements to strings, and join them with a comma:
out_string += "," + ",".join([str(i) for i in VALUE])
A: When VALUE (why uppercase, it's not a constant?) ist a list with two elements of type int and values 153 and 42, str(VALUE) will be [153,42]. When you want the output to be 153,42, you can use ','.join(VALUE) which will concatenate the elements of the list, separated by the str on which you call the join method, in this case the comma.
When writing .csv files, however, you might also want to consider using the csv module from the Python standard library.
A: The data type of your out_string is list in your case and it is giving you list of list. To convert you can use join which will convert the datatype to str and concatenate the elements of list in your case its ",".
VALUE = list(map(int, VALUE))
print(name, VALUE)
with open("data.csv", "a") as out_file:
out_string = ""
out_string += "" + name
out_string += ",".join(VALUE)
out_string += "\n"
out_file.write(out_string)`
I guess it will now give you the desired output.
| |
doc_23534795
|
MATCH (r)-[a*]->(b)
and i would like to add something to the effect of
WHERE a.someAttribute = 1
but I can't since a is a collection. Is there any good way of accomplishing this?
A: If ALL the relationships should have this property with the value, you can use the ALL predicate :
MATCH (r)-[a*]->(b)
WHERE ALL (x IN a WHERE x.someAttribute = 1)
You can also use a shorter version and specify the attribute inline :
MATCH (r)-[a* {someAttribute: 1}]->(b)
If on the other hand, only a single relationship should have this value, you can use ANY:
MATCH (r)-[a*]->(b)
WHERE ANY (x IN a WHERE x.someAttribute = 1)
| |
doc_23534796
|
Please tolerate bad coding practices as I still don't fully understand Java.
Here is my code - Window.java:
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
public class Window {
/**
* Simple color changing clock based on the website the website <a href="http://rhysperry.co.nf">rhysperry.co.nf</a>
*
* @author Rhys Perry
*/
public static void main(String[] args) throws IOException, FontFormatException, InterruptedException {
//Import font
InputStream in = Window.class.getResourceAsStream("Lato-Hairline.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(50f);
//Initialise the Frame, Panel and label
JFrame frame= new JFrame("Hex Clock");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel();
label.setFont(font);
label.setPreferredSize(new Dimension(200, 350));
label.setForeground(Color.WHITE);
//Merge Frame, Panel and "This is a test")Label. Make window visible
panel.add(label);
frame.add(panel);
frame.setSize(700, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//Setup calendar
Calendar calendar;
//Initialise some variables to do with time management
String formattedhour;
String formattedmin;
String formattedsec;
//Main loop to get the time and update the background ad Label
while(true) {
//Get hours, minutes and seconds
calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour < 10) { formattedhour = "0" + hour; } else { formattedhour = hour + "";}
int min = calendar.get(Calendar.MINUTE);
if (min < 10) { formattedmin = "0" + min; } else { formattedmin = min + "";}
int sec = calendar.get(Calendar.SECOND);
if (sec < 10) { formattedsec = "0" + sec; } else { formattedsec = sec + "";}
//Format and update the necessary components
String time = formattedhour + ":" + formattedmin + " " + formattedsec;
label.setText(time);
String hex = "#" + formattedhour + formattedmin + formattedsec;
panel.setBackground(Color.decode(hex));
panel.repaint();
}
}
}
A: You can use javax.swing.Timmer instead. It executes a task repeatedly after interval of time. https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
Timer timer = new Timer(10 ,taskPerformer);
timer.start();
| |
doc_23534797
|
// calculate if the element is in the visible window
function elementVisibleRect(element) {
element = $(element);
var rect = {
top: Math.round(element.offset().top),
left: Math.round(element.offset().left),
width: Math.round(element.outerWidth()),
height: Math.round(element.outerHeight())
};
var scrollTop = $(window).scrollTop();
var windowHeight = $(window).height();
var scrollBottom = scrollTop + windowHeight;
var elementBottom = Math.round(rect.height + rect.top);
if (scrollTop < rect.top && scrollBottom > elementBottom) {
return rect;
}
if (scrollTop > rect.top) {
rect.top = scrollTop;
}
if (scrollBottom < elementBottom) {
rect.height = scrollBottom - rect.top;
} else {
rect.height = windowHeight - (scrollBottom - elementBottom);
}
return rect;
}
and for using this information and centering the button inside
// center the element based on visible screen-frame
function elementPosition (element) {
var visibleRect = elementVisibleRect(element);
$('.editHoverButton').css({
top: visibleRect.top + ((visibleRect.height / 2) - ($('.editHoverButton').outerHeight() / 2)),
left: visibleRect.left + (visibleRect.width / 2) - ($('.editHoverButton').outerWidth() / 2)
});
}
Now my problem is that a third party library requires the parent DIV to change position from the browser default "static" to "relative" which breaks my calculations in the second function.
It might be late, but no matter what I try I can't seem to figure out how to get this working for when the parent element has position set to relative. I can't seem to get the maths quite right, and my head is beginning to hurt. Any suggestions?
EDIT - ADDED JSFIDDLE
http://jsfiddle.net/RhTY6/
A: Elements with absolute positioning are removed from the natural flow (e.g. they don't leave a space where they were) and positioned relative to their first parent with non-static positioning. Since the positioning of the right-hand box is relative (not static), you can position the button with top: 50%; and left: 50%;. This will make the top-left corner at the center of the parent. Then all you have to do is subtract half the element's height and width from the position, using margin-top and margin-left. This is much simpler than what you were doing, as you can see below:
JavaScript:
function elementPosition() {
$('.editHoverButton').css('margin-top', 0 - $('.editHoverButton').outerHeight() / 2);
$('.editHoverButton').css('margin-left', 0 - $('.editHoverButton').outerWidth() / 2);
};
CSS:
.editHoverButton {
position: absolute;
z-index: 99;
font-family: sans-serif;
font-size: 14px;
font-weight: normal;
background-color: #00bb00;
top: 50%;
left: 50%;
}
Nothing else has to change except to remove this from the elementPosition() function.
DEMO (Notice that the left one no longer works. This is because it is positioned static.)
EDIT--Using the same basic idea, this method should work:
The problem is that you have take the top and left positions of the element when defining rect. on the positioning calculations. Changing those to 0 (not the best method, but it works) fixes the problem for relative elements.
DEMO (Notice that the left one now does work. This is because it is positioned at 0,0 anyway.)
EDIT--This will work when the page scrolls:
This sets the container in a variable so that when the page scrolls, it can be repositioned automatically.
DEMO
A: EDIT: made it worked with your CSS and HTML (relative and absolute positioning) by altering the Script only.
The horizontal axis calcs were completely missing (I've applied the same calcs you applied to the vertical axis).
I've added some data and a ruler to help you finish the job: as you can see, it is (and it was, in your original fiddle) not perfectly centered (obviously you need to look at it when the container is smaller than the viewport), but this will be easy to work out.
Running Demo
Try to resize the fiddle window and to scroll both vertically and horizontally to see it works.
function elementVisibleRect(element) {
$("#data").html("");
element = $(element);
var rect = {
top: Math.round(element.offset().top),
left: Math.round(element.offset().left),
width: Math.round(element.outerWidth()),
height: Math.round(element.outerHeight())
};
var scrollTop = $(window).scrollTop();
var windowHeight = $(window).height();
var scrollBottom = scrollTop + windowHeight;
var elementBottom = Math.round(rect.height + rect.top);
var scrollLeft = $(window).scrollLeft();
var windowWidth = $(window).width();
var scrollRight = scrollLeft + windowWidth;
var elementRight = Math.round(rect.width + rect.left);
addData("rect.top", rect.top);
addData("rect.left", rect.left);
addData("rect.width", rect.width);
addData("rect.height", rect.height);
addData("scrollTop", scrollTop);
addData("windowHeight", windowHeight);
addData("scrollBottom", scrollBottom);
addData("elementBottom", elementBottom);
addData("scrollLeft", scrollLeft);
addData("windowWidth", windowWidth);
addData("scrollRight", scrollRight);
addData("elementRight", elementRight);
if (rect.top < scrollTop) {
rect.top = scrollTop;
}
if (scrollBottom < rect.top < scrollTop) {
rect.top = scrollTop;
}
if (scrollBottom < elementBottom) {
rect.height = scrollBottom - rect.top;
} else {
rect.height = windowHeight - (scrollBottom - elementBottom);
}
if (rect.left < scrollLeft) {
rect.left = scrollLeft;
}
if (scrollRight < rect.left < scrollLeft) {
rect.left = scrollLeft;
}
if (scrollRight < elementRight) {
rect.width = scrollRight - rect.left;
} else {
rect.width = windowWidth - (scrollRight - elementRight);
}
return rect;
}
| |
doc_23534798
|
[{"id": 3}, {"id": 5}, {"id": 8}]
I want to change the indexes a bit - instead of the dictionary with id = 3 to be on index 0, I want the dictionary with id = 3 to be on index 3.
I have tried:
list = []
for item in items:
list[item["id"]] = item
but that gives me indexing error. Then I tried to do the following:
list = []
for item in items:
list.insert(item["id"], item)
which just acts like a regular append (does not insert at specified index).
I have a last ditch attempt to do this on the front end when I am getting the response from the API but that defeats the whole purpose of reducing the amount of looping I do on the client side. The reason being is that the server can knock out these loops in like 50 milliseconds and on the client side it takes up to 300 milliseconds since it runs in the browser.
A: There is no problem in your code it all happens because your list has zero element
items = [{"id": 3}, {"id": 5}, {"id": 8}]
list_ = []
for item in items:
while item['id'] > len(list_):
list.append(None)
list_.insert(item["id"], item)
print(list_)
OUTPUT:
You can see here your elements are inserted inside the list.
[None, None, None, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}, None]
The above code works perfectly if the dictionary inside the list is in increasing order, But if the dictionary is in random order then first you need to first change the list to increasing order.
items = [{"id": 3}, {"id": 5}, {"id": 8},{'id':2}]
items = (sorted(items,key=lambda e:e['id'])) # sort the list
list_ = []
for item in items:
while item['id'] > len(list_):
list.append(None)
list_.append(item)
print(list)
INPUT/OUTPUT
IN:items = [{"id": 3}, {"id": 5}, {"id": 8},{'id':2}]
OUTPUT FROM FIRST ANSWER:[None, None, {'id': 2}, None, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}]
OUTPUT FROM SECOND ANSWER:[None, None, {'id': 2}, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}]
A: I think the general solution for this will be
a= [{"id": 3}, {"id": 5}, {"id": 8}]
l = [None for _ in range(max(a,key=lambda x: x["id"])["id"]+1)]
for item in a:
l[item["id"]]= item
print(l)
Also insert and item assignment is creating error because it expects that index to be exist beforehand so in that case you need to initialize your list with empty labels
A: You can't insert into an empty list at index 3. The first element you add to a list will always be at index 0. More general, you can't insert at an index that's higher than the list is long. If you want a quick way to look up items with a specific index, use another dict instead of a list as the container:
>>> lst = [{"id": 3}, {"id": 5}, {"id": 8}]
>>> d = {x["id"]: x for x in lst}
>>> d
{3: {'id': 3}, 5: {'id': 5}, 8: {'id': 8}}
>>> d[3]
{'id': 3}
This way, each element can be looked up in O(1) using its ID as the index. And this will also work if the IDs are very large numbers (when its impractical to create a mostly empty list with that many indices) or even non-numeric, e.g. strings.
A: You can do below steps;
x = [{"id": 3}, {"id": 5}, {"id": 8}]
x.insert(3, x[0])
del x[0]
A: Create an empty list with needed indexes first like
data = [{"id": 3}, {"id": 5}, {"id": 8}]
mod_list = [None]*max(x.get("id") for x in data)
Now fill the indexes with needed data
[mod_list.insert(x.get("id"),x) for x in data]
You get a list like this
[None, None, None, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}, None, None]
The None indexes can be ignored in processing.
| |
doc_23534799
|
There are 1 778 632 rows in the table and I have added indexes to all the columns but it does not make any difference to the execution speed.
Mysql version 5.7.29 is in use.
Is there any way that I can speed up the execution of the following, verbatim query?
SELECT id,postcode, ROUND((
3959 * acos (
cos ( radians(56.007165000) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-3.784005000) )
+ sin ( radians(56.007165000) )
* sin( radians( latitude ) )
)
),1) AS distance
FROM postcodelatlng
HAVING distance <= 10
ORDER BY distance
So I have updated the original query to add a bound box like this:
SELECT id,postcode, ROUND((
3959 * acos (
cos ( radians(56.007165000) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-3.784005000) )
+ sin ( radians(56.007165000) )
* sin( radians( latitude ) )
)
),1) AS distance
FROM postcodelatlng
WHERE latitude BETWEEN 56.007165000 - 10/69.172
AND 56.007165000 + 10/69.172
AND longitude BETWEEN -3.784005000 - 10/69.172 / COS(RADIANS(56.007165000))
AND -3.784005000 + 10/69.172 / COS(RADIANS(56.007165000))
HAVING distance <= 10
ORDER BY distance
--
-- Table structure for table `postcodelatlng`
--
CREATE TABLE IF NOT EXISTS `postcodelatlng` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`postcode` varchar(8) NOT NULL,
`latitude` decimal(12,9) NOT NULL,
`longitude` decimal(12,9) NOT NULL,
PRIMARY KEY (`id`)
) AUTO_INCREMENT=1;
--
-- Indexes for table `postcodelatlng`
--
ALTER TABLE `postcodelatlng`
ADD PRIMARY KEY (`id`),
ADD KEY `postcode` (`postcode`),
ADD KEY `latitude` (`latitude`,`longitude`),
ADD KEY `longitude` (`longitude`,`latitude`) USING BTREE;
here is and example of the data:
INSERT INTO postcodelatitudelongitude (postcode,latitude,longitude) VALUES ('AB10', '57.13514','-2.11731');
INSERT INTO postcodelatitudelongitude (postcode,latitude,longitude) VALUES ('AB11', '57.13875','-2.09089');
INSERT INTO postcodelatitudelongitude (postcode,latitude,longitude) VALUES ('AB12', '57.10100','-2.11060');
INSERT INTO postcodelatitudelongitude (postcode,latitude,longitude) VALUES ('AB13', '57.10801','-2.23776');
dbfiddle https://www.db-fiddle.com/f/mi4D1937k9WpeM3ubMBLjw/0
A: Since 5.7 (.9; GA: 2015-10-21) there is the ST_DISTANCE_SPHERE function for distance available (also: MariaDB).
Example:
SELECT
id,postcode,
ST_DISTANCE_SPHERE(POINT(-3.784005000, 56.007165000), POINT(longitude, latitude)) / 1000 AS distance
FROM postcodelatlng
#HAVING distance <= 10
ORDER BY distance
See dbfiddle
Alternatively, switch to a geometry data type and use a spacial index.
So as the question was asked for mile
SELECT
id,postcode,
ST_DISTANCE_SPHERE(POINT(-3.784005000, 56.007165000), POINT(longitude, latitude)) / 1609.344 AS distance
FROM postcodelatlng
HAVING distance <= 10
ORDER BY distance
A: The first step in optimizing a "find nearest" with lat/lng is to include a "bounding box" in the WHERE clause.
I discuss 5 "find nearest" algorithms in http://mysql.rjweb.org/doc.php/find_nearest_in_mysql Your code is the first, namely brute force. With 1.8M rows, any of the others will be at least a few orders of magnitude faster.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.