id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_2300
|
However, I'd like to add multiple button/radio/label in this menu by using HBoxLayout and VBoxLayout.
My problem is that after setting everything, nothing appear.
I also have a problem when I close the main UI after pressing the menu button, my process finish with an exit code "-1073740940 (0xC0000374)" and don't know what cause this.
Here is my simplified code (I just deleted QPalette and keep two buttons):
import sys
from PySide2 import QtWidgets as Qw
from PySide2 import QtCore as Qc
from PySide2 import QtGui as Qg
class MenuWidgetSignals(Qc.QObject):
# SIGNALS
CLOSE = Qc.Signal()
class MenuWidget(Qw.QWidget):
def __init__(self, parent=None):
super(MenuWidget, self).__init__(parent)
self.menu_ui()
def menu_ui(self):
# make the window frameless
self.setWindowFlags(Qc.Qt.FramelessWindowHint)
self.setAttribute(Qc.Qt.WA_TranslucentBackground)
s = self.size()
self.setMinimumSize(500, s.height()-71)
self.close_btn = self.menu_button()
self.close_btn.clicked.connect(self.close_menu)
self.save_btn = self.save_button()
self.save_btn.clicked.connect(self.save_menu)
# Layout
# init GroupBox to limit the width and the height
menu_grp_box = Qw.QGroupBox(self)
menu_grp_box.setGeometry(Qc.QRect(0, 70, 500, s.height()-71))
# init VBoxLayout
menu_v_box = Qw.QVBoxLayout(menu_grp_box)
menu_v_box.addStretch(1)
menu_v_box.setContentsMargins(0, 0, 0, 0)
# init spacer
spacer01 = Qw.QSpacerItem(20, 40, Qw.QSizePolicy.Expanding, Qw.QSizePolicy.Minimum)
# add widgets and items
menu_v_box.addItem(spacer01)
menu_v_box.addWidget(self.save_btn)
menu_v_box.addItem(spacer01)
menu_grp_box.setLayout(menu_v_box)
self.SIGNALS = MenuWidgetSignals()
def menu_button(self):
"""
Returns:
QtWidgets.QPushButton: button
"""
btn = Qw.QPushButton(self, text="To Main")
btn.setMinimumSize(Qc.QSize(83, 65))
btn.setToolTip("Close Menu")
MenuWidget.saving = False
return btn
def save_button(self):
"""
Returns:
QtWidgets.QPushButton: button
"""
btn = Qw.QPushButton(self, text="Save")
btn.setMinimumSize(Qc.QSize(80, 35))
btn.setToolTip("Saving files and folder settings and close menu")
return btn
def close_menu(self):
self.SIGNALS.CLOSE.emit()
def save_menu(self):
MenuWidget.saving = True
self.close_menu()
class MainWindow(Qw.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.set_ui()
def set_ui(self):
self.setFixedSize(1000, 700)
# init menu button
menu_btn = self.menu_button()
menu_btn.setFixedSize(Qc.QSize(83, 65))
menu_btn.move(0, 0)
menu_btn.clicked.connect(self.active_menu)
self.show()
def menu_button(self):
btn = Qw.QPushButton(self, text="To Menu")
btn.setToolTip("Open Menu")
return btn
def active_menu(self):
self._menu_frame = MenuWidget(self)
self._menu_frame.move(0, 0)
self._menu_frame.resize(self.width(), self.height())
self._menu_frame.SIGNALS.CLOSE.connect(self.close_menu)
self._menu_frame.show()
def close_menu(self):
self._menu_frame.close()
if __name__ == '__main__':
app = Qw.QApplication(sys.argv)
hyg_window = MainWindow()
sys.exit(app.exec_())
Thank you for the time you'll spent to read me and I really hope that someone could help me.
EDIT: I forgot to add the imports and the signal class. I also added a simplified version of my MainWindow class.
| |
doc_2301
|
I want to make form like below:
Current Result:
From the image, I need to configure that 2 points
*
*The padding / margin between Input Panel and the Button Panel
*The Padding / margin between tablePanel and the inputPanel
Code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
public class manageForm extends JFrame {
//Vector<String> header=new Vector<String>();
//Vector<Vector<String>>data=new Vector<Vector<String>>();
DefaultTableModel defaultTableModel;
JTable table;
JScrollPane scrollPane;
JLabel titleLabel=new JLabel("Manage Handphone");
JTable hpTable = new JTable();
JLabel idLabel = new JLabel("ID");
JLabel nameLabel = new JLabel("Name");
JLabel priceLabel = new JLabel("Price");
JLabel weightLabel = new JLabel("Weight");
JLabel cableLabel = new JLabel("Cable Length");
JLabel typeLabel = new JLabel("Type");
JTextField idtxt = new JTextField();
JTextField nametxt = new JTextField();
JTextField pricetxt = new JTextField();
JTextField weighttxt = new JTextField();
JTextField cabletxt = new JTextField();
JComboBox typeBox = new JComboBox();
JButton insertBtn = new JButton("INSERT");
JButton updateBtn = new JButton("UPDATE");
JButton deleteBtn = new JButton("DELETE");
JButton confirmBtn = new JButton("CONFIRM");
JButton cancelBtn = new JButton("CANCEL");
String header[] = {"ID","Name","Type","Price","Weight","Cable Length"};
String data[][] = {
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"},
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"},
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"}
};
public manageForm() {
JPanel headerPanel = new JPanel();
JPanel tablePanel = new JPanel();
tablePanel.setBorder(new EmptyBorder(0,0,0,0));
JPanel inputPanel = new JPanel(new GridLayout(6,2));
inputPanel.setBorder(new EmptyBorder(20,10,20,10));
//inputPanel.setBorder(new LineBorder(Color.black));
JPanel buttonPanel = new JPanel(new GridLayout(1,5));
buttonPanel.setBorder(new EmptyBorder(100,20,100,20));
JPanel footerPanel = new JPanel(new GridLayout (2,1,0,0));
headerPanel.add(titleLabel);
inputPanel.add(idLabel);
inputPanel.add(idtxt);
inputPanel.add(nameLabel);
inputPanel.add(nametxt);
inputPanel.add(priceLabel);
inputPanel.add(pricetxt);
inputPanel.add(weightLabel);
inputPanel.add(weighttxt);
inputPanel.add(cableLabel);
inputPanel.add(cabletxt);
inputPanel.add(typeLabel);
inputPanel.add(typeBox);
buttonPanel.add(confirmBtn);
buttonPanel.add(cancelBtn);
buttonPanel.add(insertBtn);
buttonPanel.add(updateBtn);
buttonPanel.add(deleteBtn);
footerPanel.add(inputPanel);
footerPanel.add(buttonPanel);
/*
JPanel panel0=new JPanel();
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel panel4=new JPanel();
JPanel panel5=new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
panel1.setLayout(new GridLayout(1, 6));
panel2.setLayout(new GridLayout(1, 2));
panel2.add(idLabel);
panel2.add(idtxt);
panel3.setLayout(new GridLayout(1, 2));
panel3.add(nameLabel);
panel3.add(nametxt);
panel4.setLayout(new GridLayout(1, 2));
panel4.add(priceLabel);
panel4.add(pricetxt);
panel5.setLayout(new GridLayout(1, 2));
panel5.add(weightLabel);
panel5.add(weighttxt);
panel6.setLayout(new GridLayout(1, 2));
panel6.add(cableLabel);
panel6.add(cabletxt);
panel7.setLayout(new GridLayout(1, 2));
panel7.add(typeLabel);
panel7.add(typeBox);
panel8.setLayout(new GridLayout(1, 5));
mainPanel.add(panel0);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
mainPanel.add(panel4);
mainPanel.add(panel5);
mainPanel.add(panel6);
mainPanel.add(panel7);
mainPanel.add(panel8);
*/
/*
header.add("ID");
header.add("Name");
header.add("Type");
header.add("Price");
header.add("Weight");
header.add("Cable Length");
*/
defaultTableModel=new DefaultTableModel(data, header);
hpTable =new JTable(defaultTableModel);
scrollPane=new JScrollPane(hpTable);
// tablePanel.add(scrollPane);
setLayout(new BorderLayout(0,5));
setTitle("Manage Form");
setSize(800,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
add(headerPanel,BorderLayout.NORTH);
add(scrollPane,BorderLayout.CENTER);
add(footerPanel,BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
new manageForm();
}
}
How exactly to manage the panel layout to meet our requirement?
I have tried EmptyBorder, but the result, it's only making a big space between the other panel.
A: Use GridBagLayout it is a powerful and best fit to your requirement. It is arranges the components in a horizontal and vertical manner.
You can put component in a grid using cells and rows. As a example:
read more - GridBagLayout
A: Strongly disagree with the suggestion to use GridBagLayout. That layout is basically a punchline for any Swing programmer.
If you're going to be programming Swing, do yourself a huge favor and use MiGLayout. It's the layout manager that Swing should have built-in.
| |
doc_2302
|
Our Firemonkey mobile app (Delphi Seattle) lets end-users to set up their own server configuration (IP and Port). They must have a Windows PC server application running in their own server, so, there isn't any HOSTNAME. They just know their server Public IP address. The server application is installed in a simple Windows PC. Not a web server, domain, etc. so there isn't any server host-name, but an IP address.
After following Apple's instructions to create a IPv6 private shared network, the problem exists. I get "Server Unreachable" error when trying to connect to any IP address from my iPad.
I have read that using brackets [ ] with the hostname will work, but I can't get it. Maybe it only works with hostnames, not ip addresses?
Here is a simplified portion of code where I do the connection to the server:
Client side (mobile app):
- TSQLConnection (Datasnap Driver. Communication protocol: tcp/ip)
- TDSProviderConnection
SQLConnection1.Params.Values['HostName'] := MY_SERVER_IP;
try
DSProviderConnection1.Connected:=true;
except
showmessage('error');
end;
I have tried XX.XX.XX.XX and [XX.XX.XX.XX] values for MY_SERVER_IP with no success.
I don't know if I have to change something in the server's Windows application or just on client-side (mobile/firemonkey)
Any solution?
A: I got it
I found a chinese forum with some tricks I haven't found before.
It is possible to configure the Datasnap Communication IP version with the following parameter:
TDBXDatasnapProperties(SQLConnection1.ConnectionData.Properties).CommunicationIPVersion
By default, if empty, it is IPv4.
So, on the TSQLConnection.OnBeforeConnect event, just added the following line:
// You need to know if you are on IPv4 or IPv6 first. I explain it later.
if ipversion='IPv4' then
TDBXDatasnapProperties(SQLConnection1.ConnectionData.Properties).CommunicationIPVersion:='IP_IPv4'
else
TDBXDatasnapProperties(SQLConnection1.ConnectionData.Properties).CommunicationIPVersion:='IP_IPv6';
And that's all!!
Of course, you need to know if you are on a IPv4 network or in a IPv6 one.
I do this with a TidTcpClient component. That component has a 'IPVersion' parameter you can set up.
So, first, try to connect using IPVersion:=Id_IPv4. If successful, you are on a IPv4 network. If not, then you probably are on a IPv6 network (or server is down). So...
IdTCPClient1.IPVersion:=Id_IPv4; // <-- try IPv4 first
IdTCPClient1.Host:=MY_IP;
try
IdTCPClient1.Connect;
result:=true;
ipversion := 'IPv4'; // <-- will tell us what ip version to use
except
end;
if IdTCPClient1.Connected=false then
begin
try
IdTCPClient1.IPVersion:=Id_IPv6; // <-- now try IPv6
IdTCPClient1.Connect;
result:=true;
ipversion:='IPv6'; // <-- will tell us what ip version to use
except
end;
end;
And that's all. Now the app works fine on both IPv4 and IPv6 from my iPad!
| |
doc_2303
|
Library can be JDK, Guava, Commons-lang, xml processing library or any reasonably well-known library.
The behavior can be stripping or escaping, but for a bunch of unique, human-readable names with no special characters, the escaping result should also be unique and reasonably human-readable.
Thanks.
A: You most probably do not want to escape the string (which is generally reversible), and instead want to "sanitize" the string (retain only a subset of its original characters, those that are safe, possibly making it impossible to recover the original string). As you mentioned in comments, IDs can be quite picky.
So we choose a safe range and remove anything outside of that. Additionally, if it starts with a non-letter, we prepend an 'i' to make it compliant.
public String toSafeId(String s) {
s = s.replaceAll("[^a-zA-Z0-9]+", "-"); // replaces runs of non-valid by '-'
return s.length() > 0 && Character.isLetter(s.charAt(0)) ? s : "i" + s;
}
Note that this does not enforce uniqueness. To enforce it, wrap it up with a Set:
public class XmlIdGenerator {
private HashSet<String> used;
// provides a unique ID
public String generate(String s) {
String base = toSafeId(s);
String id = base;
for (int i = 1; used.contains(id); i++) {
id = base + "-" + i;
}
used.add(id);
return id;
}
}
Use as:
XmlIdGenerator gen = new XmlIdGenerator(); // build a new one for each document
String oneId = gen.generate(" hi there sally!"); // -> "hi-there-sally"
String anotherId = gen.generate(" hi there.. sally?"); // -> "hi-there-sally-1"
A: sometimes i use the library XStream, check this "2 minute tuturial"
http://x-stream.github.io/tutorial.html
create the objects that have the info
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
}
public class PhoneNumber {
private int code;
private String number;
// ... constructors and methods
}
start the xtream
XStream xstream = new XStream();
insert the info as alias
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);
Insert info
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
Generete the XML
String xml = xstream.toXML(joe);
| |
doc_2304
|
Looking forward to hearing from everyone
outputStream = response.getOutputStream();
ZipOutputStream zipOutStream = null;
FileInputStream filenputStream = null;
BufferedInputStream bis = null;
try {
zipOutStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
zipOutStream.setMethod(ZipOutputStream.DEFLATED);
for (int i = 0; i < files.size(); i++) {
File file = files.get(i);
filenputStream = new FileInputStream(file);
bis = new BufferedInputStream(filenputStream);
zipOutStream.putNextEntry(new ZipEntry(fileName[i]));
int len = 0;
byte[] bs = new byte[40];
while ((len = bis.read(bs)) != -1) {
zipOutStream.write(bs,0,len);
}
bis.close();
filenputStream.close();
zipOutStream.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(Objects.nonNull(filenputStream)) {
filenputStream.close();
}
if(Objects.nonNull(bis)) {
bis.close();
}
if (Objects.nonNull(zipOutStream)) {
zipOutStream.flush();
zipOutStream.close();
}
if (Objects.nonNull(outputStream)) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
A: One of the potential issues with your code is with memory leaks and streams that are not properly flushed and closed if the code runs in to any exceptions.
One way to help reduce these leaks and to ensure all resources are properly closed, even when exceptions occur, is to use try-with-resources.
Here is an example of how your code example can be rewritten to utilize try-with-resources.
In this example, to get it to compile in a detached IDE environment, I've put it in a function named testStream since I do not have knowledge as to what contributes to the source of the parameters files and fileName. Therefore, validation and content of these two parameters are left to chance, and it is assumed both have the same number of entries, and are paired with each other (element 0 of each are paired together). Since this odd relationship exists, it's linked by the variable named i to mirror the original source code.
public void testStream( HttpServletResponse response, List<File> files, String[] fileName )
{
int i = 0;
try (
ServletOutputStream outputStream = response.getOutputStream();
ZipOutputStream zipOutStream = new ZipOutputStream( new BufferedOutputStream( outputStream ) );
)
{
zipOutStream.setMethod( ZipOutputStream.DEFLATED );
for ( File file : files )
{
try (
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream( file ) );
) {
zipOutStream.putNextEntry( new ZipEntry( fileName[i++] ) );
int len = 0;
byte[] bs = new byte[4096];
while ( (len = bis.read( bs )) != -1 )
{
zipOutStream.write( bs, 0, len );
}
// optional since putNextEntry will auto-close open entries:
zipOutStream.closeEntry();
}
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
This compiles successfully and should work; but may need some other adjustments to get it to work in your environment with your data. Hopefully it eliminates issues you may have been having with closing streams and other resources.
| |
doc_2305
|
The issue is that while the image is created successfully, when I rotate it using the img.rotate(-90)...the image rotates, but it appears the pallet/background/canvas does not (see attached image).
How can I correct this. Do I need to create a larger transparent background? Can I get the background/canvas to rotate as well...or do I rotate and then resize the background/Canvas?
FIRST EXAMPLE IMAGE (QRCODE)
img = Image.new('RGB', (x,y), 'white')
qr = qrcode.QRCode(version=1,error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=10,border=1,)
qr.add_data('QRB.NO/AbCd1')
qr.make(fit=True)
QRimg = qr.make_image()
img = img.paste(QRimg, (x,y))
img.show() #333
raw_input('(Above is unrotated QRcode image) Press enter...') #333
img = img.rotate(-90)
print img, type(img)
img.show() #333
raw_input('Above is the rotated -90 QRcode image. Press enter...') #333
SECOND EXAMPLE IMAGE
font_name = 'Arial.ttf'
font_size = 16
font = ImageFont.truetype(font_name, font_size)
img = Image.new('RGB', (x,y), color=background_color)
# Place text
draw = ImageDraw.Draw(img)
draw.text( (corner_X,corner_Y), 'QRB.NO/AbCd1', font=font, fill='#000000' )
draw.rectangle((0,0,x-1,y-1), outline = "black")
del draw
print img, type(img)
img.show() #333
raw_input('(Above is the unrotated test image). Press enter...') #333
img = img.rotate(90)
print img, type(img)
img.show() #333
raw_input('(Above is the ROTATED 90 text image). Press enter...') #333
OUTPUT
<PIL.Image.Image image mode=RGB size=71x57 at 0x10E9B8C10> <class 'PIL.Image.Image'>
(Above is unrotated QRcode image) Press enter...
<PIL.Image.Image image mode=RGB size=71x57 at 0x10E9B8F90> <class 'PIL.Image.Image'>
Above is the rotated -90 QRcode image. Press enter...
<PIL.Image.Image image mode=RGB size=57x9 at 0x10EA6CB90> <class 'PIL.Image.Image'>
(Above is the unrotated test image). Press enter...
<PIL.Image.Image image mode=RGB size=57x9 at 0x10E9B8C10> <class 'PIL.Image.Image'>
(Above is the ROTATED 90 text image). Press enter...
EDIT:
x,y = img.size
img = img.resize( (y, x), Image.ANTIALIAS )
img = img.rotate(-90)
...or...
x,y = img.size
img = img.rotate(-90)
img = img.resize( (y, x), Image.ANTIALIAS )
...don't seem to help.
A: Use the optional expand flag in the rotate method:
image.rotate(45, expand=True)
https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.rotate
A: Figured it out. I'm going to leave it up to help others, as this seems to be a subtle yet important difference.
img = img.transpose(Image.ROTATE_270)
...or...
img = img.transpose(Image.ROTATE_90)
Docs
| |
doc_2306
|
<form id="share">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="container col-md-12">
<table id="myTable" class="table table-hover table-striped table-bordered dataTable">
<thead>
<tr>
<th style="text-align:center">@Html.DisplayNameFor(m => Model.tags.First().Id)</th>
<th style="text-align:center">@Html.DisplayNameFor(m => Model.tags.First().TagName)</th>
<th style="text-align:center">@Html.DisplayNameFor(m => Model.tags.First().TagCategory)</th>
<th style="text-align:center">@Html.DisplayNameFor(m => Model.tags.First().TagValue)</th>
<th style="text-align:center"> Action</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.tags.Count(); i++)
{
<tr>
<td>
@Html.DisplayFor(m => Model.tags[i].Id)
@Html.HiddenFor(m => Model.tags[i].Id)
</td>
<td>
@Html.DisplayFor(m => Model.tags[i].TagName)
</td>
<td>
@Html.DisplayFor(m => Model.tags[i].TagCategory)
</td>
<td>
@Html.EditorFor(m => Model.tags[i].TagValue, new { htmlAttributes = new { @id = "TagVaule_" + Model.tags[i].Id, @class = "form-control" } })
@Html.ValidationMessageFor(m => Model.tags[i].TagValue, "", new { @class = "text-danger" })
</td>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content" id="myModalContent">
</div>
</div>
</div>
<button type="submit" class="btn btn-danger" id="bulkupdate">BulkUpdate</button>
</div>
</div>
$('#share').on('submit', function (e) {
debugger;
// Prevent actual form submission
e.preventDefault();
var data = table.$('input').serializeArray();
// Submit form data via Ajax
$.ajax({
type: 'POST',
url: '@Url.Action("BulkUpdate", "Home")',
data: data,
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
});
| |
doc_2307
|
function fullScreenHero(){
var width=$(window).width();
var navHeight=$('nav').height();
var height=$(window).height()-navHeight;
$('#hero').width(width);
$('#hero').height(height);
}
For mobile and tablets I added to the navbar a dropdown menu. The problem occurs when the dropdown menu is displayed and then I resize the window. The dropdown menu occupies half of the screen.
The issue is the hero gets cutted in half when you resize the window because var navHeight is double in size when the dropdown is displayed.
The function below sometimes work, but not always, so it's useless.
$(window).resize(function(){
$('nav').removeClass('dropdown-menu');
});
| |
doc_2308
|
As far as I know it's not, but I'm not 100% sure, so I need to ask
(The reason I ask, is I'm tempted to make my own LocationManagerManager that handles these sorts of problems. I might have it accept multiple Criteria objects which are tried in some sort of order under various circumstances that the traditional LocationManager isn't flexible enough for. But I don't want to be reinventing the wheel, e.g. if Google have handled this in some method/class unknown to me).
Thanks
A: Not that I'm aware of: your option is probably the best idea. Register for all the available providers and then return the best available Location value.
A: Yeah, it's already available. Just google it, u must get it. Check this function out :
`
public boolean testProviders() {
Log.e(LOG_TAG, "testProviders");
String location_context = Context.LOCATION_SERVICE;
locationmanager = (LocationManager) getSystemService(location_context);
List<String> providers = locationmanager.getProviders(true);
for (String provider : providers) {
Log.e(LOG_TAG, "registering provider " + provider);
listener = new LocationListener() {
public void onLocationChanged(Location location) {
// keep checking the location - until we have
// what we need
//if (!checkLoc(location)) {
Log.e(LOG_TAG, "onLocationChanged");
locationDetermined = checkLoc(location);
//}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
locationmanager.requestLocationUpdates(provider, 0,
0, listener);
}
Log.e(LOG_TAG, "getting updates");
return true;
}
`
| |
doc_2309
|
<webResources>
....
<resource>
<directory>${project.build.directory}/${temp.dir}</directory>
</resource>
</webResources>
the ${temp.dir} is generated conditionally by a plugin and do not exists always. When it is not there maven of course fail with an NPE, how could I fix this ?
A: I'm not sure if I understand what your problem (exactly) is, but it seems to me that Maven profiles could help you:
http://maven.apache.org/guides/introduction/introduction-to-profiles.html
In your case, probably you need profile activation on property existence, like this:
<profiles>
<profile>
<activation>
<property>
<name>temp.dir</name>
</property>
</activation>
...
</profile>
</profiles>
| |
doc_2310
|
receipt.write(output_to_receipt)
Please may someone explain what this error is?
A: Change receipt.write(output_to_receipt) to receipt.write(str(output_to_receipt)).
This will change output_to_receipt which is a tuple to a string and you'll be able to write.
A: output_to_receipt is a tuple, so you need to convert it to a string with str(output_to_receipt) or "".join(output_to_receipt) for example.
| |
doc_2311
|
import org.json.JSONArray;
import org.json.JSONException;
@RestController
public class BICOntroller{
@RequestMapping(value="/getStatus", method = RequestMethod.GET)
public ResponseEntity<JSONArray> getStatus() throws JSONException{
ResponseEntity<JSONArray> response = null;
JSONArray arr = new JSONArray();
JSONObject obj = new JSONObject();
//process data
arr.put(obj);
response = new ResponseEntity<JSONArray>(arr, HttpStatus.OK);
return response;
}
}
Angular js call :
$http({
url: 'getStatus',
method: 'GET',
responseType: 'json'
}).then(function(response){
console.log(response);
return response;
}, function(error){
console.log(error);
return error;
});
This gives 500 error :
java.lang.IllegalArgumentException: No converter found for return value of type: class org.json.JSONArray
I have included jackson-core-2.7.5.jar and jackson-databind-2.7.5.jar in the class path.
Thanks!
A: Adding the dependencies did not work for me. What did work is converting the JSONArray to String.
FYI I am using Spring Boot Application and was trying to return a JSONArray.
A: Apart from adding dependencies, you may need this.
If you are not using spring boot, update your spring xxx-servlet.xml with message converters for JSON.
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
if you are using spring boot, adding dependencies in pom.xml alone will suffice.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
| |
doc_2312
|
Thanks.
A: I solved the problem overriding jQueryMobile CSS class's.
.ui-input-text,
.ui-select
{
width: 100% !important;
padding: 0.4em 0!important;
}
| |
doc_2313
|
<application
android:fullBackupContent="@xml/backup_rules"
tools:replace="android:fullBackupContent">
Also I try this variant:
<application
android:fullBackupContent="@xml/backup_rules"
tools:replace="android:fullBackupContent"
android:allowBackup="true"
android:fullBackupOnly="true">
Backup_rules:
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<include domain="file" path="."/>
<include domain="database" path="."/>
<include domain="sharedpref" path="."/>
<include domain="external" path="."/>
<include domain="root" path="."/>
<exclude domain="sharedpref" path="EXPONEA_PUSH_TOKEN.xml"/>
</full-backup-content>
The problem is that I try to save string to shared preference and get it after re-installing the app, but something went wrong.
For example:
val namePreferences: SharedPreferences = getSharedPreferences("name", Context.MODE_PRIVATE)
namePreferences.edit().putString("name_test", user.name).apply()
val test = namePreferences.getString("name_test", "empty name")
//here test isn't empty
When I re-installing my app:
val test = namePreferences.getString("name_test", "empty name")
//here test is empty ("empty_name")
A: When you uninstall an app, all the app folder is deleted: apk, database and SharedPreferences. If you want to read a value after re-install you must store it in the Local storage instead.
| |
doc_2314
|
*
*Create subdomain
*Upload projects to the domain
*Move file form public folder
*Configure index.php
*subdomain.laravel.com work accurately
*But When subdomain.laravel.com/home there is a notice 404 not found
*But in projects home controller having index function is existed.
A: more like a server configuration issue. Make sure to point the document root to public/ and that the file public/index.php is catching all requests:
nginx:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
more on https://laravel.com/docs/master/deployment
A: Put subdomain routes firstly before
Route::get('/') of main domain
| |
doc_2315
|
Sub NewMenuMacro()
Dim myMenuItem As Object
Dim objIE As Object
Dim folderName
folderName = "..\.."
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim fullpath
fullpath = fso.GetAbsolutePathName(Me.Application.ActiveDocument)
If fso.FileExists(fullpath) Then
Dim objFile
' fullpath = fso.GetAbsolutePathName(Me.Application.ActiveDocument)
Set objFile = fso.GetFile(fullpath)
ActiveDocument.SaveAs (objFile.path)
fullpath = fso.GetAbsolutePathName(objFile)
Else
ActiveDocument.Save
fullpath = fso.GetAbsolutePathName(Me.Application.ActiveDocument)
End If
A: You can just use the FullName property.
fullpath = Me.Application.ActiveDocument.FullName
| |
doc_2316
|
I want to enable Basic Authentication on SCDF. 17.2 Basic Authentication
However I can not find the relevant documentation for Kubernetes or Spring to change the SCDF pod security.
17.2 Basic Authentication
Basic Authentication can be enabled by adding the following to application.yml or via environment variables:
security:
basic:
enabled: true
realm: Spring Cloud Data Flow
Should I change it using data flow config server shell? if so what is the command?
Or should I change security using kubectl update resource yaml? How do I put the security config in pod yaml file?
A: You are using a very old version of SCDF which is not currently maintained. I suggest you update to a recent release version from here.
The basic authentication got removed in the later versions of SCDF and the authentication/authorization is now supported via OAuth 2.
You can refer the documentation here for more information.
| |
doc_2317
|
ArrayList<RunData_L> rdUP = t.getMyPositiveRunData();
ArrayList<RunData_L> rdDOWN = t.getMyNegativeRunData();
Log.d("rdUP size", rdUP.get(0).getMyMeasurementData().size() + "");
for (int i = 0; i < rdUP.get(i).getMyMeasurementData().size(); i++) {
Log.d("i", i + "");
ArrayList<BigDecimal> tempUP = new ArrayList<BigDecimal>(), tempDOWN = new ArrayList<BigDecimal>();
for(int j = 0; j < rdUP.size(); j++) {
tempUP.add(rdUP.get(j).getMyMeasurementData().get(i));
tempDOWN.add(rdDOWN.get(j).getMyMeasurementData().get(i));
}
pdUP.add(tempUP);
pdDOWN.add(tempDOWN);
}
A: I suspect as per my comment that the use of rdUP.get(j) in the inner loop is causing the problem.
You first test to see the size of rdUP.get(i).getMyMeasurementData() in the outer loop as your bounding condition for the loop and so i runs from 0 to the size of rdUP.get(i).getMyMeasurementData().
Your inner loop then says go through each element of rdUP and get the i th value from rdUP.get(j).getMyMeasurementData(). How do you know that the j th rdUP has enough elements to satisfy your get(i) ?
| |
doc_2318
|
Are there any risks to doing this without upgrading all Angular packages to 7?
Example package.json:
"dependencies": {
"@angular/animations": "6.1.2",
"@angular/cdk": "7.0.4",
"@angular/cli": "^6.1.2",
"@angular/common": "6.1.2",
"@angular/compiler": "^6.1.2",
"@angular/compiler-cli": "^6.1.2",
"@angular/core": "6.1.2",
"@angular/forms": "6.1.2",
"@angular/http": "6.1.2",
"@angular/platform-browser": "6.1.2",
"@angular/platform-browser-dynamic": "^6.1.2",
"@angular/router": "6.1.2"
}
| |
doc_2319
|
I need to know how to certificate my projects of google app script from Googleshhets. So that when I share them with my colleagues, they don´t see a pop-up warning that the "site is not safe" when they execute some script in the sheets.
| |
doc_2320
|
After connecting a LED with the Pi and being able to run it using a python file
I would like to run this file using a simple button click on an Android App.
Additionally, I want to use a SSH connection.
In short:
Toggle_Button_Click -> send command(e.g. sudo python gpiohigh.py)
-> LED turns on
Toggle_Button_Click -> send command(e.g. sudo python gpiolow.py)
-> LED turns off
This is the general idea but I am a beginner. I've searched tons of posts(mentioning and including JSCH) but they could not help me out.
Could anyone help me out by telling me where I should start?
Thank you very much!
Taka
| |
doc_2321
|
The idea is that there is a button for each table in the database, so that the table can be viewed and edited if needed.
I want to have each button look the same and, when clicked, generate a list of table entries into the main frame of my program. To do this, I want to extend the Button() class so that I can keep some attributes concurrent while also defining the display_items function:
class TabButton(Button):
def __init__(self, *args, **kwargs):
super().__init__(Button)
self['bg'] = '#a1a1a1'
self['font'] = ('Agency', 24)
def display_items(self, tab):
pass
#mycursor.execute('SELECT * FROM (%s)', tab)
This last line (above) is what selects data from the correct table in my database - I have commented it out while I figure out the rest of the class. I know what *args and **kwargs do, but I'm not sure what purpose they have in this __init__ function (I'm not very familiar with classes and copied this class from another Stack Overflow post).
To generate the buttons, I referenced a dict instance and assigned each key to a button:
tabs = {
'Table1': '',
'Table2': '',
'Table3': '',
}
for tab in tabs:
row = 0
tabs[tab] = TabButton(side_frame, command=lambda: TabButton.display_items(tab))
tabs[tab].grid(row=row, column=0)
row += 1
The problem is, when I run the program I get this error:
AttributeError: type object 'Button' has no attribute 'tk'
Any and all guidance is welcome!
If you notice any other mistakes in my code, could you please point them out? I'm very new to programming and it will save me making another post on Stack Overflow. :p
Thanks,
J
A: Super returns a temporary object of that class and let you access its content. Super itself dosent accept any arguments.
Also see the prupose of self in that context.
self represents the instance of the class
Often, the first argument of a method is called self. This is nothing
more than a convention: the name self has absolutely no special
meaning to Python. Note, however, that by not following the convention
your code may be less readable to other Python programmers
Another issue is your use of lambda. Your argument tab will be overwritten (if it isnt stored) by each iteration of your loop. Another issue that you might not intent to use the class for this method you rather want to be calles by the instance, therefor I added the argument self to your method and changed your lambda to make use of the instance.
import tkinter as tk
tabs = {'Table1': '',
'Table2': '',
'Table3': '',
}
root=tk.Tk()
class TabButton(tk.Button):
def __init__(self,master, *args, **kwargs):
#self is a reference to the instance of that object
super().__init__(master)#super dosent need a reference
self['bg'] = kwargs.get('bg','#a1a1a1')
self['font'] = kwargs.get('font',('Agency', 24))
def display_items(self,item):
print(f'{item} to show')
for tab in tabs:
b = TabButton(root) #returns a reference to that object
b.configure(command=lambda btn=b, argument=tab:btn.display_items(argument))
b.pack()
root.mainloop()
| |
doc_2322
|
Here is my code so far:
#!/bin/bash
SPACE=" "
input="st xxx street st st"
search_string="st"
replace_string="street"
output=${input//$SPACE$search_string$SPACE/$SPACE$replace_string$SPACE}
A: Try using sed if that is possible:
echo "$input" | sed 's/\bst\b/street/g'
\b in GNU sed refers to word boundaries.
Also refer: How can I find and replace only if a match forms a whole word?
A: I'm assuming that there are never any occurrences of street at line beginning or end.
I suggest you try this:
*
*Make all street occurrences to st:
output=${input//$SPACE$replace_string$SPACE/$SPACE$search_string$SPACE}
*Now you can safely change st to street without the spaces:
output2=${output//$search_string/$replace_string}
A: Add this two
output=${output//$search_string$SPACE/$replace_string$SPACE}
output=${output//$SPACE$search_string/$SPACE$replace_string}
Update on comment, then with help of |
output="|${input//$SPACE$search_string$SPACE/$SPACE$replace_string$SPACE}|"
output=${output//"|$search_string$SPACE"/$replace_string$SPACE}
output=${output//"$SPACE$search_string|"/$SPACE$replace_string}
output=${output//|}
Or like Markante Makrele suggested
output=${input//$replace_string/$search_string}
output=${output//$search_string/$replace_string}
But better use sed.
A: I have tried a 'simple-stupid' procedure, in which I first change all spaces to newlines, then search for (temporary) lines containing just 'st', which I change to street, and I revert the newlines back in the end.
input='anst xxx street st st'
echo "$input" | sed 's/ /\n/g' | sed 's/^st$/street/g' | tr '\n' ' ' | sed 's/ $/\n/'
output:
anst xxx street street street
Words only containing st shall not be substitued.
| |
doc_2323
|
The UL list displays like so...
<ul id='suckertree1'><li><a href='index.php?cPath=21'>Summer</a>
<ul>
<li>
<a href='index.php?cPath=21_23'>Bikes</a>
<ul>
<li><a href='index.php?cPath=21_23_28'>E-Bikes</a></li>
<li><a href='index.php?cPath=21_23_27'>Mountainroad</a></li>
<li><a href='index.php?cPath=21_23_26'>Road Bikes (1)</a></li>
</ul>
</li>
<li><a href='index.php?cPath=21_24'>Clothing</a>
<ul>
<li><a href='index.php?cPath=21_23_28'>Gloves</a></li>
<li><a href='index.php?cPath=21_23_27'>Shoes</a></li>
<li><a href='index.php?cPath=21_23_26'>Protection</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href='index.php?cPath=22'>Winter</a>
</li>
</ul>
I'm using jquery to hide a portion of the menu. When you click on Bikes - it then displays the submenu of that. The problem I have is, that the submenu links do not link, they close the menu again..
Here is my (terrible) jQuery code
$(document).ready(function() {
$("ul#suckertree1 li ul li ul").hide();
$("ul#suckertree1 li ul li a").click(function(e) {
e.preventDefault();
$("ul#suckertree1 li ul li ul").slideToggle();
});
});
Because of the limitations with this menu, I am unable to assign classes or ID's to the menu other than the #suckertree1 already in place.
How can I prevent the preventDefault() from effecting the submenu points? and also, clicking an item to only toggle the submenu below?
Thanks
James
A: Instead of this:
$("ul#suckertree1 li ul li ul").slideToggle();
Find the <ul> relatively, since it's beside the <a> you clicked that's pretty easy to get at using .siblings() or .next(), like this:
$(this).siblings('ul').slideToggle();
So it'd look like this:
$(function() {
$("ul#suckertree1 li ul li ul").hide();
$("ul#suckertree1 li ul li:has(ul) > a").click(function(e) {
$(this).siblings('ul').slideToggle();
e.preventDefault();
});
});
You can give it a try here
This also fixes the sub menu links working by using :has() and the child selector (>). What we're doing is only binding this handler to links that are in an <li> that also contain a <ul> element. It if doesn't have one (no sub menu) this code doesn't even run for that anchor, and it just continues to follow it's href like normal.
| |
doc_2324
|
Does anyone have an idea on how to implement this calculation?
Thanks!
A: Assuming that the next platform is at the same height and that gravity only points downward (i.e. gravity has a zero X component), you can use the following formula:
velocityX = distance * gravity * 0.5 / velocityY
Where distance is the distance you want to cover (distance between platforms), gravity is the absolute value of gravitational acceleration (9.81 in Unity by default) and velocityY is the vertical velocity component of the player after applying the jump force/impulse (velocity).
If the platforms are not level, that'll require some more calculations.
| |
doc_2325
|
*
*For IE6-8, Opera, older versions of other browsers you get the file as you
normally do with regular form-base
uploads.
*For browsers which upload file with progress bar, you will need to get the
raw post data and write it to the
file.
So, how can I receive the raw post data in my controller and write it to a tmp file so my controller can then process it? (In my case the controller is doing some image manipulation and saving to S3.)
Some additional info:
As I'm configured right now the post is passing these parameters:
Parameters:
{"authenticity_token"=>"...", "qqfile"=>"IMG_0064.jpg"}
... and the CREATE action looks like this:
def create
@attachment = Attachment.new
@attachment.user = current_user
@attachment.file = params[:qqfile]
if @attachment.save!
respond_to do |format|
format.js { render :text => '{"success":true}' }
end
end
end
... but I get this error:
ActiveRecord::RecordInvalid (Validation failed: File file name must be set.):
app/controllers/attachments_controller.rb:7:in `create'
A: try it, add lib/qq_file.rb:
# encoding: utf-8
require 'digest/sha1'
require 'mime/types'
# Usage (paperclip example)
# @asset.data = QqFile.new(params[:qqfile], request)
class QqFile < ::Tempfile
def initialize(filename, request, tmpdir = Dir::tmpdir)
@original_filename = filename
@request = request
super Digest::SHA1.hexdigest(filename), tmpdir
fetch
end
def self.parse(*args)
return args.first unless args.first.is_a?(String)
new(*args)
end
def fetch
self.write @request.raw_post
self.rewind
self
end
def original_filename
@original_filename
end
def content_type
types = MIME::Types.type_for(@request.content_type)
types.empty? ? @request.content_type : types.first.to_s
end
end
in assets_controller type this:
def create
@asset ||= Asset.new(params[:asset])
@asset.assetable_type = params[:assetable_type]
@asset.assetable_id = params[:assetable_id] || 0
@asset.guid = params[:guid]
@asset.data = QqFile.parse(params[:qqfile], request)
@asset.user_id = 0
@success = @asset.save
respond_with(@asset) do |format|
format.html { render :text => "{'success':#{@success}}" }
format.xml { render :xml => @asset.to_xml }
format.js { render :text => "{'success':#{@success}}"}
format.json { render :json => {:success => @success} }
end
end
javascript:
var photo_uploader = new qq.FileUploader({
element: document.getElementById('photo-button'),
multiple: true,
action: '/assets',
allowedExtensions: ['png', 'gif', 'jpg', 'jpeg'],
sizeLimit: 2097152,
params: {guid: $('#idea_guid').val(), assetable_type: 'Idea', klass: 'Picture', collection: true}
});
A: That's because params[:qqfile] isn't a UploadedFile object but a String containing the file name. The content of the file is stored in the body of the request (accessible by using request.body.read). Ofcourse, you can't forget backward compatibility so you still have to support UploadedFile.
So before you can process the file in a uniform way you have to catch both cases:
def create
ajax_upload = params[:qqfile].is_a?(String)
filename = ajax_upload ? params[:qqfile] : params[:qqfile].original_filename
extension = filename.split('.').last
# Creating a temp file
tmp_file = "#{Rails.root}/tmp/uploaded.#{extension}"
id = 0
while File.exists?(tmp_file) do
tmp_file = "#{Rails.root}/tmp/uploaded-#{id}.#{extension}"
id += 1
end
# Save to temp file
File.open(tmp_file, 'wb') do |f|
if ajax_upload
f.write request.body.read
else
f.write params[:qqfile].read
end
end
# Now you can do your own stuff
end
A: Another solution is:
gem 'rack-raw-upload', :git => 'git://github.com/tb/rack-raw-upload.git'
and in config.ru:
require 'rack/raw_upload'
use Rack::RawUpload
and use params[:file] in controller.
A: Rather than creating some clutter temp file, you can use StringIO. See my answer about CarrierWave, here: https://stackoverflow.com/a/8812976/478354
| |
doc_2326
|
The |FFT(i)|^2 of each segment are averaged to compute Pxx
He suggested I use PSD but overlap it manually a frame at a time instead of passing in the whole array of data. I've attempted it and it looks like this:
def spec_draw(imag_array):
overlap_step = len(imag_array) / 128
temp = []
values = []
for x in range(0, len(imag_array), overlap_step-overlap_step/2):
try:
for i in range(0, overlap_step):
temp.append(imag_array[x+i])
except:
pass
values.append(psd(temp, sides='onesided'))
temp = []
print values
Where imag_array is an array of data from a wave file. I've sent it to him and he doesn't understand Python very well and since he can't run it, he can't debug it. Does this look correct?
| |
doc_2327
|
I am adding the write file function to this example - where the ID comes from an RFID tag, and when I open the file, the format is completely different to what I have output to my terminal.
I am working on raspberry pi with 125KHz RFID sheild.
Here is the example code with my add-ons:
/*
* RFID 125 kHz Module
*
* Copyright (C) Libelium Comunicaciones Distribuidas S.L.
* http://www.libelium.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* a
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Version: 2.0
* Design: David Gascón
* Implementation: Marcos Yarza & Luis Martin
*/
//Include ArduPi library
#include "arduPi.h"
int led = 13;
byte data_1 = 0x00;
byte data_2 = 0x00;
byte data_3 = 0x00;
byte data_4 = 0x00;
byte data_5 = 0x00;
int val = 0;
void setup(){
// Start serial port 19200 bps
Serial.begin(19200);
pinMode(led, OUTPUT);
delay(500);
// Setting Auto Read Mode - EM4102 Decoded Mode - No password
// command: FF 01 09 87 01 03 02 00 10 20 30 40 37
Serial.print(0xFF,BYTE);
Serial.print(0x01,BYTE);
Serial.print(0x09,BYTE);
Serial.print(0x87,BYTE);
Serial.print(0x01,BYTE);
Serial.print(0x03,BYTE);
Serial.print(0x02,BYTE);
Serial.print(0x00,BYTE);
Serial.print(0x10,BYTE);
Serial.print(0x20,BYTE);
Serial.print(0x30,BYTE);
Serial.print(0x40,BYTE);
Serial.print(0x37,BYTE);
delay(500);
Serial.flush();
printf("\n");
printf("RFID module started in Auto Read Mode\n");
}
void loop(){
printf("Waiting card...\n");
val = Serial.read();
while (val != 0xff){
val = Serial.read();
delay(1000);
}
// Serial.read(); // we read ff
Serial.read(); // we read 01
Serial.read(); // we read 06
Serial.read(); // we read 10
data_1 = Serial.read(); // we read data 1
data_2 = Serial.read(); // we read data 2
data_3 = Serial.read(); // we read data 3
data_4 = Serial.read(); // we read data 4
data_5 = Serial.read(); // we read data 5
Serial.read(); // we read checksum
// LED blink
for(int i = 0;i < 4;i++){
digitalWrite(led,HIGH);
delay(500);
digitalWrite(led,LOW);
delay(500);
}
// Printing the code of the card
printf("\n");
printf("EM4100 card found - Code: ");
printf("%x",data_1);
printf("%x",data_2);
printf("%x",data_3);
printf("%x",data_4);
printf("%x",data_5);
printf("\n\n");
}
int writeFile(){
ofstream myfile;
osstringstream mystream;
myfile.open(example);
mystream << data_1;
mystream << data_2;
mystream << data_3;
mystream << data_4;
mystream << data_5;
myfile << mystream.str();
myfile.close();
return 0;
}
int main (){
setup();
while(1){
loop();
writefile();
}
return (0);
}
It compiles and runs, but when I check my example file, it gives a load of rubbish. I have tried a few other tweaks on the write file, but nothing seems to work. I am a bit lost so any help would be amazing!
| |
doc_2328
|
I want that when the user opens the lyrics which can be loaded in a new activity or fragment, the audio does not stop playing. So it should never call the onPause() or onStop(). I know that I can do it by using ActivityManager and get info about the foreground activity and then handle it in my onPause() and onStop().
But I was trying to figure out a more elegant and proper way to do this.
Any ideas?
| |
doc_2329
|
I want to know the meaning of this sentence and how to use it.
My programming environment is established by GNU Gcc under win7.
A: It creates and initializes an NSAutoreleasePool object. [NSAutoreleasePool alloc] allocates the memory for it and clears it to zero; calling init on that invokes its init method, which generally does whatever a class needs to do upon startup. The little "=" sign indicates assignment, storing the object just created and initialized into a local variable called "pool" which is an NSAutoreleasePool pointer.
This line generally occurs in the main program of iOS apps, creating a default autorelease pool for the whole app. But it is sometimes used elsewhere, to create a temporary pool for some specific purpose. Googling NSAutoreleasePool will surely lead you to its documentation.
| |
doc_2330
|
Apple have a Technical Q&A that says:
Applications that use an opaque UINavigationController or UITabBarController automatically keep their content below the status bar.
When I saw this, I assumed it meant that when used as the root view controller for a whole app, the UITabBarController would automatically size the views of its tabs' view controllers so that they don't extend under the status bar.
However, creating an otherwise empty project with the code below in its AppDelegate suggests otherwise. The area under the status bar ends up red or blue, depending which tab you're on, not the white that is the underlying UIWindow's background colour.
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let vc1 = UIViewController()
vc1.view.backgroundColor = UIColor.redColor()
vc1.tabBarItem = UITabBarItem(tabBarSystemItem: .Bookmarks, tag: 1)
let vc2 = UIViewController()
vc2.view.backgroundColor = UIColor.blueColor()
vc2.tabBarItem = UITabBarItem(tabBarSystemItem: .Favorites, tag: 2)
let tbc = UITabBarController()
tbc.viewControllers = [vc1, vc2]
window!.rootViewController = tbc
window!.backgroundColor = UIColor.whiteColor()
window!.makeKeyAndVisible()
return true
}
The UITabBarController has a topLayoutGuide that I could use to add explicit constraints to to keep the content below the status bar. Presumably something involving these guides (rather than hardcoding an offset of 20 somewhere) would be the "right way". However, in my real life situation vc1 and vc2 are supposed to be UITableViewControllers, so the only approaches I can see are:
*
*Derive from UITabBarController and add constraints to manage the size of its tabs view controllers. Presumably these constraints would need to be added/removed as the user switches between the tabs. Sounds complicated, and I'm not sure how it would interact with whatever functionality in the UITabBarController is setting the contained views to their current size.
*Create a custom view controller class to use for the tab view controllers, which contains the UITableViewController as a child and constrains its view to be within its own layout guides (which appear to be set correctly).
I'm leaning towards 2, but view controller containment seems an awful lot of fuss to achieve something that the Q&A seems to imply should be happening already. I'm new to iOS/Cocoa/Swift/Xcode/EverythingApple, and I'm sure there must be a better way.
UPDATE: Actually, looking more carefully at the simulator it seems the contained view controllers extend behind the tab bar as well. There must be something really basic I'm getting wrong here...
UPDATE: edgesForExtendedLayout looks promising, but setting it to UIRectEdge.None doesn't seem to stop the view extending under the status bar in my test.
UPDATE: Actually, setting edgesForExtendedLayout to UIRectEdge.None on each of vc1 and vc2 in the example above does appear to prevent the views from extending under the tab bar, which is a step in the right direction. However, it has no effect as regards the status bar. The docs on this subject really are atrocious. I don't see how you're supposed to divine what is meant by "extended layout" or what the relationship betweem edgesForExtendedLayout and topLayoutGuide/bottomLayoutGuide is, except for trial and error, which seems to be what people have been resorting to.
UPDATE: This excellent blog entry gives a lot more detail than the docs, and explains the behaviour I'm seeing. However, I still don't see a good solution yet. I can't insert an outermost view controller to hold everything in because the docs for UITabBarController say that you should never make it a child of another view controller - it needs to be the root. I suspect that the contentInset behaviour described in the blog's point 8 is supposed to give me what I really need, which is for the top of my UITableView's content to start off below the status bar. If Apple want me to allow the content to then scroll under the status bar, that's OK with me I suppose. However, currently the top of my table view starts off under the status bar text, which is just obviously wrong looking. Perhaps something is preventing the contentInset adjustments from working.
A: I placed this in my viewDidLoad method to prevent the UITAbleView content from loading underneath the tab bar. In my case the tab bar is at the top and I had to iterate to find the offset:
self.tableView.contentInset = UIEdgeInsetsMake(70, 0, 0, 0)
the general use case is:
self.tableView.contentInset = UIEdgeInsetsMake(<#top: CGFloat#>, <#left: CGFloat#>, <#bottom: CGFloat#>, <#right: CGFloat#>)
| |
doc_2331
|
var match = new RegExp(/\.(woff|svg|ttf|eot)/g);
if (match.test(fileName)) {
// Do something
}
As I cycle through the fonts available, the only two that are being matched are
app.svg
app.eot
The app.ttf and app.woff files are not matching the expression.
I have tried out the expression over at http://www.regexr.com/ and it appears to work for my purposes. Keep in mind that I don't require much more stringent testing than this as there is only a handful of files in that directory.
If anybody can give me some guidance I would be most appreciative.
A: Your regex is correct.Tried it.
See
| |
doc_2332
|
So for all these 10-12 table I would required to write the same kind of method like this
public List<XYZType> getAllXYZType() {
return XYZRepository.findAll();
}
So this kind of code will be repeated for 10-12 times for different entities.
Is there any way so that I can make it generic ?
A: public <T> List<T> getAll(final Class<T> type) {
Session session = sessionFactory.getCurrentSession();
Criteria crit = session.createCriteria(type);
return crit.list();
}
in order to use it just pass the desired class to the function and it will return the list.
A: In that case you need to make it generic, I think the Abstract Factory Pattern is what you are looking for.
Your code should be like this:
public interface GenericDAO < T, ID extends Serializable > {
T findById(ID id);
List < T > findAll();
}
Take a look at DAO Factory patterns with Hibernate for further information.
A: public static <T> List<T> getLst(final Class<T> beanClass) {
List<T> lst = new ArrayList<T>();
Session sess = MyUtils.getSessionFactory().openSession();
try {
Criteria cr= sess.createCriteria(beanClass);
lst = cr.list();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
sess.close();
}
return lst;
}
| |
doc_2333
|
I just do:
> stack new testProject yesod-mysql
> cd testProject
> yesod devel -v
And get this output:
Yesod devel server. Type 'quit' to quit
...
[10 of 10] Compiling Application ( Application.hs, dist/build/Application.o )
Starting development server: runghc -package-dbdist/package.conf.inplace -package-idyesod-static-1.5.0.3-6NvTJROzmYNDUWjTfXoBEl -package-idyesod-form-1.4.7.1-Gzgnhxtpl1cHtZi8tpYJ6W -package-idyesod-core-1.4.20.2-LSkQJeMzDLa5Pa7kLbuyWE -package-idyesod-auth-1.4.13.2-BkxNkvnXCXHJK4Jcn5DCOG -package-idyesod-1.4.3-FozpcNynopR5dmIxJzx9wP -package-idyaml-0.8.17.1-IPQ39fXTYs6HOJXpZL5WSD -package-idwarp-3.2.6-EMPFQ0WMXK0LyTg9Lg5rBJ -package-idwai-logger-2.2.7-3YHWZq6HKajEjDJfMQEMPY -package-idwai-extra-3.0.15.1-FUnXXg3Vz52LuAJuCHPGaT -package-idwai-3.2.1-9pjoXeBvlCLGeOhAgcgOSZ -package-idvector-0.11.0.0-0444ed29a172c8c9f3affdad55a00e13 -package-idunordered-containers-0.2.7.0-eb2531a91f87979d5a2e9de1b078f8a1
-package-idtime-1.5.0.1-edbd1a50e7922b396ada189ab8e8523b -package-idtext-1.2.2.1-bd90209501b908bc79e4032fc38e47f7 -package-idtemplate-haskell-2.10.0.0-3c4cb52230f347282af9b2817f013181 -package-idshakespeare-2.0.8.2-Let4Je93qneC1Nfl494qaM -package-idsafe-0.3.9-e3aa437cf6afe091d2ac3ab91bc10ddd -package-idpersistent-template-2.1.6-EUymMpKPmxE54ia896mF3s -package-idpersistent-mysql-2.3.0.2-HpU8wMgRXTXGiRFshdlWNX -package-idpersistent-2.2.4.1-K0SUUK1ZVk4JJtT76N8FVA -package-idmysql-0.1.1.8-3047da6de17d2eaf02fcc6ae68d7ce79 -package-idmonad-logger-0.3.18-JIh1o7RvrrHLGPDtRuSVy8 -package-idmonad-control-1.0.1.0-22a9e4b9739808e702fc8251a1dc4535 -package-idhttp-conduit-2.1.10.1-DDGpLGxxWzO4lHgtxRUkKf -package-idhjsmin-0.2.0.1-JhGg7bhrA0D548DHQrOeec -package-idfile-embed-0.0.10-LIO3D2loTjuJO9Lps8PxJ7 -package-idfast-logger-2.4.6-2JY77Xt5kMm2HfluQ1ke36 -package-iddirectory-1.2.2.0-f8e14a9d121b76a00a0f669ee724a732 -package-iddata-default-0.5.3-a34fab0e414a3e31b9dccb1774520fca -package-idcontainers-0.5.6.2-e59c9b78d840fa743d4169d4bea15592 -package-idconduit-1.2.6.6-6VAuHz9CRA0HmWEsAB1s4R -package-idclassy-prelude-yesod-0.12.7-Aj4RVwagw6VEzBmKSFAy2b -package-idclassy-prelude-conduit-0.12.7-FT79eygBPV3CuOI3ecyxRd -package-idclassy-prelude-0.12.7-3FnNABKFDLNAOC5FwFI1yk -package-idcase-insensitive-1.2.0.6-5bc0eef1a20451ec195ee1b54e28c2d9 -package-idbytestring-0.10.6.0-c60f4c543b22c7f7293a06ae48820437 -package-idbase-4.8.2.0-0d6d1084fbc041e1cded9228e80e264d -package-idaeson-0.11.2.0-3W4IHFv12VV9EikLopLM1H -package-keymain app/devel.hs
: cannot satisfy -package-key main
(use -v for more information)
Exit code: ExitFailure 1
The stack build generates a valid binary. I use gentoo and have all haskell packages installed by emerge. I tried to start with "stack build && stack exec -- yesod devel", but got the same error.
A: Problem solved. Gentoo have cabal version 1.24. Yesod devel successfully started after downgrade to 1.22.8
| |
doc_2334
|
A: According to the SQLite documentation at https://www.sqlite.org/tempfiles.html
journal files are created on an as-needed basis.
| |
doc_2335
|
When using scrollTo the items bouncing vertically.
I didn't have that problem in iOS 14. The bounce is very random no logic at all for trying to understand when it will jump.
If I'm removing the padding from the scroll view it's fixed, but I need that extra space as requested by the UI designer.
Also, tried to use .frame instead of .padding and same results.
Does anyone know how to fix this problem or maybe why it happens only in iOS 15?
Code:
ScrollView(.horizontal, showsIndicators: false) {
ScrollViewReader{ proxy in
HStack(spacing: 32){
ForEach(...){ index in
QuestionCell(...)
.scaleEffect(selectedIndex == index ? 1.175 : 1.0)
.onTapGesture{
withAnimation(.spring()){
selectedIndex = index
}
}
}
}
.padding(.leading)
.padding() // Removing this fixes the bounce bug.
.onChange(of: selectedIndex) { value in
withAnimation(.spring()){
let paramsCount = <SOME MODEL>.count
if value < paramsCount{
proxy.scrollTo(value, anchor: .center)
}else{
proxy.scrollTo(paramsCount - 1, anchor: .center)
}
}
}
}
}
}
A: The problem is the vertical padding on the HStack.
Minimal reproducible example of the problem
Here is the problem in minimal code, which anyone can run. Use this code as a reference to see what changes:
struct ContentView: View {
@State private var selectedIndex = 0
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
ScrollViewReader { proxy in
HStack(spacing: 32) {
ForEach(0 ..< 10, id: \.self) { index in
Text("Question cell at index: \(index)")
.background(Color(UIColor.systemBackground))
.scaleEffect(selectedIndex == index ? 1.175 : 1.0)
.onTapGesture {
withAnimation(.spring()) {
selectedIndex = index
proxy.scrollTo(index, anchor: .center)
}
}
}
}
.padding(.leading)
.padding() // Removing this fixes the bounce bug
}
}
.background(Color.red)
}
}
Solution
You can remove the vertical padding from the HStack by just doing .horizontal padding, then add the .vertical padding to each Text view instead.
Code:
struct ContentView: View {
@State private var selectedIndex = 0
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
ScrollViewReader { proxy in
HStack(spacing: 32) {
ForEach(0 ..< 10, id: \.self) { index in
Text("Question cell at index: \(index)")
.background(Color(UIColor.systemBackground))
.scaleEffect(selectedIndex == index ? 1.175 : 1.0)
.onTapGesture {
withAnimation(.spring()) {
selectedIndex = index
proxy.scrollTo(index, anchor: .center)
}
}
.padding(.vertical) // <- HERE
}
}
.padding(.leading)
.padding(.horizontal) // <- HERE
}
}
.background(Color.red)
}
}
Before
After
A: Use .bottom instead of .center in proxy.scrollTo(index, anchor: ...).
Vertical content offset is changing during proxy.scrollTo animation if we set .top or .center anchor. It's look like some apple bug.
To avoid that we should align to such anchor that results to zero offset during scrolling.
For horizontal ScrollView we should change:
*
*.trailing -> .bottomTrailing
*.center -> .bottom
*.leading -> .bottomLeading
For vertical:
*
*.top -> .topTrailing
*.center -> .trailing
*.bottom -> .bottomTrailing
| |
doc_2336
|
#include <stdio.h>
int f1(int n) {
if (n < 2) {
return n;
}
int a, b;
a = f1(n - 1);
b = f1(n - 2);
return a + b;
}
int main(){
printf("%d", f1(40));
}
When measuring execution time, the result is:
peter@host ~ $ time ./fib1
102334155
real 0m0.511s
user 0m0.510s
sys 0m0.000s
Now let's introduce a global variable in our program and compile again using 'gcc -Ofast -o fib2 fib2.c'.
#include <stdio.h>
int global;
int f1(int n) {
if (n < 2) {
return n;
}
int a, b;
a = f1(n - 1);
b = f1(n - 2);
global = 0;
return a + b;
}
int main(){
printf("%d", f1(40));
}
Now the execution time is:
peter@host ~ $ time ./fib2
102334155
real 0m0.265s
user 0m0.265s
sys 0m0.000s
The new global variable does not do anything meaningful. However, the difference in execution time is considerable.
Apart from the question (1) what the reason is for such behavior, it also would be nice if (2) the last performance could be achieved without introducing meaningless variables. Any suggestions?
Thanks
Peter
A: I believe you hit some very clever and very weird gcc (mis-?)optimization. That's about as far as I got in researching this.
I modified your code to have an #ifdef G around the global:
$ cc -O3 -o foo foo.c && time ./foo
102334155
real 0m0.634s
user 0m0.631s
sys 0m0.001s
$ cc -O3 -DG -o foo foo.c && time ./foo
102334155
real 0m0.365s
user 0m0.362s
sys 0m0.001s
So I have the same weird performance difference.
When in doubt, read the generated assembler.
$ cc -S -O3 -o foo.s -S foo.c
$ cc -S -DG -O3 -o foog.s -S foo.c
Here it gets truly bizarre. Normally I can follow gcc-generated code pretty easily. The code that got generated here is just incomprehensible. What should be pretty straightforward recursion and addition that should fit in 15-20 instructions, gcc expanded to a several hundred instructions with a flurry of shifts, additions, subtractions, compares, branches and a large array on the stack. It looks like it tried to partially convert one or both recursions into an iteration and then unrolled that loop. One thing struck me though, the non-global function had only one recursive call to itself (the second one is the call from main):
$ grep 'call.*f1' foo.s | wc
2 4 18
While the global one one had:
$ grep 'call.*f1' foog.s | wc
33 66 297
My educated (I've seen this many times before) guess? Gcc tried to be clever and in its fervor the function that in theory should be easier to optimize generated worse code while the write to the global variable made it sufficiently confused that it couldn't optimize so hard that it led to better code. This happens all the time, many optimizations that gcc (and other compilers too, let's not single them out) uses are very specific to certain benchmarks they use and might not generate faster running code in many other cases. In fact, from experience I only ever use -O2 unless I've benchmarked things very carefully to see that -O3 makes sense. It very often doesn't.
If you really want to research this further, I'd recommend reading gcc documentation about which optimizations get enabled with -O3 as opposed to -O2 (-O2 doesn't do this), then try them one by one until you find which one causes this behavior and that optimization should be a pretty good hint for what's going on. I was about to do this, but I ran out of time (must do last minute christmas shopping).
A: On my machine (gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010) I've got this:
time ./fib1 0,36s user 0,00s system 98% cpu 0,364 total
time ./fib2 0,20s user 0,00s system 98% cpu 0,208 total
From man gcc:
-Ofast
Disregard strict standards compliance. -Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard-compliant programs. It turns on -ffast-math and the Fortran-specific -fno-protect-parens and -fstack-arrays.
Not so safe option, let's try -O2:
time ./fib1 0,38s user 0,00s system 99% cpu 0,377 total
time ./fib2 0,47s user 0,00s system 99% cpu 0,470 total
I think, that some of aggressive optimizations weren't applied to fib1, but were applied to fib2. When I switched -Ofast for -O2 - some of optimizations weren't applied to fib2, but were applied to fib1.
Let's try -O0:
time ./fib1 0,81s user 0,00s system 99% cpu 0,812 total
time ./fib2 0,81s user 0,00s system 99% cpu 0,814 total
They are equal without optimizations.
So introducing global variable in recursive function can break some optimizations on one hand and improve other optimizations on other hand.
A: This results from inline limits kicking in earlier in the second version. Because the version with the global variable does more. That strongly suggests that inlining makes run-time performance worse in this particular example.
Compile both versions with -Ofast -fno-inline and the difference in time is gone. In fact, the version without the global variable runs faster.
Alternatively, just mark the function with __attribute__((noinline)).
| |
doc_2337
|
i am using the fallowing code to unarcive a zip file.. its not working... and printing the NSLog(@"Failure To Unzip Archive"); msg
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
self.documentsDir = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/temp", self.documentsDir];
NSString *updateURL = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:@"bmlgg.zip"];
NSLog(@"Checking update at : %@", updateURL);
NSLog(@"Checking filepath at : %@", filePath);
ZipArchive *zipArchive = [[ZipArchive alloc] init];
if([zipArchive UnzipOpenFile:updateURL]) {
if ([zipArchive UnzipFileTo:filePath overWrite:YES]) {
//unzipped successfully
NSLog(@"Archive unzip Success");
//[self.fileManager removeItemAtPath:filePath error:NULL];
} else {
NSLog(@"Failure To Unzip Archive");
}
} else {
NSLog(@"Failure To Open Archive");
}
[zipArchive release];
thank u....
A: i got the solution...
the problem is the zip file is not recognized...
i changed the fallowing code
NSString *updateURL = [[NSBundle mainBundle] pathForResource:@"bmlg" ofType:@"zip" inDirectory:@"res"];
this helped me
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
self.documentsDir = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/temp", self.documentsDir];
NSString *updateURL = [[NSBundle mainBundle] pathForResource:@"bmlg" ofType:@"zip" inDirectory:@"res"];
[fileManager createDirectoryAtPath:filePath withIntermediateDirectories:NO attributes:nil error:nil];
if([fileManager fileExistsAtPath:updateURL]) {
NSLog(@"File exists at path: %@", updateURL);
} else {
NSLog(@"File does not exists at path: %@", updateURL);
}
NSLog(@"Checking update at : %@", updateURL);
NSLog(@"Checking filepath at : %@", filePath);
ZipArchive *zipArchive = [[ZipArchive alloc] init];
if([zipArchive UnzipOpenFile:updateURL]) {
if ([zipArchive UnzipFileTo:filePath overWrite:YES]) {
//unzipped successfully
NSLog(@"Archive unzip Success");
//[self.fileManager removeItemAtPath:filePath error:NULL];
} else {
NSLog(@"Failure To Unzip Archive");
}
} else {
NSLog(@"Failure To Open Archive");
}
[zipArchive release];
| |
doc_2338
| ERROR: type should be string, got "\nhttps://www.jstree.com/api/#/?q=(&f=select_node(obj [,\n supress_event, prevent_open])\n\nobj: mixed an array can be used to select multiple nodes\nsupress_event: \nBoolean if set to true the changed.jstree event won't be triggered\nprevent_open: \nBoolean if set to true parents of the selected node won't be opened\nHowever, it does not talk about suppressing the select_node event. Any suggestions?\n\nA: I see two options here:\n\n\n*\n\n*Temporarily disable your select_node event handler while you manually select a node from code.\n\n*Use the changed event instead of the select_node event and use the supress flag.\n\n\nA: I don't know if there's a better way to pull it off, but here's how I did it:\nInstead of using the select_node function, I wrote a function which takes the ID of the node and then opens it, sets it as selected, and then recursively open the parent nodes.\n$('#TreeDiv').jstree(true).open_node(actualId);\n$('#TreeDiv').jstree(true).get_node(actualId).state.selected = true;\nvar parent = $('#TreeDiv').jstree(true).get_parent(actualId);\nwhile (parent.length > 0) {\n $('#TreeDiv').jstree(true).open_node(parent);\n parent = $('#TreeDiv').jstree(true).get_parent(parent);\n}\n\n\nA: You may use the following; it works for me\n$('#TreeDiv').jstree(\"select_node\", actualId, true);\n\nAccording to the jsTree official documentation, the select_node method accepts a Boolean value as the second argument which indicates whether the corresponding event should be suppressed. See this page.\n"
| |
doc_2339
|
for (var index=0; index<4; index++)
{
var text = "Hello" + index;
var name = 'RadioButton' + (index+1);
var radioBut = document.createElement('input');
radioBut.setAttribute('type', 'radio');
radioBut.setAttribute('name', name);
document.body.appendChild(radioBut);
var newdiv = document.createElement('div');
var divIdName = 'my'+index+'Div';
newdiv.setAttribute('id',divIdName);
document.body.appendChild(newdiv);
newdiv.innerHTML = text;
}
It prints the radio buttons but the text is obviously printed below. What must I do to get the following format: RadioButton + Text?
A: Div is block level element so it's gets rendered on the new line. Use some inline element like span or label instead:
for (var index = 0; index < 4; index++) {
var text = "Hello" + index;
var name = 'RadioButton'; // + (index + 1);
var id = 'my' + index + 'Div';
var row = document.createElement('div');
document.body.appendChild(row);
var radioBut = document.createElement('input');
radioBut.setAttribute('type', 'radio');
radioBut.setAttribute('name', name);
radioBut.setAttribute('id', id);
row.appendChild(radioBut);
var label = document.createElement('label');
label.setAttribute('for', id);
label.innerHTML = text;
row.appendChild(label);
}
With label you can specify for attribute which would point to corresponding input element, this is good for UX. Also note, that it makes sense to give the same name for radio buttons.
| |
doc_2340
|
The following code is not working because dt is always null.
DataTable dt = new DataTable();
dt = dataGridView1.DataSource as DataTable;
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(@"e:\results.xml", System.Data.XmlWriteMode.IgnoreSchema);
Thank you in advance.
A: BindingSource bs = new BindingSource();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
dt.Columns.Add("1", typeof(int));
dt.Columns.Add("2");
dt.Columns.Add("3");
dt.Columns.Add("4");
dt.Columns.Add("5");
string[] row = {null,"dsadxaxsa","xasxsa","","dsad"};
string[] row1 = { "1", "ddd", "gg", "hh", "ff" };
string[] row2 = { "2", "h", "hhhh", "sas", "dsad" };
string[] row3 = { "3", "h", "hhhh", "sas", "dsad" };
string[] row4 = { null, "h", "hhhh", "sas", "dsad" };
dt.Rows.Add(row);
dt.Rows.Add(row1);
dt.Rows.Add(row2);
dt.Rows.Add(row3);
dt.Rows.Add(row4);
bs.DataSource = dt;
dataGridView1.DataSource = bs;
ds.Tables.Add(dt);
ds.WriteXml("e:\\results.xml", System.Data.XmlWriteMode.IgnoreSchema);
| |
doc_2341
|
However, I still want to know if there are better ways of handling arbitrary AJAX requests.
A: If you want low-level control over what you're sending. AbstractAjaxBehavior is probably more or less what you're looking for. You can do something like
public class MyAjaxBehavior extends AbstractAjaxBehavior{
@Override
public void onRequest() {
RequestCycle.get().scheduleRequestHandlerAfterCurrent(
new TextRequestHandler("application/json", "UTF-8", "{myVal:123}")
);
}
};
You can replace the TextRequestHandler with some other request handler (or write your own) to return exactly the data you want.
If you wish to write your own javascript handling the ajax you can look at the Wicket Ajax wiki page, where it describes how this ajax is to be invoked manually (you can get the callback URL via AbstractAjaxBehavior#getCallbackUrl()).
If all you really want is just updating the display - high-level ajax for updating wicket components is what you want. Most Wicket Ajax behaviors (like AjaxEventBehavior) attach their own ajax invocation, you don't have to do the javascript side of things at all. All you need to do is add components to the provided AjaxRequestTarget, and wicket will do the rest, updating what the component displays automatically.
Both of these methods will access the page however, and if that is not what you want, resource mounting is the way to go.
| |
doc_2342
|
# iptables-save
# Generated by iptables-save v1.4.21 on Tue Apr 5 12:52:32 2016
*nat
:PREROUTING ACCEPT [1345:188285]
:INPUT ACCEPT [1332:187243]
:OUTPUT ACCEPT [24:1510]
:POSTROUTING ACCEPT [24:1510]
:DOCKER - [0:0]
-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
-A DOCKER -i docker0 -j RETURN
COMMIT
# Completed on Tue Apr 5 12:52:32 2016
# Generated by iptables-save v1.4.21 on Tue Apr 5 12:52:32 2016
*filter
:INPUT ACCEPT [10563:913002]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [745:59756]
:DOCKER - [0:0]
:DOCKER-ISOLATION - [0:0]
-A FORWARD -j DOCKER-ISOLATION
-A FORWARD -o docker0 -j DOCKER
-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i docker0 ! -o docker0 -j ACCEPT
-A FORWARD -i docker0 -o docker0 -j ACCEPT
-A DOCKER-ISOLATION -j RETURN
COMMIT
# Completed on Tue Apr 5 12:52:32 2016
| |
doc_2343
|
So my question is i have developed a physic game that have 20 levels and menus scenes and where should i implement the inmobi ads?
Should i just implement when the game starts (in the menu scene) or should i implenment in every levels and scenes?
All the scene are in defferent .lua classes.
Thanks in Advance!
My question is not actually how to implement.
So my question is i have developed a physic game that have 20 levels and menus scenes and where should i implement the inmobi ads?
Should i just implement when the game starts (in the menu scene) or should i implenment in every levels and scenes?
All the scene are in defferent .lua classes.
Thanks in Advance!
A: In your main.lua use ads.init() to get the ads:
ads.init( "iads", "myAppId", adListener )
and then use ads.show() in all the scenes you want to show ads:
ads.show( "banner", { x=0, y=0 } )
then if you want to hide ads in some scene use:
ads.hide()
A: You need to just call the adBanner code once in your app to display an ad in every scene.
My suggestion:
*
*Here, just create a flag when you enter into the menu page first time.
*Call the inmobi adbanner code.
*Reset the flag (it will prevent you from calling the adView many in every time you entering into your menu page).
And you can show or hide the ad in any page you desire by the method that vovahost specified in the post.
A: For inmobi, you will need to setup your account with them where you will get an App ID number. Then you can use code like this:
local ads = require "ads"
local function adListener( event )
if event.isError then
-- Failed to receive an ad.
end
end
ads.init( "inmobi", "myAppId", adListener )
ads.show( "banner320x48", { x=0, y=100, interval=60, testMode=false } )
See http://docs.coronalabs.com/api/library/ads/init.html
A: Assuming you have some kind of "level complete" screen, I would put the ads there. I would think putting them on the actual levels and menus would be too annoying to the user.
| |
doc_2344
|
My Product class looks like:
public class Product {
public string Name { get; set; }
public IQueryable<Category> Categories { get; set; }
}
My Category class looks like:
public class Category {
public string Name { get; set; }
}
Currently, I'm doing this:
var myProducts = products.OrderBy(x => x.Name).Select(x => new Product {
Name = x.Name,
Categories = x.Categories(y => y.Name)
});
The trouble is, when using something like NHibernate, this creates new Product objects, essentially disconnecting the product from the NH session.
A: You don't want to modify the Product object in any way that could affect persistence and you don't want to create new Product instances.
So add this to Product class:
public IOrderedEnumerable<Category> CategoriesOrderedByName
{
get { return this.Categories.OrderBy(y => y.Name); }
}
And use product.CategoriesOrderedByName instead when you need the sorted version in your UI code.
Without this anyone using your class has no expectation that the Category objects are sorted in any way. With this you are being explicit in informing consumers of your class what to expect and that you intend to always return them in a sorted order. You can also use IOrderedEnumerable<> as the return type to make allow further sub-sorting using ThenBy().
A: Maybe this is what you want? You do not get a list of products that each has a list of categories, however. That's impossible using LINQ because you can not alter a collection using LINQ, you can only make a new collection from an existing one (in my example p.Categories is the existing collection, SortedCategories the new one).
from p in products
orderby p.Name
select new
{
Product = p,
SortedCategories = from c in p.Categories
orderby c.Name
select c
}
You say you have IQueryable's. Does that mean that you are querying against a database using this LINQ statement? I'm not sure how well this transforms to SQL (performance-wise).
A: Why not just sort the enumerable in place?
products = products.OrderBy(x => x.Name);
products.ToList().ForEach(x => x.Categories = x.Categories.OrderBy(y => y.Name));
As others have stated, this may perform poorly if you're connected.
A: If you want to enumerate over the Product objects in sorted order and within each Product you want the Categories in sorted order, you could do something like this.
var sorted = products
.Select(
p => new
{
Product = p,
Categories = p.Categories.OrderBy(c => c.Name)
}
)
.OrderBy(x => x.Product.Name);
It looks like this is basically what Ronald has, only without using LINQ syntax.
| |
doc_2345
|
Calls to CommandManager.InvalidateRequerySuggested() take far longer to take effect than I would like (1-2 second delay before UI controls become disabled).
Long Version
I have a system where I submit tasks to a background-thread based task processor. This submit happens on the WPF UI thread.
When this submit happens, the object that manages my background thread does two things:
*
*It raises a "busy" event (still on the UI thread) that several view models respond to; when they receive this event, they set an IsEnabled flag on themselves to false. Controls in my views, which are databound to this property, are immediately grayed out, which is what I would expect.
*It informs my WPF ICommand objects that they should not be allowed to execute (again, still on the UI thread). Because there is nothing like INotifyPropertyChanged for ICommand objects, I am forced to call CommandManager.InvalidateRequerySuggested() to force WPF to reconsider all of my command objects' CanExecute states (yes, I actually do need to do this: otherwise, none of these controls become disabled). Unlike item 1, though, it takes a significantly longer time for my buttons/menu items/etc that are using ICommand objects to visually change to a disabled state than it does for the UI controls that have their IsEnabled property manually set.
The problem is, from a UX point of view, this looks awful; half of my controls are immediately grayed out (because their IsEnabled property is set to false), and then a full 1-2 seconds later, the other half of my controls follow suit (because their CanExecute methods are finally re-evaluated).
So, part 1 of my question:
As silly as it sounds to ask, is there a way I can make CommandManager.InvalidateRequerySuggested() do it's job faster? I suspect that there isn't.
Fair enough, part 2 of my question:
How can I work around this? I'd prefer all of my controls be disabled at the same time. It just looks unprofessional and awkward otherwise. Any ideas? :-)
A: This solution is a reduced version of the solution proposed by Tomáš Kafka(thanks to Tomas for describing his solution in detail)in this thread.
In Tomas's solution he had
1) DelegateCommand
2) CommandManagerHelper
3) DelegateCommandExtensions
4) NotifyPropertyChangedBaseExtensions
5) INotifyPropertyChangedWithRaise
6) ThreadTools
This solution has
1) DelegateCommand
2) DelegateCommandExtensions method and NotifyPropertyChangedBaseExtensions method in Delegate Command itself.
Note Since our wpf application follows MVVM pattern and we handle commands at viewmodel level which executes in UI thread we don't need to get the reference to UI disptacher.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Input;
namespace ExampleForDelegateCommand
{
public class DelegateCommand : ICommand
{
public Predicate<object> CanExecuteDelegate { get; set; }
private List<INotifyPropertyChanged> propertiesToListenTo;
private List<WeakReference> ControlEvent;
public DelegateCommand()
{
ControlEvent= new List<WeakReference>();
}
public List<INotifyPropertyChanged> PropertiesToListenTo
{
get { return propertiesToListenTo; }
set
{
propertiesToListenTo = value;
}
}
private Action<object> executeDelegate;
public Action<object> ExecuteDelegate
{
get { return executeDelegate; }
set
{
executeDelegate = value;
ListenForNotificationFrom((INotifyPropertyChanged)executeDelegate.Target);
}
}
public static ICommand Create(Action<object> exec)
{
return new SimpleCommand { ExecuteDelegate = exec };
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (CanExecuteDelegate != null)
return CanExecuteDelegate(parameter);
return true; // if there is no can execute default to true
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
ControlEvent.Add(new WeakReference(value));
}
remove
{
CommandManager.RequerySuggested -= value;
ControlEvent.Remove(ControlEvent.Find(r => ((EventHandler) r.Target) == value));
}
}
public void Execute(object parameter)
{
if (ExecuteDelegate != null)
ExecuteDelegate(parameter);
}
#endregion
public void RaiseCanExecuteChanged()
{
if (ControlEvent != null && ControlEvent.Count > 0)
{
ControlEvent.ForEach(ce =>
{
if(ce.Target!=null)
((EventHandler) (ce.Target)).Invoke(null, EventArgs.Empty);
});
}
}
public DelegateCommand ListenOn<TObservedType, TPropertyType>(TObservedType viewModel, Expression<Func<TObservedType, TPropertyType>> propertyExpression) where TObservedType : INotifyPropertyChanged
{
string propertyName = GetPropertyName(propertyExpression);
viewModel.PropertyChanged += (PropertyChangedEventHandler)((sender, e) =>
{
if (e.PropertyName == propertyName) RaiseCanExecuteChanged();
});
return this;
}
public void ListenForNotificationFrom<TObservedType>(TObservedType viewModel) where TObservedType : INotifyPropertyChanged
{
viewModel.PropertyChanged += (PropertyChangedEventHandler)((sender, e) =>
{
RaiseCanExecuteChanged();
});
}
private string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> expression) where T : INotifyPropertyChanged
{
var lambda = expression as LambdaExpression;
MemberInfo memberInfo = GetmemberExpression(lambda).Member;
return memberInfo.Name;
}
private MemberExpression GetmemberExpression(LambdaExpression lambda)
{
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = lambda.Body as UnaryExpression;
memberExpression = unaryExpression.Operand as MemberExpression;
}
else
memberExpression = lambda.Body as MemberExpression;
return memberExpression;
}
}}
Explanation of the solution:
Normally when we bind a UI element(Button)to the ICommand implementation the WPF Button registers for a Event "CanExecuteChanged" in ICommand implementation .If your Icommand implementation for "CanExecuteChanged" hook to the CommandManager's RequesySuggest event(read this article http://joshsmithonwpf.wordpress.com/2008/06/17/allowing-commandmanager-to-query-your-icommand-objects/) then when ever CommandManager detects conditions that might change the ability of a command to execute(changes like Focus shifts and some keyboard events) , CommandManager’s RequerySuggested event occurs which in turn will cause Button'e delegate to be called since we hooked the buttos's delgate to CommandManager’s RequerySuggested in the implementation of "CanExecuteChanged" in our DelegateCommand .
But the problem is that ComandManager is not able to always detect the changes. Hence the solution it to raise "CanExecuteChanged" when our command implementation(DelegateCommand) detects there is a change.Normally when we declare the delagate for ICommand's CanExecute in our viewmodel we bind to properties declared in our viewmodel and our ICommand implementation can listen for "propertychanged" events on these properties. Thats what the "ListenForNotificationFrom" method of the DelegateCommand does. In case the client code does not register for specific property changes the DelegateCommand by defaults listens to any property change on the view model where command is declared and defined.
"ControlEvent" in DelegateCommand which is list of EventHandler that stores the Button's
"CanExecuteChange EventHandler" is declared as weak reference to avoid memory leaks.
How will ViewModel use this DelegateCommand
There are 2 ways to use it.
(the second usage is more specific to the properties that you want the Command to listen to.
delegateCommand = new DelegateCommand
{
ExecuteDelegate = Search,
CanExecuteDelegate = (r) => !IsBusy
};
anotherDelegateCommand = new DelegateCommand
{
ExecuteDelegate = SearchOne,
CanExecuteDelegate = (r) => !IsBusyOne
}.ListenOn(this, n => n.IsBusyOne);
A detailed ViewModel
public class ExampleViewModel
{
public SearchViewModelBase()
{
delegateCommand = new DelegateCommand
{
ExecuteDelegate = Search,
CanExecuteDelegate = (r) => !IsBusy
};
anotherDelegateCommand = new DelegateCommand
{
ExecuteDelegate = SearchOne,
CanExecuteDelegate = (r) => !IsBusyOne
}.ListenOn(this, n => n.IsBusyOne);
}
private bool isBusy;
public virtual bool IsBusy
{
get { return isBusy; }
set
{
if (isBusy == value) return;
isBusy = value;
NotifyPropertyChanged(MethodBase.GetCurrentMethod());
}
}
private bool isBusyOne;
public virtual bool IsBusyOne
{
get { return isBusyOne; }
set
{
if (isBusyOne == value) return;
isBusyOne = value;
NotifyPropertyChanged(MethodBase.GetCurrentMethod());
}
}
private void Search(object obj)
{
IsBusy = true;
new SearchService().Search(Callback);
}
public void Callback(ServiceResponse response)
{
IsBusy = false;
}
private void Search(object obj)
{
IsBusyOne = true;
new SearchService().Search(CallbackOne);
}
public void CallbackOne(ServiceResponse response)
{
IsBusyOne = false;
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void NotifyPropertyChanged(MethodBase methodBase)
{
string methodName = methodBase.Name;
if (!methodName.StartsWith("set_"))
{
var ex = new ArgumentException("MethodBase must refer to a Property Setter method.");
throw ex;
}
NotifyPropertyChanged(methodName.Substring(4));
}
}
A: CommandManager.InvalidateRequerySuggested() tries to validate all commands, which is totally ineffective (and in your case slow) - on every change, you are asking every command to recheck its CanExecute()!
You'd need the command to know on which objects and properties is its CanExecute dependent, and suggest requery only when they change. That way, if you change a property of an object, only commands that depend on it will change their state.
This is how I solved the problem, but at first, a teaser:
// in ViewModel's constructor - add a code to public ICommand:
this.DoStuffWithParameterCommand = new DelegateCommand<object>(
parameter =>
{
//do work with parameter (remember to check against null)
},
parameter =>
{
//can this command execute? return true or false
}
)
.ListenOn(whichObject, n => n.ObjectProperty /*type safe!*/, this.Dispatcher /*we need to pass UI dispatcher here*/)
.ListenOn(anotherObject, n => n.AnotherObjectProperty, this.Dispatcher); // chain calling!
The command is listening on NotifyPropertyChanged events from object that affect whether it can execute, and invokes the check only when a requery is needed.
Now, a lot of code (part of our in-house framework) to do this:
I use DelegateCommand from Prism, that looks like this:
/// <summary>
/// This class allows delegating the commanding logic to methods passed as parameters,
/// and enables a View to bind commands to objects that are not part of the element tree.
/// </summary>
public class DelegateCommand : ICommand
{
#region Constructors
/// <summary>
/// Constructor
/// </summary>
public DelegateCommand(Action executeMethod)
: this(executeMethod, null, false)
{
}
/// <summary>
/// Constructor
/// </summary>
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
: this(executeMethod, canExecuteMethod, false)
{
}
/// <summary>
/// Constructor
/// </summary>
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod, bool isAutomaticRequeryDisabled)
{
if (executeMethod == null)
{
throw new ArgumentNullException("executeMethod");
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
_isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
this.RaiseCanExecuteChanged();
}
#endregion
#region Public Methods
/// <summary>
/// Method to determine if the command can be executed
/// </summary>
public bool CanExecute()
{
if (_canExecuteMethod != null)
{
return _canExecuteMethod();
}
return true;
}
/// <summary>
/// Execution of the command
/// </summary>
public void Execute()
{
if (_executeMethod != null)
{
_executeMethod();
}
}
/// <summary>
/// Property to enable or disable CommandManager's automatic requery on this command
/// </summary>
public bool IsAutomaticRequeryDisabled
{
get
{
return _isAutomaticRequeryDisabled;
}
set
{
if (_isAutomaticRequeryDisabled != value)
{
if (value)
{
CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers);
}
else
{
CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers);
}
_isAutomaticRequeryDisabled = value;
}
}
}
/// <summary>
/// Raises the CanExecuteChaged event
/// </summary>
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}
/// <summary>
/// Protected virtual method to raise CanExecuteChanged event
/// </summary>
protected virtual void OnCanExecuteChanged()
{
CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers);
}
#endregion
#region ICommand Members
/// <summary>
/// ICommand.CanExecuteChanged implementation
/// </summary>
public event EventHandler CanExecuteChanged
{
add
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested += value;
}
CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2);
}
remove
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested -= value;
}
CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
}
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void ICommand.Execute(object parameter)
{
Execute();
}
#endregion
#region Data
private readonly Action _executeMethod = null;
private readonly Func<bool> _canExecuteMethod = null;
private bool _isAutomaticRequeryDisabled = false;
private List<WeakReference> _canExecuteChangedHandlers;
#endregion
}
/// <summary>
/// This class allows delegating the commanding logic to methods passed as parameters,
/// and enables a View to bind commands to objects that are not part of the element tree.
/// </summary>
/// <typeparam name="T">Type of the parameter passed to the delegates</typeparam>
public class DelegateCommand<T> : ICommand
{
#region Constructors
/// <summary>
/// Constructor
/// </summary>
public DelegateCommand(Action<T> executeMethod)
: this(executeMethod, null, false)
{
}
/// <summary>
/// Constructor
/// </summary>
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
: this(executeMethod, canExecuteMethod, false)
{
}
/// <summary>
/// Constructor
/// </summary>
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod, bool isAutomaticRequeryDisabled)
{
if (executeMethod == null)
{
throw new ArgumentNullException("executeMethod");
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
_isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
}
#endregion
#region Public Methods
/// <summary>
/// Method to determine if the command can be executed
/// </summary>
public bool CanExecute(T parameter)
{
if (_canExecuteMethod != null)
{
return _canExecuteMethod(parameter);
}
return true;
}
/// <summary>
/// Execution of the command
/// </summary>
public void Execute(T parameter)
{
if (_executeMethod != null)
{
_executeMethod(parameter);
}
}
/// <summary>
/// Raises the CanExecuteChaged event
/// </summary>
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}
/// <summary>
/// Protected virtual method to raise CanExecuteChanged event
/// </summary>
protected virtual void OnCanExecuteChanged()
{
CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers);
}
/// <summary>
/// Property to enable or disable CommandManager's automatic requery on this command
/// </summary>
public bool IsAutomaticRequeryDisabled
{
get
{
return _isAutomaticRequeryDisabled;
}
set
{
if (_isAutomaticRequeryDisabled != value)
{
if (value)
{
CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers);
}
else
{
CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers);
}
_isAutomaticRequeryDisabled = value;
}
}
}
#endregion
#region ICommand Members
/// <summary>
/// ICommand.CanExecuteChanged implementation
/// </summary>
public event EventHandler CanExecuteChanged
{
add
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested += value;
}
CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2);
}
remove
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested -= value;
}
CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
}
}
bool ICommand.CanExecute(object parameter)
{
// if T is of value type and the parameter is not
// set yet, then return false if CanExecute delegate
// exists, else return true
if (parameter == null &&
typeof(T).IsValueType)
{
return (_canExecuteMethod == null);
}
return CanExecute((T)parameter);
}
void ICommand.Execute(object parameter)
{
Execute((T)parameter);
}
#endregion
#region Data
private readonly Action<T> _executeMethod = null;
private readonly Func<T, bool> _canExecuteMethod = null;
private bool _isAutomaticRequeryDisabled = false;
private List<WeakReference> _canExecuteChangedHandlers;
#endregion
}
/// <summary>
/// This class contains methods for the CommandManager that help avoid memory leaks by
/// using weak references.
/// </summary>
internal class CommandManagerHelper
{
internal static void CallWeakReferenceHandlers(List<WeakReference> handlers)
{
if (handlers != null)
{
// Take a snapshot of the handlers before we call out to them since the handlers
// could cause the array to me modified while we are reading it.
EventHandler[] callees = new EventHandler[handlers.Count];
int count = 0;
for (int i = handlers.Count - 1; i >= 0; i--)
{
WeakReference reference = handlers[i];
EventHandler handler = reference.Target as EventHandler;
if (handler == null)
{
// Clean up old handlers that have been collected
handlers.RemoveAt(i);
}
else
{
callees[count] = handler;
count++;
}
}
// Call the handlers that we snapshotted
for (int i = 0; i < count; i++)
{
EventHandler handler = callees[i];
handler(null, EventArgs.Empty);
}
}
}
internal static void AddHandlersToRequerySuggested(List<WeakReference> handlers)
{
if (handlers != null)
{
foreach (WeakReference handlerRef in handlers)
{
EventHandler handler = handlerRef.Target as EventHandler;
if (handler != null)
{
CommandManager.RequerySuggested += handler;
}
}
}
}
internal static void RemoveHandlersFromRequerySuggested(List<WeakReference> handlers)
{
if (handlers != null)
{
foreach (WeakReference handlerRef in handlers)
{
EventHandler handler = handlerRef.Target as EventHandler;
if (handler != null)
{
CommandManager.RequerySuggested -= handler;
}
}
}
}
internal static void AddWeakReferenceHandler(ref List<WeakReference> handlers, EventHandler handler)
{
AddWeakReferenceHandler(ref handlers, handler, -1);
}
internal static void AddWeakReferenceHandler(ref List<WeakReference> handlers, EventHandler handler, int defaultListSize)
{
if (handlers == null)
{
handlers = (defaultListSize > 0 ? new List<WeakReference>(defaultListSize) : new List<WeakReference>());
}
handlers.Add(new WeakReference(handler));
}
internal static void RemoveWeakReferenceHandler(List<WeakReference> handlers, EventHandler handler)
{
if (handlers != null)
{
for (int i = handlers.Count - 1; i >= 0; i--)
{
WeakReference reference = handlers[i];
EventHandler existingHandler = reference.Target as EventHandler;
if ((existingHandler == null) || (existingHandler == handler))
{
// Clean up old handlers that have been collected
// in addition to the handler that is to be removed.
handlers.RemoveAt(i);
}
}
}
}
}
I have then written a ListenOn extension method, that 'binds' the command to a property, and invokes its RaiseCanExecuteChanged:
public static class DelegateCommandExtensions
{
/// <summary>
/// Makes DelegateCommnand listen on PropertyChanged events of some object,
/// so that DelegateCommnand can update its IsEnabled property.
/// </summary>
public static DelegateCommand ListenOn<ObservedType, PropertyType>
(this DelegateCommand delegateCommand,
ObservedType observedObject,
Expression<Func<ObservedType, PropertyType>> propertyExpression,
Dispatcher dispatcher)
where ObservedType : INotifyPropertyChanged
{
//string propertyName = observedObject.GetPropertyName(propertyExpression);
string propertyName = NotifyPropertyChangedBaseExtensions.GetPropertyName(propertyExpression);
observedObject.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == propertyName)
{
if (dispatcher != null)
{
ThreadTools.RunInDispatcher(dispatcher, delegateCommand.RaiseCanExecuteChanged);
}
else
{
delegateCommand.RaiseCanExecuteChanged();
}
}
};
return delegateCommand; //chain calling
}
/// <summary>
/// Makes DelegateCommnand listen on PropertyChanged events of some object,
/// so that DelegateCommnand can update its IsEnabled property.
/// </summary>
public static DelegateCommand<T> ListenOn<T, ObservedType, PropertyType>
(this DelegateCommand<T> delegateCommand,
ObservedType observedObject,
Expression<Func<ObservedType, PropertyType>> propertyExpression,
Dispatcher dispatcher)
where ObservedType : INotifyPropertyChanged
{
//string propertyName = observedObject.GetPropertyName(propertyExpression);
string propertyName = NotifyPropertyChangedBaseExtensions.GetPropertyName(propertyExpression);
observedObject.PropertyChanged += (object sender, PropertyChangedEventArgs e) =>
{
if (e.PropertyName == propertyName)
{
if (dispatcher != null)
{
ThreadTools.RunInDispatcher(dispatcher, delegateCommand.RaiseCanExecuteChanged);
}
else
{
delegateCommand.RaiseCanExecuteChanged();
}
}
};
return delegateCommand; //chain calling
}
}
You then need the following extension to NotifyPropertyChanged
/// <summary>
/// <see cref="http://dotnet.dzone.com/news/silverlightwpf-implementing"/>
/// </summary>
public static class NotifyPropertyChangedBaseExtensions
{
/// <summary>
/// Raises PropertyChanged event.
/// To use: call the extension method with this: this.OnPropertyChanged(n => n.Title);
/// </summary>
/// <typeparam name="T">Property owner</typeparam>
/// <typeparam name="TProperty">Type of property</typeparam>
/// <param name="observableBase"></param>
/// <param name="expression">Property expression like 'n => n.Property'</param>
public static void OnPropertyChanged<T, TProperty>(this T observableBase, Expression<Func<T, TProperty>> expression) where T : INotifyPropertyChangedWithRaise
{
observableBase.OnPropertyChanged(GetPropertyName<T, TProperty>(expression));
}
public static string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> expression) where T : INotifyPropertyChanged
{
if (expression == null)
throw new ArgumentNullException("expression");
var lambda = expression as LambdaExpression;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = lambda.Body as UnaryExpression;
memberExpression = unaryExpression.Operand as MemberExpression;
}
else
{
memberExpression = lambda.Body as MemberExpression;
}
if (memberExpression == null)
throw new ArgumentException("Please provide a lambda expression like 'n => n.PropertyName'");
MemberInfo memberInfo = memberExpression.Member;
if (String.IsNullOrEmpty(memberInfo.Name))
throw new ArgumentException("'expression' did not provide a property name.");
return memberInfo.Name;
}
}
where INotifyPropertyChangedWithRaise is this (it estabilishes standard interface for raising NotifyPropertyChanged events):
public interface INotifyPropertyChangedWithRaise : INotifyPropertyChanged
{
void OnPropertyChanged(string propertyName);
}
Last piece of puzzle is this:
public class ThreadTools
{
public static void RunInDispatcher(Dispatcher dispatcher, Action action)
{
RunInDispatcher(dispatcher, DispatcherPriority.Normal, action);
}
public static void RunInDispatcher(Dispatcher dispatcher, DispatcherPriority priority, Action action)
{
if (action == null) { return; }
if (dispatcher.CheckAccess())
{
// we are already on thread associated with the dispatcher -> just call action
try
{
action();
}
catch (Exception ex)
{
//Log error here!
}
}
else
{
// we are on different thread, invoke action on dispatcher's thread
dispatcher.BeginInvoke(
priority,
(Action)(
() =>
{
try
{
action();
}
catch (Exception ex)
{
//Log error here!
}
})
);
}
}
}
A: Tomas has a nice solution, but pls note there's a serious bug in that the CanExecute will not always fire when bound to a Button due to this :
// Call the handlers that we snapshotted
for (int i = 0; i < count; i++)
{
EventHandler handler = callees[i];
handler(null, EventArgs.Empty);
}
The 'null' parameter passed in causes issues with the CanExecuteChangedEventManager (used by the WPF Button class to listen to changes on any Command bound to it). Specifically, the CanExecuteChangedEventManager maintains a collection of weak events that need to be invoked to determine if the command Can-Execute() but this collection is keyed by the 'sender'.
The fix is simple and works for me - change the signature to
internal static void CallWeakReferenceHandlers(ICommand sender, List<WeakReference> handlers)
{
....
handler(sender, EventArgs.Empty);
}
Sorry I haven't described it too well - in a bit of a rush to catch up with my dev now after taking a few hours to figure this out !
A: I would suggest looking into ReactiveUI and specifically at the ICommand implementation it provides, ReactiveCommand. It uses a different approach than DelegateCommand/RelayCommand which are implemented with delegates for CanExecute that must be actively evaluated. ReactiveCommand's value for CanExecute is pushed using IObservables.
A:
is there a way I can make CommandManager.InvalidateRequerySuggested() do it's job faster?
Yes, there is way to make it work faster!
*
*Implement Command to keep / cache CanExecuteState in a boolean variable.
*Implement RaiseCanExecuteChanged method to recalculate CanExecuteState and if it really changed to raise CanExecuteChanged event.
*Implement CanExecute method to simply return CanExecuteState.
*When InvalidateRequerySuggested method is invoked Command subscribers will only read CanExecuteState variable by invoking CanExecute method and check if it changed or not. That's almost zero overhead. All Commands will be disabled / enabled almost the same time.
*All work will be done in RaiseCanExecuteChanged method that will be called only once for a Command and only for a limited set of Commands.
A: Try writing your own binding that calls your RaiseCanExecuteChanged() within converts? it is easier
A: Just to clarify:
*
*You want to fire an update of CanExecute when Command property changed
*Create your own binding class that detect changes in the Command property and then calls RaiseCanExecuteChanged()
*Use this binding in CommandParameter
Worked for me.
| |
doc_2346
|
from sqlalchemy.dialects.postgresql import ARRAY
class Post(db.Model):
__tablename__ = 'post'
id = db.Column(db.Integer, primary_key=True)
tags = db.Column(ARRAY(db.String))
This link recommends storing tags as text array with a GIN index.
How do I add GIN index to above table? Also does it make a difference whether I use String vs Text datatype?
A: I solved it by following:
from sqlalchemy.dialects.postgresql import ARRAY, array
class Post(db.Model):
__tablename__ = 'post'
id = db.Column(db.Integer, primary_key=True)
tags = db.Column(ARRAY(db.Text), nullable=False, default=db.cast(array([], type_=db.Text), ARRAY(db.Text)))
__table_args__ = (db.Index('ix_post_tags', tags, postgresql_using="gin"), )
And query simply by
db.session.query(Post).filter(Post.tags.contains([tag]))
Have to keep the array type to Text and not String otherwise some error happens
| |
doc_2347
|
RAILS_ENV=production bundle exec thin --ssl-disable-verify -C services/private_pub/private_pub_thin.yml start
But starting it as deamon returns a Bad File Descriptor:
user@app:~/app$ RAILS_ENV=production bundle exec thin -d --ssl-disable-verify -C services/private_pub/private_pub_thin.yml start
user@app:~/app$ /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/source/git/git_proxy.rb:149:in ``': Bad file descriptor (Errno::EBADF)
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/source/git/git_proxy.rb:149:in `block in git'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/shared_helpers.rb:72:in `call'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/shared_helpers.rb:72:in `with_clean_git_env'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/source/git/git_proxy.rb:149:in `git'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/source/git/git_proxy.rb:83:in `version'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/env.rb:78:in `git_version'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/env.rb:22:in `report'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:74:in `request_issue_report_for'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:40:in `log_error'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:100:in `rescue in with_friendly_errors'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:98:in `with_friendly_errors'
from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/exe/bundle:19:in `<top (required)>'
from /opt/rbenv/versions/2.2.1/bin/bundle:23:in `load'
from /opt/rbenv/versions/2.2.1/bin/bundle:23:in `<main>'
Any idea? This happened without any code change. There is also nothing already running.
| |
doc_2348
|
Here is the XAML for the 2 controls.
<extToolKit:IntegerUpDown Minimum="0" Margin="1,3,0,4" x:Name="iupApproachMin">
<extToolKit:IntegerUpDown.Value>
<PriorityBinding FallbackValue="50">
<Binding Path="VehicleEntryTaskStandards.MaxEntryTimeRequirement" Converter="{StaticResource timeSpanConvertor}">
</Binding>
</PriorityBinding>
</extToolKit:IntegerUpDown.Value>
</extToolKit:IntegerUpDown>
<Label>min</Label>
<extToolKit:IntegerUpDown Minimum="0" Maximum="59" Margin="1,3,0,4" FormatString="00" Value="10"></extToolKit:IntegerUpDown>
<Label>sec</Label>
Here is the converters code
[ValueConversion(typeof(TimeSpan),typeof(int))]
public class TimespanConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int minutes = ((TimeSpan)value).Minutes;
return minutes;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
TimeSpan resultTimeSpan = new TimeSpan();
int minutes;
if (int.TryParse(value.ToString(), out minutes))
{
resultTimeSpan = new TimeSpan(0, minutes, 0);
return resultTimeSpan;
}
return DependencyProperty.UnsetValue;
}
}
Can I have it accept an array or list. If so how can this be done in xaml?
Please help!
A: Instead of using a ValueConverter, use a couple of properties in a ViewModel.
In the setter of each of these properties have the TimeSpan updated appropriately.
private TimeSpan _time;
public TimeSpan Time
{
get { return _time; }
set
{
_time = value;
RaisePropertyChanged("Time");
}
}
private int _minutes
public int Minutes
{
get { return _minutes; }
set
{
_minutes = value;
CalculateTimeSpan();
RaisePropertyChanged("Minutes");
}
}
private int _seconds
public int Seconds
{
get { return _seconds; }
set
{
_seconds= value;
CalculateTimeSpan();
RaisePropertyChanged("Seconds");
}
}
| |
doc_2349
|
<!DOCTYPE html>
<html>
<head>
<title>Task List</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/
css/materialize.min.css">
</head>
<body>
<p id="saved"></p>
<nav>
<div class="nav-wrapper">
<a class="brand-logo center">Task List</a>
</div>
</nav>
<ul id="taskList"></ul>
<button id='save'>Save File</button>
<button id='open'>Open File</button>
<script>
const electron = require('electron');
const {
ipcRenderer
} = electron;
const ul = document.querySelector('ul');
const fs = require('fs');
const {
dialog
} = require('electron').remote;
ipcRenderer.on('item:add', function(e, item) {
ul.className = 'tasks';
const li = document.createElement('li');
li.className = 'task-item';
const itemText = document.createTextNode(item);
li.appendChild(itemText);
ul.appendChild(li);
});
ipcRenderer.on('item:clear', function() {
ul.className = '';
ul.innerHTML = '';
});
ul.addEventListener('dblclick', removeItem);
function removeItem(e) {
event.target.remove();
if (ul.children.length == 0) {
ul.className = '';
}
}
function saveFile() {
dialog.showSaveDialog((filename) => {
if (filename === undefined) {
alert('No files selected');
return;
}
var tasks = document.getElementsByTagName('li').value
fs.writeFile(filename[0], tasks, (err) => {
if (err) {
alert("Cannot update file", err.message);
return;
}
document.getElementById('saved').textContent = 'Save Successful';
alert('items saved', tasks);
});
})
};
or my code is in my gitHub account in the index.html file
https://github.com/UgotGoosed/TaskList
| |
doc_2350
|
Is it possible to create a machine image from an Ubuntu 1804 VMDK?
The instructions I have been following here:
https://cloud.google.com/compute/docs/import/importing-virtual-disks
list Ubuntu 1804 as one of the supported operating systems. However, when I go to the "Create an image" page, only 1404 and 1604 are listed as options.
I have also tried taking the equivalent command line and modifying the --os=ubuntu-1604 to --os=ubuntu-1804, but this resulted in:
ERROR: (gcloud.compute.images.import) argument --os: Invalid choice: 'ubuntu-1804'. Did you mean 'ubuntu-1604'?
So, is it just that the original link is incorrect in listing 1804 as a supported OS? or is there some code that needs to be updated to add it to the list of options? Or ...
I did run the precheck tool in the OS and that did give me:
########################################
# SHA2 Driver Signing Check -- SKIPPED #
########################################
* INFO: Only applicable on Windows 2008 systems.
##############################
# OS Version Check -- FAILED #
##############################
* INFO: OSInfo: &{LongName:Ubuntu 18.04.2 LTS ShortName:ubuntu Version:18.04 Kernel:5.0.0-37-generic Architecture:x86_64}
* FATAL: version: "18.04" not supported
###############################
# Powershell Check -- SKIPPED #
###############################
* INFO: Not applicable on non-Windows systems.
#########################
# Disks Check -- PASSED #
#########################
* INFO: `lsblk -i` results:
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT ...
So it would seem that 1804 is not supported. If this is the case is there a timeline for it being supported ?
Many thanks for any help.
A: It seems there is something wrong with google documentation, looking into the link you shared, in compatibility tool section, there is a compatibility issue github link where they mention the last supported Ubuntu Image is 16.04, could be a good idea to create a Public issue with Google about this.
There are two things you can try to create your VM Instance with Ubuntu 18.04.X:
*
*Use Velostrata to migrate your entire VMware machine to GCP.
*Create a VM Instance from scratch with Google Drawfork Ubuntu 18.04 LTS image.
Hope this information helps!
| |
doc_2351
|
Here my config:
haproxy config
frontend MY_FRONT_END
log 127.0.0.1 /var/log/haproxy/dev/log info
bind *:12080
default_backend HTTP_BACKEND
rsyslog config
$ModLoad imuxsock
$InputUnixListenSocketCreatePath on
$InputUnixListenSocketHostName localhost
$AddUnixListenSocket /var/log/haproxy/dev/log
*.info /var/log/haproxy/access.log
However, what i see in the log is not just haproxy log, the log contain all the info that not relate to haproxy (the first three log lines)
Dec 28 20:28:12 localhost sudo: testaccount : TTY=unknown ; PWD=/ ; USER=root ; COMMAND=/bin/sh -c ip addr show
Dec 28 20:28:12 localhost sudo: testaccount : TTY=unknown ; PWD=/ ; USER=root ; COMMAND=/bin/sh -c ip route
Dec 28 20:28:13 localhost sudo: testaccount : TTY=pts/1 ; PWD=/var/log/haproxy ; USER=root ; COMMAND=/sbin/service haproxy restart
Dec 28 20:28:13 localhost polkitd[59350]: Registered Authentication Agent for unix-process:32995:43061437 (system bus name :1.28346 [/usr/bin/pkttyagent --notify-fd 5 --fallback], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_CA.UTF-8)
Dec 28 20:28:13 localhost systemd: Stopping HAProxy Load Balancer...
Dec 28 20:28:13 localhost haproxy: [WARNING] 362/202813 (30706) : Exiting Master process...
Dec 28 20:28:13 localhost haproxy: [NOTICE] 362/202813 (30706) : haproxy version is 2.2.6
Dec 28 20:28:13 localhost haproxy: [NOTICE] 362/202813 (30706) : path to executable is /usr/local/sbin/haproxy
Dec 28 20:28:13 localhost haproxy: [ALERT] 362/202813 (30706) : Current worker #1 (30708) exited with code 143 (Terminated)
Dec 28 20:28:13 localhost haproxy: [WARNING] 362/202813 (30706) : All workers exited. Exiting... (0)
Dec 28 20:28:13 localhost systemd: Starting HAProxy Load Balancer...
Dec 28 20:28:13 localhost haproxy[33016]: Proxy MY_FRONT_END started.
Dec 28 20:28:13 localhost haproxy[33016]: Proxy HTTP_BACKEND started.
Dec 28 20:28:13 localhost haproxy: [NOTICE] 362/202813 (33016) : New worker #1 (33018) forked
Dec 28 20:28:13 localhost systemd: Started HAProxy Load Balancer.
Dec 28 20:28:13 localhost polkitd[59350]: Unregistered Authentication Agent for unix-process:32995:43061437 (system bus name :1.28346, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_CA.UTF-8) (disconnected from bus)
Dec 28 20:28:13 localhost sudo: testaccount : TTY=pts/1 ; PWD=/var/log/haproxy ; USER=root ; COMMAND=/sbin/service rsyslog restart
How do i config to achieve this (only send haproxy info log to rsyslog through unix sock) ?
A: The correct answer is probably to use a ruleset to embrace just the imuxsock part, but I don't know how to do that in legacy syntax.
A simpler solution that is less optimal is to check for the programname in the log item. To also match for severity levels 0 to 6 (emerg to info) gives the result:
if $programname=="haproxy" and $syslogseverity<=6 then /var/log/haproxy/access.log
I'm not sure, but you could alternatively try just moving your configuration earlier in the file, before the standard logging code, but then your haproxy logs would appear in the standard logs too unless you use something like
*.info /var/log/haproxy/access.log
*.* stop
where stop stops further processing of that input.
| |
doc_2352
|
My code is as follows:
import bs4
import requests
import re
root_url = 'https://www.youtube.com/'
index_url = root_url + 'user/caseyneistat/videos'
def getNeistatNewVideo():
response = requests.get(index_url)
soup = bs4.BeautifulSoup(response.text)
return [a.attrs.get('href') for a in soup.select('div.yt-lockup-thumbnail a[href^=/watch]')]
def mainLoop():
while True:
results = str(getNeistatNewVideo())
past_results = str(open("output.txt"))
if results == past_results:
print("No new videos at this time")
return True
else:
print("There is a new video!")
print('...')
print('Writing to new text file')
print('...')
f = open("output.txt", "w")
f.write(results)
print('...')
print('Done writing to new text file')
print('...')
return True
mainLoop()
A: Calling open(output.txt) returns a file object, not the the text within the file. Calling str on the file object just gives a description of the object, not the text. To get that you need to something like
output = open('output.txt')
past_results = output.read()
Also, it looks like you're calling str on the output of getNeistatNewVideo which is a list, which almost certainly not what you want to do. I guess the format of output.txt is a bunch of links on separate lines. If that's the case, then you would want
results = "\n".join(getNeistatNewVideo())
which would give a single string with each link on it's own line. You really should print the output of your str calls to see what they look like. So, the reason it always says there is something new is because
results == past_results
is always false because of the reasons outlined
| |
doc_2353
|
public enum TourismItemType : int
{
Destination = 1,
PointOfInterest = 2,
Content = 3
}
And I also have a int variable, and I want to check that variable to know it is equal to TourismItemType.Destination, like this:
int tourismType;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
switch (tourismType)
{
case TourismItemType.Destination:
ShowDestinationInfo();
break;
case TourismItemType.PointOfInterest:
ShowPointOfInterestInfo();
break;
}
}
But it throws an error.
How can I do that?
Thanks.
A: Cast tourismType to your enum type as there is no implicit conversion from ints.
switch ((TourismItemType)tourismType)
//...
A: If you're running .NET 4 then you can use the Enum.TryParse method:
TourismItemType tourismType;
if (Enum.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
switch (tourismType)
{
case TourismItemType.Destination:
ShowDestinationInfo();
break;
case TourismItemType.PointOfInterest:
ShowPointOfInterestInfo();
break;
}
}
A: You can parse tourismType to your enum type using Enum.TryParse or you can treat enum values as int like: case (int)TourismType.Destination.
A: Try
int tourismType;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
switch (tourismType)
{
case (int)TourismItemType.Destination:
ShowDestinationInfo();
break;
case (int)TourismItemType.PointOfInterest:
ShowPointOfInterestInfo();
break;
}
}
or
int tourismType;
TourismItemType tourismTypeEnum;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
tourismTypeEnum = (TourismItemType)tourismType;
switch (tourismTypeEnum)
{
case TourismItemType.Destination:
ShowDestinationInfo();
break;
case TourismItemType.PointOfInterest:
ShowPointOfInterestInfo();
break;
}
}
A: You could also do:
int tourismType;
if ( int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType )
{
if ( Enum.IsDefined(typeof(TourismItemType), tourismType) )
{
switch ((TourismItemType)tourismType)
{
...
}
}
else
{
// tourismType not a valid TourismItemType
}
}
else
{
// NavigationContext.QueryString.Values.First() not a valid int
}
Of course you could also handle invalid tourismType in the switch's default: case.
| |
doc_2354
|
When i am trying to index, getting 'mapper_parsing_exception'error. Following is my code,
#Configuration
DIR = 'D:/QA_Testing/testing/data'
ES_HOST = {"host" : "localhost", "port" : 9200}
INDEX_NAME = 'testing'
TYPE_NAME = 'documents'
URL = "D:/xyz.pdf"
es = Elasticsearch(hosts = [ES_HOST])
mapping = {
"mappings": {
"documents": {
"properties": {
"cv": { "type": "attachment" }
}}}}
file64 = open(URL, "rb").read().encode("base64")
data_dict = {'cv': file64}
data_dict = json.dumps(data_dict)
res = es.indices.create(index = INDEX_NAME, body = mapping)
es.index(index = INDEX_NAME, body = data_dict ,doc_type = "attachment", id=1)
ERROR:
Traceback (most recent call last):
File "C:/Users/537095/Desktop/QA/IndexingWorkspace/MainWorkspace/index3.py", line 51, in <module>
es.index(index = INDEX_NAME, body = data_dict ,doc_type = "attachment", id=1)
File "C:\Python27\lib\site-packages\elasticsearch\client\utils.py", line 69, in _wrapped
return func(*args, params=params, **kwargs)
File "C:\Python27\lib\site-packages\elasticsearch\client\__init__.py", line 261, in index
_make_path(index, doc_type, id), params=params, body=body)
File "C:\Python27\lib\site-packages\elasticsearch\transport.py", line 329, in perform_request
status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
File "C:\Python27\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 106, in perform_request
self._raise_error(response.status, raw_data)
File "C:\Python27\lib\site-packages\elasticsearch\connection\base.py", line 105, in _raise_error
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
RequestError: TransportError(400, u'mapper_parsing_exception', u'failed to parse')
Am i doing anything wrong?
A: You need to change your doc_type, it should be documents and not attachment
es.index(index = INDEX_NAME, body = data_dict ,doc_type = "documents", id=1)
| |
doc_2355
|
$login_xml ='<xml>'.
'<action>log_in</action>'.
'<parameters>'.
'<username>'.$var.'</username>'.
'<pass>abdef01</pass>'.
'</parameters>'.
'</xml>';
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $login_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');
$output = curl_exec($ch);
Maybe some options in the CURLOPT_HTTPHEEADER? Thanks for your time!
edit:
var_dump($output) : string '<xml><action>log_in</action><parameters><username>Ionel P</username><pass>abdef01</pass></parameters></xml>107' (length=110)
edit 2:
<?php
$xml = readfile('php://input');//file_get_contents('php://input');
var_dump($xml);
print_R($xml);
?>
var_dump($xml) = pre class='xdebug-var-dump' dir='ltr'><small>int</small> <font color='#4e9a06'>107</font>
107' (length=207)
| |
doc_2356
|
Foregound = Call and navigate.
Background and Kill App = onReceive not called. I can not get the data and not redirect.
https://gist.github.com/Omurtekinn/fcbd3ba2e83925c459b22d5614c3ea00
MyFirebaseMessaging class.
baslik=title / özel veriler= data
A: If you check the documentation you'll see that Android handle notification messages differently depending on the payload and if your app is on the foreground or background:
If your app is in the foreground you'll always receive the notification in the onMessageReceived method. Not matter the payload of the notification.
If it is on the background you have two scenarios:
Notification payload:
Message is delivered to system tray and when you click it it'll be delivered to the Launch Activity through intent extras.
Data payload:
Message will be delivered to onMessageReceived.
Looking into your scenario it seems you have a notification payload. You have two options:
1) Change the payload type to data. If you're using the FCM console you can only do option 2 because it will only send Notification messages.
2) Implement the receiving of the message in the launcher activity onCreate method.
The notification basically looks like this:
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"icon" : "myicon"
}
}
If you're adding key/value pairs it will look like this:
{
"to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"icon" : "myicon"
},
"data" : {
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
}
In your launcher activity you get the notification in the intent extras like any other activity, in onCreate():
Bundle extras = getIntent().getExtras();
if(extras!=null){
String notification = extras.getString("notification");
String dats = extras.getString("data");
}
Note that if you're using android O you need to configure the channels as well.
| |
doc_2357
|
<br> tags are valid HTML5 elements, but Jsoup keeps converting them to <br />.
I have an example setup at the link below:
http://try.jsoup.org/~zCiL6-fonHhQaGaApm2tORtfoo0
I need to figure out how to disable this behavior, but I haven't been able to figure out how to do it after pouring through the docs and examples. Perhaps it isn't an option yet?
A: After reading through the code, it appears that the Jsoup authors have fixed the issue in this commit.
| |
doc_2358
|
pds.shape
#(1159,)
pds has an index which is not sequential and at each index there is a (18,100) array
pds[pds.index[1]].shape
#(18, 100)
How can I convert this to a pandas dataframe and/or a numpy array with dimensions (1159,18,100)?
pdf = pd.DataFrame(pds)
gives me a pandas with shape
pdf.shape
(1159, 1)
A: You say you want to keep indexing, that means numpy is out (someone already posted a numpy solution as well). My recommendation would be to create a series of DataFrames, as panels are deprecated.
new series = pd.Series()
for index, element in pds:
new_series.append(pd.DataFrame(element))
Should do the trick.
A: Does this work: numpy.stack([pds[pds.index[i]] for i in range(1159)], axis=0)?
stack should put all your arrays together along the axis given.
| |
doc_2359
|
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.jsonschema.JsonSchema;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Loop {
private String name;
private Loop otherLoop;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Loop getOtherLoop() { return otherLoop; }
public void setOtherLoop(Loop otherLoop) { this.otherLoop = otherLoop; }
public static void main(String[] args) throws Exception {
Loop parent = new Loop();
parent.setName("parent");
Loop child = new Loop();
child.setName("child");
child.setOtherLoop(parent);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(child));
JsonSchema jsonSchema = mapper.generateJsonSchema(Loop.class);
System.out.println(mapper.writeValueAsString(jsonSchema));
}
}
and when I run it using Jackson 2 it goes into an infinite loop
{"name":"child","otherLoop":{"name":"parent"}}
Exception in thread "main" java.lang.StackOverflowError
at com.fasterxml.jackson.databind.cfg.MapperConfig.isEnabled(MapperConfig.java:106)
at com.fasterxml.jackson.databind.SerializationConfig.getAnnotationIntrospector(SerializationConfig.java:382)
at com.fasterxml.jackson.databind.SerializerProvider.getAnnotationIntrospector(SerializerProvider.java:307)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.createContextual(BeanSerializerBase.java:318)
at com.fasterxml.jackson.databind.SerializerProvider._handleContextual(SerializerProvider.java:971)
at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:447)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.getSchema(BeanSerializerBase.java:619)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.getSchema(BeanSerializerBase.java:621)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.getSchema(BeanSerializerBase.java:621)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.getSchema(BeanSerializerBase.java:621)
Any ideas, workarounds?!
A: @XmlAccessorType(XmlAccessType.FIELD)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Loop {
@XMLAttribute(name = "Name")
private String name;
@XMLAttribute(name = "Loops")
private List<Loop> listLoop;
//getters and setters
}
| |
doc_2360
|
I'm thinking of a schema to support updating entries and version tracking. This is for a slowly changing dimensions scenerio, with a twist. To support the behavior I want, the basic schema is replicated three times:
*
*public tables,
*private tables, and
*change tracking tables
This will work beautifully for my purpose, but the down side of the replication approach seems to be that it would be cumbersome and error prone to maintain (we generally have periodic minor schema changes).
To help with maintainability, I was thinking of using table inheritance: define the primary fields in a set of base tables, and inherit the three new sets of tables from these (augmented with bookkeeping fields). When schema changes are needed, just make them to the base table. Queries would only be made on derived tables.
So the question is: is this a valid use of table inheritance? Is there a better way to support maintainability of replicated tables? Relevant links would be appreciated.
I've never used table inheritance before, would like know if I'm strolling into a mine field. Thanks.
Edit: found one mention of using inheritance for change tracking tables in the comments of the pg8.0 docs.
A: Why do you want to replace your actual "two bases" system ? You alternative looks more complex, difficult to maintain, and calls for acrobatic coding techniques.
If it ain't broke, don't fix it
What's the added power/flexibility you expect ?
| |
doc_2361
|
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog.aspx
However, I am not being able to explain/convience myself/team:
*
*When to use custom control vs. out of box site core controller?
*When does the Out of Box Controller gets invoked?
*Benifit of custom control vs. out of box controllers?
*If we go with out of box, should we include all business logic on Views. Is this testable?
I also looked at below and still not certain:
https://bitbucket.org/demoniusrex/launch-sitecore-mvc-demo
Any help will be appreciated.
A: My personal view is that the business logic should go in command and query classes that are invoked from the controller class. From these calls you can assemble a strongly typed view model which gets passed to a dumb razor view for rendering.
Ensure that any services that the controller relies on are passed into it via constructor injection using contracts (interfaces) instead of concrete classes and you should end up with solution that is unit testable.
A: Whilst I broadly agree with Kevin Obee's statement I think it's worth reminding ourselves that controllers are being used in two distinct roles in Sitecore:
*
*Page level controller (invoked by item route)
*Component level controller (invoked by redering mechanism)
When to use: Custom controller / default Sitecore controller
Page level controller
Any route that matches an item path will by default use the Index action on the Sitecore.Mvc.Controllers.SitecoreController. This action will return a ViewResult based on the layout configuration of the item.
If you have a need for changing this behaviour (e.g. something that impacts the entire page) you can specify a custom controller and action on the item (or the Standard Values for the item). For the custom controller you can either roll your own or subclass the default controller.
Component level controller
For ViewRendering Sitecore renders the Razor views without the need for a specific controller (well I guess it's the page level controller that is in play - but just imagine that Sitecore provides a default controller that gets the model using the mvc.getModel pipeline and feeds it to the Razor view).
For ControllerRendering you provide a custom controller that can execute logic (see Kevin's answer) and provide a model for the view. There is no benefit from subclassing Sitecore.Mvc.Controllers.SitecoreController.
When are controllers invoked
Page level controller
The action on the page level controller is invoked by the routing engine.
Component level controller
The action on a ControllerRendering is invoked as the page view renders.
Benefit of using: Custom controller / default Sitecore controller
The benefit of a custom controller over the default Sitecore controller is that you are in control of the logic. The benefit of using the default Sitecore controller is that Sitecore provides the logic for you.
Should we include all business logic on Views
No. (See Kevin's answer)
| |
doc_2362
|
the error label visibility default value is false.
am having more than a 10 entry and their error label.
and after the app takes input and validates it with error labels it hides everything from the middle of the screen to the very end of the layout.
this my xaml code
<ContentPage.Content>
<ScrollView>
<StackLayout
Margin="20">
<!--Unit Type Picker-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label
Grid.Column="0"
Text="{xct:Translate UnitType}"
Style="{StaticResource PickerLabelStyle}"/>
<Picker
Grid.Column="1"
ItemsSource="{Binding UnitTypeList,Mode=OneWay}"
SelectedIndex="{Binding UnitTypeIndex,Mode=OneWayToSource}"
Style="{StaticResource PickerStyle}"/>
</Grid>
<Label
Text="{Binding UnitTypeError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding UnitTypeErrorVis,Mode=OneWay}"
/>
<!--Unit IsFurnished Picker-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label
Grid.Column="0"
Text="{xct:Translate Furnished}"
Style="{StaticResource PickerLabelStyle}"/>
<Picker
Grid.Column="1"
ItemsSource="{Binding IsFurnishedList,Mode=OneWay}"
SelectedIndex="{Binding FurnishedIndex,Mode=OneWayToSource}"
Style="{StaticResource PickerStyle}"/>
</Grid>
<Label
Text="{Binding FurnishedError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding FurnishedErrorVis,Mode=OneWay}"
/>
<!--Unit National ID-->
<Entry
Placeholder="{xct:Translate UnitNationalID}"
Text="{Binding UnitNationalID}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding UnitNationalIDError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding UnitNationalIDErrorVis,Mode=OneWay}"
/>
<!--Floor Num-->
<Entry
Placeholder="{xct:Translate FloorNum}"
Text="{Binding FloorNum,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding FloorNumError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding FloorNumErrorVis,Mode=OneWay}"
/>
<!--Unit Space-->
<Entry
Placeholder="{xct:Translate UnitSpace}"
Text="{Binding UnitSpace,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding UnitSpaceError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding UnitSpaceErrorVis,Mode=OneWay}"
/>
<!--Living Room Space-->
<Entry
Placeholder="{Binding LivingRoomSpacePH,Mode=OneWay}"
Text="{Binding LivingRoomSpace,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<!--Rooms Num-->
<Entry
Placeholder="{Binding RoomsNumPH,Mode=OneWay}"
Text="{Binding RoomsNum,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<!--Lights Num-->
<Entry
Placeholder="{Binding LightsNumPH,Mode=OneWay}"
Text="{Binding LightsNum,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<!--Baths Num-->
<Entry
Placeholder="{xct:Translate BathsNum}"
Text="{Binding BathsNum,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding BathsNumError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding BathsNumErrorVis,Mode=OneWay}"
/>
<!--Maid Rooms Num-->
<Entry
Placeholder="{xct:Translate MaidRoomsNum}"
Text="{Binding MaidRoomsNum,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding MaidRoomsNumError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding MaidRoomsNumErrorVis,Mode=OneWay}"
/>
<!--Air Conditioner Type Picker-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label
Grid.Column="0"
Text="{xct:Translate AirCondType}"
Style="{StaticResource PickerLabelStyle}"/>
<Picker
Grid.Column="1"
ItemsSource="{Binding AirCondTypeList,Mode=OneWay}"
SelectedIndex="{Binding AirCondTypeIndex,Mode=OneWayToSource}"
Style="{StaticResource PickerStyle}"/>
</Grid>
<Label
Text="{Binding AirCondTypeError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding AirCondTypeErrorVis,Mode=OneWay}"
/>
<!--Air Cond Power-->
<Entry
Placeholder="{xct:Translate AirCondPower}"
Text="{Binding AirCondPower,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding AirCondPowerError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding AirCondPowerErrorVis,Mode=OneWay}"
/>
<!--Rent-->
<Entry
Placeholder="{xct:Translate Rent}"
Text="{Binding Rent,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding RentError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding RentErrorVis,Mode=OneWay}"
/>
<!--Discount-->
<Entry
Placeholder="{Binding DiscountPH,Mode=OneWay}"
Text="{Binding Discount,Mode=OneWayToSource}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<!--Unit Availability Picker-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label
Grid.Column="0"
Text="{xct:Translate UnitAvailability}"
Style="{StaticResource PickerLabelStyle}"/>
<Picker
Grid.Column="1"
ItemsSource="{Binding UnitAvailabilityList,Mode=OneWay}"
SelectedIndex="{Binding UnitAvailabilityIndex,Mode=OneWayToSource}"
Style="{StaticResource PickerStyle}"/>
</Grid>
<Label
Text="{Binding UnitAvailabilityError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding UnitAvailabilityErrorVis,Mode=OneWay}"
/>
<!--Electricity Meter-->
<Entry
Placeholder="{xct:Translate ElectricityMeterInfo}"
Text="{Binding ElecMeter}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding ElecMeterError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding ElecMeterErrorVis,Mode=OneWay}"
/>
<!--Water Meter-->
<Entry
Placeholder="{xct:Translate WaterMeterInfo}"
Text="{Binding WaterMeter}"
Style="{StaticResource EntryStyle}"
Keyboard="Numeric"/>
<Label
Text="{Binding WaterMeterError,Mode=OneWay}"
Style="{StaticResource ErrorLabel}"
IsVisible="{Binding WaterMeterErrorVis,Mode=OneWay}"
/>
<!--Submit Button-->
<Button
Text="{xct:Translate Submit}"
Command="{Binding SubmitCommand}"
Style="{StaticResource ButtonStyle}"/>
</StackLayout>
</ScrollView>
</ContentPage.Content>
and my static resourse for styling each view
<!--Entry Style-->
<Style x:Key="EntryStyle" TargetType="Entry">
<Setter Property="VerticalOptions" Value="CenterAndExpand"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="PlaceholderColor" Value="Black"/>
<Setter Property="HorizontalTextAlignment" Value="Start"/>
</Style>
<!--Button Style-->
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="VerticalOptions" Value="CenterAndExpand"/>
<Setter Property="HorizontalOptions" Value="CenterAndExpand"/>
<Setter Property="Margin" Value="20"/>
<Setter Property="CornerRadius" Value="30"/>
<Setter Property="BackgroundColor" Value="Black"/>
<Setter Property="TextColor" Value="White"/>
<Setter Property="WidthRequest" Value="140"/>
</Style>
<!--Error Label-->
<Style x:Key="ErrorLabel" TargetType="Label">
<Setter Property="TextColor" Value="Red"/>
</Style>
<!--Picker Style-->
<Style x:Key="PickerStyle" TargetType="Picker">
<Setter Property="WidthRequest" Value="300"/>
<Setter Property="VerticalOptions" Value="CenterAndExpand"/>
<Setter Property="HorizontalOptions" Value="CenterAndExpand"/>
</Style>
<!--Picker Label Style-->
<Style x:Key="PickerLabelStyle" TargetType="Label">
<Setter Property="VerticalOptions" Value="CenterAndExpand"/>
<Setter Property="HorizontalOptions" Value="CenterAndExpand"/>
<Setter Property="TextColor" Value="Black"/>
<Setter Property="FontSize" Value="Medium"/>
</Style>
Note: the screen shot taken from android device xiaomi redmi note 7
A: It might be this open bug.
A work-around from this comment:
Replace this:
<ScrollView>
...
</ScrollView>
With this:
<Grid>
<ScrollView>
...
</ScrollView>
<Grid>
| |
doc_2363
|
I am sorry but I don't speak English very well.. :)
The problem is simple. I have a file.txt with 10000 points.
And I have to count the number of possible square.
For example : [-1,-1][2,1][4,-2][1,-4] is a square
I made an algorithm in java but there is a big problem...
To execute it, I need 15hours !!!
I will give you my code, and if you think I can optimize it please tell me how ! :)
Main.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import elements.*;
public class Main
{
public static void main(String[] parameters)
{
try
{
//String nameFile = parameters[0];
FileInputStream fileInputStream = new FileInputStream(new File("exercice4.txt"));
Processing processing = new Processing();
processing.read(fileInputStream);
processing.maxLenght();
//processing.changeTest();
processing.generateSquare();
try
{
FileWriter fileWriter = new FileWriter(new File("Square.txt"));
processing.write(fileWriter);
fileWriter.close();
}
catch (IOException exception)
{
System.out.println("Erreur lors de l'écriture dans le fichier");
}
System.out.println(processing.countSquare());
System.out.println("Fin");
try
{
fileInputStream.close();
}
catch (IOException exception)
{
System.out.println("Une erreur s'est produite lors de la fermeture de l'InputStream");
}
}
catch(FileNotFoundException exeption)
{
System.out.println("Le nom de fichier placé en paramètre est incorrect");
}
}
}
Processing.java
package elements;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.*;
import elements.*;
public class Processing
{
private ArrayList<Point> points;
private ArrayList<Square> squares;
private int maxY;
private int maxX;
private int minX;
public Processing()
{
this.points = new ArrayList<Point>();
this.squares = new ArrayList<Square>();
this.maxX = 0;
this.maxY = 0;
this.minX = 0;
}
public void read(FileInputStream f)
{
int readReturn;
int X = 0;
int Y = 0;
String string = "";
try
{
while ((readReturn = f.read()) != -1)
{
if(readReturn-48 == -38)
{
Y = Integer.parseInt(string);
Point point = new Point(X,Y);
if(!presentPoint(point))
{
points.add(point);
}
string = "";
}
else if(readReturn-48 == -16)
{
X = Integer.parseInt(string);
string = "";
}
else if(readReturn-48 == -3)
{
string += "-";
}
else
{
string += Integer.toString(readReturn-48);
}
}
}
catch(IOException exception)
{
System.out.println("Probleme lors de la lecture du fichier");
}
}
public void maxLenght()
{
Point reference = points.get(0);
int maxX = reference.getX();
int minX = reference.getX();
int maxY = reference.getY();
int minY = reference.getY();
for(Point point : points)
{
if(point.getX() < minX)
{
minX = point.getX();
}
else if(point.getX() > maxX)
{
maxX = point.getX();
}
if(point.getY() < minY)
{
minY = point.getY();
}
else if(point.getY() > maxY)
{
maxY = point.getY();
}
}
this.maxX = maxX;
this.maxY = maxY;
this.minX = minX;
}
public boolean samePoint(Point point1, Point point2)
{
boolean same = false;
if(point1.getX() == point2.getX() && point1.getY() == point2.getY())
{
same = true;
}
return same;
}
public boolean presentPoint(Point newPoint)
{
boolean present = false;
int counter = 0;
Point point;
while(present == false && counter < points.size())
{
point = this.points.get(counter);
if(samePoint(point, newPoint))
{
present = true;
}
counter++;
}
return present;
}
public boolean presentPoint(Point botomRight, Point topLeft, Point topRight)
{
boolean present = false;
boolean botomRightPresent = false;
boolean topLeftPresent = false;
boolean topRightPresent = false;
int counter = 0;
Point point;
while(present == false && counter < points.size())
{
point = this.points.get(counter);
if(samePoint(point, botomRight))
{
botomRightPresent = true;
}
if(samePoint(point, topLeft))
{
topLeftPresent = true;
}
if(samePoint(point, topRight))
{
topRightPresent = true;
}
if(botomRightPresent && topLeftPresent && topRightPresent)
{
present = true;
}
counter++;
}
return present;
}
public void generateSquare()
{
Point testBotomRight;
Point testTopLeft;
Point testTopRight;
int counter = 0;
for(Point point : this.points)
{
System.out.println(counter);
counter++;
for(int j = 0; j < this.maxY-point.getY(); j++)
{
for(int i = 1; i < this.maxX-point.getX(); i++)
{
if(verifiyBoundary(i, j, point))
{
testBotomRight = new Point(point.getX()+i, point.getY()+j);
testTopLeft = new Point(point.getX()-j, point.getY()+i);
testTopRight = new Point(point.getX()+i-j, point.getY()+i+j);
if(presentPoint(testBotomRight, testTopLeft, testTopRight))
{
Square square = new Square(point, testBotomRight, testTopLeft, testTopRight);
this.squares.add(square);
System.out.println(point.display());
System.out.println(testBotomRight.display());
System.out.println(testTopLeft.display());
System.out.println(testTopRight.display());
System.out.println("");
}
}
}
}
}
}
public boolean verifiyBoundary(int i, int j, Point point)
{
boolean verify = true;
if(point.getX() + i + j > this.maxY)
{
verify = false;
}
if(point.getX() - j < this.minX)
{
verify = false;
}
return verify;
}
public String countSquare()
{
String nbSquare = "";
nbSquare += Integer.toString(this.squares.size());
return nbSquare;
}
public void changeTest()
{
Point point = points.get(9);
point.setX(0);
point.setY(0);
point = points.get(100);
point.setX(0);
point.setY(2);
point = points.get(1000);
point.setX(2);
point.setY(2);
point = points.get(1886);
point.setX(2);
point.setY(0);
}
public void write(FileWriter fileWriter)
{
for(Square square : squares)
{
try
{
fileWriter.write(square.getVertexBottomLeft().display() + square.getVertexBottomRight().display() + square.getVertexTopRight().display() + square.getVertexTopLeft().display() + "\r\n");
}
catch (IOException e)
{
System.out.println("Erreur lors de l'écriture des carrés");
}
}
}
}
Point.java
package elements;
public class Point
{
private int X;
private int Y;
public Point(int X, int Y)
{
this.X = X;
this.Y = Y;
}
public int getX()
{
return this.X;
}
public int getY()
{
return this.Y;
}
public void setX(int X)
{
this.X = X;
}
public void setY(int Y)
{
this.Y = Y;
}
public String display()
{
return ("[" + Integer.toString(this.X) + "," + Integer.toString(this.Y) + "]");
}
}
Square.java
package elements;
public class Square
{
private Point vertexBottomLeft;
private Point vertexBottomRight;
private Point vertexTopLeft;
private Point vertexTopRight;
public Square()
{
this.vertexBottomLeft = null;
this.vertexBottomRight = null;
this.vertexTopLeft = null;
this.vertexTopRight = null;
}
public Square(Point vertexBottomLeft, Point vertexBottomRight, Point vertexTopLeft, Point vertexTopRight)
{
this.vertexBottomLeft = vertexBottomLeft;
this.vertexBottomRight = vertexBottomRight;
this.vertexTopLeft = vertexTopLeft;
this.vertexTopRight = vertexTopRight;
}
public Point getVertexBottomLeft()
{
return this.vertexBottomLeft;
}
public Point getVertexBottomRight()
{
return this.vertexBottomRight;
}
public Point getVertexTopLeft()
{
return this.vertexTopLeft;
}
public Point getVertexTopRight()
{
return this.vertexTopRight;
}
}
My programme stay 15h in the function generateSquare() in Processing.java
Thank you very much for your help !
Edit : I need to reduce the complexity = 1,000,000,000,000 how can I do that?
EDIT2 : Thanks to @BarrySW19 we reduce execution time : 5000ms now
But I need to reduce at 200-500ms, somebody have an idea?
I will give you the new code of Processing.java
package elements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
public class Processing
{
private Set<Point> points;
private List<Square> squares;
private int maxY;
private int maxX;
private int minX;
public Processing()
{
this.points = new HashSet<Point>();
this.squares = new ArrayList<Square>();
this.maxX = 0;
this.maxY = 0;
this.minX = 0;
}
/*
* Fonction de lecture du fichier input qui stocke les points dans une structure de données adaptée
* Ici la structure choisi de stockage de données est un hashSet.
* param : InputStream lié au fichier dans lequel lire les données
*
* Suivant les valeur des entiers retournés on détecte un retour chariot (sauvegarde du point)
* ou un espace (saisie terminée de l'abscisse)
*/
public void read(FileInputStream f)
{
int readReturn;
int X = 0;
int Y = 0;
String string = "";
try
{
while ((readReturn = f.read()) != -1)
{
if(readReturn-48 == -38)
{
Y = Integer.parseInt(string);
Point point = new Point(X,Y);
if(!presentPoint(point))
{
points.add(point);
}
string = "";
}
else if(readReturn-48 == -16)
{
X = Integer.parseInt(string);
string = "";
}
else if(readReturn-48 == -3)
{
string += "-";
}
else
{
string += Integer.toString(readReturn-48);
}
}
}
catch(IOException exception)
{
System.out.println("Probleme lors de la lecture du fichier");
}
}
/*
* Fonction qui sauvegarde les abscisses et ordonnés minimum et maximum des points présents
* Ceci servira à l'optimisation du programme
*/
public void maxLenght()
{
int maxX = -10000;
int minX = 10000;
int maxY = -10000;
int minY = 10000;
for(Point point : points)
{
if(point.getX() < minX)
{
minX = point.getX();
}
else if(point.getX() > maxX)
{
maxX = point.getX();
}
if(point.getY() < minY)
{
minY = point.getY();
}
else if(point.getY() > maxY)
{
maxY = point.getY();
}
}
this.maxX = maxX;
this.maxY = maxY;
this.minX = minX;
}
/*
* A l'aide de la réécriture de la fonction hashCode() et equals() cette fonction nous renvoie si un objet est présent dans le hashSet
*/
public boolean presentPoint(Point newPoint)
{
return this.points.contains(newPoint);
}
/*
* A l'aide de la réécriture de la fonction hashCode() et equals() cette fonction nous renvoie si un objet est présent dans le hashSet
*/
public boolean presentPoint(Point botomRight, Point topLeft, Point topRight)
{
return (this.points.contains(botomRight) && this.points.contains(topRight) && this.points.contains(topLeft));
}
public void generateSquare()
{
for(Point p: points)
{
// Trouve tous les points pouvant servir de coin topRight
Set<Point> pointsUpAndRight = points.stream().filter(p2 -> p2.getX() > p.getX() && p2.getY() >= p.getY()).collect(Collectors.toSet());
for(Point p2: pointsUpAndRight)
{
// calcul les vecteurs de trasformation
int[] transform = new int[] { p2.getX() - p.getX(), p2.getY() - p.getY() };
if(p.getY()+transform[0] <= this.maxY && p.getX()-transform[1] >= this.minX)
{
// génère les 2 points manquants
Point p3 = new Point(p2.getX() - transform[1], p2.getY() + transform[0]);
Point p4 = new Point(p3.getX() - transform[0], p3.getY() - transform[1]);
if(points.contains(p3) && points.contains(p4))
{
Square s = new Square(p, p3, p2, p4);
squares.add(s);
}
}
}
}
}
/*
* Fonction de basique qui répond au problème de comptage de carré
*/
public String countSquare()
{
String nbSquare = "";
nbSquare += Integer.toString(this.squares.size());
return nbSquare;
}
/*
* Cette fonctionalité suplémentaire permet de stocker dans un fichier .txt les carrés présents parmi la liste de points
*/
public void write(FileWriter fileWriter)
{
for(Square square : squares)
{
try
{
fileWriter.write(square.getVertexBottomLeft().display() + square.getVertexBottomRight().display() + square.getVertexTopRight().display() + square.getVertexTopLeft().display() + " est un carré valide " + "\r\n");
}
catch (IOException e)
{
System.out.println("Erreur lors de l'écriture des carrés");
}
}
}
}
A: To check a value is contained in a Set has time complexity of O(1) while checking a value that contains in an array list has time complexity of O(n).
so one way to speed things up is to use Set rather than ArrayList
To use set you need to Override hashCode and equals methods:
add the following to your Point class
class Point{
...
int hashCode=-1;
@Override
public int hashCode(){
if(hashCode==-1){
hashCode=Objects.hash(x,y);
}
return hashCode;
}
@Override
public boolean equals(Object o){
if(o instanceOf this.getClass()){
Point p=(Point) o;
return p.x==x && p.y==y;
}
return false;
}
}
in class Processing change:
private ArrayList<Point> points;
to:
private HashSet<Point> points;
then change your method presentPoint into something like:
public boolean presentPoint(Point p ){
return points.contains(p);
}
public boolean presentPoint(Point p1,Point p2,Point p3 ){
return points.contains(p1) && points.contains(p2) && points.contains(p3);
}
A: EDIT: Changed solution to find squares rotated in any direction.
Ok, this is my stab at a solution - it should have O(N^2) performance. Firstly, I've replaced the List of points with a Set which automatically de-duplicates the set of points and also makes checking whether a point exists much faster (you need to implement equals() and hashCode() on the Point class for this to work).
Next, when checking for squares the first thing I do is build a Set of all points which are up and right of the current point (i.e. they could form the edge 0
In pseudo-code:
for each Point
for each Point up and right of this
calculate the other two points of the square
if those points exists
add the square to the answers
end-if
end-loop
end-loop
My version of the Processing class (just the important method) which implements this is:
import static java.util.stream.Collectors.toSet;
public class Processing {
private Set<Point> points = new HashSet<>();
private List<Square> squares = new ArrayList<>();
public void generateSquare() {
for(Point p: points) {
// Find other points which could form a left-hand edge
Set<Point> pointsUpAndRight = points.stream()
.filter(p2 -> p2.getX() >= p.getX() && p2.getY() > p.getY())
.collect(toSet());
for(Point p2: pointsUpAndRight) {
int[] transform = new int[] { p2.getX() - p.getX(), p2.getY() - p.getY() };
Point p3 = new Point(p2.getX() + transform[1], p2.getY() - transform[0]);
Point p4 = new Point(p3.getX() - transform[0], p3.getY() - transform[1]);
if(points.contains(p3) && points.contains(p4)) {
Square s = new Square(p, p3, p2, p4);
squares.add(s);
}
}
}
}
}
A: Damien, the problem is that you spend a lot of time iterating through the List.
Try to introduce data structure with quicker search, for example, Map with two keys.
If you have structure like
SpacialMap<Integer, Integer, Point>
you can perform fast Point existence check by its coordinates, so the computational complexity will drop to O(n^2) at least.
Look at this thread to get a hint, how to implement multikey maps: How to implement a Map with multiple keys?
EDIT: To improve further, the resulting algorithm can look like this:
*
*Pick next point p from the list
*For every point p1 such that p.y == p1.y && p.x < p1.x check if there are two more points present to complete the square (note that if you array is not sorted initially there could be two possible squares for each two points on the same ordinate)
*If so, add 1 (or 2) to the squares counter.
| |
doc_2364
|
For example, if I have a word doc with 'this is a test' where 'is a test' is bold, red and 28 point and looking at the contents of the clipboard with clipview shows
<body lang=EN-US style='tab-interval:.5in'>
<!--StartFragment-->
<p class=MsoNormal>This <b style='mso-bidi-font-weight:normal'><span
style='font-size:28.0pt;line-height:107%;color:red'>is a test</span></b><o:p></o:p></p>
<p class=MsoNormal><o:p> </o:p></p>
<!--EndFragment-->
</body>
</html>
It would appear that it is picking up the color,size and bold attributes.
However, when I paste that into a text area using ckeditor and look at the source in ckeditor, I see
<p>This <strong>is a test</strong></p>
The attributes other than strong have been removed.
My body tag on the form is
<div class="field">
<%= f.label :body %><br>
<%= f.cktext_area :body, :rows => 80, :cols => 120 %>
</div>
I have gone into C:\Ruby200\lib\ruby\gems\2.0.0\gems\ckeditor-4.1.4\app\assets\javascripts\ckeditor\config.js and added
config.allowedContent = true;
config.extraAllowedContent = '*(*);*{*}';
config.removeFormatAttributes = '';
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
I tried adding the three config lines inside the block and that didn't work. I read a suggestion about adding them outside the config block so I tried that. I did restart the server but it still strips out the additional attributes.
This is an intranet application and, given our situation, I'm not worried about content filtering. I just want the users to be able to copy and paste with all attributes.
------ edit 1
I looked at the source of the page and see
//<![CDATA[
(function() { if (typeof CKEDITOR != 'undefined') { if (CKEDITOR.instances['document_body'] == undefined) { CKEDITOR.replace('document_body', {"allowedContent":true}); } } else { setTimeout(arguments.callee, 50); } })();
//]]>
</script>
I'm not sure if the allowedContent statement should be working.
A: There are many ways to configure CKEditor, but the most simple one is passing object as a second parameter to CKEDITOR.replace (just as it's shown in your last piece of code).
However allowedContent: true can be not enough to enable pasting anything, because there are also paste filters in CKE, enabled in default in Chrome and Safari. If you're using that browser, CKE will strip off all classes, styles and div and span elements. To disable that behaviour, you should also pass pasteFilter option set to null:
var editor = CKEDITOR.replace( 'editor', {
allowedContent: true,
pasteFilter: null
} );
If you don't want to mess with configuring CKE, you can also disable paste filter on the fly:
editor.on( 'instanceReady', function() {
editor.pasteFilter.disable();
} );
However disabling that filter can lead to producing very messy HTML, so be warned!
More info about paste filter is available in official documentation.
---edit:
Note that if you are pasting mainly from Word, there are also configuration options dedicated for that case: pasteFromWordRemoveFontStyles and pasteFromWordRemoveStyles.
| |
doc_2365
|
The info I need is the result of the GetCurrentExchangeRates method.
I test it with SoapUI, with this request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.mnb.hu/webservices/">
<soapenv:Header/>
<soapenv:Body>
<web:GetCurrentExchangeRates/>
</soapenv:Body>
</soapenv:Envelope>
I got the correct response:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetCurrentExchangeRatesResponse xmlns="http://www.mnb.hu/webservices/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<GetCurrentExchangeRatesResult><![CDATA[<MNBCurrentExchangeRates><Day date="2017-01-06"><Rate unit="1" curr="AUD">212,76</Rate><Rate unit="1" curr="BGN">157,05</Rate><Rate unit="1" curr="BRL">90,57</Rate><Rate unit="1" curr="CAD">218,75</Rate><Rate unit="1" curr="CHF">286,65</Rate><Rate unit="1" curr="CNY">41,83</Rate><Rate unit="1" curr="CZK">11,37</Rate><Rate unit="1" curr="DKK">41,32</Rate><Rate unit="1" curr="EUR">307,16</Rate><Rate unit="1" curr="GBP">358,91</Rate><Rate unit="1" curr="HKD">37,36</Rate><Rate unit="1" curr="HRK">40,53</Rate><Rate unit="100" curr="IDR">2,17</Rate><Rate unit="1" curr="ILS">75,42</Rate><Rate unit="1" curr="INR">4,26</Rate><Rate unit="1" curr="ISK">2,56</Rate><Rate unit="100" curr="JPY">249,83</Rate><Rate unit="100" curr="KRW">24,27</Rate><Rate unit="1" curr="MXN">13,58</Rate><Rate unit="1" curr="MYR">64,78</Rate><Rate unit="1" curr="NOK">34,12</Rate><Rate unit="1" curr="NZD">203,58</Rate><Rate unit="1" curr="PHP">5,87</Rate><Rate unit="1" curr="PLN">70,45</Rate><Rate unit="1" curr="RON">68,17</Rate><Rate unit="1" curr="RSD">2,48</Rate><Rate unit="1" curr="RUB">4,88</Rate><Rate unit="1" curr="SEK">32,16</Rate><Rate unit="1" curr="SGD">202,09</Rate><Rate unit="1" curr="THB">8,12</Rate><Rate unit="1" curr="TRY">80,08</Rate><Rate unit="1" curr="UAH">10,74</Rate><Rate unit="1" curr="USD">289,75</Rate><Rate unit="1" curr="ZAR">21,26</Rate></Day></MNBCurrentExchangeRates>]]></GetCurrentExchangeRatesResult>
</GetCurrentExchangeRatesResponse>
</s:Body>
</s:Envelope>
I try to read this information from SQL Server this way (I create a procedure for it, see the code below)
CREATE proc [dbo].[spHTTPRequest]
@URI varchar(2000) = '',
@methodName varchar(50) = '',
@requestBody varchar(8000) = '',
@SoapAction varchar(255),
@UserName nvarchar(100), -- Domain\UserName or UserName
@Password nvarchar(100),
@responseText varchar(8000) output
AS
SET NOCOUNT ON
IF @methodName = ''
BEGIN
select FailPoint = 'Method Name must be set'
return
END
SET @responseText = 'FAILED'
DECLARE @objectID int
DECLARE @hResult int
DECLARE @source varchar(255), @desc varchar(255)
EXEC @hResult = sp_OACreate 'MSXML2.ServerXMLHTTP', @objectID OUT
IF @hResult <> 0
BEGIN
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'Create failed',
MedthodName = @methodName
goto destroy
return
END
-- open the destination URI with Specified method
EXEC @hResult = sp_OAMethod @objectID, 'open', null, @methodName, @URI, 'false', @UserName, @Password
IF @hResult <> 0
BEGIN
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'Open failed',
MedthodName = @methodName
goto destroy
return
END
-- set request headers
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'Content-Type', 'text/xml;charset=UTF-8'
IF @hResult <> 0
BEGIN
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'SetRequestHeader failed',
MedthodName = @methodName
goto destroy
return
END
-- set soap action
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'SOAPAction', @SoapAction
IF @hResult <> 0
BEGIN
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'SetRequestHeader failed',
MedthodName = @methodName
goto destroy
return
END
declare @len int
set @len = len(@requestBody)
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'Content-Length', @len
IF @hResult <> 0
BEGIN
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'SetRequestHeader failed',
MedthodName = @methodName
goto destroy
return
END
-- send the request
EXEC @hResult = sp_OAMethod @objectID, 'send', null, @requestBody
IF @hResult <> 0
BEGIN
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'Send failed',
MedthodName = @methodName
goto destroy
return
END
declare @statusText varchar(1000), @status varchar(1000)
-- Get status text
exec sp_OAGetProperty @objectID, 'StatusText', @statusText out
exec sp_OAGetProperty @objectID, 'Status', @status out
select @status, @statusText, @methodName
-- Get response text
exec sp_OAGetProperty @objectID, 'responseText', @responseText out
IF @hResult <> 0
BEGIN
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'ResponseText failed',
MedthodName = @methodName
goto destroy
return
END
destroy:
exec sp_OADestroy @objectID
SET NOCOUNT OFF
GO
*/
declare @xmlOut varchar(8000)
Declare @RequestText as varchar(8000);
set @RequestText=
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.mnb.hu/webservices/">
<soapenv:Header/>
<soapenv:Body>
<web:GetCurrentExchangeRates/>
</soapenv:Body>
</soapenv:Envelope>'
exec spHTTPRequest 'http://www.mnb.hu/arfolyamok.asmx?wsdl', 'post', @RequestText,'http://tempuri.org/CreateOrderForMe','', '', @xmlOut out
But I always get an "Internal server" error. Can somebody suggest me a solution?
Thanks!
A: I was facing the same issue while executing my procedure. There seems to be some difference in the MSXML2.HTTP method between Windows 2012 and windows 2007. For example the send works as follows in 2012:
DECLARE @send NVARCHAR(4000) = 'send("' + REPLACE(@requestBody, '"', '''') + '")';
EXEC @hResult = sp_OAMethod @objectID, @send
unlike
sp_OAMethod @objectID, 'send', null, @requestBody
in your procedure.
| |
doc_2366
|
The email is the "sendTo" section of the swifmailer.
As I tried it doesn't work. The form is sent but no email is recieved.
How can I have it? Do you have an idea?
So the controller, the action to send the form and then the email is :
/**
* Creates a new Reservations entity.
*
*/
public function createAction(Request $request)
{
$entity = new Reservations();
$emailPool = new Pool();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
// Get the sender's email adress
$sender = $entity->getEmail();
// Get the recipients' emails adresses (pool address)
$emailPool = $this->$pool->getEmailPool(); // mal codé >> trouver la bonne méthode
// Send email
$message = \Swift_Message::newInstance()
->setSubject('Demande de véhicule')
->setFrom($sender)
->setTo($emailPool) // email à entrer [email protected]
// Indicate "High" priority
->setPriority(2)
->setBody(
$this->renderView(
// View in app/Resources/views/emails/demandereservation.html.twig
'emails/demandereservation.html.twig', array(
'reservations' => $entity)),
'text/html'
);
$this->get('mailer')->send($message);
$this->get('session')->getFlashBag()->Add('notice', 'Votre réservation a bien été envoyée');
return $this->redirect($this->generateUrl('reservations_show', array('id' => $entity->getId())));
}
return $this->render('CDCarsBundle:Reservations:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
The form (with the imbricated form (pool)) is :
<?php
namespace CD\CarsBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use CD\CarsBundle\Entity\Reservations;
use CD\CarsBundle\Entity\Vehicules;
use Application\Sonata\UserBundle\Entity\User;
class ReservationsType extends AbstractType
{
// Form for the entity "Reservations" which is used to build the car's booking form
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nomAgent', null, array(
'label' => 'Nom de l\'agent',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('prenomAgent', null, array(
'label' => 'Prénom de l\'agent',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('dga', null, array(
'label' => 'D.G.A',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('direction', null, array(
'label' => 'Direction',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('email', null, array(
'label' => 'Email',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
->add('telephone', null, array(
'label' => 'Téléphone',
//'attr' => array(
//'readonly' => true,
//'disabled' => true
//)
))
// ajouter le pool
->add('pool', new PoolType())
->add('heureDebut', null, array(
'label' => 'Date et heure de début',
'format' => 'dd-MM-yyyy H:i',
'years' => range(\date("Y") - 0, \date("Y") + 2),
)
)
->add('heureFin', null, array(
'label' => 'Date et heure de fin',
'format' => 'dd-MM-yyyy H:i',
'years' => range(\date("Y") - 0, \date("Y") + 2),
)
)
// ajouter type véhicule
->add('besoin', 'choice', array(
'label' => 'Type',
'choices' => array(
'V.L' => 'V.L',
'V.L.E' => 'V.L.E',
'V.U' => 'V.U',
'velo' => 'Vélo')
)
)
// ajouter nombre personnes
->add('nombrePersonne', 'choice', array(
'label' => 'Nombre de personne',
'choices' => array(
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5 +')
)
)
// ajouter demande de remisage -> si coché dévoiler champs pour le remisage (dématérialisation) => à faire dans la vue
->add('remisage', null, array('required' => false))
->add('adresseRemisage', null, array('label' => 'Adresse'))
->add('dateDebutRemisage', null, array(
'label' => 'Du',
'format' => 'dd-MM-yyyy H:i',
'years' => range(\date("Y") - 0, \date("Y") + 2),
)
)
->add('dateFinRemisage', null, array(
'label' => 'au',
'format' => 'dd-MM-yyyy H:i',
'years' => range(\date("Y") - 0, \date("Y") + 2),
)
)
->add('emailDirecteur', null, array(
'label' => 'Email du directeur',
'attr' => array(
'placeholder' => '[email protected]',
))
)
->add('destination', null, array('label' => 'Destination'))
->add('motifRdv', null, array('required' => false))
->add('motifFormation', null, array('required' => false))
->add('motifReunion', null, array('required' => false))
->add('motifCollecte', null, array('required' => false))
->add('motifInstallation', null, array('required' => false))
->add('motifProgrammation', null, array('required' => false))
->add('motifDepannage', null, array('required' => false))
->add('motifVad', null, array('required' => false))
->add('motifAutre', null, array('label' => 'Autre motif'))
->add('conducteur', null, array('required' => false))
// ajouter mandataire -> si coché dévoiler champs pour le mandataire (email...) => à faire dans la vue
->add('mandataire', null, array('required' => false))
->add('nomMandataire', null, array('label' => 'Votre nom'))
->add('prenomMandataire', null, array('label' => 'Votre prénom'))
->add('emailMandataire', null, array('label' => 'Votre émail'))
->add('honneur', null, array('required' => true))
;
}
The Pool form is :
<?php
namespace CD\CarsBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use CD\CarsBundle\Entity\Pool;
use CD\CarsBundle\Entity\Vehicules;
class PoolType extends AbstractType
{
// Form for the entity "pool"
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
/*->add('nom', null, array(
'label' => 'Nom',
))*/
->add('emailPool', null, array(
'label' => 'Email du pool duquel vous dépendez',
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'CD\CarsBundle\Entity\Pool'
));
}
/**
* @return string
*/
public function getName()
{
return 'cd_carsbundle_pool';
}
}
The pool entity is :
<?php
namespace CD\CarsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Pool
*/
class Pool
{
// Code for the entity "Pool"
public function __toString()
{
return (string) $this->getEmailPool();
}
//YML GENERATED CODE
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $nom;
/**
* @var string
*/
private $emailPool;
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $vehicules;
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $user;
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $reservations;
/**
* Constructor
*/
public function __construct()
{
$this->vehicules = new \Doctrine\Common\Collections\ArrayCollection();
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
$this->reservations = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* @param string $nom
* @return Pool
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set emailPool
*
* @param string $emailPool
* @return Pool
*/
public function setEmailPool($emailPool)
{
$this->emailPool = $emailPool;
return $this;
}
/**
* Get emailPool
*
* @return string
*/
public function getEmailPool()
{
return $this->emailPool;
}
/**
* Add vehicules
*
* @param \CD\CarsBundle\Entity\Vehicules $vehicules
* @return Pool
*/
public function addVehicule(\CD\CarsBundle\Entity\Vehicules $vehicules)
{
$this->vehicules[] = $vehicules;
return $this;
}
/**
* Remove vehicules
*
* @param \CD\CarsBundle\Entity\Vehicules $vehicules
*/
public function removeVehicule(\CD\CarsBundle\Entity\Vehicules $vehicules)
{
$this->vehicules->removeElement($vehicules);
}
/**
* Get vehicules
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getVehicules()
{
return $this->vehicules;
}
/**
* Add user
*
* @param \Application\Sonata\UserBundle\Entity\User $user
* @return Pool
*/
public function addUser(\Application\Sonata\UserBundle\Entity\User $user)
{
$this->user[] = $user;
return $this;
}
/**
* Remove user
*
* @param \Application\Sonata\UserBundle\Entity\User $user
*/
public function removeUser(\Application\Sonata\UserBundle\Entity\User $user)
{
$this->user->removeElement($user);
}
/**
* Get user
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Add reservations
*
* @param \CD\CarsBundle\Entity\Reservations $reservations
* @return Pool
*/
public function addReservation(\CD\CarsBundle\Entity\Reservations $reservations)
{
$this->reservations[] = $reservations;
return $this;
}
/**
* Remove reservations
*
* @param \CD\CarsBundle\Entity\Reservations $reservations
*/
public function removeReservation(\CD\CarsBundle\Entity\Reservations $reservations)
{
$this->reservations->removeElement($reservations);
}
/**
* Get reservations
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getReservations()
{
return $this->reservations;
}
}
The reservations entity is :
<?php
namespace CD\CarsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints as Asserts;
/**
* Reservations
*/
class Reservations
{
// Code for the entity "Reservations"
public function __toString()
{
return (string) $this->getId();
return (string) $this->getHeureDebut();
}
// YML GENERATED CODE
/**
* @var integer
*/
private $id;
/**
* @var \DateTime
*/
private $heureDebut;
/**
* @var \DateTime
*/
private $heureFin;
/**
* @var string
*/
private $nomAgent;
/**
* @var string
*/
private $prenomAgent;
/**
* @var string
*/
private $dga;
/**
* @var string
*/
private $direction;
/**
* @var string
*/
private $email;
/**
* @var string
*/
private $telephone;
/**
* @var string
*/
private $destination;
/**
* @var boolean
*/
private $reserve;
/**
* @var boolean
*/
private $annulation;
/**
* @var boolean
*/
private $remisage;
/**
* @var string
*/
private $adresseRemisage;
/**
* @var \DateTime
*/
private $dateDebutRemisage;
/**
* @var \DateTime
*/
private $dateFinRemisage;
/**
* @var string
*/
private $emailDirecteur;
/**
* @var boolean
*/
private $conducteur;
/**
* @var boolean
*/
private $mandataire;
/**
* @var boolean
*/
private $motifRdv;
/**
* @var boolean
*/
private $motifFormation;
/**
* @var boolean
*/
private $motifReunion;
/**
* @var boolean
*/
private $motifCollecte;
/**
* @var boolean
*/
private $motifInstallation;
/**
* @var boolean
*/
private $motifProgrammation;
/**
* @var boolean
*/
private $motifDepannage;
/**
* @var boolean
*/
private $motifVad;
/**
* @var string
*/
private $motifAutre;
/**
* @var string
*/
private $commentaires;
/**
* @var integer
*/
private $nombrePersonne;
/**
* @var string
*/
private $besoin;
/**
* @var string
*/
private $nomMandataire;
/**
* @var string
*/
private $prenomMandataire;
/**
* @var string
*/
private $emailMandataire;
/**
* @var boolean
*/
private $honneur;
/**
* @var boolean
*/
private $traite;
/**
* @var \CD\CarsBundle\Entity\Vehicules
*/
private $vehicules;
/**
* @var \Application\Sonata\UserBundle\Entity\User
*/
private $user;
/**
* @var \CD\CarsBundle\Entity\Pool
*/
private $pool;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set heureDebut
*
* @param \DateTime $heureDebut
* @return Reservations
*/
public function setHeureDebut($heureDebut)
{
$this->heureDebut = $heureDebut;
return $this;
}
/**
* Get heureDebut
*
* @return \DateTime
*/
public function getHeureDebut()
{
return $this->heureDebut;
}
/**
* Set heureFin
*
* @param \DateTime $heureFin
* @return Reservations
*/
public function setHeureFin($heureFin)
{
$this->heureFin = $heureFin;
return $this;
}
/**
* Get heureFin
*
* @return \DateTime
*/
public function getHeureFin()
{
return $this->heureFin;
}
/**
* Set nomAgent
*
* @param string $nomAgent
* @return Reservations
*/
public function setNomAgent($nomAgent)
{
$this->nomAgent = $nomAgent;
return $this;
}
/**
* Get nomAgent
*
* @return string
*/
public function getNomAgent()
{
return $this->nomAgent;
}
/**
* Set prenomAgent
*
* @param string $prenomAgent
* @return Reservations
*/
public function setPrenomAgent($prenomAgent)
{
$this->prenomAgent = $prenomAgent;
return $this;
}
/**
* Get prenomAgent
*
* @return string
*/
public function getPrenomAgent()
{
return $this->prenomAgent;
}
/**
* Set dga
*
* @param string $dga
* @return Reservations
*/
public function setDga($dga)
{
$this->dga = $dga;
return $this;
}
/**
* Get dga
*
* @return string
*/
public function getDga()
{
return $this->dga;
}
/**
* Set direction
*
* @param string $direction
* @return Reservations
*/
public function setDirection($direction)
{
$this->direction = $direction;
return $this;
}
/**
* Get direction
*
* @return string
*/
public function getDirection()
{
return $this->direction;
}
/**
* Set email
*
* @param string $email
* @return Reservations
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set telephone
*
* @param string $telephone
* @return Reservations
*/
public function setTelephone($telephone)
{
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* @return string
*/
public function getTelephone()
{
return $this->telephone;
}
/**
* Set destination
*
* @param string $destination
* @return Reservations
*/
public function setDestination($destination)
{
$this->destination = $destination;
return $this;
}
/**
* Get destination
*
* @return string
*/
public function getDestination()
{
return $this->destination;
}
/**
* Set reserve
*
* @param boolean $reserve
* @return Reservations
*/
public function setReserve($reserve)
{
$this->reserve = $reserve;
return $this;
}
/**
* Get reserve
*
* @return boolean
*/
public function getReserve()
{
return $this->reserve;
}
/**
* Set annulation
*
* @param boolean $annulation
* @return Reservations
*/
public function setAnnulation($annulation)
{
$this->annulation = $annulation;
return $this;
}
/**
* Get annulation
*
* @return boolean
*/
public function getAnnulation()
{
return $this->annulation;
}
/**
* Set remisage
*
* @param boolean $remisage
* @return Reservations
*/
public function setRemisage($remisage)
{
$this->remisage = $remisage;
return $this;
}
/**
* Get remisage
*
* @return boolean
*/
public function getRemisage()
{
return $this->remisage;
}
/**
* Set adresseRemisage
*
* @param string $adresseRemisage
* @return Reservations
*/
public function setAdresseRemisage($adresseRemisage)
{
$this->adresseRemisage = $adresseRemisage;
return $this;
}
/**
* Get adresseRemisage
*
* @return string
*/
public function getAdresseRemisage()
{
return $this->adresseRemisage;
}
/**
* Set dateDebutRemisage
*
* @param \DateTime $dateDebutRemisage
* @return Reservations
*/
public function setDateDebutRemisage($dateDebutRemisage)
{
$this->dateDebutRemisage = $dateDebutRemisage;
return $this;
}
/**
* Get dateDebutRemisage
*
* @return \DateTime
*/
public function getDateDebutRemisage()
{
return $this->dateDebutRemisage;
}
/**
* Set dateFinRemisage
*
* @param \DateTime $dateFinRemisage
* @return Reservations
*/
public function setDateFinRemisage($dateFinRemisage)
{
$this->dateFinRemisage = $dateFinRemisage;
return $this;
}
/**
* Get dateFinRemisage
*
* @return \DateTime
*/
public function getDateFinRemisage()
{
return $this->dateFinRemisage;
}
/**
* Set emailDirecteur
*
* @param string $emailDirecteur
* @return Reservations
*/
public function setEmailDirecteur($emailDirecteur)
{
$this->emailDirecteur = $emailDirecteur;
return $this;
}
/**
* Get emailDirecteur
*
* @return string
*/
public function getEmailDirecteur()
{
return $this->emailDirecteur;
}
/**
* Set vehicules
*
* @param \CD\CarsBundle\Entity\Vehicules $vehicules
* @return Reservations
*/
public function setVehicules(\CD\CarsBundle\Entity\Vehicules $vehicules = null)
{
$this->vehicules = $vehicules;
return $this;
}
/**
* Get vehicules
*
* @return \CD\CarsBundle\Entity\Vehicules
*/
public function getVehicules()
{
return $this->vehicules;
}
/**
* Set user
*
* @param \Application\Sonata\UserBundle\Entity\User $user
* @return Reservations
*/
public function setUser(\Application\Sonata\UserBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* @return \Application\Sonata\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set pool
*
* @param \CD\CarsBundle\Entity\Pool $pool
* @return Reservations
*/
public function setPool(\CD\CarsBundle\Entity\Pool $pool = null)
{
$this->pool = $pool;
return $this;
}
/**
* Get pool
*
* @return \CD\CarsBundle\Entity\Pool
*/
public function getPool()
{
return $this->pool;
}
}
Thank you. Have a nice day.
A: I have figured it out.
In the controller, at the swiftmailer section, the line to the get the recipient's email is :
// Get the recipients' emails adresses (pool address)
$recipients = $entity->getPool()->getEmailPool();
Like this it works.
Thank you to all the people who read this post and if you have an other answer, feel free to post it.
Have a nice day!
| |
doc_2367
|
here is my code to generate screenshot .
CCDirector *director = (CCDirector *) [CCDirector sharedDirector];
screenshootimage = [director screenshotUIImage];
appDelegate.screenshootimage = [Utility getImageFromView];
imgsprite = [CCSprite spriteWithCGImage:screenshootimage.CGImage key:@"s"];
- (UIImage*) screenshotUIImage
{
CGSize displaySize = [self displaySizeInPixels];
CGSize winSize = [self winSizeInPixels];
//Create buffer for pixels
GLuint bufferLength = displaySize.width * displaySize.height * 4;
GLubyte* buffer = (GLubyte*)malloc(bufferLength);
//Read Pixels from OpenGL
glReadPixels(0, 0, displaySize.width, displaySize.height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
//Make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer, bufferLength, NULL);
//Configure image
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * displaySize.width;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGImageRef iref = CGImageCreate(displaySize.width, displaySize.height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
uint32_t* pixels = (uint32_t*)malloc(bufferLength);
CGContextRef context = CGBitmapContextCreate(pixels, winSize.width, winSize.height, 8, winSize.width * 4, CGImageGetColorSpace(iref), kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextTranslateCTM(context, 0, displaySize.height);
CGContextScaleCTM(context, 1.0f, -1.0f);
switch (deviceOrientation_)
{
case CCDeviceOrientationPortrait: break;
case CCDeviceOrientationPortraitUpsideDown:
CGContextRotateCTM(context, CC_DEGREES_TO_RADIANS(180));
CGContextTranslateCTM(context, -displaySize.width, -displaySize.height);
break;
case CCDeviceOrientationLandscapeLeft:
CGContextRotateCTM(context, CC_DEGREES_TO_RADIANS(-90));
CGContextTranslateCTM(context, -displaySize.height, 0);
break;
case CCDeviceOrientationLandscapeRight:
CGContextRotateCTM(context, CC_DEGREES_TO_RADIANS(90));
CGContextTranslateCTM(context, displaySize.height-displaySize.width, -displaySize.height);
break;
}
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, displaySize.width, displaySize.height), iref);
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *outputImage = [[[UIImage alloc] initWithCGImage:imageRef] autorelease];
//Dealloc
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGImageRelease(iref);
CGColorSpaceRelease(colorSpaceRef);
CGContextRelease(context);
free(buffer);
free(pixels);
return outputImage;
}
+ (UIImage*)getImageFromView
{
// Create a graphics context with the target size
// On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
// On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
//CGSize imageSize = [[UIScreen mainScreen] bounds].size;
CGSize newImageSize = [[UIScreen mainScreen] bounds].size;
CGSize imageSize = CGSizeMake(newImageSize.height, newImageSize.width);
if (NULL != UIGraphicsBeginImageContextWithOptions)
UIGraphicsBeginImageContextWithOptions(imageSize, NO,1.0);
else
UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
// Iterate over every window from back to front
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
{
// -renderInContext: renders in the coordinate space of the layer,
// so we must first apply the layer's geometry to the graphics context
CGContextSaveGState(context);
// Center the context around the window's anchor point
CGContextTranslateCTM(context, [window center].y, [window center].x);
CGContextRotateCTM( context, degreesToRadian( -90 ) ) ;
// Apply the window's transform about the anchor point
CGContextConcatCTM(context, [window transform]);
// Offset by the portion of the bounds left of and above the anchor point
CGContextTranslateCTM(context,
-imageSize.height *[[window layer] anchorPoint].y,
-imageSize.width *[[window layer] anchorPoint].x);
// Render the layer hierarchy to the current context
[[window layer] renderInContext:context];
// Restore the context
CGContextRestoreGState(context);
}
}
// Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
any help ?!
NOTE: It also works fine in iPad Device, only problem is with iPhone Device.
| |
doc_2368
|
import React, { useState, useEffect, useContext } from 'react';
However, I noticed that the following works just fine:
import React from 'react';
const App = () => {
const [counter, setCounter] = React.useState();
React.useEffect(() => console.log('hello!'), []);
}
My question is, is there any difference between those two? Maybe when it comes to bundle size, or is Webpack smart enough to handle that?
Otherwise, is that bad practice? Which approach do you use, and why?
A: its better to use import {useState } from 'react'just because of readability , less typing and clean coding . it doesn't matter in performance and bundle size
A: Both are the same,
import {useState } from 'react' is less verbose and easy for readability and maintenance.
A: You need React when you want to use JSX.
So if you are doing this in a component where you need to have JSX:
import React from "react";
is the way to go since React already imports the other hooks and its properties. You can simply write is as React.use...
However, if your component (or a custom hook) does not use JSX, then it makes sense to not to import all of React and only the required hooks like useEffect, useState, etc.
import { useEffect, ... } from "react";
I do agree with others about readability but it boils down to personal preference.
| |
doc_2369
|
I've heard using Sensor but don't have idea and can't find on net.
UPDATES1
I found SensorManager.getAltitude(float, float) using API Level 9 up but don't have idea on how to implement it. Would you share with us.
A: I know it's late but for anyone looking for it, that might help
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
public class MyActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private float altitude = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
}
@Override
protected void onResume() {
super.onResume();
if (sensor != null)
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
@Override
public void onSensorChanged(SensorEvent event) {
float presure = event.values[0];
altitude = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, presure);
System.out.println("altitude => " + altitude);
}
}
| |
doc_2370
|
I tried Login.setBackground("loginbackground.png"); but it didn't go per my requirements. This question has duplicates but I didn't found a perfect solution that's why posting it :S
Thanks.
A: if you want to add image to button in background try it using below code :
Bitmap bitmap = Bitmap.getBitmapResource("rectangle.png");
Background background = BackgroundFactory.createBitmapBackground(bitmap);
button1 = new ButtonField("Button1", ButtonField.USE_ALL_WIDTH);
button1.setBackground(background);
add(button1);
or You can do it by adding image and adding click function to it in the below way :
Bitmap msg = Bitmap.getBitmapResource("msg.png");
BitmapField message = new BitmapField(msg, Field.FOCUSABLE)
{
protected boolean navigationClick(int status,int time)
{
label.setText("Messages");
Dialog.alert("Message icon selected");
return true;
}
};
add(message)
| |
doc_2371
|
Here is part of the code
## repeated for every worker
for i in range(2):
self.Vl_name_location = QtWidgets.QVBoxLayout()
self.Vl_name_location.setObjectName("Vl_name_location")
self.worker_name = QtWidgets.QLabel(self.groupBox)
self.worker_name.setAlignment(QtCore.Qt.AlignCenter)
## from db
self.worker_name.setText("worker_name")
self.worker_name.setObjectName("worker_name")
self.Vl_name_location.addWidget(self.worker_name)
self.worker_location = QtWidgets.QLabel(self.groupBox)
self.worker_location.setAlignment(QtCore.Qt.AlignCenter)
self.worker_location.setObjectName("worker_location")
# from db
self.worker_location.setText("Eng,Zone B")
self.Vl_name_location.addWidget(self.worker_location)
self.Hl_worker.addLayout(self.Vl_name_location)
#####
### assign button to connect the name of the worker to the image on the db
#####
self.assign_button = QtWidgets.QPushButton(self.groupBox)
self.assign_button.setMinimumSize(QtCore.QSize(50, 25))
self.assign_button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.assign_button.setStyleSheet("")
self.assign_button.setObjectName("assign_button")
self.assign_button.setText( "Assign" )
btns.append(self.assign_button)
self.Hl_worker.addWidget(self.assign_button)
preview of GUI
A: I'm not sure if I understood your question correctly, but I assume that when one of the two buttons is pressed, you want to set the text of the corresponding worker_name label. If this is the case, then one way to achieve this is to add the buttons and labels as keys and values to a dictionary, and use self.dct[self.sender()] to extract the label when the button is pressed, e.g.
class MyWidget(QtWidgets.QWidget):
def __init__(self, ...):
...
# dictionary for storing button-label pairs
self.label_dct = {}
self.add_workers()
def add_workers(self):
for i in range(10):
worker_label = QtWidgets.QLabel('worker name')
assign_button = QtWidgets.QPushButton('Assign')
self.label_dct[assign_button] = worker_label
# rest of setup
assign_button.clicked.connect(self.set_label)
@pyqtSlot()
def set_label(self):
button = self.sender()
label = self.label_dct[button]
label.setText("John Doe")
| |
doc_2372
|
However, when I run the C# program it complains:
Unhandled Exception: System.IO.FileNotFoundException: The specified module could
not be found. (Exception from HRESULT: 0x8007007E)
Any idea what else have to be done?
Thanks.
A: I think that you're missing the other assemblies or dll's references by your managed C++ assembly.
A: Does your managed C++ assembly have an other dependencies, including unmanaged dlls? You'll see this error at runtime if your referenced assembly fails to load a dependency.
A: Are you running the application in release on a machine without VS installed?
I only ask because I ran into a similar problem here: Mixed Mode Library and CRT Dependencies - HELP
if you scroll down to my answer you can see what I did that helped me.
A: Check that the c++ assembly is present in the same folder as your c# program. It should be copied over automatically if the 'Copy Local' property is set to true (on the reference to the c++ dll in your c# app).
If the c++ dll is there, the most likely problem is that the c++ dll depends on another non-managed dll which cannot be found (i.e. c# will not copy these to your app folder because it does not know about unmanaged references). You can use DependencyWalker on the c++ dll to check for missing dependencies.
Another probable couse could be a problem with your MSVC runtime dlls. see if DependencyWalker complains about missing MSVCR*.dll, MSVCP*.dll etc... files.
| |
doc_2373
|
Here's the setup. In my "foo" directory I have "bar", "bar19", "bar27", etc.
Ideally I'd like to match on the first two characters of the "v" parameter. So like this:
I would like a request for ..................... to be served from:
www.example.com/foo/bar/something.html .......... foo/bar/something.html
www.example.com/foo/bar/something.html?v=19xxx ... foo/bar19/something.html
www.example.com/foo/bar/something.html?v=27xxx ... foo/bar27/something.html
Of course I would expect that if a value for "v" parameter that doesn't have a corresponding directory to 404.
I've done some Mod_Rewrite magic before, but I'm kind of stuck here. Any ideas?
A: Add a .htaccess file in directory /foo with the following content. Of course you can also insert it into your httpd.conf:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /foo
# match query parameter v with two-digit value; capture
# the value as %2 and the query string before and after v
# as %1 and %3, respectively
RewriteCond %{QUERY_STRING} ^(.*)v=(\d\d)[^&]*(&.*)?$
# match path into "bar" and rest; insert two-digit value from
# RewriteCond inbetween; append rest of query string without v value;
# use case-insensitivity
RewriteRule ^(bar)(.*)$ $1%2$2?%1%3 [NC]
</IfModule>
I think the key is to use captured values from the RewriteCond (accessible as %1, %2, etc.) and at the same time captured values from the RewriteRule itself (as usual $1, $2, etc.).
| |
doc_2374
| ||
doc_2375
|
Here's my code and the error produced:-
IP="xxx.xxx.x.xxx"
username="xyz"
import paramiko
import os
ssh=paramiko.SSHClient()
privatekeyfile=os.path.expanduser('/address/on_pi/to/id_rsa')
mykey=paramiko.RSAKey.from_private_key_file(privatekeyfile)
ssh.connect(IP[0],username=user[0], pkey=mykey)
x_file=open('/address/on/remote/mac/file.txt','w')
x_file.write("anything")
The error comes as:-
Trackback (most recent call last):
File "my_paramiko.py", line 8, in <module>
ssh.connect(IP[0],username=user[0], pkey=mykey)
NameError: name 'user' is not defined
My python version is 2.7.3 and paramiko is 1.7.7.1 (George)
I researched for solution, but most of them did only with bash terminal, or had errors in reading keys.
EDIT
The problem was solved. Instead of using
ssh.connect(IP[0],username=user[0], pkey=mykey)
I used
ssh.connect("xxx.xxx.x.xxx", username="xyz", pkey=mykey)
stdin, stdout, stderr=ssh.exec_command("ls -l")
Then called in sftp
sftp=ssh.open_sftp()
sftp.put('file/address','file/address')
sftp.close
ssh.close
Even though it worked, I am in some doubt about the code. Please suggest or point out if any redundant method identified, or if there a better way.
Thanks
| |
doc_2376
|
Is it ok to remove TestContext or would doing that indicate my unit tests are poorly structured?
A: If you don't need it, remove it. You can always introduce it again afterwards. I've hardly used it too...
A: No harm in retaining the TestContext property, particularly if your unit test class makes use of data-driven test methods. Particularly useful if you use this type of statement:
Assert.AreEqual(myValue, this.TestContext.DataRow["ExpectedValue"].ToString())
Conversely, if you're using a hand-coded test class (i.e. not one generated by the VS "Add New Item" menu option), adding a property declaration as follows gives you instant access to the record of test data as it relates to the current unit test:
public TestContext TestContext { get; set; }
Hope that helps!
| |
doc_2377
|
I tried resolving it by using document.styleSheets[0].cssRules however the stylesheet does not appear in the list of document stylesheets (I assume because its an external source?)
How can I resolve this?
A: Update: To avoid the flash of invisible text add &display=swap to the end of the Google Font URL.
| |
doc_2378
|
I've been struggling with this for a while and I've seen so many variants of solving this problem, more or less riddled with hassle and angst.
I know the question seems subjective, but it really shouldn't be in my opinion. There must be a way considered to be the best when the circumstances involve MFC and the standard libs that come with those circumstances.
I'm looking for a one-line solution that just works. Sort of like long.ToString() in C#.
A: There are many ways to do this:
CString str("");
long l(42);
str.Format("%ld", l); // 1
char buff[3];
_ltoa_s(l, buff, 3, 10); // 2
str = buff;
str = boost::lexical_cast<std::string>(l).c_str(); // 3
std::ostringstream oss;
oss << l; // 4
str = oss.str().c_str();
// etc
A: It's as simple as:
long myLong=0;
CString s;
// Your one line solution is below
s.Format("%ld",myLong);
| |
doc_2379
|
i want the select statement to give a-c where b=d; which works fine but i need the value of a-c to give if the corresponding b=d doesn't exist, i hope i have been able to explain
table 1:
(a,b)
(10,1)
(10,2)
(10,3)
table 2: (c,d)
(5,1)
(5,2)
so, select (a-c),b from tables where b=d returns
(a-c,b)
(5,1)
(5,2)
where i want
(a-c,b)
(5,1)
(5,2)
(10,3)
thanks for your help!
A: You could use:
SELECT t1.a-COALESCE(t2.c,0), t1.b
FROM t1
LEFT JOIN t2
ON t1.b = t2.d
| |
doc_2380
|
What is the difference between 2.1.1, 2.1.1[global], and 2.1.1[my-project-name]?
Why would I want to use one over the other?
A: The names in the brackets are actually not created by IntelliJ/RubyMine. Rather they are created by RVM: they are the names of RVM gemsets. RVM lets you create multiple sets of gems by creating named gemsets. The global gemset is created by default and is shared by all the other gemsets. The rest of the named gemsets were either manually or automatically created (by a .ruby-gemset file, for example). IntelliJ picks up on the Rubies and gemsets managed by RVM and creates an SDK entry for each Ruby/gemset combination.
The reason you would use one of the SDKs that correspond to a named gemset is if you've installed gems specific to that project inside that gemset. If you are not using gemsets to manage your Rubygems then you can just use one of the Ruby SDKs without a gemset name in brackets.
For more information about gemsets you can see the RVM documentation here: https://rvm.io/gemsets/basics
| |
doc_2381
|
Is it appropriate to implement paging of data within the Solidity contract? If not, what other options are there?
A:
since the array could potentially contain thousands of elements I wouldn't want to do this due to high gas price
The .call() web3 method invokes the eth_call RPC method, which is gas free.
It can't change the contract state (update storage, emit events, ...) but it shouldn't matter in your use case, if you're only reading the data. It's recommended to use the call() method only in combination with Solidity functions that are marked with the view or pure state mutability modifiers.
| |
doc_2382
|
We configured our IAM accounts such that every user can create EC2 machines with a specific 'team_id' tag (of his team). That helps us control the resources, prevent mistakes and monitor usage.
When Pipeline tries to launch the EMR cluster, it (probably) does it without the tags and therefore it fails with Terminated with errors: User account is not authorized to call EC2. I tried to find a configuration in the EMRCluster resource but couldn't find anything that will help me set that. I'm pretty sure that it fails because of the tags policy.
Any idea how I can overcome this?
Does it help if If create a CloudFormation template for that? Do I have more control there? (I'm going to create the pipeline as a part of the application template anyway, just wanted to experience the product before).
Thanks!
A: I could not find a solution for how to add tags to EMR(and how to set it to be visible to all users) so I have created a python script to run as bootstrap action. If its still relevant you can find it here
| |
doc_2383
|
I also want to have the ability to edit this information, so if the user clicks on the newly created span with text, it will turn back into the input field with the current information for their editing pleasure.
For reference, I'm looking to have a functionality pretty much like on editing a photo title on Flickr.
If possible, I'd also like to have the textbox show "saving..." for half a second after the blur to reflect interaction with server.
A: Why not make a CSS style for :focus for the input, making it look like a text-box, and a CSS style otherwise which makes it look like an inline text element?
input.ez-edit {
display: inline;
padding: 0;
background-color: transparent;
border-style: none;
color: inherit;
font-size: inherit;
}
input.ez-edit:hover {
text-decoration: underline;
}
input.ez-edit:focus {
display: inline-block;
padding: 3px;
background-color: #FFFFFF;
border: 1px solid #000000;
}
input.ez-edit:focus:hover {
text-decoration: none;
}
A: I played around with this based on @strager's suggestions and composed the following, excellently functional code
jQuery:
$(":text[value='']").addClass('empty');
$(":text[value>='']").removeClass('empty');
$('.ez-edit').blur(function() {
if ($(this).val().length >= 0) {
$(this).removeClass('empty');
}
if ($(this).val().length <= 0) {
$(this).addClass('empty');
}
});
and CSS:
input.ez-edit {
font-family:"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, Verdana, sans-serif;
font-weight:bold;
display: inline;
padding:5px 8px 5px 2px;
background-color: transparent;
border-style: none;
border-top: 1px solid #cdcdcd;
color: inherit;
font-size: inherit;
}
input.ez-edit:hover {
text-decoration: underline;
/* following "pencil" img from: http://enon.in/6j */
background:url(../images/pencil.gif) no-repeat right #ffffdc;
border-style:1px hidden;
border-top:1px solid #fff;
border-right-color:#fff;
border-bottom-color:#fff;
border-left-color:#fff;
}
input.ez-edit:focus, input.ez-edit:focus:hover {
display:inline-block;
border:1px solid #4d4d4d;
font-size:12px;
background-color:#FFFFDc;
color:#333;
font-weight:normal;
}
A: I don't exactly know the function on Flickr you're referring to, but also consider not changing the input's type at all, but just its style. Much easier and doable without fiddling in the DOM. A setting like
background-color: white;
border-color: transparent;
would make a text input look like a span.
A downside to this is that a text input, different from a <span>, always has a fixed width.
| |
doc_2384
|
The last batch to the second table won't get written unless I explicitly closes the connection. I find it strange since the database is in auto-commit mode (i.e. connection.commit() throws an error).
I would like to keep the connection open since I'll do quite some calls to the write method.
Is there anything beside commit() I can do to force a write to the disk?
Here's a close to minimal code example, note that if I uncomment the conn.close() it will work as I want to.
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:result");
Statement stat = conn.createStatement();
stat.executeUpdate("create table if not exists " +
"a (a1, aID INTEGER PRIMARY KEY ASC)");
stat.executeUpdate("create table if not exists " +
"b (aID, b1, attributePathID INTEGER PRIMARY KEY ASC)");
PreparedStatement pa = conn.prepareStatement(
"insert into a (a1) values (?);");
PreparedStatement pb = conn.prepareStatement(
"insert into b (aID,b1) values (?,?);");
int[] aSet = new int[] {10,20,30};
int[] bSet = new int[] {1,2};
for(int ai : aSet){
pa.setInt(1,ai);
pa.execute();
ResultSet rs = pa.getGeneratedKeys();
rs.next();
long aID = rs.getLong(1);
for(int bi : bSet){
pb.setLong(1,aID);
pb.setInt(2,bi);
pb.execute();
}
}
//conn.close();
A: Haven't worked with jdbc and sqllite much, but this should work:
conn.setAutoCommit(false);
for(int bi : bSet){
pb.setLong(1,aID);
pb.setInt(2,bi);
pb.executeUpdate();
}
conn.commit();
conn.setAutoCommit(true);
Also, take a look at http://www.zentus.com/sqlitejdbc/ which has a nice example similar to yours.
| |
doc_2385
|
In OpenCL we have pointer to the first element and then can use get_global_id(0) to get current index. But we can still access all other elements. In Renderscript, do we only have pointer to the current element?
2) How can I loop through an Allocation in forEach_root()?
I have a code that uses nested (double) loop in java. Renderscript automates the outer loop, but I can't find any information on implementing the inner loop. Below is my best effort:
void root(const float3 *v_in, float3 *v_out) {
rs_allocation alloc = rsGetAllocation(v_in);
uint32_t cnt = rsAllocationGetDimX(alloc);
*v_out = 0;
for(int i=0; i<cnt; i++)
*v_out += v_in[i];
}
But here rsGetAllocation() fails when called from forEach_root().
05-11 21:31:29.639: E/RenderScript(17032): ScriptC::ptrToAllocation, failed to find 0x5beb1a40
Just in case I add my OpenCL code that works great under Windows. I'm trying to port it to Renderscript
typedef float4 wType;
__kernel void gravity_kernel(__global wType *src,__global wType *dst)
{
int id = get_global_id(0);
int count = get_global_size(0);
double4 tmp = 0;
for(int i=0;i<count;i++) {
float4 diff = src[i] - src[id];
float sq_dist = dot(diff, diff);
float4 norm = normalize(diff);
if (sq_dist<0.5/60)
tmp += convert_double4(norm*sq_dist);
else
tmp += convert_double4(norm/sq_dist);
}
dst[id] = convert_float4(tmp);
}
A: You can provide data apart from your root function. In the current android version (4.2) you could do the following (It is an example from an image processing scenario):
Renderscript snippet:
#pragma version(1)
#pragma rs java_package_name(com.example.renderscripttests)
//Define global variables in your renderscript:
rs_allocation pixels;
int width;
int height;
// And access these in your root function via rsGetElementAt(pixels, px, py)
void root(uchar4 *v_out, uint32_t x, uint32_t y)
{
for(int px = 0; px < width; ++px)
for(int py = 0; py < height; ++py)
{
// unpack a color to a float4
float4 f4 = rsUnpackColor8888(*(uchar*)rsGetElementAt(pixels, px, py));
...
Java file snippet
// In your java file, create a renderscript:
RenderScript renderscript = RenderScript.create(this);
ScriptC_myscript script = new ScriptC_myscript(renderscript);
// Create Allocations for in- and output (As input the bitmap 'bitmapIn' should be used):
Allocation pixelsIn = Allocation.createFromBitmap(renderscript, bitmapIn,
Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
Allocation pixelsOut = Allocation.createTyped(renderscript, pixelsIn.getType());
// Set width, height and pixels in the script:
script.set_width(640);
script.set_height(480);
script.set_pixels(pixelsIn);
// Call the for each loop:
script.forEach_root(pixelsOut);
// Copy Allocation to the bitmap 'bitmapOut':
pixelsOut.copyTo(bitmapOut);
You can see, the input 'pixelsIn' is previously set and used inside the renderscript when calling the forEach_root function to calculate values for 'pixelsOut'. Also width and height are previously set.
| |
doc_2386
|
Save code :
Directory directory = org.apache.lucene.store.FSDirectory.open(path);
IndexWriterConfig config = new IndexWriterConfig(new SimpleAnalyzer());
IndexWriter indexWriter = new IndexWriter(directory, config);
indexWriter.commit();
org.apache.lucene.document.Document doc = new org.apache.lucene.document.Document();
if (filePath != null) {
File file = new File(filePath); // current directory
doc.add(new TextField("path", file.getPath(), Field.Store.YES));
}
doc.add(new StringField("id", String.valueOf(objectId), Field.Store.YES));
FieldType fieldType = new FieldType(TextField.TYPE_STORED);
fieldType.setTokenized(false);
if(groupNotes!=null) {
doc.add(new Field("contents", text + "\n" + tagFileName+"\n"+String.valueOf(groupNotes.getNoteNumber()), fieldType));
}else {
doc.add(new Field("contents", text + "\n" + tagFileName, fieldType));
}
Search code :
File file = new File(path.toString());
if ((file.isDirectory()) && (file.list().length > 0)) {
if(text.contains(" ")) {
String[] textArray = text.split(" ");
for(String str : textArray) {
Directory directory = FSDirectory.open(path);
IndexReader indexReader = DirectoryReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Query query = new WildcardQuery(new Term("contents","*"+str + "*"));
TopDocs topDocs = indexSearcher.search(query, 100);
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
System.out.println("Score is "+scoreDoc.score);
org.apache.lucene.document.Document document = indexSearcher.doc(scoreDoc.doc);
objectIds.add(Integer.valueOf(document.get("id")));
}
indexSearcher.getIndexReader().close();
directory.close();
}
}
}
}
Thank you.
A: Your question is not a bit very clear to me so below are just guessed answers ,
*
*There are methods in IndexSearcher which take org.apache.lucene.search.Sort as argument ,
public TopFieldDocs search(Query query, int n,
Sort sort, boolean doDocScores, boolean doMaxScore) throws IOException OR
public TopFieldDocs search(Query query, int n, Sort sort) throws IOException
See if these methods solve your issue.
*If you simply want to sort on the basis of scores then don't collect only document Ids but collect score too in a pojo that has that score field .
Collect all these pojos in some List then outside loop sort list on the basis
of score.
for (ScoreDoc hit : hits) {
//additional code
pojo.setScore(hit.score);
list.add(pojo);
}
then outside for loop ,
list.sort((POJO p1, POJO p2) -> p2
.getScore().compareTo(p1.getScore()));
| |
doc_2387
|
router.post('/add', function(req, res) {
console.log('add route hit at ' + currentDate);
console.log(req.body);
knex('users').insert(
{first_name: req.body.first_name},
{last_name: req.body.last_name}
)
});
For some reason, this does not insert data into my database, but does not return any errors either. Can someone help?
Thank you!!
A: You need to call then on the knex chain
router.post('/add', function (req, res) {
return knex('users')
.insert(req.body)
.then(function () {
res.send('welcome') // or something
})
})
| |
doc_2388
|
$cert=(Get-ChildItem -Path Cert:\LocalMachine\Root -CodeSigningCert)[0]
Set-AuthenticodeSignature -FilePath "C:\Scripts\ServiceFailureAlert.PS1" $cert
But I'm getting Access to the path is denied.
I'm sure that its something super simple, but I'm banging my head against the wall at this point. The script is something that I created. Its not read only, the directory isn't read only, all users have full rights, I'm an admin on the server, I'm running powershell as an admin. Any help would be greatly appreciated.
A: The action was being blocked by an application on the server that I didn't have visibility to. I spoke with the server team, got rights added, and re-ran the command without issue. Everything works now. Thanks for the look/response Theo, appreciate it.
A: I was getting the same issue and under the Security event log I found the following:
Audit Failure:
Cryptographic Operation:
Operation: Open Key.
Return Code: 0x80090016
The problem for me was that the user which was signing the scripts was a different user than the one I had used to import the certificates, and didn't have access to the private keys. To fix, I did the following:
*
*Manage Certificates for Local Computer
*Locate the Authenticode Certificate with the private key
*Right click > All tasks > Manage private keys...
*Granted the user Full Control over the private keys
After this I was able to use Set-AuthenticodeSignature under my desired user credential with no issues
| |
doc_2389
|
Test Summary Report
-------------------
t/00_load_scrappy.t (Wstat: 65280 Tests: 1 Failed: 1)
Failed test: 1
Non-zero exit status: 255
Parse errors: Bad plan. You planned 12 tests but ran 1.
t/00_test_function_back.t (Wstat: 512 Tests: 0 Failed: 0)
Non-zero exit status: 2
Parse errors: No plan found in TAP output
t/00_test_function_content.t (Wstat: 512 Tests: 0 Failed: 0)
Non-zero exit status: 2
Parse errors: No plan found in TAP output
t/00_test_function_control.t (Wstat: 512 Tests: 0 Failed: 0)
Non-zero exit status: 2
Parse errors: No plan found in TAP output
t/00_test_function_cookies.t (Wstat: 512 Tests: 0 Failed: 0)
Non-zero exit status: 2
Parse errors: No plan found in TAP output
t/00_test_function_crawl.t (Wstat: 512 Tests: 0 Failed: 0)
Non-zero exit status: 2
Parse errors: No plan found in TAP output
t/00_test_function_debug.t (Wstat: 512 Tests: 0 Failed: 0)
Non-zero exit status: 2
Parse errors: No plan found in TAP output
t/00_test_function_domain.t (Wstat: 512 Tests: 0 Failed: 0)
Non-zero exit status: 2
Parse errors: No plan found in TAP output
t/00_test_function_download.t (Wstat: 512 Tests: 0 Failed: 0)
Non-zero exit status: 2
Parse errors: No plan found in TAP output
t/01_load_scrappy.t (Wstat: 65280 Tests: 1 Failed: 1)
Failed test: 1
Non-zero exit status: 255
Parse errors: Bad plan. You planned 8 tests but ran 1.
Files=39, Tests=2, 1 wallclock secs ( 0.08 usr 0.08 sys + 0.85 cusr 0.15 csys = 1.16 CPU)
Result: FAIL
Failed 10/39 test programs. 2/2 subtests failed.
make: *** [test_dynamic] Error 255
AWNCORP/Scrappy-0.94112090.tar.gz
7 dependencies missing (String::TT,WWW::Mechanize,Web::Scraper,YAML::Syck,Template,HTML::TreeBuilder,Moose); additionally test harness failed
make test -- NOT OK
//hint// to see the cpan-testers results for installing this module, try:
reports AWNCORP/Scrappy-0.94112090.tar.gz
Running make install
make test had returned bad status, won't install without force
Could not read metadata file. Falling back to other methods to determine prerequisites
Failed during this command:
ROBIN/PadWalker-1.96.tar.gz : make NO
ABW/Template-Toolkit-2.24.tar.gz : make NO
BOBTFISH/String-TT-0.03.tar.gz : make_test NO 2 dependencies missing (PadWalker,Template); additionally test harness failed
GAAS/HTML-Parser-3.69.tar.gz : make NO
CJM/HTML-Tree-5.03.tar.gz : make_test NO 2 dependencies missing (HTML::Parser,HTML::Entities); additionally test harness failed
MIROD/HTML-TreeBuilder-XPath-0.14.tar.gz : make_test NO one dependency not OK (HTML::TreeBuilder); additionally test harness failed
GAAS/libwww-perl-6.04.tar.gz : make_test NO 2 dependencies missing (HTML::HeadParser,HTML::Entities); additionally test harness failed
MIYAGAWA/Web-Scraper-0.36.tar.gz : make_test NO 4 dependencies missing (HTML::TreeBuilder::XPath,HTML::Entities,HTML::TreeBuilder,LWP); additionally test harness failed
DOY/Package-Stash-XS-0.25.tar.gz : make NO
DROLSKY/Class-Load-XS-0.04.tar.gz : make NO
DOY/Moose-2.0604.tar.gz : make NO
GAAS/HTML-Form-6.03.tar.gz : make_test NO one dependency not OK (HTML::TokeParser); additionally test harness failed
JESSE/WWW-Mechanize-1.72.tar.gz : make_test NO 7 dependencies missing (HTML::Form,LWP::UserAgent,HTML::TokeParser,HTML::Parser,HTML::HeadParser,HTML::TreeBuilder,LWP); additionally test harness failed
TODDR/YAML-Syck-1.21.tar.gz : writemakefile NO '/usr/bin/perl Makefile.PL INSTALLDIRS=site' returned status 512
AWNCORP/Scrappy-0.94112090.tar.gz : make_test NO 7 dependencies missing (String::TT,WWW::Mechanize,Web::Scraper,YAML::Syck,Template,HTML::TreeBuilder,Moose); additionally test harness failed
Then I tried to install one of the dependant modules alone:
cpan[2]> install PadWalker
Running install for module 'PadWalker'
Running make for R/RO/ROBIN/PadWalker-1.96.tar.gz
Has already been unwrapped into directory /root/.cpan/build/PadWalker-1.96-n6C9km
Could not make: Unknown error
Running make test
Can't test without successful make
Running make install
Make had returned bad status, install seems impossible
Could someone point me in the right direction? I am root and it is Ubuntu 12.04.1 up to date as of now.
A: It is possible to install Scrappy with CPAN. In my case only Moose had to be forced (Failed 1/382 test programs. 0/18150 subtests failed).
cpan[6]> force install Moose
[...]
cpan[7]> install Scrappy
Running install for module 'Scrappy'
Running make for A/AW/AWNCORP/Scrappy-0.94112090.tar.gz
[...]
Installing /home/david/perl5/bin/scrappy
Appending installation info to /home/david/perl5/lib/perl5/x86_64-linux-gnu-thread-multi/perllocal.pod
AWNCORP/Scrappy-0.94112090.tar.gz
/usr/bin/make install -- OK
You should try to install PadWalker manually to find out what is the reason behind Could not make: Unknown error.
In my case PadWalker could be installed from ~/.cpan/build/PadWalker-1.96-XW0Mq2 as follow:
perl Makefile.PL
Checking if your kit is complete...
Looks good
Writing Makefile for PadWalker
Writing MYMETA.yml
make
cp PadWalker.pm blib/lib/PadWalker.pm
/usr/bin/perl /usr/share/perl/5.14/ExtUtils/xsubpp -typemap /usr/share/perl/5.14/ExtUtils/typemap PadWalker.xs > PadWalker.xsc && mv PadWalker.xsc PadWalker.c
cc -c -D_REENTRANT -D_GNU_SOURCE -DDEBIAN -fno-strict-aliasing -pipe -fstack-protector -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O2 -g -DVERSION=\"1.96\" -DXS_VERSION=\"1.96\" -fPIC "-I/usr/lib/perl/5.14/CORE" PadWalker.c
[...]
chmod 755 blib/arch/auto/PadWalker/PadWalker.so
cp PadWalker.bs blib/arch/auto/PadWalker/PadWalker.bs
chmod 644 blib/arch/auto/PadWalker/PadWalker.bs
Manifying blib/man3/PadWalker.3pm
make test
PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/closure.t ... ok
t/dm.t ........ ok
[...]
Result: PASS
make install
Files found in blib/arch: installing files in blib/lib into architecture dependent library tree
Installing /home/david/perl5/man/man3/PadWalker.3pm
Appending installation info to /home/david/perl5/lib/perl5/x86_64-linux-gnu-thread-multi/perllocal.pod
| |
doc_2390
|
Timestamped by "CN=GlobalSign TSA for Advanced - G3 - 001-02, O=GMO GlobalSign K.K., C=JP" on Mo Apr 10 11:48:34 UTC 2017
Timestamp digest algorithm: SHA-256
Timestamp signature algorithm: SHA256withRSA, 2048-bit key
I already found out that the SHA-256 at the timestamp digest algoirthm and the SHA256withRSA at the timestamp signature algorithm are causing problems when running the jar file on a system which java version is below 1.7.0_76 (jar file is treaded as unsigned).
Can somebody tell me from which java versions on these two algorithms are supported at the timestamp digest and at the timestamp signature?
A: Java version below 1.7.0_76 not supporting SHA-256 for timestamping caused by https://bugs.openjdk.java.net/browse/JDK-8049480
(The fix included in 1.7.0_76 http://www.oracle.com/technetwork/java/javase/2col/7u76-bugfixes-2389098.html)
From "Oracle JRE and JDK Cryptographic Roadmap", SHA-1 still not be planned to disable on code signing.
So I think the best choice (to support old Java version) for now is using SHA-1 as Timestamping algorithm. (Use below 8u101, 7u111 for signing OR Use the -tsadigestalg option on 8u101, 7u111 or above)
I have tested jar file signed with
Digest algorithm: SHA-256
Signature algorithm: SHA256withRSA, 2048-bit key
Timestamp digest algorithm: SHA-1
Timestamp signature algorithm: SHA1withRSA, 2048-bit key
work fine with Java 7, 8, 9(ea+174)
A: One solution would be to just not time-stamp the jar file.
Waiting for some better recommendation...
| |
doc_2391
|
int main() {
char str1[127];
char str2[127];
int result;
int option = 0;
while (option < 1 || option > 4)
{
printoptions();
scanf("%d", &option);
switch (option)
{
case 1:
printf("Please enter first string: ");
gets(str1);
printf("Please enter second string: ");
gets(str2);
// bla bla
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
break;
}
}
printf("\nPress any key to continue");
getch();
return 0;
}
So my problem here is that after the user select the option 1 i can see this output:
Please enter first string: Please enter second string:
Why this is happening ?
| |
doc_2392
|
.box {
width: 300px;
height: 300px;
background-color: green;
}
.link:hover ~ .box{
transform: scale(1.1);
}
<div class="box" src=""></div>
<a class="link" href="#">
<p class="projectTitles">link</p>
</a>
as you can see, it doesn't work.
| |
doc_2393
|
python manage.py runserver 192.168.0.1:8000
everything works fine. That is, I delete the row, the table refreshes, and the deleted row is not displayed.
This is a summary of the HTTP calls:
// An initial GET command to populate the table
GET /myapp/get_list (returns a list to display)
// I now select a row and delete it which causes this POST to fire
POST /myapp/delete (deletes a row from the list)
// After the POST the code automatically follows up with a GET to refresh the table
GET /myapp/get_list (returns a list to display)
The problem is when I use nginx/gunicorn the second GET call returns the same list as the first GET including the row that I know has been deleted from the backend database.
I'm not sure it's a caching problem either because this is the response header I get from the first GET:
Date Fri, 23 Dec 2011 15:04:16 GMT
Last-Modified Fri, 23 Dec 2011 15:04:16 GMT
Server nginx/0.7.65
Vary Cookie
Content-Type application/javascript
Cache-Control max-age=0
Expires Fri, 23 Dec 2011 15:04:16 GMT
A: The problem can be solved also by sending an added parameter to the server so that the browser doesn't cache the call. With jQuery you can simply use:
$.ajaxSetup({ cache: false});
Otherwise you must creat manually the parameter. Usually you create a timestamp
var nocache = new Date().getTime();
//send nocache as a parameter so that the browser thinks it's a new call
A: You can use Django's add_never_cache_headers or never_cache decorator to tell the browser not to cache given request. Documentation is here. I thinks it's cleaner solution than forcing the cache off in the javascript.
from django.utils.cache import add_never_cache_headers
def your_view(request):
(...)
add_never_cache_headers(response)
return response
from django.views.decorators.cache import never_cache
@never_cache
def your_other_view(request):
(...)
A: try this
oTable.fnDeleteRow( anSelected, null, true );
and b.t.w what version of datatables do you use?
A: I fixed the problem by changing
GET /myapp/get_list
to
POST /myapp/get_list
After doing this, I no longer get a cached response.
| |
doc_2394
|
I wrote a simple "touch me" application where it says 'touched me X times' where X increments for each click.
Suppose I change the code from touchCount++ to touchCount+=2 in my Java source code. Is there a way to make the android emulator quickly incorporate this change into the code without restarting the emulator altogether?
A: You don't have to restart the emulator every-time you want to update your code. that would be a painful process and a true time killer.
just use debug button. to reupload your apk to the emulator.
take a look here for more about android emulator usage :Emulator usage
A: No, you need to run the program again so it can rebuild it. Besides, you wouldn't really want to do this. While it may seem like it would make it easier, a change in one part of your program could effect other parts that you didn't realize then you would have to go back and figure out which change you made that created the new problem.
Also, just a tip, I would suggest getting a real device to test on. It is much more efficient and I would say accurate. Depending on what you are doing, invest in a cheap Android device that you can test on for now or use your phone if that's an option.
Edit
In case this was the issue, I certainly wasn't suggesting that the emulator would need to be restarted each time. This is why I said "you need to run the program again".
A: You can keep the emulator running in the background. just press the back button to exit out of the program that was running on it to get back to the emulators home screen. Do not close the emulator. Then when you rebuild your app with the new code it should start up the newer version on the emulator.
A: I've had troubles where re-running the application would launch a new instance instead of re-using an existing, open emulator. The way I've solved this is to have it ask me every time which prevents new ones from launching.
To allow Eclipse to prompt you:
*
*Open the Run menu > Run configurations
*Within the new window, double click Android Application
*
*This creates a new run configuration
*Open the Target tab
*Select Always prompt to pick device
*Click Apply
*Click Close
Launch a new emulator the first time and leave it open.
Now the next time you run your application, it will ask you to start a new emulator or use one that is already open. Choose the one that is already open.
This also has the added benefit of allowing you to choose different AVD versions to test your app if you have multiple versions of emulators with different versions of Android.
Also you are able to plug in your phone to your computer via USB and it will appear in this list as well.
I've found this to speed up testing dramatically for me.
| |
doc_2395
|
[{"event":"open","email":"[email protected]","timestamp":1414435811,"category":["Newsletter"],"newsletter":{"newsletter_user_list_id":"18177422","newsletter_id":"3318683","newsletter_send_id":"3470425"}}]
[{"event":"open","email":"[email protected]","timestamp":1414435811,"category":["Newsletter"],"newsletter":{"newsletter_user_list_id":"18177422","newsletter_id":"3318683","newsletter_send_id":"3470425"}}]
And I want to read this file and update them into my database. I tried to put together snippets from around the web but it's not really working... I (think I) am having trouble figuring out how to read multiple arrays.
[{"event":"open","email":"[email protected]","timestamp":1414435811,"category":["Newsletter"],"newsletter":{"newsletter_user_list_id":"18177422","newsletter_id":"3318683","newsletter_send_id":"3470425"}]
To work with the example given above, when webhook.log file is only filled with the first part of the Json file, it works correctly and outputs: open myemail@email 10/27/2014 01:50:11. When I try to read more than one of the arrays, it gives me :Uncaught exception 'InvalidArgumentException' with message 'Passed variable is not an array or object, using empty array instead.' And since $json outputs the entire file when prompted, I am assuming "json_decode($json, TRUE)" is not doing its job. I am new to this and need some help... Thanks!
$filename = "webhook.log";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
$json = file_get_contents($filename);
fclose($handle);
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
// echo "$key:\n";
}
else {
if ($key!=Newsletter){
// echo "$key => $val\n";
if ($key==event){
$status=$val;
echo $status;
}
if ($key==email){
$email=$val;
echo $email;
}
if ($key==timestamp){
$date=date('m/d/Y h:i:s', $val);
echo $date;
}
}
}
}
A: The file you have provided as an example is not a valid JSON string. That is kind of a hard-stop.
You can confirm the in-validity of the JSON string here:
Parse error on line 15:
...5" } }][ { "eve
--------------------^
Expecting 'EOF', '}', ',', ']'
What this is pointing out, specifically, is the butting of your arrays:
[... array data ...]
[... another array ...]
This is not correct syntax. It is possible to decode multiple JSON arrays, but they would have to be housed in a parent container, and have a valid deliminator between them:
[
[... array data ...],
[... another array ...]
]
Where [ ... ] is the parent array, and the , is separating them. This will provide you with an array of arrays.
Unfortunately, there is no way to parse the JSON string to make what you have behave correctly. Regex is not the solution here, well, not a simple Regex anyway. See if you can get the data in the correct form. OR, if you get the data from two different places/calls, and write it to the file in the first place yourself, write it in the correct form.
If you are going to have a file filled with JSON Arrays, that you want to write to incrementally and read out as an Array of Arrays, try writing them as you have here, but with a , separating them. When you read them out, simply wrap them with [ ... ] and decode. This should give you expected results:
Write one to empty file:
[... json array 1 ...]
Write another (add a coma to the end of the existing file and append the JSON):
[... json array 1 ...],
[... json array 2 ...]
Read exactly that into a PHP string, wrapped in [ ... ]:
$file_string = $...; // the above
$json_string = "[$file_string]"; // now valid
// decode
That should do it for you.
| |
doc_2396
|
this.behaviour.trembling.start(with many args...)
and create a function in my class called
startTrembling(with the same many args...)
which simply calls the first function passing the args. Something like this:
startTrembling(arg1, arg2, arg3, arg4, ...) {
this.behaviour.trembling.start(arg1, arg2, arg3, arg4, ...); }
The issue is that if I change an argument in the first function I also have to change it in the second one. I was just wondering if there is a way to simply rename the first function, using direclty its parameters.
Thanks in advance!
A: You can use the arguments object combined with the spread operator:
Here, arguments will contain every argument from the parent function, all you have to do is spread those arguments.
startTrembling(arg1, arg2, arg3, arg4, ...) {
this.behaviour.trembling.start(...arguments);
}
A: Assuming you're not using arrow functions:
You can use spread operator over the implicit arguments object
function startTrembling() {
this.behaviour.trembling.start(...arguments);
}
| |
doc_2397
|
Can someone help me out please?
<nav>
<div class="logo">
<h4>The Logo</h4>
</div>
<ul class="nav-links">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Work</a></li>
<li><a href="#">Projects</a></li>
</ul>
<div class="burger">
<div class="line1"></div>
<div class="line2"></div>
<div class="line3"></div>
</div>
</nav>
Codepen
A: You can use the following as a starter. Essentially you add a click handler to the navlink a tags and check to see if the nav is currently out by looking for the appropriate nav-active class. If it is found, then reverse the animations by removing the relevant classes you added to expand the menu.
const links = document.querySelectorAll(".nav-links li a");
links.forEach(link => {
link.addEventListener(`click`, () => {
if(nav.classList.contains('nav-active')) {
nav.classList.remove(`nav-active`);
burger.classList.remove(`toggle`);
navLinks.forEach((link, index) => {
if (link.style.animation) {
link.style.animation = ``;
} else {
link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 +
0.3}s`;
}
});
}
});
});
The complete JS from your codepen:
const navSlide = () => {
const burger = document.querySelector(`.burger`);
const nav = document.querySelector(`.nav-links`);
const navLinks = document.querySelectorAll(".nav-links li");
const links = document.querySelectorAll(".nav-links li a");
links.forEach(link => {
link.addEventListener(`click`, () => {
if(nav.classList.contains('nav-active')) {
nav.classList.remove(`nav-active`);
burger.classList.remove(`toggle`);
navLinks.forEach((link, index) => {
if (link.style.animation) {
link.style.animation = ``;
} else {
link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 +
0.3}s`;
}
});
}
});
});
// Nav animation
burger.addEventListener(`click`, () => {
nav.classList.toggle(`nav-active`);
// Links animation
navLinks.forEach((link, index) => {
if (link.style.animation) {
link.style.animation = ``;
} else {
link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 +
0.3}s`;
}
});
// Burger animation
burger.classList.toggle(`toggle`);
});
};
navSlide();
| |
doc_2398
|
What options and preferences should I use for preforming this task?
A: You should be able to git clone the https://github.com/angular/angular.git repository.
Navigate to the aio file and install the modules with yarn.
| |
doc_2399
|
My question is how can I load and run our JS on an external page and ignore / run before any existing JS errors on the given page.
Example : Our snippet is within the footer of the customers page. They release an update to one of their JS scripts and they fat finger some code and it breaks. Now our JS code will not load.
What is the best way to handle this?
A: Use a separate <script> element for your script. Each script will run independently (although they will do so in a shared environment).
If you are depending on their script running successfully (e.g. to provide you with functions or elements in the DOM), then you need to program defensively and test for things you depend on before using them. How you handle those errors is up to you, you could substitute your own replacements, throw your own error, and so on.
A: You can't. If the browser has thrown an error earlier, it will never get to your code. The best you can do is putting a <noscript> tag in to explain that something went wrong.
If you get the customer to put your script tag in the head (before their code) and mark it as async, it might still run, but I wouldn't depend on it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.