text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Text size Epson TM-H5000II
I'm trying to reduce the size of the text, according to the manual i need to use the ESC ! 1 (https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=23) but i dont know how to pass it to java code, i try define a bite and use decimal, hex and ASCII but doesnt work.
public class JavaPrinter implements PrinterApi {
private Logger logger = LogManager.getLogger(JavaPrinter.class);
PrintService printService;
boolean isFile = false;
String printerName = null;
PrintStream prnStr;
private PipedInputStream pipe;
PipedOutputStream dataOutput;
Doc mydoc;
byte[] widthNormal = { 0x1b, '!', '1' };
@Override
public void setNormal() {
if (isFile)
return;
try {
prnStr.write(widthNormal);
} catch (IOException e) {
throw new DeviceServerRuntimeException("", e);
}
}
Above is part of the code i write, i appreciate any advice, help! THX
A:
You need to use 1 as a number with the ESC ! command to change from the larger Font A to the smaller Font B in ESC/POS.
You also need to follow it with some text and a newline, which I can't see in your example. A self-contained Java example would look like this:
import java.io.FileOutputStream;
import java.io.IOException;
class FontChangeDemo {
public static void main(String[] argv) throws IOException {
byte[] reset = {0x1b, '@'};
byte[] fontA = {0x1b, '!', 0x00};
byte[] fontB = {0x1b, '!', 0x01};
try(FileOutputStream outp = new FileOutputStream("/dev/usb/lp0")) {
outp.write(reset);
outp.write("Font A\n".getBytes());
outp.write(fontB);
outp.write("Font B\n".getBytes());
outp.write(fontA);
outp.write("Font A again\n".getBytes());
}
}
}
Which displays this on a TM-T20II:
This assumes that your setup is otherwise functioning, and is capable of shipping binary data to your printer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Moving multiple objects at once in three.js
I am trying to move multiple balls at once in three.js. I made a function that creates a ball and created three balls using it. Afterwards I created a function that moves balls and it works for one ball but whenever I try to move them all at once it doesn't work. Any help would be much appreciated.
Here is the code:
ball function:
function Ball(valuex, valuey, valuez, ballname, color)
{
var balMaterial, balGeometry, balMesh;
balMaterial = new THREE.MeshLambertMaterial({ color: color});
balGeometry = new THREE.SphereGeometry(0.3,50,50);
balMesh = new THREE.Mesh(balGeometry, balMaterial);
balMesh.position.set(valuex,valuey,valuez);
balMesh.name = ballname;
balMesh.ballDirection = new THREE.Vector3();
balMesh.ballDirection.x = -5;
balMesh.ballDirection.z = 1;
balMesh.ballDirection.normalize();
balMesh.moveSpeed = 25;
scene.add(balMesh);
}
move balls:
function moveBalls (ball) {
var tempbal = scene.getObjectByName(ball);
var ballDirection = tempbal.ballDirection;
tempbal.position.add(speed.copy(ballDirection).multiplyScalar(clock.getDelta() * tempbal.moveSpeed));
if (tempbal.position.x < -4.7) {
ballDirection.x = Math.abs(ballDirection.x);
}
if (tempbal.position.x > 4.7) {
ballDirection.x = -Math.abs(ballDirection.x);
}
if (tempbal.position.z > 12.2) {
ballDirection.z = -Math.abs(ballDirection.z);
}
if (tempbal.position.z < -12.2) {
ballDirection.z = Math.abs(ballDirection.z);
}
if (tempbal.moveSpeed > 0)
{
tempbal.moveSpeed = tempbal.moveSpeed - 0.002;
}
}
Create balls:
Ball(0,4.5,0, "ball1", 0xffffff);
Ball(2,4.5,0, "ball2", 0xffffff);
Ball(0,4.5,6, "ball3", 0xff0000);
Animate Scene:
function animateScene()
{
moveBalls("ball1");
moveBalls("ball2");
moveBalls("ball3");
requestAnimationFrame(animateScene);
renderer.render(scene, camera);
}
PS: I am new here and this is my first post so if I did anything wrong in this post please tell me so I can learn from it.
A:
The function clock.getDelta() returns the seconds passed since the last call to clock.getDelta() which means only your first ball may move. Indeed, the first ball calls getDelta() (which returns something greater than 0). In the same frame (meaning approximately at the same time), you call clock.getDelta() for the 2nd ball, which returns 0. The same happens to the 3rd ball.
Try to do the following :
function moveBalls (ball, deltaTime) {
var tempbal = scene.getObjectByName(ball);
var ballDirection = tempbal.ballDirection;
tempbal.position.add(speed.copy(ballDirection).multiplyScalar(deltaTime
* tempbal.moveSpeed));
if (tempbal.position.x < -4.7) {
ballDirection.x = Math.abs(ballDirection.x);
}
if (tempbal.position.x > 4.7) {
ballDirection.x = -Math.abs(ballDirection.x);
}
if (tempbal.position.z > 12.2) {
ballDirection.z = -Math.abs(ballDirection.z);
}
if (tempbal.position.z < -12.2) {
ballDirection.z = Math.abs(ballDirection.z);
}
if (tempbal.moveSpeed > 0)
{
tempbal.moveSpeed = tempbal.moveSpeed - 0.002;
}
}
// ...
function animateScene()
{
var deltaTime = clock.getDelta() ;
moveBalls("ball1", deltaTime);
moveBalls("ball2", deltaTime);
moveBalls("ball3", deltaTime);
requestAnimationFrame(animateScene);
renderer.render(scene, camera);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
DynDNS configuration - second to last packet is timed out during tracert
I have a NAS in a separate location which I connect into through a DynDNS domain I got for it. When I tracert to that DynDNS name, the following comes up:
1 3 ms 2 ms <1 ms Wireless_Broadband_Router.home [192.168.1.1]
2 4 ms 4 ms 4 ms L***.CITY-VFTTP-***.verizon-gni.net [**.***.**.***]
3 5 ms 11 ms 11 ms G*-*-*-*.CITY-LCR-**.verizon-gni.net [***.***.***.***]
4 8 ms 5 ms 5 ms so-*-*-*-*.******-BB-****.verizon-gni.net [***.***.***.***]
5 22 ms 31 ms 23 ms P**-0-0.OTHERCITY-LCR-**.verizon-gni.net [***.***.***.***]
6 * * * Request timed out.
7 24 ms 21 ms 21 ms pool-***-**-***-***.othercity.fios.verizon.net [***.***.***.***]
As you can guess, the cities aren't far and the connection is all through Verizon fios. What I'm concerned about is the 6th line (which I haven't changed at all). Is that supposed to happen? Is there some way I can not have it time out and have a faster connection?
Thanks!
A:
A tracert sends a packet that will expire at each point in the path to the destination. When a router receives a packet that has expired (TTL goes to zero) it should send an ICMP packet back to the source to let it know that the packet expired.
Tracert measures the time between the sending packet and the ICMP notification to work out the latency for each hop.
However, there is no guarantee that the ICMP packet will be sent. Firewalls are generally configured to silently drop any packet targetted at them, and many routers are configured to not send ICMP packets in this scenario.
The hop you are seeing no response from is configured in this way. It is perfectly normal and has no bearing on your connection speed. Tracert would indicate an issue if you had no responses beyond a certain point in the path. You are getting a 21ms response from the next hop after the one that doesn't respond, which is pretty good latency.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery show hidden content to a particular div on click on li element
I have some question regarding showing hidden content in a particular place regarding the context.
So I have here this layout:
<div class="col-md-12">
<div style="display:table; margin:auto; width:470px; height:470px; border:1px dashed;">
<br />
<div id="ShowPhotoContext" style="margin:auto;">
Here should come hidden content from li element
</div>
</div>
<br />
<div id="slider1" style="margin:auto;">
<div class="thumbelina-but horiz left">˂</div>
<ul class="menu">
<li> Click me
<div class="caption" id="comment_id1" style="display:none;">
<p>Some comments to display</p>
<div class="btn-group">
<ul class="dropdown-menu" role="menu">
<li> First menu </li>
<li> Second menu </li>
</ul>
</div>
</div>
</li>
</ul>
<div class="thumbelina-but horiz right">˃</div>
</div>
</div>
So I have here a list of menu "Click me" when you click on this li element, the hidden content in li, caption should be made visible in the ShowPhotoContext div above.
How can I do that with JQuery?
A:
Use:
$(document).on('click','.menu>li',function(){
$('#ShowPhotoContext').html($(this).find('div.caption').show())
});
Working Fiddle
A:
$("li").click(function(){
$("#ShowPhotoContext").html($(this).find(".caption").show());
});
Could you try that?
To duplicate your content to the new div try this:
$("li").click(function(){
$("#ShowPhotoContext").html($(this).find(".caption").show().clone());
$(this).find(".caption").hide();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Cache Memory Blocks Organization
I am not able to understand how exactly the cache is organized in the following scenario.
The cache size is 256 bytes. The cache line size is 8 bytes. All variables are 4 bytes. Assume that an array A[1024] is stored in memory locations 0-4095. Suppose if we are using fully associative mapping technique, how is the array mapped to this particular cache ? Consider that the cache is initially empty and we use LRU algorithm for replacement. During each replacement, an entire line of cache is replaced.
Initial analysis :
There will be 32 cache blocks each with 8 bytes length. But the variables to be stored in these locations is only 4 bytes long. I am not able to take this analysis any further as to how these array elements are mapped to the 32 cache blocks.
A:
Let's assume it's accessed sequentially:
for (int i=0; i<1024; ++i)
read(A[i]);
In that case, you'll fill the first 64 elements (A[0] through A[63]) into the 32 cache blocks in adjacent pairs like MSalters said.
The next access would have to kick out the least recently used line, which, since you access the array in sequential order is A[64]. It would have to pick a victim to kick out, and since you're using LRU that would be the first block (way 0). You therefore replace A[0] and A[1] with A[64] and A[65] and so on, so in general you'll have element i mapped into way floor(i/2)%32.
Now computing the hit rate requires an additional assumption - each memory line fetched is the size of a full block (8 bytes), since you can't fill half blocks (actually there are ways using mask bits, but let's assume the simple case). We therefore get each second element "for free" - fetching A[0] would also fetch A[1] and so on. In theory this means that the hit rate could be 50% (miss even elements, hit odds, in reality most CPUs would perform the accesses in parallel so you won't really have that hit rate, but let's say the accesses are serialized here).
Note that each new block fetched after the first 64 elements would have to evict a block from the cache, if processing the elements also modifies them you'll have to write them back too.
| {
"pile_set_name": "StackExchange"
} |
Q:
.append something that is .load -ed with jQuery
I have a webpage like:
<html>
<head>
. . .
</head>
<body>
<div id="wrapper">
<p>Lots of content here!</p>
</div>
</body>
</html>
I also have an external file like this:
<div id="more-stuff"><p>Even more content!</p></div>
What I want is for to have a webpage like this:
<html>
<head>
. . .
</head>
<body>
<div id="wrapper">
<p>Lots of content here!</p>
<div id="more-stuff"><p>Even more content!</p></div>
</div>
</body>
</html>
Using jQuery. My guess is something like this:
$(document).ready(function(){
$('#wrapper').append.load('/external.htm');
});
But it won't work and I can't seem to find a good solution.
A:
Try something like this:
$(document).ready(function(){
$.get('/external.htm', function(data) {
$('#wrapper').append(data);
});
});
It tells jQuery to request the html file, and then to run the callback (which in turn appends the data returned by the request) when it is ready.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I set the colour of the UINavigationItem in the UINavigationController added via storyboard?
I have a setup in which I am using storyboards to create the structure of my app. I make use of a UINavigationController, however I want to change the colour of the UINavigationItem from the default blue that apple assigns. Please can someone advise on where to do this? I looked in IB but the option is not shown. I have also considered setting it in one of my classes however I'm not sure where, since the UINavigationController is not initialized manually.
Please can someone offer some advice?
A:
You could use UIAppearance, as following
in your appdelegate didFinishLaunchingWithOptions add the following line
[[UINavigationBar appearance] setTintColor:[UIColor greenColor]];
This will change the color of the navigation bar to green
| {
"pile_set_name": "StackExchange"
} |
Q:
WCF hosting and port forward issue
I am beginner for WCF technology. So I create a simple wcf service hello application. It is working fine in my own network but when I host it one another machine out of my network then my wcf client is not being able to connect wcf service. I host my wcf on a machine which has static IP but still no luck. I searched Google and came to know that I need to forward port from that machine router, but unfortunately I have no access to the router of that machine. So please tell me how to handle this situation. Tell me what is short cut way as a result my client wcf can connect wcf server apps.
I am familiar with web service. When we host web service in remote machine then we can connect web service from any remote machine. This kind of port forwarding problem was not there.
1) I host my wcf service in windows application on remote machine.windows application is running along with wcf service but client not being able to connect it. If I host wcf service in IIS of remote machine then also do I need to forward port on remote machine?
My concept is not clear regarding wcf hosting. So please tell me when I need to forward port for wcf service.
2) Do I need to forward port when I host wcf service in win application or win service?
3) Do I need to forward port also when I host wcf service in IIS?
4) Is there any way that when wcf service run on remote machine first time then routine will be called from my win application which will forward port programmatically.
Please discuss my all points in detail, thanks.
A:
You need IIS server (web server) to host WCF service. Just like you can open a website from the internet, you need to be able to open a WCF service. If it is being hosted in HTTP, IIS server should do. It needs its own address and port. You can also use TCP connection in the WCF. First of all, you need a webserver and add a sample webpage to that server and view that webpage from your end and then deploy the service to the IIS server and configure it. You need access to that server to configure start/restart the WCF service. It is just like a webpage.
It should work like http://somewebsiteaddress234234.com:234242344/YourServiceName1.svc
http://address:port/servicename.svc
| {
"pile_set_name": "StackExchange"
} |
Q:
Microsoft Dynamics CRM 2013 Plugin - There is no active transaction error
I have been struggling with a an error in a plugin for MS Dynamics CRM Online. (see below).
It appears to happen at random times, but more likely to occur when the activity is high.
I have verified and there are no try/catch-continue issues as the exception suggests.
And that there are no member references to the OrganizationService Kept as this post suggests:
https://community.dynamics.com/crm/f/117/t/138785.aspx
Does anyone know what is causing the issue, or how to get around it?
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220911</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>There is no active transaction. This error is usually caused by custom plug-ins that ignore errors from service calls and continue processing.</Message>
<Timestamp>2014-09-10T00:30:02.6905225Z</Timestamp>
<InnerFault>
<ErrorCode>-2147220911</ErrorCode>
<ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>There is no active transaction. This error is usually caused by custom plug-ins that ignore errors from service calls and continue processing.</Message>
<Timestamp>2014-09-10T00:30:02.6905225Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText i:nil="true" />
</InnerFault>
<TraceText>
A:
BlueSam was really close, it turns out it was not our plugins that were causing the issue, it was Microsoft's ActivityFeeds plugins.
After disabling the ActivityFeeds.Plugins.CaseCreate: Create of case for account and Create of case for contact, we have not gotten any more "There is no active transaction" issues.
I hope this helps someone.
| {
"pile_set_name": "StackExchange"
} |
Q:
android textView.setText() gives me null pointer exception
I've create a custom adapter to put images one my listView but is giving me a null pointer exception in my textView.setText(text).
this is the part when i get exception my adapter :
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageFileView);
TextView textView = (TextView) rowView.findViewById(R.id.fileName);
int pos = position+4;
String name = Names[pos];
String extFile = Names[pos].substring(Names[pos].lastIndexOf(".")+1);
String uri = "drawable/"+extFile+".png";
textView.setText(name);
Uri imgUri=Uri.parse(uri);
imageView.setImageURI(imgUri);
return rowView;
}
this is my LogCat when a i have exception:
06-14 12:15:04.616: E/AndroidRuntime(678): FATAL EXCEPTION: main
06-14 12:15:04.616: E/AndroidRuntime(678): java.lang.NullPointerException
06-14 12:15:04.616: E/AndroidRuntime(678): at com.example.poc_cubbyhole.ItemAdapter.getView(ItemAdapter.java:59)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.AbsListView.obtainView(AbsListView.java:1430)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.ListView.makeAndAddView(ListView.java:1745)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.ListView.fillSpecific(ListView.java:1290)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.ListView.layoutChildren(ListView.java:1588)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.AbsListView.onLayout(AbsListView.java:1260)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.view.View.layout(View.java:7175)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.view.View.layout(View.java:7175)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.view.View.layout(View.java:7175)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.LinearLayout.onLayout(LinearLayout.java:1047)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.view.View.layout(View.java:7175)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.view.View.layout(View.java:7175)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.view.ViewRoot.performTraversals(ViewRoot.java:1140)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.os.Handler.dispatchMessage(Handler.java:99)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.os.Looper.loop(Looper.java:123)
06-14 12:15:04.616: E/AndroidRuntime(678): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-14 12:15:04.616: E/AndroidRuntime(678): at java.lang.reflect.Method.invokeNative(Native Method)
06-14 12:15:04.616: E/AndroidRuntime(678): at java.lang.reflect.Method.invoke(Method.java:507)
06-14 12:15:04.616: E/AndroidRuntime(678): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-14 12:15:04.616: E/AndroidRuntime(678): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-14 12:15:04.616: E/AndroidRuntime(678): at dalvik.system.NativeStart.main(Native Method)
this is xml file that create items in my listView :
<ImageView
android:id="@+id/imageFileView"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="9dp"
android:layout_alignParentTop="true"/>
<TextView
android:layout_alignBottom="@+id/fileName"
android:layout_width="97dp"
android:layout_height="32dp"
android:id="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_marginLeft="66dp"
android:layout_alignParentRight="true"
android:gravity="center_vertical"/>
and this is my listView :
<com.example.poc_cubbyhole.widgets.PullToRefreshListView
android:id="@+id/list_files"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/button_upload"
android:layout_alignParentTop="true"
/>
i use a widget to change add the pull and refresh to my listView
A:
Change this
TextView textView = (TextView) rowView.findViewById(R.id.fileName);
to
TextView textView = (TextView) rowView.findViewById(R.id.textView);
in your getView method,Because your TextView Id is textView not fileName
| {
"pile_set_name": "StackExchange"
} |
Q:
Broken selection in a custom QAbstractItemModel and QTableView
I'm working on a QTableView control with lazy loading.
I have thousands of records it has to display and it used to lag badly when I used a simple QListWidget approach.
Now I use QAbstractItemModel with the following data method:
QVariant MyModel::data(const QModelIndex & index, int role) const
{
int col = index.column();
int row = index.row();
if (role == Qt::DecorationRole && col == 0)
{
return getIcon(row); // icons in the first column
}
else if (role == Qt::DisplayRole && col == 1)
{
return getText(row); // text in the second column
}
else
{
return QVariant();
}
}
The resulting table view works great: it is fast and smooth.
There's one major problem though: the selection is completely broken.
When I select an item/items, they are not highlighted in blue right away, I need to scroll the table so that it repaints and shows blue background. (I'm using Windows 7.)
Also I don't see the dotted rectangle when selecting items.
I checked, the selection model of the table view is not null. Also I looked at some other model implementations in Qt, they have similar data method, but there's no selection problems with them.
I also tried subclassing from QAbstractTableItem and QAbstractListItem, nothing.
Appreciate your help here.
A:
Sorry about this silly question...
I solved this by removing the following line:
tableView->setRootIndex(model->index(0, 0));
| {
"pile_set_name": "StackExchange"
} |
Q:
Inserting JSON data into MySQL
I have a solution with PHP as server-side, Vue JS for front-end and MySQL as DB.
The UI bundles data as JSON and posts it to PHP through axios, and PHP in turn will decode the JSON and inserts into MySQL.
Here is my PHP code (omitting the other lines like connecting etc.):
$data = file_get_contents("php://input");
$jsonData = json_decode($data, true);
//echo var_dump($jsonData);
// Below is the jsonData as dumped
//[{"candidate_id":"SM_009","FirstName":"test","LastName":"dummy","DOB":"1990-06-05"}]
$tableName = 'profile';
foreach((array)$jsonData as $id=>$row) {
$insertPairs = array();
foreach ((array)$row as $key=>$val) {
$insertPairs[addslashes($key)] = addslashes($val);
}
$insertKeys = '`' . implode('`,`', array_keys($insertPairs)) . '`';
$insertVals = '"' . implode('","', array_values($insertPairs)) . '"';
$sql = "INSERT INTO `{$tableName}` ({$insertKeys}) VALUES ({$insertVals});" ;
//echo var_dump($sql);
$stmt = $con->prepare($sql);
$stmt->execute();
}
However, here is the actual insert statement generated, which is obviously wrong.
INSERT INTO `profile` (`0`) VALUES ("[{\"candidate_id\":\"SM_009\",\"FirstName\":\"test\",\"LastName\":\"dummy\",\"DOB\":\"1990-06-05\"}]");
Where am I doing wrong? Any help would be greatly appreciated..
Thanks
Note: When I use the same dumped jsondata as hardcoded string, it works.
$data ='[{"candidate_id":"SM_009","FirstName":"test","LastName":"dummy","DOB":"1990-06-12"}]';
//$data = file_get_contents("php://input");
...
Generated statement:
"INSERT INTO `profile` (`candidate_id`,`FirstName`,`LastName`,`DOB`) VALUES ("SM_009","test","dummy","1990-06-12");"
A:
The reason you are still receiving the json in your insert statement is because you decoded the first part of your json string and received the data array which still contains the json string inside of it. To resolve this just decode the $jsonData variable again like so:
<?php
$data = file_get_contents("php://input");
$jsonData = json_decode($data, true);
$jsonData = json_decode($jsonData['data'], true); //Decode the data as well
$tableName = 'profile';
foreach((array)$jsonData as $id => $row){
$insertPairs = array();
foreach ((array)$row as $key=>$val) {
$insertPairs[addslashes($key)] = addslashes($val);
}
$insertKeys = '`' . implode('`,`', array_keys($insertPairs)) . '`';
$insertVals = '"' . implode('","', array_values($insertPairs)) . '"';
$sql = "INSERT INTO `{$tableName}` ({$insertKeys}) VALUES ({$insertVals});" ;
$stmt = $con->prepare($sql);
$stmt->execute();
}
You can check out a working example here: https://ideone.com/i86iVP
| {
"pile_set_name": "StackExchange"
} |
Q:
Wrong x value for sensors when using for augmented reality
I use the following (assuming to be quite standard) code to retrieve the orientation of a tablet device for augmented reality purpose (so the back-camera should point a valid direction).
private Sensor mAccelerometer;
private Sensor mMagnetometer;
private float[] mLastAccelerometer = new float[3];
private boolean mLastAccelerometerSet = false;
private float[] mLastMagnetometer = new float[3];
private boolean mLastMagnetometerSet = false;
private Sensor mAccelerometer;
private Sensor mMagnetometer;
private float[] mLastAccelerometer = new float[3];
private boolean mLastAccelerometerSet = false;
private float[] mLastMagnetometer = new float[3];
private boolean mLastMagnetometerSet = false;
private float[] inR = new float[9];
private float[] mR = new float[9];
private float[] mOrientation = new float[3];
...
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
...
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
...
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_FASTEST);
...
public void onSensorChanged(SensorEvent event) {
synchronized (this) {
if (event.sensor == mAccelerometer) {
System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
mLastAccelerometerSet = true;
} else if (event.sensor == mMagnetometer) {
System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
mLastMagnetometerSet = true;
}
if (mLastAccelerometerSet && mLastMagnetometerSet && scene.camera() != null && mPlane1 != null) {
SensorManager.getRotationMatrix(inR, null, mLastAccelerometer, mLastMagnetometer);
SensorManager.remapCoordinateSystem(inR, SensorManager.AXIS_X, SensorManager.AXIS_Z, mR);
SensorManager.getOrientation(mR, mOrientation);
/* my code that handles mOrientation */
}
}
}
The problem is that this code works flawlessly on a Samsung Galaxy Tab 10.1 (P7500, first version). With the same code running on a Asus Transformer Pad Infinity (TF700), the first value mOrientation[0] only varies between +2.0 and +3.0 when rotating the tablet around myself (I would expect that it will go between 0 and 3.14).
Is there something wrong with the device or are there other variables that I overlooked?
A:
There must have been some error with the hardware of the Asus TF700. It's either in this specific version that we had or in the design of the device. With other Android devices the application worked as expected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filling google chart chartArea with a gradient
I've been exploring the features of google charts and now I'm trying to customize a scatter chart.
I got the following function:
function drawScatterChart(){
var data = google.visualization.arrayToDataTable([
['Chance', 'Impact'],
[ 5, 4],
[ 1, 2]
]);
var options = {
hAxis: {title: 'Chance', minValue: 0, maxValue: 5},
vAxis: {title: 'Impact', minValue: 0, maxValue: 5},
legend: 'none',
'chartArea' : { 'backgroundColor' : '#F4F4F4' }
};
var chart = new google.visualization.ScatterChart(document.getElementById('scatter_chart'));
chart.draw(data, options);
}
This succesfully changes the background color of only the chartArea to gray, which is great. But now I'd like to implement a gradient that goes from the left bottom to the top right of the chart and containing 3 colors (green to yellow to red).
Is there any way to hack this into the chart since I've been trying to find anything in the documentation and only could find some old documentation (namely: https://developers.google.com/chart/image/docs/chart_params) but couldn't find a way to implement this.
Thanks!
A:
This chart will be created using SVG.
In SVG gradients will be created via the <linearGradient/>-element.
Take a look at http://tutorials.jenkov.com/svg/svg-gradients.html to see how these elements look like.
What you can do:
When the chart has been drawn inject a <linearGradient/> into the <defs/> .
The styles may be set via CSS, but note: SVG has it's own style-properties, see: http://tutorials.jenkov.com/svg/svg-and-css.html
Demo:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(function() {
var container = document.getElementById('chart_div'),
data = google.visualization.arrayToDataTable([
['Chance', 'Impact'],
[ 5, 4],
[ 1, 2]
]),
options = {
hAxis: {title: 'Chance', minValue: 0, maxValue: 5},
vAxis: {title: 'Impact', minValue: 0, maxValue: 5},
legend: 'none'
},
chart = new google.visualization.ScatterChart(container,options),
createSVG = function(n,a,b){
var xmlns = "http://www.w3.org/2000/svg",
e = document.createElementNS (xmlns, n);
for(var k in a){
e.setAttributeNS (null, k,a[k]);
}
for(var k in b){
e.setAttribute (k,b[k]);
}
return e;
};
google.visualization.events.addListener(chart, 'ready', function(){
var gradient =createSVG('linearGradient',{
x1:0,y1:1,x2:1,y2:0
},{
id:'fx'
}
);
document.getElementById('chart_div')
.querySelector('svg>defs').appendChild(gradient);
gradient.appendChild(createSVG('stop',{offset:'0%'}));
gradient.appendChild(createSVG('stop',{offset:'50%'}));
gradient.appendChild(createSVG('stop',{offset:'100%'}));
});
chart.draw(data, options);
});
html,body,#chart_div{
height:100%;
margin:0;
padding:0;
}
#chart_div svg>g>rect {
fill: url(#fx) !important;
fill-opacity:1 !important;
}
#fx stop:nth-child(1){
stop-color: green;
}
#fx stop:nth-child(2){
stop-color: yellow;
}
#fx stop:nth-child(3){
stop-color: red;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
google assistant actions without voice input
I'm trying some home automation where the idea is that motion sensors detect a person in the room and the output from the sensors wakes up a Google Home device which starts talking to the person pro-actively. Is this even possible? Is there any way to trigger Google Assistant without speaking?
A:
This is not possible at the moment using the Google Home. If you were to use the Google Assistant SDK, you can use anything as a trigger for your own hardware.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHPMailer is sending with incorrect "date"
I have an issue with my code. All emails are sent with same date "31-mar-2017". here's the mail notification.
Return-Path: <[email protected]>
Received: from ip-172-31-29-190 (ec2-xx-xxx-xx.xx.ap-south-1.compute.amazonaws.com. [xx-xxx-xx.xx])
by smtp.googlemail.com with ESMTPSA id a81sm7358557pfe.32.2017.11.02.08.27.05
for <[email protected]>
(version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
Thu, 02 Nov 2017 08:27:06 -0700 (PDT)
Date: Fri, 31 Mar 2017 21:40:26 +0530
Can't figure out what the problem is... Appreciate your help.
Edit-1:
I have inherited this code. Following config is found:
defined('SMTP_HOST') ? null : define("SMTP_HOST", "ssl://smtp.googlemail.com");
defined('SMTP_PORT') ? null : define("SMTP_PORT", "465");
defined('SMTP_SECURE') ? null : define("SMTP_SECURE", "tls");
Edit-2:
Our implementation is similar to How to build an email queue with PHPmailer?. ie., all emails are written to a jobs table and then picked up for processing.
The issue is emails are not working on my local and Test servers. However, they work on Production :(
It's becoming a herculean task to figure out why these things are not working on local and Test servers when the sample code https://github.com/phpmailer/phpmailer works perfectly fine on both.
This issue need to be solved prior to looking to the original issue posted here. No emails in the mail queue. Any pointers??
A:
Well, the issue was not related to phpmailer or associated configuration.
Even setting the date_default_timezone_set('Asia/Kolkata') didn't help.
At the end, updating system clock and rebooting the server as per Setting the Time for Your Linux Instance fixed the incorrect date issue.
Regarding emails not working on Test Server, my predecessor used supervisord to handle these processes. I had to just start that daemon as it wasn't part of init.d.
Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does my Android Adapter not have the getActivity() method
Why does my Android Adapter not have the getActivity() method ? and yet many tutorials out there have access to the getActivity() method inside lets say recyclerview Adapters
I already tried passing the getActivity() from a fragment using the constructor but still does not accomplish what i want.
My Fragment that calls the Adapter
package layout;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.example.elm.login.Navigation;
import com.example.elm.login.R;
import com.example.elm.login.adapter.NotesAdapter;
import com.example.elm.login.model.Note;
import com.example.elm.login.services.note.UploadNote;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link NotesFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link NotesFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class NotesFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public List<Note> notes = new ArrayList<>();
private RecyclerView recyclerView;
public NotesAdapter notesAdapter;
public NotesFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment NotesFragment.
*/
// TODO: Rename and change types and number of parameters
public static NotesFragment newInstance(String param1, String param2) {
NotesFragment fragment = new NotesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
private UploadReceiver receiver;
private SyncReceiver syncReceiver;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_notes2, container, false);
//register broadcast receiver
IntentFilter filter = new IntentFilter(UploadNote.ACTION_RESP);
//filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new UploadReceiver();
getActivity().registerReceiver(receiver, filter);
IntentFilter intentFilter = new IntentFilter(SyncReceiver.SYNC_ACTION);
syncReceiver = new SyncReceiver();
getActivity().registerReceiver(syncReceiver, intentFilter);
recyclerView = (RecyclerView) view.findViewById(R.id.notes_recycler);
notes = Note.find(Note.class, null,null,null,"noteid DESC", null);
notesAdapter = new NotesAdapter(notes);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(notesAdapter);
return view;
//return inflater.inflate(R.layout.fragment_notes2, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
/* @Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
*/
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
@Override
public void onResume() {
super.onResume();
}
/**
* redraw the recycler -view --all of it
*/
public void addNew(Note note){
if (notesAdapter!=null){
notesAdapter.newData(note);
recyclerView.smoothScrollToPosition(0);
}
}
public void update(Note note){
if (notesAdapter!=null){
notesAdapter.updateItem(note);
}
}
/**
* receive broadcasts
*/
public class UploadReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.e("vane", "vane");
Bundle bundle = intent.getExtras();
String newNote = bundle.getString("note");
Gson gson = new Gson();
Type type = new TypeToken<Note>(){
}.getType();
Note note = gson.fromJson(newNote, type);
addNew(note);
}
}
public class SyncReceiver extends BroadcastReceiver{
public static final String SYNC_ACTION = "sync_action";
@Override
public void onReceive(Context context, Intent intent) {
Log.e("received_sync", "yes");
Bundle bundle = intent.getExtras();
String newNote = bundle.getString("note");
Gson gson = new Gson();
Type type = new TypeToken<Note>(){
}.getType();
Note note = gson.fromJson(newNote, type);
update(note);
}
}
}
and my Adapter: in which i cant declare an instance of getActivity method.
package com.example.elm.login.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bignerdranch.android.multiselector.ModalMultiSelectorCallback;
import com.bignerdranch.android.multiselector.MultiSelector;
import com.bignerdranch.android.multiselector.SwappingHolder;
import com.example.elm.login.FullNote;
import com.example.elm.login.Navigation;
import com.example.elm.login.R;
import com.example.elm.login.model.Note;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by elm on 7/17/17.
*/
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.myViewHolder> {
private Context context;
public List<Note> allnotes;
private MultiSelector multiSelector = new MultiSelector();
private ModalMultiSelectorCallback modalMultiSelectorCallback = new ModalMultiSelectorCallback(multiSelector) {
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
return super.onCreateActionMode(actionMode, menu);
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
};
public NotesAdapter(List<Note> allnotes) {
this.allnotes = allnotes;
}
@Override
public NotesAdapter.myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_note_card, parent, false);
return new myViewHolder(view);
}
@Override
public void onBindViewHolder(NotesAdapter.myViewHolder holder, int position) {
//context = holder
Note notes = allnotes.get(position);
holder.title.setText(notes.getTitle());
holder.note.setText(notes.getNote());
if (notes.getUploadflag()){
holder.imageView.setImageResource(R.mipmap.ic_cloud);
}else {
holder.imageView.setImageResource(R.mipmap.ic_cloud_done);
}
}
@Override
public int getItemCount() {
return allnotes.size();
}
public class myViewHolder extends SwappingHolder{
public TextView title, note;
public ImageView imageView;
public myViewHolder(View itemView) {
super(itemView, multiSelector);
title = (TextView) itemView.findViewById(R.id.card_title);
note = (TextView) itemView.findViewById(R.id.card_note);
imageView = (ImageView) itemView.findViewById(R.id.uploadstatus);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = getLayoutPosition();
Note note = allnotes.get(pos);
Intent intent = new Intent(v.getContext(), FullNote.class);
intent.putExtra("noteId", note.getId());
v.getContext().startActivity(intent);
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (!multiSelector.isSelectable()){
((AppCompatActivity) v.getContext()).startSupportActionMode(modalMultiSelectorCallback);
multiSelector.setSelectable(true);
multiSelector.setSelected(myViewHolder.this, true);
return true;
}
return false;
}
});
}
}
public void swapAll(List<Note> notes){
allnotes.clear();
allnotes.addAll(notes);
this.notifyDataSetChanged();
}
public void newData(Note note){
this.allnotes.add(0, note);
notifyItemInserted(0);
notifyItemRangeChanged(0, allnotes.size());
}
public void updateItem(Note note){
Log.e("atview", String.valueOf(note.getId()));
Note data = null;
for (Note n: allnotes){
Log.e("id", String.valueOf(n.getId()));
if (n.getId().equals(note.getId())){
Log.e("found", String.valueOf(allnotes.indexOf(n)));
int position = allnotes.indexOf(n);
allnotes.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, allnotes.size());
allnotes.add(position, note);
notifyItemInserted(position);
notifyItemRangeChanged(position, allnotes.size());
break;
}
}
}
public void removeItem(int position){
allnotes.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, allnotes.size());
}
}
A:
You can pass Context around to you adapter, but you cannot access the getActivity() method from an inner class.
Add a method, or place Context as a parameter in your constructor:
addContext(Context context);
When you initialize the adapter you can call your new method
myAdapter.addContext(MyActivity.this);
If you want to call activity specific methods (i.e. a refreshViews() method), you can check the class and use casting:
if (context.getClass().equals(MyActivity.class)) {
((MyActivity) context).refreshView();
}
Edit::
Be sure to clear your references to context when you are done with your adapter to avoid memory leaks.
A:
It doesn't have it because there is no use of Context internal to Adapter. Context is used when you need it for a specific app wide side effect or resource retrieval.
When you find a code piece which uses Context inside of an Adapter, you will notice it uses that Context for either creating a View, getting a resource from XML files (i.e strings.xml) or some factory which provides utility. Those code examples are written that way to provide clarity.
An actual Adapter implementor is expected to know those use cases and implement her own solution via either acquiring the Context from the instantiator of the Adapter or via coding her own indirection for the retrieved resource and/or utility.
One simple way to achieve that is to define an interface with a single method that returns a Context.
interface ContextProvider {
Context getContext();
}
Then whoever allocates a new Adapter of yours (i.e an Activity, a Fragment) can forward its Context via the provider interface.
// Your MyActivity.java or MyFragment.java
MyAdapter anAdapter = new MyAdapter(new ContextProvider {
@Override
public Context getContext() {
return getActivity(); // For fragments
return MyActivity.this; // For activities
}
});
// MyAdapter.java
class MyAdapter extends SomeAdapterFromSDK {
private final ContextProvider mContextProvider;
public MyAdapter(ContextProvider cp) {
mContextProvider = cp;
}
public void someAdapterMethod() {
Context c = mContextProvider.getContext();
// Use c as your context (i.e c.getString(R.string.message))
}
}
Huge disclaimer: Don't pass your Context directly like new Adapter(getActivity()). It will leak due to retaining it in a property when your app returns to home screen.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to avoid race condition with $http promises angular 1.5
I have a situation where I don't want one promise to complete until the other one (or potentially a few others) are complete. in this scenario, I have different payment options, and each time the user clicks a button, a payment is made... while the payments are made the user can also click delete. this is leading to weird race conditions where the delete is processed before the pay finishes. I don't want the delete to process/hit the database until the pay actions are complete. Here is the relevant code:
$ctrl.deletePayment = function(paymentRecord) {
PaymentsService.deletePaymentRequest($ctrl.paymentRecord.id, paymentRecord)
.then(updateTotal)
.catch(updateTotal);
}
$ctrl.payOff = function(dataItem) {
let payOffRecords = dataItem.payoffRecords;
PaymentsService.submitPaymentRequestViaPatch($ctrl.temporaryPaymentAdvice.id, payOffRecords)
.then(updateTotal)
.catch(updateTotal);
}
$ctrl.payAllInView = function(payOff) {
let paymentRecords = dataSource.map((rowItem) => {
return rowItem.payoffRecords;
});
if (paymentRecords.length > 0) {
PaymentsService.submitPaymentRequestViaPatch($ctrl.temporaryPaymentAdvice.id, paymentRecords)
.then(updateTotal)
.catch(updateTotal);
}
}
how can I prevent deletePayment from processing before until a payment action is complete? I was thinking of having a modal show up to block the UI, but was also wondering if there was an angular way to handle this async/race condition.
A:
You probably want to store the promise for reference and use $q.all(...) to ensure everything is complete before continuing. Something along the lines of:
let promises = [];
$ctrl.deletePayment = function(paymentRecord) {
$q.all(promises).then((values) => {
promises = [ PaymentsService.deletePaymentRequest(...)
.then(updateTemporaryPaymentAdviceTotal)
.catch(updateTemporaryPaymentAdviceTotal) ];
});
}
...each method would need to add its promise to the promises array when called.
| {
"pile_set_name": "StackExchange"
} |
Q:
Microsoft Cognitive API Image Search
Im trying to use the Microsoft API of Bing image described here
I only want to use the image insights to find similar images by sending a image at the body of the post request, as the doc says i can provide a url or the image.
The image is being captured by a phone camera and sent to the api, the idea is to end up getting similar image results.
At first i was getting a error saying the 'q' parameter was required, but i do not want to use a search query just the image.
So i changed the ContentType to "multipart/form-data" and used "/search?modulesRequested=similarimages"
This seems to do something as now i dont get any error, the api response is just a empty string so im really lost here...
Heres my code to send the request.
public async Task<string> GetImageInsights(byte[] image)
{
var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?modulesRequested=similarimages";
var response = await RequestHelper.MakePostRequest(uri, new string(Encoding.UTF8.GetChars(image)), key, "multipart/form-data");
var respString = await response.Content.ReadAsStringAsync();
return respString;
}
public static async Task<HttpResponseMessage> MakePostRequest(string uri, string body, string key, string contentType)
{
var client = new HttpClient();
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
// Request body
byte[] byteData = Encoding.UTF8.GetBytes(body);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return await client.PostAsync(uri, content);
}
}
Im using C# with Xamarin on Android
A:
For the service to work correctly, both a name and filename are required for the form part:
public async Task<string> GetImageInsights(byte[] image)
{
var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?modulesRequested=similarimages";
var response = await RequestHelper.MakePostRequest(uri, image, key);
var respString = await response.Content.ReadAsStringAsync();
return respString;
}
class RequestHelper
{
public static async Task<HttpResponseMessage> MakePostRequest(String uri, byte[] imageData, string key)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
var content = new MultipartFormDataContent();
content.Add(new ByteArrayContent(imageData), "image", "image.png");
return await client.PostAsync(uri, content);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
.NET : How do you remove a specific node from an XMLDocument using XPATH?
Using C#
How do you remove a specific node from an XMLDocument using XPATH?
A:
If you want to delete nodes, that are not direct children of the documents root, you can do this:
XmlDocument doc = new XmlDocument();
// ... fill or load the XML Document
XmlNode childNode = doc.SelectSingleNode("/rootnode/childnode/etc"); // apply your xpath here
childNode.ParentNode.RemoveChild(childNode);
A:
Here you go. ChildNodeName, could be just the node name or an XPath query.
XmlDocument doc = new XmlDocument();
// Load you XML Document
XmlNode childNode = doc.SelectSingleNode(childNodeName);
// Remove from the document
doc.RemoveChild(childNode);
There is a different way using Linq, but I guessed you were using .NET 2.0
A:
XPath can only select nodes from a document, not modify the document.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using MongooseJS to Changing Mongodb _id to BSON UUID for ref
I currently use MongooseJS to change "_id" for each of my collections to a BSON UUID. On top of this I use a virtual to "id" to convert "_id" to its string equivalent. It works pretty good and gives me the benefit of using a UUID for the "_id" and not store it as a string which wastes disk resources.
Here is a snippet of code to show how this is done
const uuid = require("uuid-mongodb");
require("mongoose-uuid2")(mongoose);
let schema_options = {
"id": false,
"toObject": {
"getters": true,
"virtuals": true
},
"toJSON": {
"getters": true,
"virtuals": true,
"transform"(doc, ret) {
delete ret._id;
}
} };
let schema = new Schema(
{
"_id": {
"type": UUID,
"default": uuid.v4,
"required": true
},
"code": {
"type": String,
"required": true,
"unique": true
},
"name": {
"type": String,
"required": true
}
},
schema_options);
schema.virtual("id").get(function() {
return uuid.from(this._id).toString();
});
schema.virtual("id").set(function(uuid_string) {
this._id = uuid.from(uuid_string);
});
However, if I add a "ref" to another collection as with
schema.add({
"test_references": {
"type": [
{
"type": mongoose.Types.UUID,
"ref": "test_references"
}
],
"required": true
}
});
I get a hash representation of the BSON UUID. Is there a way to make MongooseJS during a get operation to show these refs as UUID string representations
i.e. - I expect this "104e0f2e-3b54-405b-ba81-e87c5eb9f263" but get this "EE4PLjtUQFu6geh8XrnyYw=="
Note:: If this is the incorrect forum for this post, please let me know and I will move this to the correct forum immediately
A:
After some more research, I was able to apply a transform to the returned value.
This looks like the following:
this.schema.options.toJSON.transform = function(doc, ret, option) {
let items = [];
delete ret._id;
ret.items.forEach((item) => {
items.push(mongoose.uuid.from(item).toString());
});
ret.items = items;
return ret;
};
It is not ideal to look through all the items in the array but it is the best I could find in my research
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the difference?
Possible Duplicate:
String vs string in C#
What's the difference between string and String, if any?
They both seem to perform the same function, but the casing is different. So, there are only TWO things that are different (that I know of) and they are:
When spelled with a capital letter, the color of its text is Blue in VStudio.
Casing.
A:
string is a keyword which aliases type System.String. String is just a short name for type System.String, which is brought into your scope when you write using System;. Similarly, object is a keyword alias for System.Object, int is a keyword alias for System.Int32, and so on.
VS highlights keywords with blue, which is why string is blue, while String is not.
| {
"pile_set_name": "StackExchange"
} |
Q:
Menu system in c
I'm having serious trouble with my program it is supposed to provide a menu and do all the functions the code is pretty explanatory my problem is I only have visual studios which doesnt allow scanf and scanf_s and messes with things so I use online compilers but those are still iffy. Can any one help and give me some tips. I'm having trouble with the math and function to list accounts, some whiles are empty as well I wasn't sure if that was best to use. I'm relatively new to this forum. It also can't have struct and can only be in C :-(
#include <stdio.h>
char name[20];
float avail_bal;
void options();
void open();
void list();
void deposit();
void withdraw();
void exit();
int main(void)
{
char option;
while(1){
printf("****Banking System WELCOME****\n");
printf("Enter 1-5 of the following options: \n");
option = getchar();
scanf("%c\n", &option);
switch(option)
{
case '1': open();
break;
case '2': list();
break;
case '3': deposit();
break;
case '4': withdraw();
break;
case '5': return 0;
default: exit();
break;
}
}
return 0;
}
void options()
{
printf("1. Open Account\n");
printf("2. List Accounts\n");
printf("3. Deposit\n");
printf("4. Withdraw\n");
printf("5. Exit");
}
void open()
{
float avail_bal = 0;
char name[20];
int acc_num;
printf("Open new account(enter number 1-5)\n\n");
scanf("%d", &acc_num);
printf("Account number: %d\n");
printf("Available balance: %f\n");
}
void list()
{
}
void deposit()
{
float add;
int acc_num;
printf("Which count do you want to deposit money in?");
scanf(" %d", &acc_num);
printf("Amount to deposit: ");
scanf("%f", &add);
while()
{
}
}
void withdraw()
{
int acc_num;
float withdraw;
printf("Account to withdraw from: ");
scanf("%d", &acc_num);
printf("Amount to withdraw from account: ")
scanf("%f", &withdraw);
while()
{
printf("Current balance for account %d: %f ");
break;
} acc_num++
}
A:
The problem with scanf was interesting. Here is an example for how to do without (although you shouldn't) such that you can play with your code easier.
#include <stdio.h>
#include <stdlib.h>
// only 5 accounts possible
int accounts[5];
// each its balance
float avail_bal[5];
void options();
// open(P) is a standard Posix function
void bopen();
void list();
void deposit();
void withdraw();
// exit(3) is a standard C function
void pexit();
int main(void)
{
char option;
while (1) {
printf("****Banking System WELCOME****\n");
printf("Enter 1-5 of the following options: \n");
options();
option = getc(stdin);
// swallow the '\n'
getc(stdin);
switch (option) {
case '1':
bopen();
break;
case '2':
list();
break;
case '3':
deposit();
break;
case '4':
withdraw();
break;
case '5':
pexit();
default:
pexit();
}
}
return 0;
}
void options()
{
puts("1. Open Account");
puts("2. List Accounts");
puts("3. Deposit");
puts("4. Withdraw");
puts("5. Exit");
}
void bopen()
{
int acc_num;
char c;
puts("Open new account(enter number 1-5)");
c = getc(stdin);
getc(stdin);
// assuming ASCII here where the digits 0-9 start at place 48 in the table
acc_num = (int) c - 48;
if (acc_num < 1 || acc_num > 5) {
puts("Account number must be between one and five inclusive");
return;
}
if (accounts[acc_num] != 0) {
printf("Account number %d is already taken\n", acc_num);
return;
}
// mark account as taken
accounts[acc_num] = 1;
// spend a fiver for the new client for being a new client
avail_bal[acc_num] = 5.0;
printf("Account number: %d\n", acc_num);
printf("Available balance: %f\n", avail_bal[acc_num]);
}
void list()
{
int i;
for (i = 0; i < 5; i++) {
if (accounts[i] != 0) {
printf("Account 000%d: %f\n", i, avail_bal[i]);
}
}
}
void deposit()
{
float add;
int acc_num;
char c;
char s[100];
puts("Which account do you want to deposit money in?");
c = getc(stdin);
getc(stdin);
acc_num = (int) c - 48;
printf("Amount to deposit: ");
// to get a number without scanf() we have to read the input as a string
// (fgets() adds a '\0' at the end, so keep a seat free for it)
fgets(s, 99, stdin);
// and convert it to a double (atof() only for brevity, use strtod() instead)
add = atof(s);
avail_bal[acc_num] += add;
printf("Amount deposited %f\n", add);
}
void withdraw()
{
int acc_num;
float withdraw;
char c;
char s[100];
// all checks ommitted!
puts("Account to withdraw from: ");
c = getc(stdin);
getc(stdin);
acc_num = (int) c - 48;
puts("Amount to withdraw from account: ");
fgets(s, 99, stdin);
withdraw = atof(s);
avail_bal[acc_num] -= withdraw;
printf("Current balance for account %d: %f\n", acc_num, avail_bal[acc_num]);
}
void pexit()
{
// place logic to save data here or use a function triggered by atexit() for that task
puts("Imagine all of your data would have been put in a safe place!");
exit(EXIT_SUCCESS);
}
Just replace the constructs with scanf before you pass your work for grading.
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Fijar disposición y tamaño de componentes (RecyclerView)?
Tengo un card_video.xml (que es el elemento del que se rellena mi RecyclerView) el cual debería verse así según la vista de diseño de Android Studio, entiendo que no siempre se ve de esa manera debido a las propiedades de cada dispositivo, pero así debería verse para cada elemento:
Lo cual tiene el siguiente codigo:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="15dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:layout_weight=".1"
android:paddingLeft="10dp"
android:id="@+id/textViewIndex"
android:textSize="20sp"
android:layout_gravity="center_vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="1"/>
<TextView
android:layout_weight=".8"
android:id="@+id/textViewNameCourse"
android:textAlignment="center"
android:layout_gravity="center_vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Introduction"/>
<ImageButton
android:id="@+id/imageButtonSee"
style="@style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".1"
android:src="@drawable/ic_eye_black_24dp" />
</LinearLayout>
</android.support.v7.widget.CardView>
Al llenar de datos el Recycler, termina viendose de esta manera:
Aquí el codigo del Adapter
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.ViewHolder>{
ArrayList<Video> nVideoList;
private int layout;
private static OnItemClickListener listener;
public VideoAdapter(ArrayList<Video> nVideoList, int layout, OnItemClickListener listener) {
this.nVideoList = nVideoList;
this.layout = layout;
this.listener = listener;
}
@Override
public VideoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
return new VideoAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(VideoAdapter.ViewHolder holder, int position) {
holder.index.setText((position+1)+"");
holder.name.setText(nVideoList.get(position).getName());
//events
}
@Override
public int getItemCount() {
return nVideoList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView name;
TextView index;
ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.textViewNameCourse);
index = itemView.findViewById(R.id.textViewIndex);
imageView = itemView.findViewById(R.id.imageButtonSee);
imageView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Llamas el método onItemClickListener() de la interfaz OnItemClickListener
listener.onItemClickListener(view, getLayoutPosition());
}
}
public interface OnItemClickListener{
// Este método recibe como parámetro la vista del elemento seleccionado
void onItemClickListener(View view, int position);
}
}
Aquí el XML donde esta el RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.vycto.atomiccourses.VideoActivity">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal"
android:weightSum="1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageButton
android:id="@+id/buttonBackToCourses"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:src="@drawable/ic_arrow_back_white_24dp" />
<ImageButton
android:id="@+id/buttonHome"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:src="@drawable/ic_home_white" />
<ImageButton
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:src="@drawable/ic_list_white" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:orientation="vertical"
android:padding="10dp"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/linearLayout">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="15dp">
<ImageView
android:id="@+id/imageViewCoverVideos"
android:layout_width="match_parent"
android:layout_height="127dp"
android:scaleType="fitStart"
android:src="@drawable/cover_default" />
</android.support.v7.widget.CardView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textViewNameCourse"
android:text="Android"
android:layout_marginTop="3dp"
android:textAlignment="center"
android:textSize="22sp"/>
<TextView
android:id="@+id/textViewDescriptionCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Ingrese aqui descripcion"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textViewCost1"
android:layout_gravity="end"
android:textStyle="bold"
android:text="Cost: $0 (1 MONTH)"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerViewVideos"
android:layout_width="match_parent"
android:layout_height="200dp"></android.support.v7.widget.RecyclerView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/buttonBuy"
android:text="Buy"
android:layout_marginTop="5dp"
android:layout_marginBottom="3dp"
style="@style/Widget.AppCompat.Button.Colored"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Necesito que se muestren todos los que cree como la primera imagen, gracias.
A:
En realidad tu archivo card_video.xml es correcto, los elementos que mostraría el RecyclerView tendrían este aspecto :
El "problema" real por el cual se muestran incorrectamente los elementos del RecyclerView es que estas usando un ConstraintLayout, te aconsejo revisar la documentación para trabajar con este tipo de layout, ya que puede provocar comportamientos no esperados como el que indicas en tu pregunta:
Para solucionar este problema, en la definición del RecyclerView define android:layout_height="match_parent" en lugar de android:layout_height="200dp" :
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerViewV"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
Con esto provocaras que ademas de mostrar todos los elementos, estos se muestren correctamente.
Si es estrictamente necesario para tu aplicación definir 200dp como altura para tu RecyclerView:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerViewV"
android:layout_width="match_parent"
android:layout_height="200dp">
</android.support.v7.widget.RecyclerView>
La opción es cambiar el contenedor principal de un ConstraintLayout a un LinearLayout con orientación vertical,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.vycto.atomiccourses.VideoActivity">
...
...
</LinearLayout>
mediante este cambio tendrás el mismo resultado, mostrando correctamente los elementos dentro del RecyclerView.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to mount root to a directory in express?
I am trying to mount a particular directory in an app to root. The structure of my app is
/app
/server.js
/views
/statics
/index.html
/partials
/public
/javascript
/css
/images
I want the static to be served as root so I can access index.html at localhostL:4001/index.html instead of localhostL:4001/static/views/index/html
I have tried to use express.statics. However, it didn't work.
in server.js
app.use(express.static('public'));
app.use('/', express.static('views/statics'));
A:
it should be app.use('/', express.static('views/statics'));
check the working model here : https://repl.it/@VikashSingh1/SlategrayDeadRobot
| {
"pile_set_name": "StackExchange"
} |
Q:
Constructor call must be the first statement in a constructor when there is no constructor call at all
I am trying to write unit tests for the code provided in http://www.keithschwarz.com/interesting/code/?dir=fibonacci-heap
I am stuck in the first line though. My test looks like this:
public class fibonacciHeapTest {
fibonacciHeap<Integer> fibHeap= new fibonacciHeap<>();
@Test(expected = HeapEmptyException.class)
public void testGetMin() throws HeapEmptyException {
System.assert(true, fibHeap.isEmpty()); // Here I get the error mentioned in the title.
}
Also the same line when looked at System, gives the following message int he dropdown : System cannot be resolved into a variable.
What am I doing wrong ? Thank you.
A:
Lets give some more precise feedback to get you going:
public class FibonacciHeapTest { // as mentioned, UpperCase!
Your first test could be:
@Test
public void testIsEmptyOnNewHeap() {
assertThat(new FibonnacciHeap<String>().isEmpty(), is(true));
}
The point is: isEmpty() should obviously not throw an exception, so you dont want the "expected" statement. Please note: I turned to assertThat and the hamcrest is matcher - don't waste your time learning about other asserts. assertThat is the only assert you will ever need. (but it takes a bit of reading to learn about it)
Then:
@Test(expected=HeapEmptyException.class)
public void testGetOnEmptyHeap() {
new FibonacciHeap<String>().pop();
}
The point here: your heap has a method to get values, I called it "pop()". And obviously - when you pop something from an empty stack, you should see an exception.
These are some examples how you write unit tests. You do one thing in your test; and you check one thing; either using asserts, or by expecting exceptions.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I access properties from parent document to use in children
I am new to Umbraco CMS. PLease help.
I have a Umbraco website in which I created a DocumentType called 'Master'. The 'Master' page lets user input a goal and amount for a fund raising initiate they are undertaking. On the 'Master' page I have a Macro which automatically does the math to generate a percent that will be used throughout the site. The Macro calls the following XSLT
<xsl:for-each select="$currentPage/ancestor-or-self::*">
<xsl:variable name="amount" select="* [@alias = 'FundraisingCurrentAmount']"/>
<xsl:variable name="goal" select="* [@alias = 'FundraisingGoal']"/>
<xsl:variable name="percentage" select="$amount div $goal * 100"/>
<xsl:value-of select="$percentage"/>
</xsl:for-each>
This works but, I am assuming because it is a 'for-each' it is also returning two NaN results. How can I rewrite this (a) cleaner and (b) so that it works better.
I understand ASP.NET Webforms so if you could compare to that it'd help out.
Appreciate the help.
A:
In Umbraco you can have what are called recursive values. This are basically page values which look up the node hierachy until it filnds a value.
These can be passed to macros as well.
So in your case assuming your macro is called "charityTotaliser" you could use the following macro call:
<umbraco:macro alias="charityTotaliser" ammount="[$FundraisingCurrentAmount]" goal="[$FundraisingGoal]"runat="server"/>
The $ indicates that the value is recursive.
The XSLT would look something like this (not tested just an example):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:Stylesheet [ <!ENTITY nbsp " "> ]>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxml="urn:schemas-microsoft-com:xslt"
xmlns:umbraco.library="urn:umbraco.library"
xmlns:Exslt.ExsltMath="urn:Exslt.ExsltMath"
exclude-result-prefixes="msxml umbraco.library Exslt.ExsltMath">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:param name="currentPage"/>
<!-- Macro parameters -->
<xsl:variable name="FundraisingCurrentAmount" select="/macro/FundraisingCurrentAmount"/>
<xsl:variable name="FundraisingGoal" select="/macro/FundraisingGoal"/>
<xsl:template match="/">
<xsl:value-of select="$FundraisingCurrentAmount div $FundraisingGoal * 100"/>
</xsl:template>
</xsl:stylesheet>
If requied you can also specify fallback values to be passed (in case the recursive value cannot be found):
<umbraco:macro alias="charityTotaliser" ammount="[$FundraisingCurrentAmount], [#FallBackAmmount], 1234" goal="[$FundraisingGoal]"runat="server"/>
For more information on macro parameters you can read this documentation
| {
"pile_set_name": "StackExchange"
} |
Q:
Brew MP handset developer activation
I have a Brew MP which I want to upload my app to. But I understand, it must first be "developer activated" before it will accept my apps. In the Qualcomm tools, I use the Target Manager, but I find no way to activate the phone.
I have a Brewmp.com account, and I read the instructions, but they are not clear to me.
The Target Manager says "Connected Status: Currently not connected", if that means anything. The phone is connected enough for the tool to display it in the list of the physical devices though.
The handset is a Dopod F3188 running Brew MP 1.0.2.481.
I installed the generic gateway USB driver found in the Brew Tools. However, if I enable a developer mode which is more than USB gateway (+ COM) in the phone, the phone is not recognized by Windows and I can not find any drivers for the phone.
A:
The problem disappeared once I started using a real Windows XP machine instead of a virtual machine. (VirtualBox in this case.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I hook to log4net Log, Debug, Info, and Error?
I want to set different console colors depending on the severity of the logged message.
I would want something like
_log.Error("Expected exception",e);
to somehow do
Console.PushColor(ConsoleColor.DarkRed);
_log.Error("Expected exception",e);
Console.PopColor();
Is there an easy way to hook the console logger to do stuff like this?
A:
First yes, log4Net provides it's own color log adapter:
We use two appender configurations to enable output to both std:out and std:err
<log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<root>
<level value="ALL" />
<appender-ref ref="console.out" />
<appender-ref ref="console.error" />
</root>
<appender name="console.out" type="log4net.Appender.ColoredConsoleAppender">
<target value="Console.Out" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG"/><!-- "DEBUG" OR "INFO" if you want to display these -->
<levelMax value="INFO"/>
</filter>
<mapping>
<level value="INFO"/>
<foreColor value="White, HighIntensity"/>
</mapping>
<mapping>
<level value="DEBUG"/>
<foreColor value="White"/>
</mapping>
</appender>
<appender name="console.error" type="log4net.Appender.ColoredConsoleAppender">
<target value="Console.Error" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="WARN"/>
<levelMax value="FATAL"/>
</filter>
<mapping>
<level value="FATAL"/>
<foreColor value="Yellow, HighIntensity"/>
<backColor value="Red"/>
</mapping>
<mapping>
<level value="ERROR"/>
<foreColor value="Red, HighIntensity"/>
</mapping>
<mapping>
<level value="WARN"/>
<foreColor value="Yellow, HighIntensity"/>
</mapping>
</appender>
</log4net>
If you still want to hand-code the output, use an ILog implementation. It basically gives you methods for each type of output. To bind your custom adapter you create the configuration section like this...
<appender name="name" type="NameSpace.ClassOfTypeILog, AssemblyName">
...
</appender>
| {
"pile_set_name": "StackExchange"
} |
Q:
Display each mySQL result as link to another page php
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "sbsuite";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from sys_frm WHERE ParamType='Title';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["Data"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?
This is code that give me two results..
Client
Server
I want to insert them as link to another php page with image, depends on what we click on its goes to another php page...
Thanks for help!
A:
This is a simple HTML. Replace the client/server php and jpg to what you want.
<a href="client.php"><img src="client.jpg" alt="Client" /></a><br />
<a href="server.php"><img src="server.jpg" alt="Server" /></a>
With PHP
<?php
while ($row = $result->fetch_assoc()) {
?>
<a href="<?php echo $row["Data"]; ?>.php"><img src="<?php echo $row["Data"]; ?>.jpg" alt="<?php echo $row["Data"]; ?>" /></a><br />
<?php
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to determine the Blob type of all the blobs in a container in Azure?
I know how to list all the blobs in a container but I need to know the type of blob too. Right now I am blindly using the class CloudBlockBlob because of which I am getting an error as (com.microsoft.azure.storage.StorageException: Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected BLOCK_BLOB, actual PAGE_BLOB.) there's one PageBlob type in the list. Is there a way to determine the type of the Blob?
This is how my code looks like:
public static void getContainerFiles(CloudStorageAccount storageAccount, String containerName) {
String fName = "";
Date lstMdfdDate = null;
try
{
// Define the connection-string with your values
String storageConnectionString = "DefaultEndpointsProtocol=https;" +"AccountName=" + storageName + ";AccountKey="+key;
// Retrieve storage account from connection-string.
storageAccount = CloudStorageAccount.parse(storageConnectionString);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.getContainerReference(containerName);
StorageCredentials cred = storageAccount.getCredentials();
System.out.println(">>> AccountName: " + cred.getAccountName());
System.out.println("Listing files of \"" + containerName + "\" container");
// Loop over template directory within the container to get the template file names.
CloudBlockBlob blob = null;
for (ListBlobItem blobItem : container.listBlobs()) {
fName = getFileNameFromBlobURI(blobItem.getUri(), containerName);
blob = container.getBlockBlobReference(fName);
blob.downloadAttributes();
lstMdfdDate = blob.getProperties().getLastModified();
}
} catch (Exception e) {
}
}
private static String getFileNameFromBlobURI(URI uri, String containerName)
{
String urlStr = uri.toString();
String keyword = "/"+containerName+"/";
int index = urlStr.indexOf(keyword) + keyword.length();
String filePath = urlStr.substring(index);
return filePath;
}
A:
You can check the type of the blobItem. For example, something like the following:
if (CloudBlockBlob.class == blobItem.getClass()) {
blob = (CloudBlockBlob)blobItem;
}
else if (CloudPageBlob.class == blobItem.getClass()) {
blob = (CloudPageBlob)blobItem;
}
else if (CloudAppendBlob.class == blobItem.getClass()) {
blob = (CloudAppendBlob)blobItem;
}
You can omit the CloudAppendBlob block if you're on older versions of the library, but I'd recommend updating to get the latest bug fixes as well as that feature. Also notice that this removes the need to parse the name out.
| {
"pile_set_name": "StackExchange"
} |
Q:
Define a COM smarter pointer as a member in header file?
I am wondering how to define a COM smart pointer in a header file as a class member? Here is what did:
In .cpp file, I have:
long MyClass:MyFun(long &deviceCount)
{
RESULT h = CoInitialize(NULL);
MyComPtr ptr(__uuidof(MyComClass));
if(deviceCount > 0)
ptr->Connect();
}
But since other functions need to use ptr, I am thinking about changing it to a class member and define it in the header file, something like this:
In .h file:
MyComPtr _ptr;
then in .cpp file, I have:
_ptr(__uuidof(MyComClass));
But the compile did not go through, it says "term does not evaluate to a function taking 1 argument". I am very confused how I can implement this. Any ideas? Thanks.
EDIT: So to use initilizer list, it shoule be something like this?
MyClass:MyClass() : _ptr(new MyCom)
{
_ptr(__uuidof(MyComClass));
}
A:
The initializer list is called at construction time to set variables that would otherwise be const. It's commonly used for const variables, references, etc. I don't actually know COM, but if the smart pointer has similar mechanics to a reference (i.e. once set it cannot be retargeted) then it will have to be initialized at construction time, using an initializer list.
Constructor() : _Ptr(new MyComObject)
{
// Other constructor stuff here
}
The syntax is probably wrong - as I said, I don't know COM - but this might be helpful?
EDIT:
Assuming you have the following class:
class MyClass
{
public:
MyClass(); // constructor
MyComPtr _ptr;
};
Then in your .cpp, define your constructor like this :
MyClass::MyClass() : _ptr(__uuidof(MyComClass)
{
// rest of constructor code
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make the value text of input tag positioned in the upper left?
I made the input box bigger (like 500 by 500 pixels), but the text would start from the middle, not the top. I tried putting the padding to zero but it doesn't seem to work. This is under the form tag.
Here's my html code:
<form>
<input class="postbox" value="Hello."><br>
</form>
and this is my css code:
.postbox{
padding:0;
height:500;
width:500;}
A:
you stretched the input-line to 500px, not the form.
As Alvaro Menéndez noticed, you might want to use a textarea, not an input.
Use something like
<form>
<textarea class="postbox" placeholder="Hello"></textarea><br>
</form>
<style>
.postbox {
padding:0;
height:500px;
width:500px;
}
</style>
http://pascha.org/test/2.php
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL query to pivot data in below table
I've Attendance Catlog Table as follow,
As an example illustrated in above image,
There are 4 students in class having roll number 1,2,3,4.
Three Teachers named PNT, SGP and DAP have taken attendance of same class at the time of corresponding lecture.
Above table shows Total Absency of each student with respect to each teacher.
I want to generate output as follow,
This table illustrate total absency of each student under the lecture of corresponding teacher.
How to get such result from given table?
DDL and sample Data :
create table mytable ( TeacherID varchar(3), RollNo number, Total_Absency number);
insert into mytable values('PNT', 1, 0);
insert into mytable values('PNT', 2, 4);
insert into mytable values('PNT', 3, 0);
insert into mytable values('PNT', 4, 1);
insert into mytable values('SGP', 1, 2);
insert into mytable values('SGP', 2, 1);
insert into mytable values('SGP', 3, 1);
insert into mytable values('SGP', 4, 1);
insert into mytable values('DAP', 1, 1);
insert into mytable values('DAP', 2, 1);
insert into mytable values('DAP', 3, 1);
insert into mytable values('DAP', 4, 0);
A:
With Oracle, use the PIVOT clause :
SELECT * FROM
(
SELECT TeacherID, RollNo, Total_Absency FROM mytable
)
PIVOT
(
MAX(Total_Absency)
FOR TeacherID
IN ( 'PNT', 'SGP', 'DAP' )
)
ORDER BY RollNo
Demo on DB Fiddle :
ROLLNO | 'PNT' | 'SGP' | 'DAP'
-----: | ----: | ----: | ----:
1 | 0 | 2 | 1
2 | 4 | 1 | 1
3 | 0 | 1 | 1
4 | 1 | 1 | 0
With other RDBMS, the general solution is to use condition aggregation :
SELECT
RollNo,
MAX(CASE WHEN TeacherID = 'PNT' THEN Total_Absency END) AS PNT,
MAX(CASE WHEN TeacherID = 'SGP' THEN Total_Absency END) AS SGP,
MAX(CASE WHEN TeacherID = 'DAP' THEN Total_Absency END) AS DAP
FROM mytable
GROUP BY RollNo
ORDER BY RollNo
| {
"pile_set_name": "StackExchange"
} |
Q:
Storing Tags in Database. Store tag once or many times?
I would like a bit more clarification on the toxi method of storing tags in a database – mentioned elsewhere on SO.
The database schema is:
Table: Item
Columns: ItemID, Title, Content
Table: Tag
Columns: TagID, Title
Table: ItemTag
Columns: ItemID, TagID
This is probably a stupid question (but I don't know the answer)... Should each entry, in the Table Tag, have a unique title. i.e. I only store a tag once or store it every time I use it?
To illustrate, which of the two tables below should I end up with:
TagID Title
1 Fish
2 Cat
3 Dog
or
TagID Title
1 Fish
2 Fish
3 Cat
4 Fish
5 Dog
6 Cat
If using the first table, before entering the tag I would first have to run and sql statement to find out if it exists, correct?
Any help will be appreciated. I had my fingers burn recently due to hacking together and indexing, want to start getting the basics correct.
A:
The basics are that you need to store tags like you're showing in first case. It's good for checking if tag exists (since in second case for existing tags your db would return as many rows as there are those appearances of tag) and good for retrieving items by tag (select item id by one tag id is better than selecting item ids by a set of tag_id which has same representational meaning).
If you had burnt your fingers because of indexing - you should always check how query is being executed (for mysql it's EXPLAIN/DESCRIBE SELECT).
| {
"pile_set_name": "StackExchange"
} |
Q:
What do kids say instead of "videotape”?
In a conversation I just had I used the word "videotape" to mean recording a video on a cell phone. It occurred to me that this is probably not the word youngsters use today, but I couldn't think of a suitable alternative (other than "record," which seems too formal to me).
Google didn't provide any enlightening answers and I didn't see anything related on this site.
What words or expressions for "recording a video" are commonly used by kids in casual conversation? I'm mostly interested in American English.
A:
In my shop we shoot digital video with a camera; more generically (embracing other methods such as screen-grabbing motion footage†), we capture it. We also speak of shooting or capturing the subject.
Video which is constructed from scratch in software by manipulating digital still images is built and rendered.
† Yeah, it's still "footage" even when it's measured in bytes, because taken at the level where people deal with it rather than software it's still a linear sequence of "frames".
A:
As others wrote, I think "video" is what you're looking for.
Speaking only from personal experience, "video" is in common use in the U.S., at least among the young (say, 2-30 years old), who know little about videotaping and never use the term. "Did you video it?" is common and clearly understood, as is "I videoed it" and "We'll video Christmas morning."
Thankfully, the monstrous word "videoing" has not seemed to gain similar currency. Few would say, "Please move; I'm videoing," instead saying, "Please move; I'm shooting a video."
This is, again, anecdotal, but is drawn from interactions with teens and young adults on east and west coasts as well as Texas.
A:
In casual conversation, I have heard the word video used in the manner which you are describing and I think this is what you are looking for.
Google definition:
verb: video; 3rd person present: videos; past tense: videoed; past participle: videoed; gerund or present participle: videoing
1.
record on videotape.
"he declined an invitation to be videoed"
I hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Interlacing Theorem on Singular Values
Does the Cauchy's interlacing theorem hold for "singular values" of matrices too? I saw on this publication first Theorem that it does. It states that singular values of a matrix interlace the singular values of its principal sub-matrices. I would have thought given the original (celebrated) Cauchy's interlacing theorem that is on the "eigenvalues" of symmetric matrices and their sub-matrices, that to make interlacing statements about singular values we would need a restriction on positivity of the matrix. Is my intuition wrong?
A:
Your intuition is wrong; singular values are "nice" that way.
In particular: suppose that $A$ can be divided as
$$
A = \pmatrix{A_0 & B\\C & D}
$$
The interlacing property compares the singular values of $A$ to the singular values of $A_0$. That is, we are comparing the eigenvalues of $A^*A$ to the eigenvalues of $A_0^*A_0$. However, $A^*A$ has the structure
$$
A^*A = \pmatrix{
A_0^*A + C^*C & A_0^*B + C^*D\\
B^*A_0 + D^*C & B^*B + D^*D}
$$
Perhaps you can see how, at least in the case of $C = 0$, the Cauchy interlacing property applies directly. Remember that we can equivalently consider $AA^*$ and $AA^*$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why \n is't working from database?
I fill the ListView from Database. One of the fields in DB contains text with \n. But when I put this text into the item, then I don't get Newline instead of \n. How does I must correctly take this text from DB and put it into the item?
My code:
txtComment = (TextView) convertView.findViewById(R.id.txt_comment);
this.cur.moveToPosition(position);
txtComment.setText(this.cur.getString(this.cur.getColumnIndex("comment")));
In DB item:
The probe was built to land on the larger ... rock to bring back to Earth.\nSuch a venture should ...
result in android:
The probe was built to land on the larger ... rock to bring back to Earth.\nSuch a venture should ...
I expected:
The probe was built to land on the larger ... rock to bring back to Earth.
Such a venture should ...
TextView from item.xml:
<TextView
android:id="@+id/txt_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="5dip"
android:padding="5dip"
android:textColor="#fff"
android:textSize="12sp" />
Content for DB I am taking by parsing JSON. I can ask developer to insert smth else instead of \n. But what?
A:
A string containing a backslash followed by an n is very different to a string containing a newline. It's only when a string is parsed as a string literal that Java treats them differently. If you want to store a newline in a database, you should just store it in the value to start with. If you want to apply Java string literal escaping, you'll need to find some appropriate code to do so - which isn't just as simple as text.replace("\\n", "\n") for example, as you also need to take account of situations like "escaped\\n".
I suspect there'll be some string utility libraries somewhere which can do this - the StringEscapeUtils class from Apache Commons 3.1 looks like a good starting point, if it works in Android, for example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Assembly MIPS. How change the content of two positions of vector?
What I want:
Example:
v[0] = 5
v[1] = 10
after...
v[0] = 10
v[1] = 5
Apparently everything works, but when we will print the content, only the content of $s0 print the correct value.
If you try print the content of the saver $s2 one error appears:
"Runtime exception at 0x00400018: address out of range 0x00000000" . Can someone help-me?
Thanks very much
.data
vector : .word 5,10
.text
la $s0, vector
la $s1, vector
add $s1, $s1, 4
# $s0 is v[0]
# $s1 is v[1]
# $s2 is the saver
lw $s2, 0($s1)
sw $s0, 0($s1)
sw $s2, 0($s0)
li $v0, 1
lw $a0, 0($s0)
syscall
li $v0, 1
lw $a0, 0($s1)
syscall
A:
First of all, your swap is incorrect. What you're doing with sw $s0, 0($s1) is storing the address of one of the elements, not storing the value of that element. So you need to do something like this instead:
lw $s2, 0($s0)
lw $s3, 0($s1)
sw $s2, 0($s1)
sw $s3, 0($s0)
Secondly, you're not terminating your program properly. At the end of your code you should execute the exit syscall:
li $v0, 10 # syscall_exit
syscall
And if you want a space or newline between the numbers you'll have to print one using syscall 4 or 11.
| {
"pile_set_name": "StackExchange"
} |
Q:
checking whether a string contains any special character or string in javascript
I want to check whether a string has any special characters or not. I am using this script:
var name = $("#name").val();
if(name.match(/[_\W]0-9/))
{
alert('Not A Name');
}
It doesn't alert even when name="sas23"
A:
instead /[_\W]0-9/ your regex literal should be /[_\W0-9]/
| {
"pile_set_name": "StackExchange"
} |
Q:
Overriding standard C library functions in C++ program
I wanted to know how does the compiler/linker selects from the 2 printf functions available. One is the user defined and the other is the standard c library implementation.
#include <stdio.h>
int printf(const char* c, ...) {
return 0;
}
int main() {
printf("\n Hello World\n");
}
I know what overloading is but here both implementations have same signatures. Basically I don't understand this concept of 'overriding' of functions.
Does this somehow violate ODR? Is this a well defined C++ program or can it have UB on some platforms?
A:
Overriding is a completely different concept from overloading.
You override a virtual member function.
No overloading takes place here.
What actually happens is you are defining printf with the exact same signature as stdio.h declares. So it's the same function (with "C" linkage!). You are just providing its definition. It is undefined behaviour to define a standard library function, except for those functions explicitly mentioned as user-replaceable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Panel of TextFields in JOptionPane, DocumentListener? - Beginner
Edited to add the setName function:
I've been using stackoverflow for over a year to help with learning java after only about 6 hours of CS in college. You guys are the best! So getting to it...
My problem is that I've got a JOptionPane with multiple textFields. All the examples of retreiving the text from these fields only show a single textField. I could create a separate DocumentListener for each textField that handles each box separately, but it just seems that there should be a way to create one DocumentListener that can say :
if(namebox changed)
edit name
else if(dataBox changed)
edit data
etc....
Here is my code as it originates:
public class HumanPlayer extends Player
{
/**
* Constructor for objects of class HumanPlayer
*/
public HumanPlayer()
{
setName("Human " + getOrder());
}
@Override
public void chooseSoldiers()
{
JLabel nameLabel = new JLabel("Enter name: " );
//humans.setPreferredSize(new Dimension(100,50));
final JTextField nameBox = new JTextField();
final JTextField infantryBox = new JTextField();
final JTextField scoutBox = new JTextField();
final JTextField sniperBox = new JTextField();
JLabel infLabel = new JLabel("Infantry: " );
JLabel scLabel = new JLabel("Scouts: " );
JLabel snLabel = new JLabel("Snipers: " );
JPanel soldierPanel = new JPanel();
soldierPanel.setLayout(new GridLayout(4,2,5, 8));
soldierPanel.add(nameLabel);
soldierPanel.add(nameBox);
soldierPanel.add(infLabel);
soldierPanel.add(infantryBox);
soldierPanel.add(scLabel);
soldierPanel.add(scoutBox);
soldierPanel.add(snLabel);
soldierPanel.add(sniperBox);
nameBox.getDocument().addDocumentListener(new NameListener());
infantryBox.getDocument().addDocumentListener(new NameListener());
scoutBox.getDocument().addDocumentListener(new NameListener());
sniperBox.getDocument().addDocumentListener(new NameListener());
int ok = JOptionPane.showOptionDialog(null, soldierPanel,
"Player " + getOrder(), JOptionPane.CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
}
public class NameListener implements DocumentListener
{
@Override
public void changedUpdate(DocumentEvent e) {}
@Override
public void insertUpdate(DocumentEvent e) {
try {
setName(e.getDocument().getText(0,e.getDocument().getLength()));
} catch (BadLocationException e1) {e1.printStackTrace();}
}
@Override
public void removeUpdate(DocumentEvent e) {
try {
setName(e.getDocument().getText(0,e.getDocument().getLength()));
} catch (BadLocationException e1) {e1.printStackTrace();
}
}
}
}
Separate File:
public abstract class Player
{
....
private String name;
....
public void setName(String _name)
{
name = _name;
}
A:
If i am understanding you correctly, you want to use one document listener and get it responding with all the JTextFeild data change event. Unfortunately, a DocumentListener's event sources are the Documents to which is registered using addDocumentListener function, not the text component. SO the idea is to use:
Document's putProperty("owner", txtFeild): to track the owner text field of this Document
On Document change event use getProperty("owner") to get the owner of the event source: document instance.
assigning PropertyChangeListener to each text field to set this property to their own document: as it is unpredictable if a new document's is set to the TextComponent we are using.
Check the following code snippets carefully:
class MyDocumentListener implements DocumentListener{
public void updateComponent(DocumentEvent e)
{
boolean valid = checkDataValidity(e.getDocument());
JTextField txtField = (JTextField) e.getDocument().getProperty("owner");
if(!valid)
txtField.setEnabled(false);
else txtField.setEnabled(true);
}
@Override
public void insertUpdate(DocumentEvent e) {updateComponent(e);}
@Override
public void removeUpdate(DocumentEvent e) {updateComponent(e);}
@Override
public void changedUpdate(DocumentEvent e) {}
}
class MyPropChangeListener implements PropertyChangeListener{
DocumentListener documentListenr;
public MyPropChangeListener(DocumentListener documentListener) {
this.documentListenr = documentListener;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("chaning document!!");
JTextField txtFeild = (JTextField)evt.getSource();
txtFeild.getDocument().putProperty("owner", txtFeild);
txtFeild.getDocument().addDocumentListener(documentListenr);
}
}
//..............
MyPropChangeListener propChangeListener = new MyPropChangeListener(new MyDocumentListener());
jTextField1.addPropertyChangeListener("document", propChangeListener);
jTextField1.setDocument(new PlainDocument());
jTextField2.addPropertyChangeListener("document", propChangeListener);
jTextField2.setDocument(new PlainDocument());
| {
"pile_set_name": "StackExchange"
} |
Q:
how can I compile a Go database/sql program with multiple drivers?
I'm writing a test program in Go for sql databases (Postgres and Mysql) currently. I don't know much about the "_" option for packages however I am using it (see below).
What I would like to be able to do is to compile once to use multiple sql drivers for the one RDBMS and also for multiple RDBMS's and when running the program, select which driver and RDBMS to use. I'm not sure if that's possible. Currently I compile with one Postgres and one Mysql driver and then select which one I'm using at run time (Postgres/Mysql). That works OK, but I need to remember which driver was compiled. It would be good to be able to compile with multiple drivers for the one RDBMS and then at run-time select which one to use. I guess that's not possible. Alternatively it would be good to be able to select at compile time which drivers to use, and at run-time to know which drivers are being used. Without one of these facilities, one could be testing eg. Postgres and think they are using one driver when in fact the program has been compiled with another driver.
Is it possible to have a compiler option to select particular drivers, and then at run-time know which driver is being used? An alternative is obviously to edit the program to indicate this.
An example of the import is as follows :
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
////_ "github.com/lib/pq"
_ "github.com/lxn/go-pgsql"
........
A:
I don't know much about the "_" option for packages however I am using it (see below).
Prepending _ to a import path will import the package just normally (running its' init() function) but it won't associate a name in your current package with the imported package.
What I would like to be able to do is to compile once to use multiple sql drivers for the one RDBMS and also for multiple RDBMS's and when running the program, select which driver and RDBMS to use. I'm not sure if that's possible.
The init() function of package "github.com/go-sql-driver/mysql" does the following:
func init() {
sql.Register("mysql", &MySQLDriver{})
}
It will call database/sql's Register function which is defined to be:
func Register(name string, driver driver.Driver)
And has the condition:
If Register is called twice with the same name or if driver is nil, it panics.
After a driver has been registered, you can use sql.Open:
func Open(driverName, dataSourceName string) (*DB, error)
to open a new connection to a database, using the driver specified by the first argument, e.g:
db, e := sql.Open("mysql", "user:pass@host:port")
By the way, github.com/lxn/go-pgsql's init() function looks like this:
func init() {
sql.Register("postgres", sqlDriver{})
}
I have re-read your question and I think that additionally, you'd like to specify what database and driver you want to use when running the program.
For this, you can use the flag package and run your application like this:
./my_app -driver=mysql -db="user:pass@host:port"
and pass these strings to sql.Open.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the reason for the color scheming of Nolan's Batman franchise?
Throughout the three Batman films, there has been one running theme in common. Each movie has its own color scheme.
Batman Begins - Brown & Black
The Dark Knight - Blue & Red
Dark Knight Rises - White & Black
What is Nolan's reason for this? Is there a meaning behind the colors that directly link back into the major theme of the films? Or are these colors a way to represent the overall situation throughout the movie?
A:
I see these colors/movie titles as the day in the life of a bat, beginning at sunset (orange) and ending at sunrise (white/bight) with a dark night in between (blue). Also plays on the titles; BEGINS, NIGHT and sunRISE. That is another nice conclusion to the saga.
A:
Not knowing much about the upcoming movie, nor anything about Bane the main adversary, I can only comment on the first two.
The choice of brown evokes grime and dirt and brooding menance - a perfect analogy of the scene in Gotham, particularly with The Narrows - a slum part of the city, a no-go area for police similar to the (no-longer existing) Kowloon in Hong Kong. The main adversary is Scarecrow, and the brown and black theme also evokes earthiness.
The brighter blue/red theme in The Dark Knight is perfect for the character of the Joker. The burning Batman symbol evokes a smiling Joker mouth, and ties into a key line of Alfreds:
Well, because he thought it was good sport. Because some men aren't looking for anything logical, like money. They can't be bought, bullied, reasoned, or negotiated with. Some men just want to watch the world burn
A:
I recently stumbled upon an article explaining the same
Batman Begins had a dominatly brown color scheme to paint Gotham City
as the crime infested wasteland shithole that it was. The Dark
Knight's color scheme was mostly blue,which was done to create a
contrast...at first it is used to create a vibe of calm relaxation in
showing that Batman has really made a difference and gotten the city
out of the slump it was in in Batman Begins...but then when the shit
starts to go down,the blue turns out to be a corrupted false sense of
security and is then used as a means of shaping the dark and bleak
atmosphere that will carry over the remander of the film
This post on a forum is a good read itself.
| {
"pile_set_name": "StackExchange"
} |
Q:
looping through array not working
I'm trying to get the value of fields object in the array o . I'm not able to get the value inside the property. What am I doing wrong?
var o = {
"templatename": "sdgds",
"fields": {
"s1_req_1": 1,
"s1_req_2": 1,
"s1_req_3": 1,
"s1_req_4": 1,
"s1_req_5": 1,
"s1_req_6": 1,
"s1_req_7": 1,
"s1_req_8": 1,
"s1_req_9": 1,
"s1_req_10": 1,
"s1_req_11": 1,
"s1_req_12": 1,
"s1_req_13": 1,
"s1_req_14": 1,
"v1_dm_1": 1,
"v1_dm_5": 1,
"v1_dm_6": 1,
"f1_fs_3": 1,
"f1_fs_1": 1,
"f1_fs_2": 1,
"e3_eh_19": 1,
"f1_fs_11": 1,
"s3_sh_1": 1,
"s3_sh_6": 1,
"s3_sh_7": 1,
"v1_dm_7": 1,
"v1_dm_13": 1,
"v1_dm_9": 1
},
"customerid": 'SMRTsspd'
};
$('#template').val(o.templatename);
$(o.fields).each(function(t) {
$('input[value=' + t.name + ']').prop('checked', true);
});
A:
You can loop through object without jquery:
Object.keys(o.fields).forEach(function (key) {
$('input[value=' + key + ']').prop('checked', o.fields[key]);
});
As others have said, o.fields is an object, so to iterate through its values, you need to extract its keys first, via Object.keys(o.fields) method. Then you can iterate through those keys via simple Array.forEach(keys). Finally to use the value, you can just do o.fields[key].
Or with jquery, use it like this:
$.each(o.fields, function(key, value) {
$('input[value=' + key + ']').prop('checked', value);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with OnClick of Javascript for button occured
Is there a problem with my javascript on a custom button? Before it was set to URL with the URL variable filled in, but now i want to add logic to this.
Thanks
{!REQUIRESCRIPT("/soap/ajax/21.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}
var url = '/apex/QuoteRequestDetailsPage?QuoteRequestId={!Quote_Request__c.Id}
&OpportunitySegmentId={!Quote_Request__c.Opportunity_SegmentId__c}';
window.open(url,"_self");
A:
You can't use a literal newline in a JavaScript string. This causes an "unterminated string" parsing error.
To fix it, use string concatenation:
var url = '/apex/QuoteRequestDetailsPage?'+
'QuoteRequestId={!JSENCODE(Quote_Request__c.Id)}'+
'&OpportunitySegmentId={!JSENCODE(Quote_Request__c.Opportunity_SegmentId__c)}';
Personally, I'd recommend using URLFOR:
var myUrl = "{!URLFOR($Page.QuoteRequestDetailsPage, null,
[QuoteRequestId=Quote_Request__c.Id,
OpportunitySegmentId=Quote_Request__c.Opportunity_SegmentId__c])}";
window.open(myUrl, "_self");
URLFOR will take care of all the pesky details of encoding, line breaks, and so on.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# collections optimised for index 0 insert?
What C# collections are best optimised for both zero-index insert and append to end?
I guess the easy one is LinkedList, but given my interest is in large byte-buffers, I suspect the memory cost per node may be prohibitively expensive for my needs.
My understanding is that a normal List has a buffer backing with a capacity usually larger than the actual data. When the data fills the buffer, a new buffer is created and the contents of the old are transferred to the new. That's great for appending to end, but horrible for growth on the beginning. My tests, appending/inserting a million random integers to a List:
List Append time 0.014sec.
List Zero-Insert time 173.343sec
A:
A data structure which has the form of a list but is optimized for insertion and removal on both ends -- but not the middle -- is called a deque, which is short for "Double Ended QUEue". I do not know whether the standard library contains a deque these days.
If you are interested in techniques for constructing immutable deques, I suggest you read, in order of increasing complexity:
My series of articles on immutable data types, specifically this one: https://blogs.msdn.microsoft.com/ericlippert/2008/02/12/immutability-in-c-part-eleven-a-working-double-ended-queue/
This awesome SO question and answers: Implement an immutable deque as a balanced binary tree?
Chris Okasaki's book "Purely Functional Data Structures" describes how to create a deque that is O(1) in all operations by clever use of lazy construction and memoization
Should you wish to create a mutable deque it is pretty straightforward to do so using the same techniques that a list. A list is just a wrapper around an array where the array is "too big" on the far end. To make a mutable deque you can make an array that is too big but the data sits in the middle, not at the small end. You just have to keep track of what the top and bottom indices of the data are, and when you bump up against either end of the array, re-allocate the array and copy the data to the middle.
A:
You could create your own IList<T> implementation that contains two lists: one for items added to the front (stored in reverse order), and one for items added to the back (in proper order). This would ensure that all your inserts to the very beginning or end of the list are O(1) (except for the few cases where the capacity needs to be increased).
public class TwoEndedList<T> : IList<T>
{
private readonly List<T> front = new List<T>();
private readonly List<T> back = new List<T>();
public void Add(T item)
{
back.Add(item);
}
public void Insert(int index, T item)
{
if (index == 0)
front.Add(item);
else if (index < front.Count)
front.Insert(front.Count - index, item);
else
back.Insert(index - front.Count, item);
}
public IEnumerator<T> GetEnumerator()
{
return front.Reverse<T>().Concat(back).GetEnumerator();
}
// rest of implementation
}
A:
My solution is as Eric Lippert mentioned; keep the real data floating in the middle of the backing-buffer, rather than at the beginning. However, this is still a list, not a queue; can still Add/Remove/Replace everywhere.
public class BList<T> : IList<T>, IReadOnlyList<T>
{
private const int InitialCapacity = 16;
private const int InitialOffset = 8;
private int _size;
private int _offset;
private int _capacity;
private int _version;
private T[] _items;
public BList()
{
_version = 0;
_size = 0;
_offset = InitialOffset;
_capacity = InitialCapacity;
_items = new T[InitialCapacity];
}
public BList(int initialCapacity)
{
_size = 0;
_version = 0;
_offset = initialCapacity/2;
_capacity = initialCapacity;
_items = new T[initialCapacity];
}
public void Insert(int insertIndex, T item)
{
if (insertIndex < 0)
throw new ArgumentOutOfRangeException(nameof(insertIndex));
var padRight = Math.Max(0, (insertIndex == 0) ? 0 : (insertIndex + 1) - _size);
var padLeft = insertIndex == 0 ? 1 : 0;
var requiresResize = _offset - padLeft <= 0 ||
_offset + _size + padRight >= _capacity;
if (requiresResize)
{
var newSize = _size + 1;
var newCapacity = Math.Max(newSize, _capacity * 2);
var newOffset = (newCapacity / 2) - (newSize / 2) - padLeft;
var newItems = new T[newCapacity];
Array.Copy(_items, _offset, newItems, newOffset, insertIndex);
Array.Copy(_items, _offset, newItems, newOffset + 1, _size - insertIndex);
newItems[newOffset + insertIndex] = item;
_items = newItems;
_offset = newOffset;
_size = newSize;
_capacity = newCapacity;
}
else
{
if (insertIndex == 0)
_offset = _offset - 1;
else if (insertIndex < _size)
Array.Copy(_items, _offset + insertIndex, _items, _offset + insertIndex + 1, _size - insertIndex);
_items[_offset + insertIndex] = item;
_size = _size + 1;
}
_version++;
}
Full code
Test insert Count : 131072
| {
"pile_set_name": "StackExchange"
} |
Q:
Вывод в Toast контента из 2х удалённых файлов
Всем привет, есть код вывода содержания файла в интернете. Мне нужно, чтобы в тоаст выводилось содержание из 2х файлов. вот полный код активити
package com.example.byfile;
import android.os.Bundle;
import com.example.byfile.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.net.*;
import java.io.*;
import java.nio.charset.Charset;
public class MainActivity extends Activity {
Button btnSend;
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
final Button btnSend = (Button)this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
final URL myURL = new URL("http://мой-сайт/1.txt");
final URLConnection connection = myURL.openConnection();
connection.setDoInput(true);
final Reader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
final URL myURL2 = new URL("http://мой-сайт/2.txt");
final URLConnection connection2 = myURL2.openConnection();
connection2.setDoInput(true);
final Reader reader2 = new BufferedReader(new InputStreamReader(connection2.getInputStream(), Charset.forName("UTF-8")));
try
{
//буфер 1
final char [] buffer1 = new char[1024];
final StringBuilder message = new StringBuilder();
int readCount;
do
{
readCount = reader.read(buffer1);
message.append(buffer1);
}
while (readCount >= buffer1.length);
//буфер 2
final char [] buffer2 = new char[1024];
final StringBuilder message2 = new StringBuilder();
int readCount2;
do
{
readCount2 = reader2.read(buffer2);
message2.append(buffer2);
}
while (readCount2 >= buffer2.length);
MainActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(MainActivity.this.getApplicationContext(), message + message2.toString(), Toast.LENGTH_LONG).show();
}
});
}
catch (final IOException ex)
{
Log.d("IOException", ex.getMessage());
}
finally
{
reader.close();
}
}
catch (final Exception ex)
{
Log.d("Some exception", ex.getMessage());
}
}
}).start();
}
});
}}
A:
Может вообще дело в этом:
Toast.makeText(MainActivity.this.getApplicationContext(), message + message2.toString(), Toast.LENGTH_LONG).show();
И надо заменить на:
Toast.makeText(MainActivity.this.getApplicationContext(), message.toString() + message2.toString(), Toast.LENGTH_LONG).show();
| {
"pile_set_name": "StackExchange"
} |
Q:
Append text on same line to the JEditorPane as html format
I want to append html content in the JEditorPane, but when I append in this way it inserts a line break automatically at the end of existing text, how to avoid this.
JEditorPane pn = new JEditorPane();
pn.setContentType("text/html");
pn.setText("This is line 1");
...
//after some time
HTMLDocument doc = (HTMLDocument) pn.getDocument();
HTMLEditorKit kit = (HTMLEditorKit) pn.getEditorKit();
kit.insertHTML(doc, doc.getLength(), "<b>Hello</b>", 0, 0, null);
kit.insertHTML(doc, doc.getLength(), "World", 0, 0, null);
It is going to place a linebreak at the end of existing text, everytime insertHTML() is called.
Is this a default behaviour?
If so how I can handle it?
A:
HTMLDocument has methods
public void insertAfterStart(Element elem, String htmlText)
public void insertBeforeEnd(Element elem, String htmlText)
public void insertBeforeStart(Element elem, String htmlText)
public void insertAfterEnd(Element elem, String htmlText)
Where you can pass paragraph or character element (leaf) and html to be inserted
| {
"pile_set_name": "StackExchange"
} |
Q:
Move files based on a date string in the file name batch
I have directory that is continuously being updated with pdf files. The file names look like this:
0001_2014_02_14_000000001_018_001_000.pdf
0001_2014_02_14_000000002_018_002_000.pdf
0001_2014_02_15_000000003_018_001_000.pdf
0001_2014_02_15_000000004_018_002_000.pdf
How would I create a batch file that will parse the date (character place 6) and move the files to a directory called d:\send. To make it more complex I need to subtract 3 days from today's date and only move those files. BTW the modified date of the files won't work. The correct date is the date in the file name.
example:
today is 2/21/2014
find the files that have a prefix of 0001_2014_02_18_??????????.pdf and send them to d:\send
Of course today's date will change daily and this will be scheduled to run everyday.
Thanks for your help.
A:
Test this on some sample files:
@echo off
set day=-3
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
move "????_%yyyy%_%mm%_%dd%_*.pdf" "d:\send"
pause
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does MySQL (InnoDB) table get faster after OPTIMIZE TABLE, but then don't work?
I have a Django web application that stores data in a MySQL InnoDB database. There is a particular page that is accessed a lot on the django admin, and the query is taking a long time (~20 seconds). Since it's the Django internals, the query cannot be changed.
There are 3 tables, A, B, and C. The query looks like:
SELECT *
FROM A
INNER JOIN B ON (A.b_id = B.foo)
INNER JOIN C ON (B.foo = C.id)
ORDER BY A.id DESC
LIMIT 100
A simple join-3-tables together.
The id fields are primary keys and have indexes. A.b_id, B.foo both have their own indexes.
However the query plan looks wrong and says it's not using any keys on B (but it is using the keys for the other joins). From reading lots of MySQL performance stuff it should in theory be using indexes, since it's various const joins that can 'fall through'. It says it has to scan all ~1,200 rows of B.
The weird thing is that I OPTIMIZEed each one on my local machine and re-ran the queries (with SQL_NO_CACHE) and it was much faster, 0.02sec vs. the original 20sec. EXPLAIN on the same query gave a different, and much more sensible result, showing that it can use an index on each one, and that it doesn't have to scan the whole lot. A co-worker ran OPTIMIZE for each one on a testing machine with approximately the same data (which was recently recreated from a loaded dump file) and it also showed a speed increase, and a sensible-explain.
So we ran that on the live system… and it didn't change anything (the speed nor explain). I recreated my MySQL database (DROPed the database and reloaded from a dump), and now the OPTIMIZE doesn't change anything (i.e. ~20sec run time, bad query plan).
Why does this happen? How can I get MySQL to use the correct indexes and get back my 0.02s query time? This blog post ( http://www.xaprb.com/blog/2010/02/07/how-often-should-you-use-optimize-table/ ) implies that OPTIMIZE only really optimizes the primary key (not that b_id, foo are not primary indexes). How can I "rebuild secondary index"? I tried doing ALTER TABLE A ENGINE=InnoDB (and the same for B & C) and there was no change.
Actually the more I look at this, the more it seems to be a MySQL query plan fail. It's doing the wrong query plan and not using indexes that it could use. After doing an OPTIMIZE TABLE etc., it is sometimes able to use the correct indexes. When there's a bad query plan like this, it can be sorta randomly selected, that's why (I think) different machines have different results.
A:
OPTIMIZE rebuilds the table. This (for InnoDB) squeezes out some of the fragmentation and wasted space. This is unlikely to make a noticeable difference in any query.
Also, OPTIMIZE does an ANALYZE. This has a chance of changing the statistics, thereby leading to a different (better or worse) EXPLAIN plan.
Since ANALYZE is much faster (on InnoDB) than OPTIMIZE, just do the ANALYZE.
Various non-ANALYZE actions cause an ANALYZE to be done.
ANALYZE randomly probes the BTrees, gathering stats. Sometimes the resulting stats are poor. There is effectively no way to prevent this from happening. Several partial hacks have been created over the years; 5.6.7 gets close to eliminating this problem with ANALYZE. Here's one of them: http://dev.mysql.com/doc/refman/5.6/en/innodb-parameters.html#sysvar_innodb_stats_persistent_sample_pages
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel 5.5 - From within an API Resource class, how do I get the underlying model class name?
I have a Laravel 5.5 app with an API resource class. How do I get the underlying model class name from within the toArray() method? I'm aware that you can access the properties and methods of the underlying model using $this-> because the class will automatically proxy it to the underlying model. But how do I actually retrieve either the underlying model itself, or more importantly, the model class name? Is there a way?
A:
If you look at the constructor of the Resource class, you'll see the instance is loaded into a $resource property.
get_class($this->resource);
| {
"pile_set_name": "StackExchange"
} |
Q:
Full-page / holy Grail layout with flex
I am trying to use Flexbox with the latest browsers (FF 36, Chrome 41, Opera 28, Safari 8) to achieve full-page holy grail layout. I've gotten it working in everything but Firefox.
The page is split vertically into header, main, footer. main is then split horizontally into three panels. Each panel should scroll independently if their content overflows their bounds. Firefox is the only one that will not do this.
Here is my example: http://jsfiddle.net/bpnjx3v9/1/
html, body {
margin: 0;
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
background-color: blue;
}
#header, #footer {
flex: 0 0 100px;
background-color: blue;
}
#main {
background-color: yellow;
flex: 1 0 0px; /** Don't set parent of component to auto */
display: flex;
flex-direction: row;
}
.panel {
display: flex;
flex-direction: column;
flex: 1 0 auto;
overflow: auto;
}
What I don't understand even after reading the spec is how to make #main only use the height allocated to them by the parent. Instead FF seems to make their "intrinsic height" the height of all the child elements. What makes this work in all other browsers but not FF? Bonus points for pointing out the correct section of the spec that explains this.
A:
Ok, so setting min-height: 0px on #main fixes Firefox and keeps everyone else happy.
http://jsfiddle.net/hughes_matt/bpnjx3v9/7/
#main {
background-color: yellow;
flex: 1 0 0px; /** Don't set parent of component to auto */
display: flex;
flex-direction: row;
}
Couldn't quite explain it but then found this in the spec:
By default, flex items won’t shrink below their minimum content size (the length of the longest word or fixed-size element). To change this, set the min-width or min-height property. (See Implied Minimum Size of Flex Items.)
main's minimum content height is the height of all its children, the panels. By giving that container explicit permission to be smaller than that, it maxes out at the height of its parent. Chrome/Safari/Opera were happy with a flex-basis: 0px, but Firefox needed min-height in addition to that.
Can anyone tell if this is a violation of the spec? Is FF being too strict or the other browsers being too lenient?
| {
"pile_set_name": "StackExchange"
} |
Q:
Get items whose maximal values of nested field less than a parameter value
I have following mapping in elasticsearch:
"mappings": {
"company": {
"properties": {
"name": {
"type": "keyword"
},
"employee": {
"type": "object",
"properties": {
"age": {
"type": "long"
}
}
}
}
}
}
I would like to know if it was possible to get all of companies whose maximal values of employees age are less than 30. In SQL i just need to select company while joining employee and group by company id and make a where clause that max value of age less than 30.
A:
In your case this is easy. Since you will never get duplicate company's back because you only have document per company, you can just do straight search. Example:
GET yourindex/_search
{
"query": {
"bool": {
"must_not": [
{"range": {
"employee.age": {
"gt": 30
}
}}
]
}
}
}
It's worth noting, that if you ever want to do searches that combine employee fields you may run into issues. For example if you want to search for all companies that have an employee with age < 30 AND gender=MALE this model will break down. By default ElasticSearch treats all fields as independent. That means that query would return any companies that had at least one employee that was MALE and one employee that was under 30 years old. You would have no way to say they must be the same person. If you need to do these types of queries, you will need to look at nested mappings and queries, which would change the query above a little bit.
Details:
https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Express: res.json for Array
I want to do the following:
uploads.forEach(function(object){
res.json({
sessionId: object.sessionId,
fileId: object.id,
path: `${baseUrl}/sessions/${object.sessionId}/files/${object.id}/tokens`
});
});
My response looks good so far:
{
"sessionId": "9ff1c415-2dcc-4505-8414-4391967064bc",
"fileId": "510647c3-62fc-4412-b189-a6b872606f10",
"path": "http://localhost:3001/sessions/9ff1c415-2dcc-4505-8414-4391967064bc/files/510647c3-62fc-4412-b189-a6b872606f10/tokens"
}
But I get an error in my console:
Error: Can't set headers after they are sent.
So how do I avoid that error?
A:
res.json will end the request/response cycle so I don't believe you can put this in a forEach as this will attempt to issue a response after one has already fired.(Thats why the error about the headers because they were sent during the first iteration of the for loop and the next iteration trys to change them which isn't allowed because they aren't there anymore -- the response already left for the client)
Instead try filling an Array of objects in your 'forEach'. then pass this into your response object outside of the loop.
var data = []
uploads.forEach(function(object){
data.push({
sessionId: object.sessionId,
fileId: object.id,
path: `${baseUrl}/sessions/${object.sessionId}/files/${object.id}/tokens`
});
});
res.json(data);
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET Identity Framework ApplicationUser is not part of the model
I was searching for a solution for my problem but I didn't find it for my case.
I'm having two projects which shall be linked together. One of them is a database and the other one is an ASP.NET MVC project using the identity framework.
For using my own database I wrote:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MyDataSource", throwIfV1Schema: false)
{
}
[...]
}
But I'm getting the error message:
The entity type ApplicationUser is not part of the model for the current context.
The solutions I found here were refering to inherit the ApplicationDbContext from the IdentityDbContext but that obviously didn't work for me.
A:
It's very generic error.
If you are using model-first or db-first, check your connection string and if it auto generated by EF like this:
<add name="MyDataSource" connectionString="metadata=res://*/Models.***.csdl|res://*/Models.***.ssdl|res://*/Models.***.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(localdb)\ProjectsV12;Initial Catalog=DB_Projectname;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"" providerName="System.Data.EntityClient" />
Then change it to:
<add name="MyDataSource" connectionString="Data Source=(localdb)\ProjectsV12;Initial Catalog=DB_Projectname;Integrated Security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
Yes, just delete model metadata and change provider name to System.Data.SqlClient.
Also, make sure that Identity is connected correctly. You can create an empty asp.net mvc project and compare Startup.cs and Startup.Auth.cs with your app.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to refer to 'this' cell in a conditional formatting formula?
For a field I have conditional formatting with custom formula: =today()>C8+14 and =today()>C8+30 with different styling, basically I want to have a visual styling to highlight older and oldest stuff, two weeks and month. This works. Column C have a date, row can be any row N, so C$N does not help.
However the problem is that I have new rows all the time and it would be easier just to copy-paste the field with rules, and change the date. Rules, however stay as referring to the original here C$N cell.
Could I replace the specific C$N with a this(), self() or is there something like that - to make it more generic copy/pasteable conditional formatting?
A:
Generally: the way to refer to "this" cell is to enter notation for the upper-left corner of the range being formatted. For example, if the range is C1:C, then C1 means "this cell".
For example, formatting C1:C with custom formula
=C1 < today() - 14
will format all cells in C with dates two weeks in the past.
If the range you want to format begins with row 8, and you think you may be inserting rows above that (thus shifting the range), then this formula can be used:
=and(C1 < today() - 14, row(C1) >= 8)
The formatting will apply only to rows starting with 8, but the range being the entire column, the formula will handle insertion of rows above row 8.
A:
This is the shortest possible way I've found to reference the current cell in conditional formatting spanning a range: INDIRECT("RC",FALSE). Documentation is here.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to draw divs to a specific position without collapse already exits div or without override
I am working on a demo where page have selectable jQuery for creation square block(area).
User can select any area and write some comment with color, entire block will be shown specify position. It working fine.
But my main concern is if someone select same area or selecting area with contain already exists blocks.How i can restrict it.
Both block should be exits.
Both should not at same position.
DEMO
A:
The first step for adding multiple rectangles, is to either use another id, or setup the created div directly:
$('<div>')
.css({
'position': 'relative',
'width': width,
'height': height,
'left': beginX,
'top': beginY,
'background': '#000000'
})
.appendTo(this);
step 1.1 is to make the position absolute, so the subsequent elements are not positioned relational to the other added elements.
Step 2 is preventing overlap. Since the selectable is used, this can be done quite easily by checking if any elements are selected (any divs with the .ui-selected element) and don't add the new rectangle in case any are selected inside the stop event callback:
if($(".ui-selected", this).length)return;
An example implementation (took the liberty of introducing a Rect object to contain the positions, but that isn't obligatory. same with the demo class)
$(function() {
var startpos;
function getpos(e){return {X:e.pageX, Y:e.pageY};}
function Rect(start,stop){
this.left = Math.min(start.X,stop.X);
this.top = Math.min(start.Y,stop.Y);
this.width = Math.abs(stop.X - start.X);
this.height = Math.abs(stop.Y - start.Y);
}
$('#tar').selectable({
start: function(e) {
startpos = getpos(e);
},
cancel: '.demo',
stop: function(e) {
if($(".ui-selected", this).length) return;
var rect = new Rect(startpos,getpos(e));
$('<div>')
.css({
'width': rect.width,
'height': rect.height,
'left': rect.left,
'top': rect.top
})
.addClass('demo')
.appendTo(this);
}
});
});
Demo fiddle
edit: as an extra, an easy indication can be given of an intersect by colouring every element that would be 'selected red':
.ui-selecting{
background: red;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How exactly lithium metal is produced?
Wikipedia and other sites say that lithium metal is produced by making the electrolysis of a mixture of half lithium chloride and half potassium chloride "at about 450°C"... What is the chemical reaction of this electro-chemical reaction?
A:
The electrolysis is done as a molten salt.
$\ce{LiCl(liquid) ->[LiCl/KCl @ 400-460 C] Li(liquid) + 1/2Cl2(g)}$
| {
"pile_set_name": "StackExchange"
} |
Q:
Attach a blob to an input of type file in a form
How to append blob to input of type file?
<!-- Input of type file -->
<input type="file" name="uploadedFile" id="uploadedFile" accept="image/*"><br>
// I am getting image from webcam and converting it to a blob
function takepicture() {
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(video, 0, 1, width, height);
var data = canvas.toDataURL('image/png');
var dataURL = canvas.toDataURL();
var blob = dataURItoBlob(dataURL);
photo.setAttribute('src', data);
}
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
}
// How can I append this var blob to "uploadedFile". I want to add this on form submit
A:
I had a similar problem with a fairly complex form in an angular app, so instead of the form I just sent the blob individually using XMLHttpRequest(). This particular "blob" was created in a WebAudioAPI context, creating an audio track in the user's browser.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'someURLForTheUpload', true); //my url had the ID of the item that the blob corresponded to
xhr.responseType = 'Blob';
xhr.setRequestHeader("x-csrf-token",csrf); //if you are doing CSRF stuff
xhr.onload = function(e) { /*irrelevant code*/ };
xhr.send(blob);
A:
You can't change the file input but you can use a hidden input to pass data. ex.:
var hidden_elem = document.getElementById("hidden");
hidden_elem.value = blob;
| {
"pile_set_name": "StackExchange"
} |
Q:
Why scanf("%s",&str); behaves as scanf("%s",str);?
Look at the following code:
#include <stdio.h>
int main()
{
char str[80];
int n;
scanf("%s%n",str,&n);
printf("%s\t%d",str,n);
putchar('\n');
getchar(); //to remove '\n'
scanf("%s%n",&str,&n);
printf("%s\t%d",str,n);
return 0;
}
Here is the input and output:
abc
abc 3
123
123 3
As we know, scanf is a variable parametric function, so its parameters will not be cast when it's called. As a result, parameters must be passed in the type exactly what them should be. However, the type of str is char * (decayed from char (*)[80]), while &str has the type of char (*)[80], although they have the same value, namely &str[0].
So why can scanf("%s",&str); work properly without causing segfault due to pointer arithmetic?
A:
The two pointer values (str and &str) have the same binary value, namely the address of str. They do, however, have different types: When passed as an argument, str is converted to type char *, while &str has type char (*)[80]. The former is correct, while the latter is incorrect. It works, but you are using an incorrect pointer type, and in fact gcc warns about the incorrect argument type to scanf.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Socket Programming - need to do something while listening for connections
I am in the process of designing some hardware interface with python. what I need to do is as follows,
~initialize the drivers
~start the device
~create a socket at port 2626 and wait for clients to connect for receiving data
~if any client got connected then send the hello message while serving all other connected client and add this client to the connected client list.
~if any event happened on the device lets say temperature raise is detected then through this event data to all connected clients.
~any connected clients can ask the server for any specific data.
This is my process. I got the device part working great now its printing data to console and for the socket server I have this following code this working fine as I expect.
but what is problem is after calling "run()" its going inside the while loop. its obvious though. when I am listening for new connections I am not able to call any other function.
while listening for connections I should be able to send / recv. any ideas how to do this?
this is my server program which is working fine for listening for connections. while listening you are not allowed to to anything. :(
#!/usr/bin/env python
import socket
import select
class ChatServer:
def __init__( self, port ):
self.port = port;
self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.srvsock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
self.srvsock.bind( ("", port) )
self.srvsock.listen( 5 )
self.descriptors = [self.srvsock]
print 'Server started on port %s' % port
def run( self ):
while 1:
# Await an event on a readable socket descriptor
(sread, swrite, sexc) = select.select( self.descriptors, [], [] )
# Iterate through the tagged read descriptors
for sock in sread:
# Received a connect to the server (listening) socket
if sock == self.srvsock:
self.accept_new_connection()
else:
# Received something on a client socket
str = sock.recv(100)
# Check to see if the peer socket closed
if str == '':
host,port = sock.getpeername()
str = 'Client left %s:%s\r\n' % (host, port)
self.broadcast_string( str, sock )
sock.close
self.descriptors.remove(sock)
else:
host,port = sock.getpeername()
newstr = '[%s:%s] %s' % (host, port, str)
self.broadcast_string( newstr, sock )
def accept_new_connection( self ):
newsock, (remhost, remport) = self.srvsock.accept()
self.descriptors.append( newsock )
newsock.send("You're connected to the Python server\r\n")
str = 'Client joined %s:%s\r\n' % (remhost, remport)
self.broadcast_string( str, newsock )
def broadcast_string( self, str, omit_sock ):
for sock in self.descriptors:
if sock != self.srvsock and sock != omit_sock:
sock.send(str)
print str,
myServer = ChatServer( 2626 ).run()
Thanks in advance for all your help :)
A:
Since twisted is out of question, I suggest using the socketserver module.
For an easy start, see this example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Capture high resolution video/image html5
I use geUserMedia() to capture image from webcam Intro.
Best resolution that I get is 640 X 480, but I have HD webcam that
records video with 1280 X 720,
takes a picture 2592 X 1944.
How can I capture High Resolution photos?
Here is one sample of code. It doesn't care about canvas size:
<video autoplay id="vid" style="display:none;"></video>
<canvas id="canvas" width="1280" height="720" style="border:1px solid #d3d3d3;"></canvas><br>
<button onclick="snapshot()">Take Picture</button>
<script type="text/javascript">
var video = document.querySelector("#vid");
var canvas = document.querySelector('#canvas');
var ctx = canvas.getContext('2d');
var localMediaStream = null;
var onCameraFail = function (e) {
console.log('Camera did not work.', e);
};
function snapshot() {
if (localMediaStream) {
ctx.drawImage(video, 0, 0);
}
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia({video:true}, function (stream) {
video.src = window.URL.createObjectURL(stream);
localMediaStream = stream;
}, onCameraFail);
</script>
A:
http://www.html5rocks.com/en/tutorials/getusermedia/intro/
=> Setting media constraints (resolution, height, width)
A:
As far as I know WebRTC is currently limited to 640x480 no matter what camera you have. Hopefully this will change soon.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use template parameter class on virtual methods?
I know that is not possible to use template on virtual method, because the compile there is no way to know how to implement all possibilities, but what I need is to use template on a restricted way, like that:
template<typename T, size_t N>
class MatBase {
public:
static constexpr size_t order = N;
using value_type = T;
MatBase() = default;
virtual ~MatBase() = default;
template<class Fn = T(T)>
virtual void Map(Fn&& fn) = 0;
template<class Fn = T(T,T)>
virtual T Reduce(Fn&& fn) = 0;
};
It means, Fn uses the template declared on class, so I think it is possible to compiler infer all possible types. Are there way to do something like that C++?
A:
As you stated you cannot have a templated virtual function. However, why do you need templates at all? See the following example code.
Example Code
#include <cstddef>
template<typename T, size_t N>
class MatBase
{
public:
static constexpr size_t order = N;
using MapFn = T (*)(T);
using ReduceFn = T (*)(T, T);
using value_type = T;
MatBase() = default;
virtual ~MatBase() = default;
virtual void Map(MapFn&& fn) {}
virtual T Reduce(ReduceFn&& fn) {}
};
int main()
{
MatBase<int, 3> m;
return 0;
}
Live Example
A more flexible solution may consider using std::function (e.g., std::function<T (T)>) for the parameters since it gives the caller more flexibility. For example, the caller could use a normal function, a member function, a lambda expression, or a functor object.
| {
"pile_set_name": "StackExchange"
} |
Q:
Torque with single node, Mismatching protocol
I'm trying configure Torque v6.1.1.1 on one server (-> one node, the server itself) with Ubuntu 14.04.
I install it with defauts parameters (configure). After building packages, I installed these modules : server, client and mom.
I configure like this :
server_priv/nodes
hostname
server_name
hostname
mom_priv/config
$pbsserver hostname
$logevent 20
I get this error from mom_log:
LOG_ERROR::read_tcp_reply, Mismatching protocols. Expected protocol 4 but read reply for 0
from server_log
LOG_ERROR::tcp_connect_sockaddr, Failed when trying to open tcp connection - connect() failed [rc = -2] [addr = 127.0.1.1:15003]
I tried severals things like : give a name for mom in config file and add this name in /etc/hosts, replaced hostname by localhost without results.
How can i do for resolved it ?
Thanks a lot
A:
Tkanks a lot, i solved it by
install v6.0.1
run ./torque.setup localhost root
server_priv/nodes : localhost
mom_priv/config : $pbsserver <hostname> and $mom_host localhost
servername : <hostname>
| {
"pile_set_name": "StackExchange"
} |
Q:
create a new entity based on the creation of another (postPersist) Doctrine2
I'm trying to create a new entity based on the creation of another. Example: I have a relationship
Sale <-- 1:M --> Payment
Now, when I persist a Sale, then you must create an initial Payment but i dont know exactly how do it.
i've try:
usage @ORM\HasLifecycleCallbacks(), @ORM\prePersist or @ORM\postPersist, but these methods does not get arguments and i can't persist the Entity Payment. I've even tried to relate Sale with Payment (in prePersist method $payment->setSale($this)) hoping EntityManager to persist Payment for me. info from here
I tried to create a listener (guided from here), but it just does not work, at no time the listener runs
Do it in my SaleController::createAction(), this way is obviously simple and it works, but this is nothing elegant and also goes against the good design of my application, this operation is part of the business logic and repeated in various parts
A:
Out of the 3 solutions you listed 3 is still the least wrong in my opinion. It's simple, not overly complicated and easy to refactor later.
But if you're looking for a clean solution, I think what you need is a form handler or a similar service.
Take a look at FOSUserBundle one.
Basically you will create a PaymentManager class & after handling all the Sales form stuff, pass all the gathered info to PaymentManager and let it handle all the create/persist logic of Payment entity.
| {
"pile_set_name": "StackExchange"
} |
Q:
Construction of Gdiplus::Font in own Constructor
I am trying to construct a Gdiplus::Font inside my own Class constructor.
My Class looks like this:
drawGui.h:
class drawGui {
private:
Gdiplus::Font* font; // Better would be std::unique_ptr<Gdiplus::Font>
public:
drawGui();
~drawGui();
void draw(Gdiplus::Bitmap* image);
};
I tryed the following construction methods in my drawGui.cpp:
drawGui::drawGui() {
Gdiplus::Font fontBuffer(L"Arial", 12);
font = fontBuffer.Clone(); // Exception
}
drawGui::drawGui() { // Compiles but font == NULL
font = new Gdiplus::Font(L"Arial", 12);
}
drawGui::~drawGui() {
delete font;
}
void drawGui::draw(Gdiplus::Bitmap* image) { /* Draw the Font onto an Image */ }
My draw() function is geting called once a second so I want to store the font object in my class and reuse it everytime I call draw().
I am using the latest version of VS2015.
A:
The problem was that GdiplusStartup() was called by another class. Gdi+ was active in my class methods, but not in the class constructor.
| {
"pile_set_name": "StackExchange"
} |
Q:
why the answers and comments has been removed from this question?
Yesterday I read a question and commented on it and there was an answer also on this question why it has been removed and who removed it..
the question is here.
https://islam.stackexchange.com/questions/17042/i-am-drawing-a-picture-of-mohammed-what-did-he-look-like
A:
There was only one answer to that question, which was heavily flagged and deleted (as much for plagiarism as for being offensive), but that wasn't until after you posted this meta question. There was no other answer posted or deleted.
As for the deleted comments, they were flagged as being non-constructive.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fix konsole `\033[0m` not working start from second page of scroll?
I noticed konsole has problem to reset color on next page of scrolling, as screenshot below, run with command for i in {1..100}; do echo "$i"; echo -en '\033[1;42m AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \033[0m'; echo -e 'next text'; done; :
As you can see, the \033[0m get ignored started from 11th row which is the next page of current window view.
gnome-terminal no such issue., but I'm konsole user and looking for a solution to this.
[UPDATE]
I reported bug at https://bugs.kde.org/show_bug.cgi?id=409016
A:
If you change
\033[0m
to
\033[0m\033[K
that will do what you intended. The difference is that when the terminal scrolls up, it will fill the new line with the current background color:
The \E[K clears the current line from the current position to the end of the line (undoing the color-filling done by scrolling).
The color behavior is a feature of Linux console, implemented in other terminals (rxvt, xterm, konsole).
See also:
Background color whitespace when end of the terminal reached
| {
"pile_set_name": "StackExchange"
} |
Q:
Printable prints BufferedImage with incorrect size
So yeah what I am trying here is printing a BufferedImage, all works just fine until you see the outcome. The outcome is to big, the print is to large and doesn't it scales up everything when printing for some reason.
I used ((MM * DPI)/25,4) to calculate the correct pixel length according to paper size from Millimeters but when I print it its to big.
This is the code I wrote for it:
package frik.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import java.awt.event.*;
import javax.swing.*;
import frik.data.Config;
import frik.utils.ImgUtil;
public class Previewer implements Config, Printable, ActionListener{
private JFrame Frame;
private JPanel ImagePanel;
private JLabel PicLabel;
private JButton PrintButton;
private static BufferedImage before;
private static boolean Scaled;
public Previewer(BufferedImage Image, boolean scaled){
this.before = Image;
this.Scaled = scaled;
loop();
}
public int print(Graphics g, PageFormat pf, int page) throws PrinterException{
if (page > 0) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
g.drawImage(0, 0, null);
return Printable.PAGE_EXISTS;
}
public void actionPerformed(ActionEvent e){
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(null, "The Printjob did not successfully complete.", "Print Failure.", JOptionPane.WARNING_MESSAGE);
}
}
}
public void loop(){
UIManager.put("swing.boldMetal", Boolean.FALSE);
Frame = new JFrame("Mold Preview");
ImagePanel = new JPanel();
PrintButton = new JButton("Print Mold");
Frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
if(Scaled){
PicLabel = new JLabel(new ImageIcon(ImgUtil.scaleImage(PAPER_WIDTH / 3, PAPER_HEIGHT / 3, before)));
}else if (!Scaled){
PicLabel = new JLabel(new ImageIcon(before));
}
ImagePanel.setBackground(Color.orange);
ImagePanel.add(PicLabel);
Frame.add("Center", ImagePanel);
PrintButton.addActionListener(this);
Frame.add("North", PrintButton);
Frame.pack();
Frame.setVisible(true);
Frame.setResizable(false);
}
public static void main(String args[]){
new Previewer(before, Scaled);
//////////////////////////////
}
}
So if someone could help me scale the image before printing it according to the printers scale factor, because I am assuming the printers DPI is causing this, so that the image is the exact size in Millimeters when printed exact to the size input in pixels.
That would be great.
A:
I'm not sure if this is an answer per se, but it solves one of the "niggly" issues I'm having.
I think the problem I have is you don't have a source DPI, so it's not possible to convert from one context to another. Let's say you have a image of 200x200, what does that actually mean?
Without the DPI it's meaningless. If the image is 300dpi, then we could use pixels / dpi = inches = 200 / 72 = 0.667 inches. Then we can convert that to pixels @ 72dpi using inches * dpi = 0.667 * 72 = 48
Now, the question the becomes, how do I get the DPI of an image. That's not nearly as easy as it sounds...
import core.ui.UIUtilities;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class TestDPI {
public static final float INCH_PER_MM = 25.4f;
public static void main(String[] args) {
File imageFile = new File("/path/to/your/image");
ImageInputStream iis = null;
try {
iis = ImageIO.createImageInputStream(imageFile);
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (!readers.hasNext()) {
throw new IOException("Bad format, no readers");
}
ImageReader reader = readers.next();
reader.setInput(iis);
IIOMetadata meta = reader.getImageMetadata(0);
Node root = meta.getAsTree("javax_imageio_1.0");
NodeList nl = root.getChildNodes();
float horizontalPixelSize = 0;
float verticalPixelSize = 0;
for (int index = 0; index < nl.getLength(); index++) {
Node child = nl.item(index);
if ("Dimension".equals(child.getNodeName())) {
NodeList dnl = child.getChildNodes();
for (int inner = 0; inner < dnl.getLength(); inner++) {
child = dnl.item(inner);
if ("HorizontalPixelSize".equals(child.getNodeName())) {
horizontalPixelSize = Float.parseFloat(child.getAttributes().getNamedItem("value").getNodeValue());
} else if ("VerticalPixelSize".equals(child.getNodeName())) {
verticalPixelSize = Float.parseFloat(child.getAttributes().getNamedItem("value").getNodeValue());
}
}
}
}
// As "I" understand it. The horizontalPixelSize and verticalPixelSize
// are the number of millimeters per pixel that should be occupied...
System.out.println((INCH_PER_MM / horizontalPixelSize) + "x" + (INCH_PER_MM / verticalPixelSize));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
iis.close();
} catch (Exception e) {
}
}
}
}
Update with preview example
This example basically uses the images own DPI and a target DPI to produce a "print preview"
My test image is 1667x1609 @ 300dpi
300dpi test...
Original size = 1667x1609
cmSize = 14.11396110802889x13.622893474996092
Target (pixel) size = 1667x1609
72dpi test...
Original size = 1667x1609
cmSize = 14.11396110802889x13.622893474996092
Target (pixel) size = 400x386
import static core.ui.ImageUtilities.getScaleFactor;
import static core.ui.ImageUtilities.getScaleFactorToFit;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class TestPrintPreview {
public static void main(String[] args) {
new TestPrintPreview();
}
public TestPrintPreview() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
File imageFile = new File("C:\\hold\\thumbnails\\RentAZilla-300dpi.png");
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(new PreviewPane(imageFile, 300)));
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
// The size of an A4 sheet in CMs
public static final double[] A4_PAPER_SIZE = new double[]{21.0, 29.7};
// The number of CMs per Inch
public static final double CM_PER_INCH = 0.393700787d;
// The number of Inches per CMs
public static final double INCH_PER_CM = 2.545d;
// The numer of Inches per mm's
public static final double INCH_PER_MM = 25.45d;
public class PreviewPane extends JPanel {
private BufferedImage img;
private float targetDPI;
private BufferedImage gridBackground;
public PreviewPane(File imageFile, float outputDPI) {
// This determines the output DPI we want...
targetDPI = outputDPI;
try {
// Get the DPI from the image...
double[] imgDPI = getDPI(imageFile);
// Read the image
img = ImageIO.read(imageFile);
// Output the original size...
System.out.println("Original size = " + img.getWidth() + "x" + img.getHeight());
// Calculate the size of the image in cm's
double cmWidth = pixelsToCms(img.getWidth(), imgDPI[0]);
double cmHeight = pixelsToCms(img.getHeight(), imgDPI[1]);
System.out.println("cmSize = " + cmWidth + "x" + cmHeight);
// Calculate the new image size based on the target DPI and
// the cm size of the image...
int imgWidth = (int) Math.round(cmsToPixel(cmWidth, targetDPI));
int imgHeight = (int) Math.round(cmsToPixel(cmHeight, targetDPI));
System.out.println("Target size = " + imgWidth + "x" + imgHeight);
// Create a scaled instance of the image to fit within the
// target boundries
img = getScaledInstanceToFit(img, new Dimension(imgWidth, imgHeight));
} catch (IOException ex) {
Logger.getLogger(TestPrintPreview.class.getName()).log(Level.SEVERE, null, ex);
}
setBackground(Color.WHITE);
}
@Override
public Dimension getPreferredSize() {
// Return the size of the component based on the size of
// an A4 sheet of paper and the target DPI
return new Dimension(
(int) Math.round(cmsToPixel(A4_PAPER_SIZE[0], targetDPI)),
(int) Math.round(cmsToPixel(A4_PAPER_SIZE[1], targetDPI)));
}
/**
* Generates a grid of 1x1 cm cells. This is used to allow you
* to compare the differences of different DPI and ensure that the
* output is what you are expecting...
* @return
*/
protected BufferedImage getGridBackground() {
if (gridBackground == null) {
// Calculate the width and height we need...
int width = (int) Math.round(cmsToPixel(A4_PAPER_SIZE[0], targetDPI));
int height = (int) Math.round(cmsToPixel(A4_PAPER_SIZE[1], targetDPI));
// Create the grid...
gridBackground = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = gridBackground.createGraphics();
// Calculate the size of each cell (1cm square)
double cmAsPixel = cmsToPixel(1, targetDPI);
float xPos = 0;
float yPos = 0;
g2d.setColor(new Color(225, 0, 0, 128));
int count = 0;
Font font = g2d.getFont();
g2d.setFont(font.deriveFont(8f));
FontMetrics fm = g2d.getFontMetrics();
// Draw the horizontal lines
while (xPos < gridBackground.getWidth()) {
g2d.draw(new Line2D.Float(xPos, 0, xPos, gridBackground.getHeight()));
// Add the text markers...
String text = (count++) + "cm";
float x = xPos - fm.stringWidth(text);
g2d.drawString(text, x, fm.getAscent());
xPos += cmAsPixel;
}
// Draw the vertical lines
count = 0;
while (yPos < gridBackground.getHeight()) {
g2d.draw(new Line2D.Float(0, yPos, gridBackground.getWidth(), yPos));
// Add the text markers
String text = (count++) + "cm";
float y = (yPos - fm.getHeight()) + fm.getAscent();
g2d.drawString(text, 0, y);
yPos += cmAsPixel;
}
g2d.dispose();
}
return gridBackground;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
// Paint the image...
g2d.drawImage(img, 0, 0, this);
// Paint the grid...
g2d.drawImage(getGridBackground(), 0, 0, this);
g2d.dispose();
}
}
/**
* Converts the given pixels to cm's based on the supplied DPI
* @param pixels
* @param dpi
* @return
*/
public static double pixelsToCms(double pixels, double dpi) {
return inchesToCms(pixels / dpi);
}
/**
* Converts the given cm's to pixels based on the supplied DPI
* @param cms
* @param dpi
* @return
*/
public static double cmsToPixel(double cms, double dpi) {
return cmToInches(cms) * dpi;
}
/**
* Converts the given cm's to inches
* @param cms
* @return
*/
public static double cmToInches(double cms) {
return cms * CM_PER_INCH;
}
/**
* Converts the given inches to cm's
* @param inch
* @return
*/
public static double inchesToCms(double inch) {
return inch * INCH_PER_CM;
}
/**
* Gets the DPI for the specified image. This does return the horizontal
* and vertical DPI, but you could conceivably use just use one of the values
* @param imageFile
* @return
* @throws IOException
*/
public double[] getDPI(File imageFile) throws IOException {
double[] dpi = new double[]{72, 72};
ImageInputStream iis = null;
try {
iis = ImageIO.createImageInputStream(imageFile);
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (!readers.hasNext()) {
throw new IOException("Bad format, no readers");
}
ImageReader reader = readers.next();
reader.setInput(iis);
IIOMetadata meta = reader.getImageMetadata(0);
Node root = meta.getAsTree("javax_imageio_1.0");
NodeList nl = root.getChildNodes();
float horizontalPixelSize = 0;
float verticalPixelSize = 0;
for (int index = 0; index < nl.getLength(); index++) {
Node child = nl.item(index);
if ("Dimension".equals(child.getNodeName())) {
NodeList dnl = child.getChildNodes();
for (int inner = 0; inner < dnl.getLength(); inner++) {
child = dnl.item(inner);
if ("HorizontalPixelSize".equals(child.getNodeName())) {
horizontalPixelSize = Float.parseFloat(child.getAttributes().getNamedItem("value").getNodeValue());
} else if ("VerticalPixelSize".equals(child.getNodeName())) {
verticalPixelSize = Float.parseFloat(child.getAttributes().getNamedItem("value").getNodeValue());
}
}
}
}
dpi = new double[]{(INCH_PER_MM / horizontalPixelSize), (INCH_PER_MM / verticalPixelSize)};
} finally {
try {
iis.close();
} catch (Exception e) {
}
}
return dpi;
}
/**
* Returns a scaled instance of the image to fit within the specified
* area. This means that the image is guaranteed to be <= size.width and
* <= size.height
* @param img
* @param size
* @return
*/
public static BufferedImage getScaledInstanceToFit(BufferedImage img, Dimension size) {
double scaleFactor = getScaleFactorToFit(img, size);
return getScaledInstance(img, scaleFactor);
}
public static double getScaleFactorToFit(BufferedImage img, Dimension size) {
double dScale = 1;
if (img != null) {
int imageWidth = img.getWidth();
int imageHeight = img.getHeight();
dScale = getScaleFactorToFit(new Dimension(imageWidth, imageHeight), size);
}
return dScale;
}
/**
* Returns the required scale factor to fit the original size into the toFit
* size.
* @param original
* @param toFit
* @return
*/
public static double getScaleFactorToFit(Dimension original, Dimension toFit) {
double dScale = 1d;
if (original != null && toFit != null) {
double dScaleWidth = getScaleFactor(original.width, toFit.width);
double dScaleHeight = getScaleFactor(original.height, toFit.height);
dScale = Math.min(dScaleHeight, dScaleWidth);
}
return dScale;
}
/**
* Returns the scale factor required to go from the master size to the
* target size
* @param iMasterSize
* @param iTargetSize
* @return
*/
public static double getScaleFactor(int iMasterSize, int iTargetSize) {
return (double) iTargetSize / (double) iMasterSize;
}
/**
* Returns a scaled instance of the image based on the supplied scale factor.
*
* The images width and height are multiplied by the supplied scale factor
* @param img
* @param dScaleFactor
* @return
*/
protected static BufferedImage getScaledInstance(BufferedImage img, double dScaleFactor) {
BufferedImage imgScale = img;
int iImageWidth = (int) Math.round(img.getWidth() * dScaleFactor);
int iImageHeight = (int) Math.round(img.getHeight() * dScaleFactor);
if (dScaleFactor <= 1.0d) {
imgScale = getScaledDownInstance(img, iImageWidth, iImageHeight);
} else {
imgScale = getScaledUpInstance(img, iImageWidth, iImageHeight);
}
return imgScale;
}
/**
* Scales the specified image down to be less then equal to the target width
* and height.
*
* The image is scaled using a divide an conquer approach to provide
* the best scaling possible
* @param img
* @param targetWidth
* @param targetHeight
* @return
*/
protected static BufferedImage getScaledDownInstance(BufferedImage img,
int targetWidth,
int targetHeight) {
int type = (img.getTransparency() == Transparency.OPAQUE)
? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = (BufferedImage) img;
if (targetHeight > 0 || targetWidth > 0) {
int w, h;
w = img.getWidth();
h = img.getHeight();
do {
if (w > targetWidth) {
w /= 2;
if (w < targetWidth) {
w = targetWidth;
}
}
if (h > targetHeight) {
h /= 2;
if (h < targetHeight) {
h = targetHeight;
}
}
BufferedImage tmp = new BufferedImage(Math.max(w, 1), Math.max(h, 1), type);
Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
} while (w != targetWidth || h != targetHeight);
} else {
ret = new BufferedImage(1, 1, type);
}
return ret;
}
/**
/**
* Scales the specified image up
*
* The image is scaled using a divide an conquer approach to provide
* the best scaling possible
* @param img
* @param targetWidth
* @param targetHeight
* @return
*/
protected static BufferedImage getScaledUpInstance(BufferedImage img,
int targetWidth,
int targetHeight) {
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = (BufferedImage) img;
int w, h;
w = img.getWidth();
h = img.getHeight();
do {
if (w < targetWidth) {
w *= 2;
if (w > targetWidth) {
w = targetWidth;
}
}
if (h < targetHeight) {
h *= 2;
if (h > targetHeight) {
h = targetHeight;
}
}
BufferedImage tmp = new BufferedImage(w, h, type);
Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
tmp = null;
} while (w != targetWidth || h != targetHeight);
return ret;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to know if something is a primitive concept, a law, a definition or a theorem
Some basic Physics books are often misguiding in the sense that they don't make clear whether something is a primitive concept, a law, a definition or a theorem. This is often a little confusing. I've asked here some moments ago if there's a definition of force, and I've been redirected to a question about whether Newton's Laws are laws or definitions of mass and force.
This is just an example, but there are many others, like for instance, the conservation of energy, which some books present as a theorem, and some places says that this is a law of Physics. Time on the other hand, is something that according to Feynman's lectures on Physics, cannot be defined, so we just say how to measure it and leave it as a primitive concept.
In this context: how in general can we identify whether something is a primitive concept, a fundamental law of Physics, a definition or a theorem?
A:
how in general can we identify whether something is a primitive concept, a fundamental law of Physics, a definition or a theorem?
You can't, because it depends completely on context and on the taste of whoever has written the presentation you're using.
For example, some people like to consider Gauss's law to be a definition of charge, some people call it a law of physics, and some people call it a theorem. None of these choices are right or wrong in and of themselves.
Here's an example from mathematics. You can take Euclid's postulates and prove the Pythagorean theorem. But you can also take Euclid's first four postulates, get rid of the parallel postulate, and add in the Pythagorean "theorem" as a postulate. Then the parallel postulate becomes a theorem.
So applying this to physics, nobody can say whether the Pythagorean theorem is a law (in the sense that it's an empirical fact about how space behaves) or a theorem.
The same thing happens with primitive notions. For example, a line can be a primitive notion (as in Euclid) or a defined one (in the Cartesian approach where you define it as a set of points).
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if record exists before saving
I have a Customer class linked to several other classes via foreign key. I want to have the forms working in such a way that if the submitted customer record already exists, then this record will be used as the foreign key for the dependent class.
I've declared the Customer class as:
class Customer(CustomerBaseInfo):
date_time_added = models.DateTimeField(default=datetime.today)
source = models.ForeignKey(Source, blank=False)
email_address = models.CharField(max_length=75)
phone_number = models.CharField(max_length=20)
preffered_contact_method = models.ForeignKey(PreferredContact)
best_time_to_contact = models.ForeignKey(BestTime)
def __unicode__(self):
return self.first_name
One of the classes that link to the Customer class look like this:
class Message(models.Model):
date_time_added = models.DateTimeField(default=datetime.today)
message_type = models.ForeignKey(MessageType)
customer = models.ForeignKey(Customer)
representative = models.ForeignKey(Representative)
vehicle = models.CharField(max_length=80)
message = models.TextField(null=True)
def __unicode__(self):
return self.date_time_added
A:
get_or_create() will return the model after creating it if it does not exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
conditional where Sql server
I have a query
select idpays,idannonce,idville
from annonces
and i need to make a conditional where, where idpays=1 don't show idville null else for other idpays show idville null
How can i do this please?
regards
A:
You may looking for this
WHERE ( idpays = 1 AND idville NOT NULL) OR idpays > 1
A:
You don't specify what, exactly, should be displayed when idpays=1, but here's a basis for what you've asked - you can do this with a case in the SELECT which sounds more like the problem you've described rather than a where clause:
select idpays,idannounce,
case when idpays=1 then idville
else null end
from unknowntable
EDIT based on OP comments- must admit I'm not sure I understand the OP's requirements exactly at this point:
select
from table
where (idpays<>1) or
(idpays=1 and idville not null)
| {
"pile_set_name": "StackExchange"
} |
Q:
bash sh differences, script conversion
I have this script that was written in bash
#!/bin/sh
# script makes grep directly on dmesg output
# looking for 'USB disconnect' phrase if
# it finds it then machine is rebooted
# ver 1.2
clear
UNPLUG_MESSAGE="PLEASE UNPLUG THE USB STICK NOW"
echo $UNPLUG_MESSAGE && sleep 2
while true; do
USB_STATUS=`dmesg | tail -n 5 | grep 'disconnect'`
if [[ $USB_STATUS == *USB?disconnect* ]]
then
clear && echo "Rebooting... bye"
sleep 1 && sudo reboot
elif [[ $USB_STATUS != *USB?disconnect* ]]
then
clear && echo "Please remove USB drive..."
sleep 2
fi
done
exit 0
After changing #!/bin/bash to #!/bin/sh, the script does not work any more - what should I change in this script?
I got errors like unknown operand USB?disconnect, ./reboot.sh: 16: ./reboot.sh: [[: not found, etc.
A:
On ubuntu sh is dash (you can run ls -l $(which sh) to see this).
In dash there is no [[ (double brackets) operator. You have to use the test builtin function or [ (single brackets) only.
You can replace:
if [[ $USB_STATUS == *USB?disconnect* ]]
...
elif [[ $USB_STATUS != *USB?disconnect* ]]
By:
if [ $(echo $USB_STATUS | grep -c "USB disconnect") != 0 ]
...
elif [ $(echo $USB_STATUS | grep -c "USB disconnect") = 0 ]
| {
"pile_set_name": "StackExchange"
} |
Q:
Integration of refinery cms in rails 4 existing application
How to integrate refinery cms in existing rails 4 application.
I have already added in gemfile this gem 'refinerycms-i18n',
github: 'refinery/refinerycms-i18n', branch: 'master'
gem 'refinerycms', github: 'refinery/refinerycms', branch: "master"
and I tried to do
rails g refinery:engine app name:string description:text
but the error is
Could not find generator refinery:engine.
How to resolve this
A:
I never do this, but here there is a official: Guide I hope it's useful!
| {
"pile_set_name": "StackExchange"
} |
Q:
TCP Connection: Recreating a socket that has been closed
I am writing a client-side FTP program, and so far, after a successful connection the server will run in extended passive mode. Using the port number returned from the EPSV command, I can create client-side sockets like this:
void create_data_channel() {
if ((data_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Cannot create client socket for data connection :(");
exit(1);
}
data_server_addr.sin_family = AF_INET;
data_server_addr.sin_port = htons(port);
data_server_addr.sin_addr = *((struct in_addr *)ftp_server->h_addr);
bzero(&(data_server_addr.sin_zero),8);
// Connect to the ftp server at given port for data connection
if (connect(data_sock, (struct sockaddr *)&data_server_addr,
sizeof(struct sockaddr)) == -1) {
perror("Cannot connect to the ftp server for data connection :(");
exit(1);
}
}
Now, whenever I want to send a command involving the data channel (e.g. LIST), I can first open a new socket using the method above, and get/send whatever data I need from/to the ftp server. Then, I close the data connection using close(data_sock).
This works well for the first LIST command. However, if I were to try to run two or more LIST command, the program fails with my error message "Cannot connect to the ftp server for data connection :(". Why is this so? What am I missing here?
A:
Typically a FTP server does not accept multiple connections to the same dynamic port. Therefore the PASV or EPSV commands need to be done before each data transfer so that the server creates a new listen socket and returns its port number to the client.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set a dict value using another key of the same dict
I want to do something like this:
my_dict = {"key": "value", "key1": "value1", "key2": my_dict["key"]}
and have the result be:
{"key": "value", "key1": "value1", "key2": "value"}
Currently getting unresolved reference unless I declare the dict() prior. Otherwise I get a key error.
A:
Set the value of key2 to something phony (say, None), initialize my_dict properly, and then change the value of my_dict['key2'] to my_dict["key"].
| {
"pile_set_name": "StackExchange"
} |
Q:
Android: Positioning in file (similar to fseek in C++)?
I'm trying to read some data from html file that I opened from internet using httpClient. I'm using readLine() function in loop for reading.
The lines I want to read start at 500th row. Is there a faster way to position at file?
Problem is that reading all that unnecessary data takes too long (almost 10 seconds to finish loading all).
A:
From the InputStream you can skip a number of characters using skip(long n)
| {
"pile_set_name": "StackExchange"
} |
Q:
Reference request: Oldest calculus, real analysis books with exercises?
Per the title, what are some of the oldest calculus, real analysis books out there with exercises? Maybe there are some hidden gems from before the 20th century out there.
Edit. Unsolved exercises are fine. Same with solved.
A:
It depends if you mean exercises with or without solutions.
The former don’t differ much from example-driven textbooks (e.g. Euler’s Institutiones (1755, 1768, 1769, 1770), Lehmus’ Uebungs-Aufgaben (1823), Gregory’s Examples (1841), Sohncke’s Aufgaben (1850), Todhunter’s Treatise (1852, 1857), Lübsen’s Selbstunterricht books (1853-), Schlömilch’s Übungsbücher (1868, 1870)), papers (e.g. Cauchy’s Exercices (1826-) are really reprints of his papers), or tables (e.g. Bierens de Haan (1858)). In fact, like many “earliest” questions this soon devolves into meaninglessness, as old texts often called Proposition what we would call an Exercise or Problem: e.g. Newton (1687), l’Hôpital (1696) — in that sense they all qualify.
The latter are a more recent phenomenon, e.g. Boole’s book (1859) seems to be an early one with mostly unsolved exercises at chapters’ ends.
A:
In my search for "the oldest", I found two pre-1800 textbooks on analysis with solved problems:
Select Exercises for Young Proficients in the Mathematicks is from 1752. Part 5 deals with the method of fluxions, which is how Newton referred to real analysis.
More solved problems on fluxions by the same author, Thomas Simpson, are in his 1776 book The doctrine and application of fluxions.
Here is one problem from the 1776 book:
A:
L'hôpital's 1696 Analyse des Infiniment Petits was the most popular and influential calculus textbook of the eighteenth century. Here is an image from plate 7 in John Quincy Adams's copy:
This corresponds to the following problem from page 201:
Soient données trois lignes quelconques L, M, N; (Fig. 128, Pl. 7) &
soient entendues de chacun des points L, l de la ligne L deux tangents
LM & LN, lm & ln, aux deux courbes M & N, une à chacune. On demande la
quatriéme courbe C, qui ait pour tangentes toutes les droites MN, mn
qui joignent les points touchans des courbes M, N.
I translate this as:
Let three curves $L, M, N$ be given, and from each point $l$ on the curve
$L$ let the two tangents $lm$ and $ln$ be extended to the two curves $M$ and
$N$. What is the fourth curve $C$, which has for tangents all the lines
$mn$ which join the points touching the curves $M$ and $N$?
| {
"pile_set_name": "StackExchange"
} |
Q:
Integral of $\sqrt{1+\tan^2x}$
Possible Duplicate:
Ways to evaluate $\int \sec \theta d \theta$
I'm having a bit of a problem with an integral. The original problem was the length of a curve given parametrically. I've managed to reduce that integral to:
$$\int_0^{\pi/4}\sqrt{1+\tan^2x}\ \mathrm{d}x$$
I've tried some substitions for $\tan x$, but always got stuck on a worse form.
A:
This integral is discussed in most calculus books. I will write a detailed solution, because thinking about this integral gives a good workout in techniques of integration.
You have already been told about the useful identity
$$1+\tan^2 x=\frac{1}{\cos^2 x}.$$
You may have seen this identity as
$$1+\tan^2x =\sec^2 x.$$
There are slightly tricky things about taking square roots, but they are not a problem in the interval where you are working. We end up wanting to find
$\int \sec x dx$, or equivalently $\int dx/(\cos x)$.
The strategy we will use is one that is useful when we are integrating a combination of powers of $\sin x$ and $\cos x$, with one of the powers odd.
Rewrite the integral as
$$\int \frac{\cos x}{\cos^2 x}dx = \int \frac{ \cos x}{1 -\sin^2 x}dx.$$
Make the substitution $u=\sin x$. Then $du=\cos x dx$.
So now our indefinite integral is
$$\int \frac{du}{1-u^2}.$$
It is more convenient to make the substitution in the "limits" of integration. When $x=\pi/4$, we have $u=1/\sqrt{2}$ and when $x=0$, we have $u=0$, so we want
$$\int_{u=0}^{\pi/4} \frac{du}{1-u^2}.$$
Our integral is now in perfect shape for the method of "partial fractions." By going through the machinery of partial fractions, or by inspection, we have
$$\frac{1}{1-u^2}=\frac{1}{1-u^2}=\frac{1/2}{1-u}+\frac{1/2}{1+u}.$$
We have arrived at
$$\int_0^{1/\sqrt{2}} \left(\frac{1/2}{1-u}+\frac{1/2}{1+u}\right)du.$$
Finally, everything is easy. By substitution, or by inspection, we have
$$\int\frac{1/2}{1-u}du=-(1/2)\ln(|1-u|) +C \qquad\text{and}\qquad \int\frac{1/2}{1+u}du=(1/2)\ln(|1+u|) +C.$$
(We don't have to worry about the constant of integration, since now we will be substituting the limits.)
If we are in the mood, we can combine things, using the properties of logarithms, to conclude that the indefinite integral is
$$\frac{1}{2}\ln\left(\left|\frac{1+u}{1-u}\right|\right)+C.$$
A lot of work! But at least we got to practice a lot of techniques of integration. The integral $\int \sec x dx$ is one of the nastiest ones that one is likely to meet. Actually, it does show up in real applications.
A magic way: We want
$$\int \sec x dx.$$
Multiply "top" and "bottom" by $\sec x +\tan x$. We get
$$\int \frac{\sec^2 x +\sec x\tan x}{\sec x+\tan x}dx.$$
Let $u=\sec x+\tan x$. Then from standard (?) differentiation formulas, we have
$$du =\sec x\tan x+\sec^2 x.$$
Note that this is more or less exactly what we have on top.
So our indefinite integral simplifies to
$$\int \frac{du}{u}=\ln |u| +C$$
and it's over.
Why the magic substitution? Because it works, and I happen to remember it. However, the slow, systematic procedure that was the first one discussed is the one you should concentrate on.
And there are a number of other approaches to the integral!
A:
As DJC told you, you may write $1+\tan^2 x$ using a common denominator as
$$\frac{\cos^2 x+ \sin^2 x}{\cos^2 x} = \frac{1}{\cos^2 x} $$
so the square root of it is simply $\cos x$. Well, it's the absolute value - for real values of $\cos x$ - but $\cos x$ is positive between $0$ and $\pi/4$, anyway.
So the goal is to integral $1/\cos x$ from $0$ to $\pi/4$. One finds the indefinite integral first. It is
$$ \int \frac{1}{\cos x} dx = \ln \left[\frac{\cos (x/2) + \sin(x/2)}{\cos (x/2) - \sin(x/2)}\right] + C $$
You may differentiate the right hand side to see that you get the left hand side. Now, the definite integral is the difference of this function between $\pi/4$ and $0$ which is actually ${\rm arcsinh}(1)$.
A:
Here is a way to understand the "Magic way."
What is the derivative of $\sec(x)$? It is $\tan(x)\sec(x)dx$. What is the derivative of $\tan(x)$? It is $\sec(x)^2dx$. From looking at this, we can see that if we factor $\sec(x)$ out of the sum, we get the sum again ! Precisely this means that $$(\sec(x)+\tan(x))'=\sec(x)(\sec(x)+\tan(x)).$$ Hence $$\sec(x)=\frac{(\sec(x)+\tan(x))'}{\sec(x)+\tan(x)}=\left(\log |\sec(x)+\tan(x)|\right)'$$ where the last equality comes from recognizing the logarithmic derivative.
Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenOffice xSentenceCursor stuck at end of paragraph
I am using this routine to iterate over sentences in an OpenOffice document:
while (moreParagraphsOO) {
while (moreSentencesOO) {
xSentenceCursor.gotoEndOfSentence(true);
textSentence = xSentenceCursor.getString();
xTextViewCursor.gotoRange(xSentenceCursor.getStart(), false);
xTextViewCursor.gotoRange(xSentenceCursor.getEnd(), true);
if (!textSentence.equals("")) {
return textSentence;
}
moreSentencesOO = xSentenceCursor.gotoNextSentence(false);
}
moreParagraphsOO = xParagraphCursor.gotoNextParagraph(false);
moreSentencesOO = xSentenceCursor.gotoStartOfSentence(false);
}
It works fine unless it finds a paragraph which ends with ". ", this is, a period and one or several whitespaces after it. In that case it enters and infinite loop executing the
while (moreSentencesOO)
...
moreSentencesOO = xSentenceCursor.gotoNextSentence(false);
endlessly. I am not so proeficient with OpenOffice API, and I am quite stuck here. Any ideas?
Thanks.
EDIT: I have come with a somewhat awkward patch consisting in checking the current position of the cursor, and if it does not advance between two iterations, jump to next paragraph:
while (moreParagraphsOO) {
while (moreSentencesOO) {
/**********************************/
int previousPosX = xTextViewCursor.getPosition().X;
int previousPosY = xTextViewCursor.getPosition().Y;
/*********************************/
xSentenceCursor.gotoEndOfSentence(true);
textSentence = xSentenceCursor.getString();
xTextViewCursor.gotoRange(xSentenceCursor.getStart(), false);
xTextViewCursor.gotoRange(xSentenceCursor.getEnd(), true);
if (!textSentence.equals("")) {
return textSentence;
}
moreSentencesOO = xSentenceCursor.gotoNextSentence(false);
/**********************************/
if (previousPosX == xTextViewCursor.getPosition().X &&
previousPosY == xTextViewCursor.getPosition().Y){
xParagraphCursor.gotoNextParagraph(false);
}
/**********************************/
}
moreParagraphsOO = xParagraphCursor.gotoNextParagraph(false);
moreSentencesOO = xSentenceCursor.gotoStartOfSentence(false);
}
It seems to work, but I am unsure about whether it could introduce future problems. I would rather prefer an "elegant" solution.
A:
According to gotoNextSentence(), it should only return true if the cursor was moved, so this is a bug. Consider filing a report.
The problem seems to occur when isEndOfSentence() but not isStartOfSentence(). So test for that instead of getPosition().
Here is Andrew Pitonyak's Basic macro that I modified to include this fix.
Sub CountSentences
oCursor = ThisComponent.Text.createTextCursor()
oCursor.gotoStart(False)
Do
nSentences = nSentences + 1
If oCursor.isEndOfSentence() And Not oCursor.isStartOfSentence() Then
oCursor.goRight(1, False)
End If
Loop While oCursor.gotoNextSentence(False)
MsgBox nSentences & " sentences."
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the safest way to run .exe files on Ubuntu GNOME?
I have already tried wine, but that just gave me a mess!! But I never tried PlayOnLinux yet, but I think it will just cause the same issue! I already tried using a Windows 10 ISO for a VM, but it took forever and failed to boot. If someone could help find the safest way to run .exe files virus-free please.
And before, it broke my Package System!
A:
There is no (safe or unsafe) way to run .exe files on Linux systems ... "virus-free"" or not ...
.exe files are Windows executables, to run them you have to use wine or a Windows VM.
Maybe you did not setup the Windows VM properly ... it needs a bit of time to learn everything.
I recommend to use KVM or VirtualBox for this purpose, both solutions are available in Ubuntu.
VirtualBox is the most easy application to learn about and use virtualization and qemu (KVM) with virt-manager, which provides a better performance, is better for more advanced users.
| {
"pile_set_name": "StackExchange"
} |
Q:
$error variable not available in modules?
I've grown very fond of using try..catch statements in Powershell scripts (specially when calling external programs/COM objects etc), and then use the automatic $error variable for error handling.
My problem is that I've found that when encapsualting such methods in modules, the $error variable doesn't work anymore. I guess this has something to do with what invocation you're actually running when calling a function from within a module, but it's infuriating anyway. Does anyone here know why, or even better: have a solution?
I do have a workaround: using Invoke-Expression with the -errorVariable parameter for making any external calls, but this is rather complicated - and not always fool proof.
A:
Maybe using the $_ variable within the catch block will do?
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ safeguards exceeding limits of integer
I am working on a chapter review of a book: at the end of the chapter there are some questions/tasks which you are to complete.
I decided to do them in the format of a program rather than a text file:
#include <iostream>
int main(int argc, char* argv[]) {
std::cout << "Chapter review\n"
<< "1. Why does C++ have more than one integer type?\n"
<< "\tTo be able to represent more accurate values & save memory by only allocating what is needed for the task at hand.\n"
<< "2. Declare variables matching the following descriptions:\n"
<< "a.\tA short integer with the value 80:\n";
short myVal1 = 80;
std::cout << "\t\t\"short myVal1 = 80;\": " << myVal1 << std::endl
<< "b.\tAn unsigned int integer with the value 42,110:\n";
unsigned int myVal2 = 42110;
std::cout << "\t\t\"unsigned int myVal2 = 42110;\": " << myVal2 << std::endl
<< "c.\tAn integer with the value 3,000,000,000:\n";
float myVal3 = 3E+9;
std::cout << "\t\t\"float myVal3 = 3E+9;\": " << static_cast<unsigned int>(myVal3) << std::endl
<< "3. What safeguards does C++ provide to keep you from exceeding the limits of an integer type?\n"
<< "\tWhen it reaches maximum number it starts from the begging again (lowest point).\n"
<< "4. What is the distinction between 33L and 33?\n"
<< "\t33L is of type long, 33 is of type int.\n"
<< "5. Consider the two C++ statements that follow:\n\tchar grade = 65;\n\tchar grade = 'A';\nAre they equivalent?\n"
<< "\tYes, the ASCII decimal number for 'A' is '65'.\n"
<< "6. How could you use C++ to find out which character the code 88 represents?\nCome up with at least two ways.\n"
<< "\t1: \"static_cast<char>(88);\": " << static_cast<char>(88) << std::endl; // 1.
char myChar = 88;
std::cout << "\t2: \"char myChar = 88;\": " << myChar << std::endl // 2.
<< "\t3: \"std::cout << (char) 88;\" " << (char) 88 << std::endl // 3.
<< "\t4: \"std::cout << char (88);\": " << char (88) << std::endl // 4.
<< "7. Assigning a long value to a float can result in a rounding error. What about assigning long to double? long long to double?\n"
<< "\tlong -> double: Rounding error.\n\tlong long -> double: Significantly incorrect number and/or rounding error.\n"
<< "8. Evaluate the following expressions as C++ would:\n"
<< "a.\t8 * 9 + 2\n"
<< "\t\tMultiplication (8 * 9 = 72) -> addition (72 + 2 = 74).\n"
<< "b.\t6 * 3 / 4\n"
<< "\t\tMultiplication (6 * 3 = 18 -> division (18 / 4 = 4).\n"
<< "c.\t3 / 4 * 6\n"
<< "\t\tDivision (3 / 4 = 0) -> multiplication (0 * 6 = 0).\n"
<< "d.\t6.0 * 3 / 4\n"
<< "\t\tMultiplication (6.0 * 3 -> 18.0) -> division (18.0 / 4 = 4.5).\n"
<< "e.\t 15 % 4\n"
<< "\t\tDivision (15 / 4 = 3.75) Then returns the reminder, basically how many times can 4 go into 15 in this case that is 3 (3*4 = 12).\n"
<< "9. Suppose x1 and x2 are two type of double variables that you want to add as integers and assign to an integer variable. Construct a C++ statement for doing so. What if you wanted to add them as type double and then convert to int?\n"
<< "\t1: \"int myInt = static_cast<double>(doubleVar);\"\n\t2: \"int myInt = int (doubleVar);\".\n"
<< "10. What is the variable type for each of the following declarations?\n"
<< "a.\t\"auto cars = 15;\"\n\t\tint\n"
<< "b.\t\"auto iou = 150.37f;\"\n\t\tfloat\n"
<< "c.\t\"auto level = 'B';\"\n\t\tchar\n"
<< "d.\t\"auto crat = U'/U00002155';\"\n\t\twchar_t ?\n"
<< "e.\t\"auto fract = 8.25f/.25;\"\n\t\tfloat" << std::endl;
return 0;
}
It's been a while since I read chapter 3 due to moving/some other real life stuff.
What I am unsure about here is basically question number 3: it says safeguards as in plural.
However I am only aware of one: that it starts from the beginning again after reaching maximum value? Am I missing something here?
Let me know if you see any other errors also - I am doing this to learn after all :).
A:
Basically I can't accept a comment as an answer so to sum it up:
There are none safeguards, I misunderstood that question which @n.m. clarified for me.
10.e was wrong as pointed out by @Jarod42, which is correct.
Thanks!
| {
"pile_set_name": "StackExchange"
} |
Q:
React router nested not working
I'm trying to create routes in my provider but it doesn't work out for nested levels.
Until one level it is working fine.
Find the code snippet below
render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={PageTemplate}>
<Route path="/login" component={Login}/>
<Route path="/secure" component={BodyTemplate}>
<Route path="page1" component={Page1}/>
<Route path="page2" component={Page2}/>
<Route path="page3" component={Page3}/>
</Route>
<Route path="*" component={InvalidPage}/>
</Route>
</Router>
</Provider>, document.getElementById('app'))
If I open the URL localhost:3000/login it is working fine
but if I give the URL localhost:3000/secure/page1
I see the error in the browser console as below
bundle.min.js:1 Uncaught SyntaxError: Unexpected token <
Kindly help me if there is anything wrong in my router configuration.
A:
Changing the script loading from
<script src="bundle.min.js"></script>
to
<script src="/bundle.min.js"></script>
worked as it is trying to load from ur current url when we go to the second level i.e., localhost:3000/login/bundle.min.js which is wrong changing it to root url made it working localhost:3000/bundle.min.js
| {
"pile_set_name": "StackExchange"
} |
Q:
Extended range in geom_ribbon
I have an issue with geom_ribbon, and with its limits.
i have a datatable like that (Length and Perf being means, and Length.sd and Perf.sd, the standard deviation)
Ex <- data.frame(Temperature = as.factor(c("16", "16", "16", "16", "16")),
Level = Level = as.factor(c(0, 1, 2, 3, 4)), Length = c(1.623333, 2.161143, 2.924545, 3.895429, 5.068788),
Length.sd = c(0.1578897, 0.1161331, 0.1850691, 0.1691039, 0.1937743),Perf = c(0.6693438, 0.5292980, 0.1979450, 0.1034701, 0.0827987),
Perf.sd = c(0.04479068, 0.07299800, 0.02513500, 0.00876010, 0.00679870))
Then, I built my graph, I use geom point for the mean, geom_errorbar for the vertical error bars, geom_errorbarh for the vertical error bars, and stat_function to draw the linear regression of my dataset. Until now, everything is fine
ggplot(data=Ex, aes(x=log10(Length), y=log10(Perf), color=Temperature))+
geom_point(aes(shape=Level), size = 2)+
geom_errorbarh(aes(xmax = log10(Ex$Length + Ex$Length.sd), xmin = log10(Ex$Length - Ex$Length.sd), height = 0.01))+
geom_errorbar(aes(ymax = log10(Ex$Perf + Ex$Perf.sd), ymin = log10(Ex$Perf - Ex$Perf.sd), width = 0.01))+
scale_color_manual(values=c("blue"))+
scale_shape_manual(values=c(7, 15, 17, 19, 6))+
stat_function(fun=function(x){0.2746- 1.9945*x}, colour="red", size=1) +
theme_bw() +
scale_x_continuous("Length") +
scale_y_continuous("Perf")
Then, the geom_ribbon.
ggplot(data=Ex, aes(x=log10(Length), y=log10(Perf), color=Temperature))+
geom_point(aes(shape=Level), size = 2)+
geom_errorbarh(aes(xmax = log10(Ex$Length + Ex$Length.sd), xmin = log10(Ex$Length - Ex$Length.sd), height = 0.01))+
geom_errorbar(aes(ymax = log10(Ex$Perf + Ex$Perf.sd), ymin = log10(Ex$Perf - Ex$Perf.sd), width = 0.01))+
scale_color_manual(values=c("blue"))+
scale_shape_manual(values=c(7, 15, 17, 19, 6))+
stat_function(fun=function(x){0.2746- 1.9945*x}, colour="red", size=1) +
geom_ribbon(aes(ymax= 0.3186 -2.1155*x+0.1197*x^2 ,
ymin= 0.2338 -1.8895*x-0.1033*x^2 ), fill="red", colour= NA, alpha=.2) + #CI 16
theme_bw() +
scale_x_continuous("Length") +
scale_y_continuous("Perf")
First, I have a error message, like if it doesn't see the x=log10(Length) in aes
Error: Aesthetics must be either length 1 or the same as the data (5):
ymax, ymin, x, y
Then, if I write before the ggplot x=log10(Ex$Length), it works. But the ribbon stops at the means of the values, and doesn't extend until the extremes
But if I try to change the x, like x=seq(0.1, 1, by=1), I have the error message
Error: Aesthetics must be either length 1 or the same as the data (5):
ymax, ymin, x, y
like if geom_ribbon doesn't see I use a function to draw the upper and lower limits of the ribbon. it works perfectly if I remove geom_errorbarh, but I need it.
Do somebody would have a solution to force the ribbon to extend until determined limits?
Thank you very much!
A:
I think this is what you want
x=log10(Ex$Length)
x_new = c(0,log10(Ex$Length), 1)
z_new = data.frame(x = x_new, ymin = 0.2338 -1.8895*x_new-0.1033*x_new^2, ymax = 0.3186 -2.1155*x_new+0.1197*x_new^2)
ggplot(data=Ex)+
geom_point(aes(x=log10(Length), y=log10(Perf), color=Temperature,shape=Level), size = 2)+
geom_errorbarh(aes(x=log10(Length),y=log10(Perf), xmax = log10(Ex$Length + Ex$Length.sd), xmin = log10(Ex$Length - Ex$Length.sd), height = 0.01, color = Temperature))+
geom_errorbar(aes(x=log10(Length),ymax = log10(Ex$Perf + Ex$Perf.sd), ymin = log10(Ex$Perf - Ex$Perf.sd), width = 0.01, color = Temperature))+
scale_color_manual(values=c("blue"))+
scale_shape_manual(values=c(7, 15, 17, 19, 6))+
stat_function(fun=function(z){0.2746- 1.9945*z}, colour="red", size=1) +
geom_ribbon(data = z_new, aes(x = x, ymin= ymin, ymax = ymax), fill="red", colour= NA, alpha=.2) + #CI 1
theme_bw() +
scale_x_continuous(limits = c(0,1), "Length") +
scale_y_continuous("Perf")
For whatever reason stat_function is evaluating your function over the limits of the x-axis of the graph and not the limits of the variable Length in your data set. However, geom_ribbon is only being plotted within the limits of the variable Length which is why they do not match up. I'm not sure why this happens but this is how I would go about getting around it. First decide on a limit for the x-axis using scale_x_continuous(limits = c(0,1), "Length"). Next, create a new x variable (x_new) that spans the range of the limits of the x axis. Then, create a data frame that evaluates the ymin and ymax for each value of x_new according to your equation (z_new). Use this data set in the geom_ribbon function. BUT to do this you need to remove the aesthetics from the first line of the ggplot function and specify them individually for each element in the plot(geom_point, geomerrorbarh, geom_errorbar). This is annoying but necessary to incorporate variables from outside of the main data set in other aspects of the plot.
An easier way to do this would be to use stat_smooth to run and plot the linear model. This function automatically plots a 95% confidence interval (which can be changed by adding level = some number between 0 and 1). To suppress the automatically generated CI use se = FALSE. It will only plot the line to the extent of the variable Length in your data. You can then use geom_ribbon as you've already specified. If there is no reason for the line to extend beyond the data, this is much easier.
ggplot(data=Ex, aes(x=log10(Length), y=log10(Perf)))+
geom_point(aes(shape=Level), size = 2, color = "blue")+
geom_errorbarh(aes(xmax = log10(Ex$Length + Ex$Length.sd), xmin =
log10(Ex$Length - Ex$Length.sd), height = 0.01), color = "blue")+
geom_errorbar(aes(ymax = log10(Ex$Perf + Ex$Perf.sd), ymin = log10(Ex$Perf - Ex$Perf.sd), width = 0.01), color = "blue")+
scale_shape_manual(values=c(7, 15, 17, 19, 6))+
stat_smooth(method = "lm", color = "red", alpha = .2, se = FALSE) +
geom_ribbon(aes(ymax= 0.3186 -2.1155*x+0.1197*x^2 ,
ymin= 0.2338 -1.8895*x-0.1033*x^2 ), fill="red", colour= NA, alpha=.2) + #CI 16
theme_bw() +
scale_x_continuous("Length") +
scale_y_continuous("Perf")
| {
"pile_set_name": "StackExchange"
} |
Q:
Using char in C, pointer issue, objective C
for (int i=0; i < strlen(chars1); i++) {
//*buf=chars1[i];
NSLog(@"Received %c\n", chars1[i]);
ichar = [ NSString stringWithUTF8String:chars1[i] ];
NSLog(@"Received ", ichar);
counter=strlen(chars1)-i;
gnutls_record_send (session, [ichar UTF8String] , counter);
}
I am trying to use this method to send information to my server but i keep getting an warning:
warning: passing argument 1 of 'stringWithUTF8String:' makes pointer from integer without a cast
the warning is for this line:
ichar = [ NSString stringWithUTF8String:chars1[i] ];
is there anyway i can store chars1[i] into a temp char or string and the use it in my loop for sending?
UPDATED
I am just looking for a way to parse a NSString from starting character to end and then be able to use that without getting this warning:
makes pointer from integer without a cast
A:
Maybe this is what you want.
NSString *unicodeString = [NSString stringWithUTF8String:chars1];
for (int i=0; i < [unicodeString length]; i++) {
NSString *ichar = [unicodeString substringWithRange:NSMakeRange(i, 1)];
NSLog(@"Received %@", ichar);
counter=strlen(chars1)-i;
gnutls_record_send (session, [ichar UTF8String] , counter);
}
That will take a string encoded in UTF-8 in chars1, and send the UTF-8 encoding of each individual character (which itself might be 1 or a few bytes) to gnutls_record_send.
| {
"pile_set_name": "StackExchange"
} |
Q:
Websockets Vs Long Polling For User Specific Details
I'm learning about server side websockets and have a question about a certain implementation and whether it's simply not a good idea or if it could be made to work.
Suppose a user is looking at their profile for a website they've joined and for some reason, they're expecting something specific to their account to change, e.g. their karma points to increase based on a funny post they made (Suppose their karma is private).
You could have a /karma websocket endpoint, and post to it whenever anyone's karma changes, but then everyone could potentially see everyone else's karma and in this scenario it's supposed to be private (Filtering it out on the client side is unacceptable, as I wouldn't want anyone except the target user to even receive a notification).
You could somehow store the userId against the web socket connection, and only send the karma notification to the intended user, but that doesn't feel scalable (It might work for this particular example, but probably not in cases where it's something like "send this message to everyone called john", as you could have a very large foreach loop to process).
The alternative is simply long polling with an ajax request, with a simple "get karma for this user" on a timer, which would work just fine, but be less fancy and require more requests to the server than is actually necessary (e.g. you might poll 1000 times but your karma changes just once during that time).
What's a good way of addressing such a requirement, keep it simple with long polling, or is there a websocket'y way that I'm missing?
If the requirement was "publicly get latest karma changes for all users" then websockets would be ideal, but I just can't see an obvious and simple way to make it work for more granular requirements.
Thanks
A:
First off, I know of no circumstance where long polling is more efficient than a webSocket connection for server push. So, if you want to push data from server to client and have the client get it pretty much real time, you will want to use a webSocket connection from client to server and then you can send data to the client at any time and the client will receive and process it immediately.
The rest of your question is a little hard to understand what your objection is to using a webSocket.
If you're concerned about data being kept private (only the specific user can see their karma value), then that's just a matter of proper implementation to enforce that. When a webSocket connection is established, the user has to be authenticated so you know exactly which user is making the webSocket connection. Assuming your web pages have some sort of user authentication already, you can piggy back on that same auth when the webSocket connection is established because cookies are passed with the http request that starts a webSocket connection. So, now let's assume you have an authenticated webSocket connection and the server knows which webSocket belongs to which user.
So, now it's a matter of only sending appropriate data on each webSocket. Your server needs to implement the correct logic for taking a given karma change for a given user, find the authenticated webSocket connections belonging to that user and then sending a message over only those webSocket connections to alert the client that there's a new karma value.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery .ajax method in IE7 & IE6 not working but working fine in Firefox
This relates to my previous post:
jQuery .load Method causing page refresh AJAX
I changed my implmentation to use the .ajax method instead of .load and it works fine in Firefox but not in IE7 or IE6:
$('ul#coverTabs > li > a').live('click', function(event) {
// Find href of current tab
var $tabValue = $(this).attr('href');
$.ajax({
type: "GET",
cache: false,
dataType: "html",
url: $(this).attr('href'),
success: function(data){
$(data).find('.benefitWrap').each(function(){
var $benefitWrap = $(this).html();
$('.benefitWrap').replaceWith($('<div class="benefitWrap">' + $benefitWrap + '</div>'));
});
}
});
event.preventDefault();
});
This is killing me as it has taken ages to get this far.
Any ideas where i am going wrong?
A:
Just an quick though. I have had some frustrating issues with jQuery in the past that silently failed with IE6/7. In almost all cases, somewhere in my code (not necessarily in the ajax call in question) I had a extra comma after an argument like this:
$.ajax({
type: "GET",
cache: false,
dataType: "html",
url: $(this).attr('href'),
success: function(){},
)}
I would run the script through jslint to see if there is anything funny in the syntax causing this issue before doing proper debugging.
A:
I accidentally worked out what the issue was.
The link referenced in this variable:
var $tabValue = $(this).attr('href');
Had a hash value on the end like so:
https://bupacouk.bwa.local.internal.bupa.co.uk/cash-plan-quote/quoteAction.do?getBenefitLevelDetails=getBenefitLevelDetails&productPolicyId=7850#a1
This cause the AJAX to fall over in bothe versions of IE.
Using the following code:
var $withoutHash = $tabValue.substr(0,$tabValue.indexOf('#'));
Getrs rid of it and it now works :)
| {
"pile_set_name": "StackExchange"
} |
Q:
OutputCache has no effect
I'm back on a MVC app where I thought that output caching was working as expected. However, while revisiting it, I see that the OutputCache attribute I use has no effect (Duration is set to a high value). Whether I add it or not, the breakpoint in my action is always hit and Firebug shows me a 200 OK on the requested page in each case.
In a more complex action where I use VaryByCustom, the GetVaryByCustomString method in global.asax is never called. I know that it was called in the past since I was able to debug there but now it's not.
I wonder what I did to break this... Any idea?
(in order to not only test localhost, I use a dyndns.org address so that it's a valid external URL. I also use IIS).
Update: when I use the localhost URL, targetting the same url does not enter the action code again. Hitting F5 does. When using the internet URL it always visits the action code.
Update 2: Fiddler is showing this in the response headers:
200 OK
Cache:
Cache-Control: public, no-cache="Set-Cookie", max-age=86400
Date: Mon, 16 Jul 2012 19:38:46 GMT
Expires: Tue, 17 Jul 2012 19:38:46 GMT
Vary: *
Expires = Date + 24h each time I request the same url, which shows that a new page is served each time. Also I should get 200 the first time and 304 thereafter.
A:
Just discovered the culprit, which is contextual to my application:
If I remove the 51degrees.mobi nuget package from my app, it just works again. Put it back (even without using its features) and caching is dead. Well, in fact there are 2 cases:
If you just add the package, GetVaryByCustomString is never called. The action method is called once correctly and then is served from the cache.
If you add the package AND you also use a CompressFilter attribute, then GetVaryByCustomString is never called AND the action method is always called (no page served from the cache).
I posted to their forums to report this issue.
Update: these issues appear starting with 51degrees version 2.1.4.9. I notice that this is the first version using Microsoft.Web.Infrastructure, in case this is relevant...
Update 2: they found the cause of this issue and it will be fixed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to inject in to elastic search after scrapping the data using Beautiful soup
Hi I am scrapping the website and trying to injest in to Elaastic search.
I am able to create dictionary. I want to know to how to injest into elastic search. Each doctor is a document here. I am pasting the output of the below code
import urllib.request
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
url = 'https://health.usnews.com/doctors/new-jersey'
#data = data.encode('utf-8')
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686)"
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
resp_data = resp.read()
#print(resp_data)
soup = BeautifulSoup(resp_data, 'html.parser')
doc = soup.findAll('a', {'class': 'search-result-link bar-tighter'})
links = ['https://health.usnews.com' + do.get('href', None) for do in doc]
for link in links:
headers = {}
doctor = []
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686)"
doc_req = urllib.request.Request(link,headers=headers)
doc_resp = urllib.request.urlopen(doc_req)
doc_resp_data = doc_resp.read()
doc_soup = BeautifulSoup(doc_resp_data, 'html.parser')
doc_name = doc_soup.find('h1')
doc_name_text = (doc_name.text).strip()
doc_name_text_mod = (re.sub('\s+', ' ', doc_name_text))
doc_name_text_mod_1 = ('Name' ':' +doc_name_text_mod)
doctor.append(doc_name_text_mod_1)
doc_overview = doc_soup.find('p')
doc_overview_text = (doc_overview.text).strip()
doc_overview_text_mod = (re.sub('\n\| ', ', ', doc_overview_text))
doc_overview_text_mod_1 = ('Specialised and Location' ':' + doc_overview_text_mod)
doctor.append(doc_overview_text_mod_1)
#print (doctor)
dicto = (dict(s.split(':') for s in doctor))
print(dicto)
>>>Output
{'Name': 'Dr. Tajwar Aamir MD', 'Specialised and Location': 'Pediatrics, Princeton, NJ'}
{'Name': 'Dr. Bernard Aaron MD', 'Specialised and Location': 'Gastroenterology, Brick, NJ'}
A:
Below are the link to code
Pandas : https://github.com/mak705/Python_ELK/blob/master/ELK_Python.ipynb
ES: https://github.com/mak705/Python_ELK/blob/master/ELK.ipynb
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to store json object array in state, then map the items into render
I am new to react.
I am trying to store json object array in state, then map the items into the component render.
I am not sure how to debug this/no console errors either :/
https://codepen.io/bkdigital/pen/XWrLrxX?editors=1111
class App extends React.Component {
state = {
users: [],
isLoading: true,
errors: null
};
getUsers() {
axios.get("REMOVED")
.then(response =>
response.data.results.map(user => ({
name: `${user.Id}`,
Company: `${user.Company}`,
}))
)
.then(users => {
this.setState({
users,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
componentDidMount() {
this.getUsers();
}
render() {
const { isLoading, users } = this.state;
return (
<React.Fragment>
<h2>Random User</h2>
<div>
{!isLoading ? (
users.map(user => {
const { Company, Id } = user;
return (
<div key={Id}>
<p>{Company}</p>
<hr />
</div>
);
})
) : (
<p>Loading...</p>
)}
</div>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
The name of the company should be rendered.
A:
Your code is looking good. I think, you are not getting the expected data. Please try to log your response.
Replace this code:
.then(response =>
response.data.results.map(user => ({
name: `${user.Id}`,
Company: `${user.Company}`,
}))
)
with
.then(response => {
console.log(response);
return response.data.results.map(user => ({
name: `${user.Id}`,
Company: `${user.Company}`,
}))
})
And check the response object in your console.
Update
Your code should look like this (when CORS plugin is ON or your server and client are setup such that there is no CORS error):
.then(response =>
response.data.map(user => ({
name: `${user.Id}`,
Company: `${user.Company}`,
}))
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Python converting UUID's from string
I have a text file that includes UUIDS that all look like this:
A4AB4CD2-016B-411E-8BA1-0000C592BF17
When I try and parse/print the file with python, most (but not all) end up looking like this:
12:40:54:457
There are three chunks per line that I'm parsing, a double, a date, and this uuid. The first two parts work fine. The relevant lines of code are:
for line in fileLines:
parts = line.split()
# Parse first two chunks
outputFile.write(""" WHERE tableID = '""" + uuid.UUID(parts[2]) + """'""")
This fails because the UUIDs are already of the form 12:40:54:547, but I don't know what this sub-type of UUID is called, let alone how to appropriately parse it. My goal is simply to read in the uuid exactly as it is, and re-print it with some extra text around it so I can run it as an SQL script.
I'm running python 3.3.2
A full line of input looks like this:
339.00 2013-06-18 12:40:54.457 A4AB4CD2-016B-411E-8BA1-0000C592BF17
A:
If the UUID will always be last in the line, access it with [-1]
outputFile.write(""" WHERE tableID = '""" + uuid.UUID(parts[-1]) + """'""")
In the example you give parts[2] will always return the time. If your lines are consistent, you can use parts[2], but if the data up to the UUID varies, just always pick the last element after the split
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular5 LandingPage without /home url
I would like my landing page URL to be myapp.com.
Currently, inside src/index.html I have
<head>
<base href="/">
</head>
In app.component.html I have
<router-outlet></router-outlet>
In app.module.ts I have
const appRoutes: Routes = [
{path: 'home', component: HomeComponent},
{path: '', redirectTo: '/home', pathMatch: 'full'}
];
I don't want to redirect myapp.com to myapp.com/home, I want myapp.com to show my landing page and I would like myapp.com/feature to show another page.
A:
If you do not want myapp.com to redirect to nyapp.com/home why are you telling it to do so?
get rid of this line:
{path: '', redirectTo: '/home', pathMatch: 'full'}
So your routes would look like this:
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{path: 'feature', component: FeatureComponent}
];
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual studio 2013 installation troubleshooting
I had some problems with my VS2013 and I uninstlled it.
After I uninstlled VS2013 I restarted my computer, downloaded from Microsoft's website .exe file Microsoft Visual Studio Professional 2013 with Update 4
and I started installation process.
On the installation process I get this window:
In the window above on, Please provide a location to search for the packages text box I have this string:
C:\Users\userName\Downloads\packages\BuildTools_MSBuild_x86\BuildTools_MSBuild.msi
Any idea why I get this window and how to solve this issue?
A:
You mention that you are using the .exe file from the website to install your Visual Studio. The .exe file is an online installer which, based on what you choose to install, will selectively download the packages that you need. If the online installer has any problems downloading any of the packages, the installation will fail.
I would suggest you download the .iso, which contains an offline installer. The offline installer contains all the packages necessary to install Visual Studio with all the options, and can be burnt onto a DVD. The advantage of this is that once you have downloaded it, you can install it on as many computers as you want without needing to download the same files for each machine.
Try downloading the .iso installer for the version you want: this will remove the possibility that the installer was unable to download part of the package. Optionally, use the File Checksum Integrity Verifier tool to check it's downloaded successfully.
I've included links to both the standard and the Ultimate versions since you mention Professional in the text of your question and the image says Ultimate.
Visual Studio 2013 with Update 4
main download page
direct link to the .iso installer.
Visual Studio Ultimate 2013 with Update 4
main download page
direct link to .iso installer.
It looks like others have had your problem - I suspect your problem is the same as the problem in the social.msdn.microsoft.com thread Visual Studio 2013 Update 1 failing on Msi_BuildTools, "The hash value is not correct" which, while relating to 2013 Update 1, reads to me like the same problem. Using the .iso installer solved the problem there.
Note that Visual Studio 2013 Update 5 has also been released - you can get the online installer from here or, if you have a Visual Studio account, you can download it from VisualStudio.com here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any apps that will post to multiple social networking accounts at once?
I currently use Ping.fm to post to multiple social networks at once, but it's been irritating me for a while and I'm thinking of writing a tool to replace it for myself. But I figure it's possible that someone has already done that. To be a suitable replacement it needs to handle twitter, and facebook; myspace, linkedin, and google buzz are a bonus, of course everything else is frosting. In addition to allowing me to send messages it must also be able to read multiple rss feeds and aggregate them to the networks I set up. If 2 or more tools, in conjunction can be made to do this that is also acceptable, e.g. feedreader | cleanupforstream | post2stream.
If it doesn't exist I think I'll just write some Perl to do it for me, and put it on CPAN.
A:
Gwibber has the ability to send to multiple services at once. According to their website it supports the following protocols/services:
Twitter
Identi.ca/StatusNet
Ping.fm
Facebook
FriendFeed
Buzz
Digg
Flickr
Qaiku
As far as I know, it has the ability to receive content from all of the listed services, but I'm not sure if there is a way to receive arbitrary RSS feeds.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I include stylesheets with symfony properly?
I have a simple Template (layout.php) and I use Propel as ORM.
When i include sylesheets (into of layout.php) with the function: include_stylesheets() I became 2 css:
/sfPropelORMPlugin/css/global.css
/sfPropelORMPlugin/css/default.css
why?
when I look into my view.yml actually I just have this:
default:
http_metas:
content-type: text/html
stylesheets:
has_layout: true
layout: layout
I configure no stylesheets but I see Propel css in my Head Tag!
my generator.yml :
generator:
class: sfPropelGenerator
param:
##CONFIG##
config:
actions: ~
fields: ~
list: ~
filter: ~
form: ~
edit: ~
new: ~
Is this a bug? or just a misconfiguration?
A:
This mainly because there are automatically loaded when you use a the admin template (see this file):
<?php if (isset($this->params['css']) && ($this->params['css'] !== false)): ?>
[?php use_stylesheet('<?php echo $this->params['css'] ?>', 'first') ?]
<?php elseif(!isset($this->params['css'])): ?>
[?php use_stylesheet('<?php echo sfConfig::get('sf_admin_module_web_dir').'/css/global.css' ?>', 'first') ?]
[?php use_stylesheet('<?php echo sfConfig::get('sf_admin_module_web_dir').'/css/default.css' ?>', 'first') ?]
<?php endif; ?>
This means you can define your own css in the generator.yml (and it won't load the default ones), like :
generator:
class: sfPropelGenerator
param:
css: /css/my_css.css
Or removed them:
generator:
class: sfPropelGenerator
param:
css: false
edit:
And finally you can remove them from the view.yml:
default:
http_metas:
content-type: text/html
stylesheets:
- -/sfPropelORMPlugin/css/global.css
- -/sfPropelORMPlugin/css/default.css
has_layout: true
layout: layout
| {
"pile_set_name": "StackExchange"
} |
Q:
Divide a data frame with same data frame (sliced) in panda's
I have the data frame
df =
a b c
0 1.0 4.0 5.0
1 3.0 8.0 45.0
2 5.0 3.0 67.0
3 2.0 7.0 34.0
I'd want to now divide the dataframe df's 2nd and 3rd rows with the 0th and 1st rows of df i.e I'd want to divide i th row with i-k th row. The expected result should be
a b c
0 Nan Nan Nan
1 Nan Nan Nan
2 5.0/1 3.0/4 67/5
3 2/3 7/8 34/45
As a simple formula it is (price[t]/price[t-N]) if price is assumed to be dataframe and t are the rows.
Is there a simple way to do this.
A:
Use div with shift:
print (df.shift(2))
a b c
0 NaN NaN NaN
1 NaN NaN NaN
2 1.0 4.0 5.0
3 3.0 8.0 45.0
print (df.div(df.shift(2)))
a b c
0 NaN NaN NaN
1 NaN NaN NaN
2 5.000000 0.750 13.400000
3 0.666667 0.875 0.755556
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL - Sum with Group BY and Max
I have following sample table where I need to have sum of columns values where VA1 and Val2 are same , need to sum cvalue and seelct the ID where cValue is max
+---------------------------+
¦ ID ¦ Val1 ¦ Val2 ¦ CValue ¦
¦----+------+------+--------¦
¦ 1 ¦ 1 ¦ 1 ¦ 1 ¦
¦----+------+------+--------¦
¦ 2 ¦ 1 ¦ 1 ¦ 9 ¦
¦----+------+------+--------¦
¦ 3 ¦ 1 ¦ 1 ¦ 1 ¦
¦----+------+------+--------¦
¦ 4 ¦ 5 ¦ 3 ¦ 2 ¦
¦----+------+------+--------¦
¦ 5 ¦ 5 ¦ 3 ¦ 8 ¦
¦----+------+------+--------¦
¦ 6 ¦ 7 ¦ 5 ¦ 8 ¦
¦----+------+------+--------¦
¦ 7 ¦ 8 ¦ 9 ¦ 4 ¦
+---------------------------+
for above raw data below is the required output:
+---------------------------+
¦ ID ¦ Val1 ¦ Val2 ¦ CValue ¦
¦----+------+------+--------¦
¦ 2 ¦ 1 ¦ 1 ¦ 11 ¦
¦----+------+------+--------¦
¦ 4 ¦ 5 ¦ 3 ¦ 10 ¦
¦----+------+------+--------¦
¦ 6 ¦ 7 ¦ 8 ¦ 8 ¦
¦----+------+------+--------¦
¦ 7 ¦ 8 ¦ 9 ¦ 4 ¦
+---------------------------+
Can someone help to provide the right query to achieve this.
Thanks
A:
Try This, using KEEP..DENSE_RANK
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE yourtable
(ID int, Val1 int, Val2 int, CValue int)
;
INSERT ALL
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (1, 1, 1, 1)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (2, 1, 1, 9)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (3, 1, 1, 1)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (4, 5, 3, 2)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (5, 5, 3, 8)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (6, 7, 5, 8)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (7, 8, 9, 4)
SELECT * FROM dual
;
Query 1:
SELECT MAX(ID) KEEP (
DENSE_RANK FIRST ORDER BY cvalue DESC
) as ID
,Val1
,Val2
,SUM(CValue) AS CValue
FROM yourtable
GROUP BY Val1
,Val2
Results:
| ID | VAL1 | VAL2 | CVALUE |
|----|------|------|--------|
| 2 | 1 | 1 | 11 |
| 5 | 5 | 3 | 10 |
| 6 | 7 | 5 | 8 |
| 7 | 8 | 9 | 4 |
| {
"pile_set_name": "StackExchange"
} |
Q:
php5-fpm.sock not found / created in /var/run
I fail to connect to php5-fpm.sock. I have tried many solutions but still getting this error:
2017/11/20 11:17:21 [crit] 9670#9670: *1 connect() to unix:/var/run/php5-fpm.sock failed (2: No such file or directory) while connecting to upstream, client: 192.168.224.8, server: babylon, request: "GET /webmail/ HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "babylon"
My configuration is like this:
location /webmail {
alias /srv/roundcubemail;
index index.php index.html;
# Favicon
location ~ ^/webmail/favicon.ico$ {
root /srv/roundcubemail/skins/classic/images;
log_not_found off;
access_log off;
expires max;
}
# Robots file
location ~ ^/webmail/robots.txt {
allow all;
log_not_found off;
access_log off;
}
# Deny Protected directories
location ~ ^/webmail/(config|temp|logs)/ {
deny all;
}
location ~ ^/webmail/(README|INSTALL|LICENSE|CHANGELOG|UPGRADING)$ {
deny all;
}
location ~ ^/webmail/(bin|SQL)/ {
deny all;
}
# Hide .md files
location ~ ^/webmail/(.+\.md)$ {
deny all;
}
# Hide all dot files
location ~ ^/webmail/\. {
deny all;
access_log off;
log_not_found off;
}
#Roundcube fastcgi config
location ~ /webmail(/.*\.php)$ {
error_log /var/log/nginx/x.log error;
include fastcgi_params;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^/webmail/(.+\.php)(/.*)$;
fastcgi_index index.php;
#fastcgi_param SCRIPT_FILENAME /srv/roundcubemail/$fastcgi_script_name;
fastcgi_param SCRIPT_FILENAME /srv/roundcubemail/index.php;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
Is it maybe a problem with permissions over directories? I don't think so.
The attempts that I made were:
I change the listen of my www.conf, for socket and IP but still not working
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
user = www-data
group = www-data
; The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific address on
; a specific port;
; 'port' - to listen on a TCP socket to all addresses on a
; specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /var/run/php5-fpm.sock
;listen = 127.0.0.1:9000
; Set listen(2) backlog.
; Default Value: 65535 (-1 on FreeBSD and OpenBSD)
;listen.backlog = 65535
; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions.
; Default Values: user and group are set as the running user
; mode is set to 0660
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
I have restarted php5-fm and nginx and still nothing.
Any ideas how I can fix that?
A:
First, ensure that php-fpm is installed, you could use this to check the current version if any:
php-fpm -v
Second check the php-fpm.conf configuration, and search for this line:
listen = /tmp/php-fpm.socket
In case it doesn't exist just add it, it can be also something like:
listen = /var/run/php5-fpm.sock
In some Linux distros normally this is used:
listen = /var/run/php5-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
In case you want to use a TCP socket:
Listen 127.0.0.1:9000
Restart php-fpm and check that the socket has been created in case of using a Unix domain socket, this can be done by doing this:
$ file /var/run/php5-fpm.sock
If socket exists if should print out something like this:
/var/run/php5-fpm.sock: socket
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.