query_id stringlengths 4 64 | query_authorID stringlengths 6 40 | query_text stringlengths 66 72.1k | candidate_id stringlengths 5 64 | candidate_authorID stringlengths 6 40 | candidate_text stringlengths 9 101k |
|---|---|---|---|---|---|
22a211369609d79bb8af657addca32012f5b0fa5216aaabe5aca11e03817cc46 | ['9e32c388d61a4ff5b9f661025a438842'] | What are you trying to tell me? I asked a simple, clear question. What I'm trying to do in detail is not relevant. Yes, like you, I would prefer such a perfect command line tool - like Linux' fdisk and mkfs. But since this is not Christmas I limited the criteria to CLI and free, if there is a perfect tool without overhead, I'm even more happy. | 11850dde4de4e38849281e4201bd2fa8d463d27d7267e62a610f1ccda8f8cf9d | ['9e32c388d61a4ff5b9f661025a438842'] | I am attempting to help a colleague with data analysis and I'm a bit swamped as to what is appropriate. We are trying create a formula to explain why children in various provinces have stunted growth and we predict it is due to Vitamin A deficiency and damage from Diarrhea events (Simplified of course).
I have proportional data for nine provinces on:
the percentage of stunted children
the percent that have received Vitamin A recently
the percent that have recently had diarrhea.
Example such as:
Province 1 ---- 14.5% Stunted-----75.4% Vitamin A intake -----14% Diarrhea
Since the data is not normal and also inherently bounded by 0 and 100%, I assume I should not be using linear regression. This website suggests using a probit or two-limit tobit model, but I've found suggestions to use GLMM, ancovas, or logistic regression.
I use normally use SPSS but can use R, JMP if needed.
Any suggestions would be greatly appreciated.
|
e7a510d4f5c87602156c6cc9750b790a892f8c1a0789103bfdcf6f3a5c744f98 | ['9e37bfb5a0e34193906a11d1c64a6521'] | I am new on OpenCV. I am always wish to learn new image processing technologies / Programming. I have seen few tutorial on Object detection, tracking, counting etc.
I wish to learn the same and try to make my own similar project.
With lot of searching on internet and papers. Finally i came to know about Kalman Filter for object tracking. I have used following codes as per following:
Background Subtract
Smoothing , Blur etc. filters.
Find Contours
Draw Rectangle and find Centroid.
Apply Kalman Filter
Now, i can track ONE Object with my codes. I want to track multiple objects.(i.e. people running on the roads, vehicle running etc.)
I would be pleased and appreciate if someone can guide me or give me example codes to try with.
Looking forward your positive reply.
Shan
using namespace std;
using namespace cv;
#define drawCross( img, center, color, d )\
line(img, Point(center.x - d, center.y - d), Point(center.x + d, center.y + d), color, 2, CV_AA, 0);\
line(img, Point(center.x + d, center.y - d), Point(center.x - d, center.y + d), color, 2, CV_AA, 0 )\
vector<Point> mousev,kalmanv;
cv<IP_ADDRESS>KalmanFilter KF;
cv<IP_ADDRESS>Mat_<float> measurement(2,1);
Mat_<float> state(4, 1); // (x, y, Vx, Vy)
int incr=0;
void initKalman(float x, float y)
{
// Instantate Kalman Filter with
// 4 dynamic parameters and 2 measurement parameters,
// where my measurement is: 2D location of object,
// and dynamic is: 2D location and 2D velocity.
KF.init(4, 2, 0);
measurement = Mat_<float>::zeros(2,1);
measurement.at<float>(0, 0) = x;
measurement.at<float>(0, 0) = y;
KF.statePre.setTo(0);
KF.statePre.at<float>(0, 0) = x;
KF.statePre.at<float>(1, 0) = y;
KF.statePost.setTo(0);
KF.statePost.at<float>(0, 0) = x;
KF.statePost.at<float>(1, 0) = y;
setIdentity(KF.transitionMatrix);
setIdentity(KF.measurementMatrix);
setIdentity(KF.processNoiseCov, Scalar<IP_ADDRESS>all(.005)); //adjust this for faster convergence - but higher noise
setIdentity(KF.measurementNoiseCov, Scalar<IP_ADDRESS>all(1e-1));
setIdentity(KF.errorCovPost, Scalar<IP_ADDRESS>all(.1));
}
Point kalmanPredict()
{
Mat prediction = KF.predict();
Point predictPt(prediction.at<float>(0),prediction.at<float>(1));
KF.statePre.copyTo(KF.statePost);
KF.errorCovPre.copyTo(KF.errorCovPost);
return predictPt;
}
Point kalmanCorrect(float x, float y)
{
measurement(0) = x;
measurement(1) = y;
Mat estimated = KF.correct(measurement);
Point statePt(estimated.at<float>(0),estimated.at<float>(1));
return statePt;
}
int main()
{
Mat frame, thresh_frame;
vector<Mat> channels;
VideoCapture capture;
vector<Vec4i> hierarchy;
vector<vector<Point> > contours;
// cv<IP_ADDRESS>Mat frame;
cv<IP_ADDRESS>Mat back;
cv<IP_ADDRESS>Mat fore;
cv<IP_ADDRESS>BackgroundSubtractorMOG2 bg;
bg.nmixtures = 3;
bg.bShadowDetection = false;
int incr=0;
int track=0;
capture.open("E:/demo1.avi");
if(!capture.isOpened())
cerr << "Problem opening video source" << endl;
mousev.clear();
kalmanv.clear();
initKalman(0, 0);
while((char)waitKey(1) != 'q' && capture.grab())
{
Point s, p;
capture.retrieve(frame);
bg.operator ()(frame,fore);
bg.getBackgroundImage(back);
erode(fore,fore,Mat());
erode(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
cv<IP_ADDRESS>normalize(fore, fore, 0, 1., cv<IP_ADDRESS>NORM_MINMAX);
cv<IP_ADDRESS>threshold(fore, fore, .5, 1., CV_THRESH_BINARY);
split(frame, channels);
add(channels[0], channels[1], channels[1]);
subtract(channels[2], channels[1], channels[2]);
threshold(channels[2], thresh_frame, 50, 255, CV_THRESH_BINARY);
medianBlur(thresh_frame, thresh_frame, 5);
// imshow("Red", channels[1]);
findContours(fore, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
vector<vector<Point> > contours_poly( contours.size() );
vector<Rect> boundRect( contours.size() );
Mat drawing = Mat<IP_ADDRESS>zeros(thresh_frame.size(), CV_8UC1);
for(size_t i = 0; i < contours.size(); i++)
{
// cout << contourArea(contours[i]) << endl;
if(contourArea(contours[i]) > 500)
drawContours(drawing, contours, i, Scalar<IP_ADDRESS>all(255), CV_FILLED, 8, vector<Vec4i>(), 0, Point());
}
thresh_frame = drawing;
findContours(fore, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
drawing = Mat<IP_ADDRESS>zeros(thresh_frame.size(), CV_8UC1);
for(size_t i = 0; i < contours.size(); i++)
{
// cout << contourArea(contours[i]) << endl;
if(contourArea(contours[i]) > 3000)
drawContours(drawing, contours, i, Scalar<IP_ADDRESS>all(255), CV_FILLED, 8, vector<Vec4i>(), 0, Point());
}
thresh_frame = drawing;
// Get the moments
vector<Moments> mu(contours.size() );
for( size_t i = 0; i < contours.size(); i++ )
{
mu[i] = moments( contours[i], false ); }
// Get the mass centers:
vector<Point2f> mc( contours.size() );
for( size_t i = 0; i < contours.size(); i++ )
{
mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 );
/*
for(size_t i = 0; i < mc.size(); i++)
{
// drawCross(frame, mc[i], Scalar(255, 0, 0), 5);
//measurement(0) = mc[i].x;
//measurement(1) = mc[i].y;
// line(frame, p, s, Scalar(255,255,0), 1);
// if (measurement(1) <= 130 && measurement(1) >= 120) {
// incr++;
// cout << "Conter " << incr << " Loation " << measurement(1) << endl;
// }
}*/
}
for( size_t i = 0; i < contours.size(); i++ )
{ approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
boundRect[i] = boundingRect( Mat(contours_poly[i]) );
}
p = kalmanPredict();
// cout << "kalman prediction: " << p.x << " " << p.y << endl;
mousev.push_back(p);
for( size_t i = 0; i < contours.size(); i++ )
{
if(contourArea(contours[i]) > 1000){
rectangle( frame, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 2, 8, 0 );
Point center = Point(boundRect[i].x + (boundRect[i].width /2), boundRect[i].y + (boundRect[i].height/2));
cv<IP_ADDRESS><IP_ADDRESS>zeros(2,1);
measurement.at<float>(0, 0) = x;
measurement.at<float>(0, 0) = y;
KF.statePre.setTo(0);
KF.statePre.at<float>(0, 0) = x;
KF.statePre.at<float>(1, 0) = y;
KF.statePost.setTo(0);
KF.statePost.at<float>(0, 0) = x;
KF.statePost.at<float>(1, 0) = y;
setIdentity(KF.transitionMatrix);
setIdentity(KF.measurementMatrix);
setIdentity(KF.processNoiseCov, Scalar::all(.005)); //adjust this for faster convergence - but higher noise
setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));
setIdentity(KF.errorCovPost, Scalar::all(.1));
}
Point kalmanPredict()
{
Mat prediction = KF.predict();
Point predictPt(prediction.at<float>(0),prediction.at<float>(1));
KF.statePre.copyTo(KF.statePost);
KF.errorCovPre.copyTo(KF.errorCovPost);
return predictPt;
}
Point kalmanCorrect(float x, float y)
{
measurement(0) = x;
measurement(1) = y;
Mat estimated = KF.correct(measurement);
Point statePt(estimated.at<float>(0),estimated.at<float>(1));
return statePt;
}
int main()
{
Mat frame, thresh_frame;
vector<Mat> channels;
VideoCapture capture;
vector<Vec4i> hierarchy;
vector<vector<Point> > contours;
// cv::Mat frame;
cv::Mat back;
cv::Mat fore;
cv::BackgroundSubtractorMOG2 bg;
bg.nmixtures = 3;
bg.bShadowDetection = false;
int incr=0;
int track=0;
capture.open("E:/demo1.avi");
if(!capture.isOpened())
cerr << "Problem opening video source" << endl;
mousev.clear();
kalmanv.clear();
initKalman(0, 0);
while((char)waitKey(1) != 'q' && capture.grab())
{
Point s, p;
capture.retrieve(frame);
bg.operator ()(frame,fore);
bg.getBackgroundImage(back);
erode(fore,fore,Mat());
erode(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
dilate(fore,fore,Mat());
cv::normalize(fore, fore, 0, 1., cv::NORM_MINMAX);
cv::threshold(fore, fore, .5, 1., CV_THRESH_BINARY);
split(frame, channels);
add(channels[0], channels[1], channels[1]);
subtract(channels[2], channels[1], channels[2]);
threshold(channels[2], thresh_frame, 50, 255, CV_THRESH_BINARY);
medianBlur(thresh_frame, thresh_frame, 5);
// imshow("Red", channels[1]);
findContours(fore, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
vector<vector<Point> > contours_poly( contours.size() );
vector<Rect> boundRect( contours.size() );
Mat drawing = Mat::zeros(thresh_frame.size(), CV_8UC1);
for(size_t i = 0; i < contours.size(); i++)
{
// cout << contourArea(contours[i]) << endl;
if(contourArea(contours[i]) > 500)
drawContours(drawing, contours, i, Scalar::all(255), CV_FILLED, 8, vector<Vec4i>(), 0, Point());
}
thresh_frame = drawing;
findContours(fore, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
drawing = Mat::zeros(thresh_frame.size(), CV_8UC1);
for(size_t i = 0; i < contours.size(); i++)
{
// cout << contourArea(contours[i]) << endl;
if(contourArea(contours[i]) > 3000)
drawContours(drawing, contours, i, Scalar::all(255), CV_FILLED, 8, vector<Vec4i>(), 0, Point());
}
thresh_frame = drawing;
// Get the moments
vector<Moments> mu(contours.size() );
for( size_t i = 0; i < contours.size(); i++ )
{
mu[i] = moments( contours[i], false ); }
// Get the mass centers:
vector<Point2f> mc( contours.size() );
for( size_t i = 0; i < contours.size(); i++ )
{
mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 );
/*
for(size_t i = 0; i < mc.size(); i++)
{
// drawCross(frame, mc[i], Scalar(255, 0, 0), 5);
//measurement(0) = mc[i].x;
//measurement(1) = mc[i].y;
// line(frame, p, s, Scalar(255,255,0), 1);
// if (measurement(1) <= 130 && measurement(1) >= 120) {
// incr++;
// cout << "Conter " << incr << " Loation " << measurement(1) << endl;
// }
}*/
}
for( size_t i = 0; i < contours.size(); i++ )
{ approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
boundRect[i] = boundingRect( Mat(contours_poly[i]) );
}
p = kalmanPredict();
// cout << "kalman prediction: " << p.x << " " << p.y << endl;
mousev.push_back(p);
for( size_t i = 0; i < contours.size(); i++ )
{
if(contourArea(contours[i]) > 1000){
rectangle( frame, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 2, 8, 0 );
Point center = Point(boundRect[i].x + (boundRect[i].width /2), boundRect[i].y + (boundRect[i].height/2));
cv::circle(frame,center, 8, Scalar(0, 0, 255), -1, 1,0);
s = kalmanCorrect(center.x, center.y);
drawCross(frame, s, Scalar(255, 255, 255), 5);
if (s.y <= 130 && p.y > 130 && s.x > 15) {
incr++;
cout << "Counter " << incr << endl;
}
for (int i = mousev.size()-20; i < mousev.size()-1; i++) {
line(frame, mousev[i], mousev[i+1], Scalar(0,255,0), 1);
}
}
}
imshow("Video", frame);
imshow("Red", channels[2]);
imshow("Binary", thresh_frame);
}
return 0;
}
| 1ae1af181cb5698d00f0953c2c1cab95d7df82d37fb17a07f5d850f2ea245650 | ['9e37bfb5a0e34193906a11d1c64a6521'] | I am bit new with Opencv / C++. I have been learning Opencv for last few months and trying to do work on a project to count persons in a video.
would you please tell me how to count only one time. I draw a virtual line on the image and when the centroid of bounding box crosses then increase by 1. But it counts multiple time of a single person . would you please suggest me how to do it.
Background subtraction MOG
Filters
Find Contours
Drawcontours
Draw Rectangles
Centroid Rectangles
Br.y is Bounding Box Bottom
if (center.y < 270 && Br.y > 272) { incr++;}
Regards <PERSON>
|
2d8b9c4b027c082cf8cdcbdbbcb2318e1f23a72370d6b7a80f59d2d536099eab | ['9e4383eff3c843388d936d0af6151277'] | I have an application that requires a transactional mail server that also supports inbound mail parsing. The application was previously setup to use Sendgrid for this using their inbound parse API (receives mail and POSTs to webhook endpoint on our application), but a fully on-premise solution is needed in this case.
Does any open source or commercial software exist that will meet these requirements? Most of the transactional mail software I have found either don't have an on-premise option or don't support inbound mail parse.
If there is no such all-in-one solution, is there software that will handle the inbound parse side of things? The only solution I have found so far is using postfix with shell scripts to parse and POST the email contents.
| 317de8627a0d3e10856517cf52a1280988cfd0245eff9c5fc1890057f924cf41 | ['9e4383eff3c843388d936d0af6151277'] | I want a script that can check the age of files in different directories and delete those that exceed an expiration age. There can be hundreds of thousand of files with different creation dates. Some directories don't have that many files. There are approximately 100 directories. The directories have different expiration ages. I was thinking YAML for configuration and Perl 5 or Python 3 as the scripting language. Which would get the job done faster? Can this be done in a few hours (3-5) or would it take days?
The script will run on Linux.
|
bc5a98e179bf3af924b2396d668fd722b1ea199d1fd63a4622302e644bc13bb8 | ['9e4b98545c34423bb4cefdd11cd9a37c'] | I was looking at an example of a simple audio amplifier circuit and have a few questions...
In the circuit below what represents the 1 and 2? What is their role in the circuit? Also, I've seen multiple different circuits and some have the potentiometer before going through the op amp and others have it after. What is the difference in having one before as opposed to after? Thank you!
| e0774962727987a495659d3f15b8c02c51a636c3ae4d0f8ca1d8cbd10aa1cb3c | ['9e4b98545c34423bb4cefdd11cd9a37c'] | I'm not a native English speaker and the American accent is the most familiar to me.
I plan to visit NZ for a Working holiday program, but I'm concerned that I won't understand what they say. I can fully understand the North American speakers, but when I heard New Zealanders speak on TV, I couldn't understand half of it.
How to make sure that I will understand this accent and will it make my English worse for other places if I stay there long term?
Thanks
|
dba1c130716ad5ad11ba6c8ba5ff36d2d3c47223e3c16d168d44d98591f0decb | ['9e4eaf61b81c4ec3893dd0f8c85b2d49'] | I have a MySQL database (called database) with tables: event, gebruiker and situatie. Now I need to write code in Java (using netbeans) to test my restful webservice. I'm able to retrieve all users (=gebruikers, dutch), but when I want to retrieve one specific user by searching on it's primary key 'Username', I get this 500-error when testing the restful webservice. please help!
this is my code in java:
@Stateless
@Path("gebruikers")
public class GebruikerService {
@Resource(name = "jdbc/socialebuurt")
private DataSource source;
/*
* Request all users.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Gebruiker> getGebruikers() {
try (Connection conn = source.getConnection()) {
try (PreparedStatement stat = conn.prepareStatement("SELECT * FROM gebruiker")) {
try (ResultSet rs = stat.executeQuery()) {
List<Gebruiker> results = new ArrayList<>();
while (rs.next()) {
Gebruiker g = new Gebruiker();
g.setUsername(rs.getString("Username"));
g.setNaam(rs.getString("Naam"));
g.setVoornaam(rs.getString("Voornaam"));
g.setStraat(rs.getString("Straat"));
g.setHuisNr(rs.getInt("huisnr"));
g.setPostcode(rs.getInt("postcode"));
g.setGemeente(rs.getString("gemeente"));
g.setWachtwoord(rs.getString("wachtwoord"));
results.add(g);
}
return results;
}
}
} catch (SQLException ex) {
throw new WebApplicationException(ex);
}
}
/*
* Request one specific user.
*/
@Path("{username}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public <PERSON> getGebruiker(@PathParam("username") String username) {
try (Connection conn = source.getConnection()) {
try (PreparedStatement stat = conn.prepareStatement("SELECT * FROM <PERSON> WHERE username = ?")) {
stat.setString(1,"");
try (ResultSet rs = stat.executeQuery()) {
if (rs.next()) {
Gebruiker <PERSON> = new <PERSON>();
ge.setUsername(rs.getString("Username"));
ge.setNaam(rs.getString("Naam"));
ge.setVoornaam(rs.getString("Voornaam"));
ge.setStraat(rs.getString("Straat"));
ge.setHuisNr(rs.getInt("huisnr"));
ge.setPostcode(rs.getInt("postcode"));
ge.setGemeente(rs.getString("gemeente"));
ge.setWachtwoord(rs.getString("wachtwoord"));
return ge;
} else {
throw new WebApplicationException(Status.NOT_FOUND);
}
}
}
} catch (SQLException ex) {
throw new WebApplicationException(ex);
}
}
}
Table 'gebruiker' has following attributes: username (primary key, varchar(26)), <PERSON> (text), <PERSON> (text), <PERSON> (text), huisNr (int(11)), postcode (int(4)), <PERSON> (text), <PERSON> (text).
If more info is needed, please ask.
Thanks to all!
| be553b2738f2c66c604203cd47149ffe67ccf1f8677e8212871d74a784c09ae9 | ['9e4eaf61b81c4ec3893dd0f8c85b2d49'] | I got this following code that retrieves data from my web service:
using System;
using System.Collections.Generic;
using System.Windows;
using Microsoft.Phone.Controls;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace BlogIT
{
public partial class BlogPage : PhoneApplicationPage
{
public BlogPage()
{
InitializeComponent();
// listbox <PERSON> alle posts
var client = new RestClient();
client.BaseUrl = "http://localhost:8080/blog/api";
RestRequest request = new RestRequest();
request.Resource = "posts";
request.RequestFormat = DataFormat.Json;
request.Method = Method.GET;
client.ExecuteAsync<List<CreatePost>>(request, (response)
=>
{
if (response.ResponseStatus != ResponseStatus.Error
&& response.StatusCode == System.Net.HttpStatusCode.OK)
{
var x = response.Content;
}
else
{
MessageBox.Show("Error occured.");
}
});
}
}
}
Var x contains the following <PERSON> string:
[
{"blog":
{"blogNaam":"Kevinsblog",
"owner":
{"username":"Kevin"}
},
"postbeschrijving":"Dit is een post om te testen",
"postId":1,
"titel":"TestPost"
},
{"blog":
{"blogNaam":"Kevinsblog",
"owner":
{"username":"Kevin"}
},
"postbeschrijving":"Dit is een post om te testen2",
"postId":2,
"titel":"TestPost2"
},
{"blog":
{"blogNaam":"Kevinsblog",
"owner":
{"username":"Kevin"}
},
"postbeschrijving":"Dit is een post om te testen3",
"postId":3,
"titel":"TestPost3"
}
]
The first question is how to loop trough this <PERSON> string and put it into an array
so the array[0] contains
{"blog":
{"blogNaam":"Kevinsblog",
"owner":
{"username":"Kevin"}
},
"postbeschrijving":"Dit is een post om te testen",
"postId":1,
"titel":"TestPost"
}
array[1] contains
{"blog":
{"blogNaam":"Kevinsblog",
"owner":
{"username":"Kevin"}
},
"postbeschrijving":"Dit is een post om te testen2",
"postId":2,
"titel":"TestPost2"
}
and array[2] contains
{"blog":
{"blogNaam":"Kevinsblog",
"owner":
{"username":"Kevin"}
},
"postbeschrijving":"Dit is een post om te testen3",
"postId":3,
"titel":"TestPost3"
}
and the second question is how to access these values once they're put into an array so i can put them into a listbox in my WP7 app
If any other code is needed, just ask.
|
2a6f4bfbcfc5f1a4923ab3ee3b32c3f80ae5be25416d640c891fc6670d4017a4 | ['9e533a32ccb94b05ad418b9a4e463967'] | I cannot reconstruct this: Retrieve only the queried element in an object array in MongoDB collection.
Remember, there are two id which should match and I want the Image: [] back.
This is my structur.
{
"_id" : ObjectId("5ee4e57a6e5a926bdeb1e406"),
"Display" : [
{
"_id" : ObjectId("5ee5b7db9245084840dc624f"),
"Image" : [
{Document I want},
{Document I want}]
}
]
}
My best try:
db.User.aggregate([
{"$match" :
{"_id": ObjectId("5ee4e57a6e5a926bdeb1e406")}
},{
"$project" :{
"Display" : {
$filter: {
input: ObjectId("5ee5b7db9245084840dc624f"),
as: "id",
cond: {
"$Display._id": "$$id"}
}
}
}
}]);
| 8f7c23e8c8e59c10438ac503363935dd6b6098215c1ccd1a9d61611e5f22f73f | ['9e533a32ccb94b05ad418b9a4e463967'] | I want to create a Grid with 3 columns and * rows. The problem is something with this row.appendChild(col); element. This work 2 runs or zero runs. There isn't an error, I tried different browsers, I haven't a clue.
Can a buffer overload or a memory got overfilled?
var Jsonstring ='[{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_1e9b5.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_21c02.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_542b9.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_66721.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_8bbfd.jpg"}]';
function doShowUploadedPictures() {
try {
var obDaten = JSON.parse(Jsonstring);
//
var div = document.getElementById("uploaded");
div.innerHTML = "";
div.classList.add("pt-3");
//
var row = document.createElement("div");
row.classList.add("row");
//
var icount = 1;
for (var i in obDaten) {
if (true) {
var btndiv = document.createElement("div");
btndiv.classList.add("position-absolute");
btndiv.style = "display: none";
var button = document.createElement("button");
button.classList.add("btn", "btn-danger");
button.innerHTML = "del";
btndiv.appendChild(button);
var img = document.createElement("img");
if (obDaten[i].Imgname !== null) {
img.src = obDaten[i].Imgname;
}
if (obDaten[i].alt !== null) {
img.alt = obDaten[i].alt;
}
img.classList.add("img-thumbnail", "pt-0", "position-absolute");
var col = document.createElement("div");
col.classList.add("col-md-4", "position-relative");
col.addEventListener('mouseover', function (event) {
event.target.parentNode.childNodes[1].style = "display: flex";
});
col.addEventListener('mouseout', function (event) {
event.target.parentNode.childNodes[1].style = "display: none";
});
//
col.appendChild(img);
col.appendChild(btndiv);
row.appendChild(col);
//
if (icount && (icount % 3 === 0)) {
div.appendChild(row);
row.innerHTML = "";
}
icount++;
}
}
div.appendChild(row);
} catch (e) {
console.log("Error " + e);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button onclick="doShowUploadedPictures()">click</button>
<div id="uploaded"></id>
</body>
</html>
|
6e38de8018cab4b4a72490090014bdce2f01490eef8064183ed67376b3c6a5b0 | ['9e6cbfd024a94a13a296334de6ebe905'] | I would like to make a single facetted plot (lattice style) by varying the span parameter to the loess smoother. I tried using a for loop as below but no plot was produced. If I were to use the ggsave function, the plots are saved separately.
In addition, I was wondering if there is a more parsimonious way to do such a task?
x <- rep(1:10,4)
y <- 1.2*x + rnorm(40,0,3)
s <- seq(0.2,0.8,0.1)
# plot the series of plots by varying the span parameter
for (s_i in s) {
qplot(x, y, geom = 'c('point','smooth'), span = s_i)
}
| d92d1ffe79ada4687cb1cadcd84da263b02e2f5c57f5b5c66b615f125133070e | ['9e6cbfd024a94a13a296334de6ebe905'] | I would like to generate a sequence of dates by quarter backwards from a given date (31 July 2015). Instead of getting the last day of April, I get the first day of May as below:
> seq(as.Date('2015-07-31'), as.Date('2014-09-30'), by = '-3 month')
[1] "2015-07-31" "2015-05-01" "2015-01-31" "2014-10-31"
I also tried passing -quarter in the by option but I got the following error:
> seq(as.Date('2015-07-31'), as.Date('2014-09-30'), by = '-quarter')
Error in seq.Date(as.Date("2015-07-31"), as.Date("2014-09-30"), by = "-quarter") :
invalid string for 'by'
While I can check the day of the month and correct accordingly should the dates have been over-adjusted into the wrong month, I was wondering if there exists a parsimonious snippet of code to do the above?
|
2ee1a160f43aa5d5ae0cebef351016c837c2ac72747400ec8e78f0671eec44d8 | ['9e74736714014773b34a56642cb525fe'] | To anyone who is interested , i have a backreference to Recipient from Address. SO I was able to do this following
m.CreateMap<SalesOrder, OrderDTO>()
.ForMember(d => d.OrderBy, conf => conf.MapFrom(o => o.OrderBy.DefaultAddress))
.ForMember(d => <PERSON>, conf => conf.MapFrom(o => o.BillTo.DefaultAddress));
m.CreateMap<Address, RecipientDTO>()
.ForMember(r => r.CustomerRecipientId, conf => conf.MapFrom(ra => ra.Recipient.CustRecipId))
.ForMember(r => r.Address1, conf => conf.MapFrom(ra => ra.Addr1))
.ForMember(r => r.Address2, conf => conf.MapFrom(ra => ra.Addr2))
....
m.CreateMap<SalesOrderLine, OrderLineDTO>()
.ForMember(l => l.OrderQuantity, conf => conf.MapFrom(l => l.OrderQty ?? 0))
.ForMember(l => l.ShipTo, conf => conf.MapFrom(z => z.ShipToAddress));
| 4351202f59ad116faca7cbbc40414d835ec081dfeaccf87bdaccae7aef9cd074 | ['9e74736714014773b34a56642cb525fe'] | I have an angular app hosted by asp.net core as a SPA. I need to integrate it with SalesForce Canvas using Signed Request. I understand that Salesforce does a POST to the callback URL with the signed request body which can be validated (see here).
But Angular SPA cannot handle POSTs. It can only handle GETs. Which among the two is a better option
Have Salesforce do a POST to the backend (ASP.NET Web API in our case) and redirect to the Angular App after validation from the backend.
Wire the ASP.NET Core FrontEnd pipeline to handle the SalesForce POST and redirect.
Is there another better way?
|
b69890532a67595a57b00bbd5f031f9e17ed34815e62fd8e6b0bd3d016d2fa17 | ['9e75b185f4c34c69851ea41225740a36'] | The <pre> tag will interpret its contents literally -- so you need to add some spaces.
<pre><code>somevar = array.join("-")
somevar.split("-")
puts "#{somevar} is cool yay!"
if somevar.nil?
puts 'it's nil!'
end
</code></pre>
should become
<pre><code> somevar = array.join("-")
somevar.split("-")
puts "#{somevar} is cool yay!"
if somevar.nil?
puts 'it's nil!'
end
</code></pre>
| 425e4e5e3dc2810b0cc56020f2f57566a3d48cd55b1fe1436523b2a2925a7cd0 | ['9e75b185f4c34c69851ea41225740a36'] | Thank to <PERSON> feedbacks, I have rewritten the code as the following:
def grayscale(image):
return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
def sobel_xy(gray, sobel_kernel=9, absolute=True):
sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
if absolute:
sobel_x, sobel_y = np.absolute(sobel_x), np.absolute(sobel_y)
return sobel_x, sobel_y
def sobel_abs(gray, orient='x'):
orientation = {'x': 0,'y': 1}[orient]
sobel = sobel_xy(gray)
return sobel[orientation]
def scale(sobel, MAX=255, dtype=np.uint8):
return dtype(MAX * sobel / np.max(sobel))
def mask(image, lower, upper):
return (image >= lower) & (image <= upper)
def gradient_abs_sobel(image, orient='x', thresh=(0, 255)):
gray = grayscale(image)
<PERSON> = sobel_abs(gray, orient=orient)
sobel_scale = scale(sobel, MAX=thresh[1], dtype=np.uint8)
return mask(sobel_scale, thresh[0], thresh[1])
def gradient_magnitude(image, sobel_kernel=9, thresh=(0, 255)):
gray = grayscale(image)
<PERSON> = np.hypot(*sobel_xy(gray, sobel_kernel=sobel_kernel, absolute=False))
<PERSON> = scale(gradmag, MAX=thresh[1], dtype=np.uint8)
return mask(gradmag, thresh[0], thresh[1])
def gradient_direction(image, sobel_kernel=15, thresh=(0, np.pi/2)): # thresh=(0.7, 1.3)
gray = grayscale(image)
<PERSON> = np.arctan2(*sobel_xy(gray, sobel_kernel=sobel_kernel, absolute=True))
return mask(absgraddir, thresh[0], thresh[1])
def main():
# parameters and placeholders
args = PARSE_ARGS()
# Choose a Sobel kernel size
ksize = 9
# Read images
image = mpimg.imread(args.sand+'signs_vehicles_xygrad.jpg')
img_solution = mpimg.imread(args.sand+'binary-combo-example.jpg')
# Apply each of the thresholding functions
gradx = gradient_sobel_abs(image, orient='x', sobel_kernel=ksize, thresh=(20, 100))
grady = gradient_sobel_abs(image, orient='y', sobel_kernel=ksize, thresh=(20, 100))
mag_binary = gradient_magnitude(image, sobel_kernel=ksize, thresh=(20, 100))
dir_binary = gradient_direction(image, sobel_kernel=15, thresh=(0.7, 1.3))
# combine thresholds
combined1, combined2, combined3 = np.zeros_like(dir_binary), np.zeros_like(dir_binary), np.zeros_like(dir_binary)
combined1[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1
combined2[((gradx == 1) & (grady == 1))] = 1
combined3[((mag_binary == 1) & (dir_binary == 1))] = 1
# Plot the result
row, column = [5, 2]
figure, axes = plt.subplots(row, column, figsize=(15, 20))
figure.tight_layout()
list_title_image = [['Original Image',image],
['Expected result', img_solution],
['gradx', gradx],
['grady', grady],
['mag_binary', mag_binary],
['dir_binary', dir_binary],
['combined1', combined1],
['combined2', combined2],
['combined3', combined3],
['Original Image', image] ]
for ax, img in zip(axes.flatten(), list_title_image):
ax.imshow(img[1], cmap='gray')
ax.set_title(img[0], fontsize=15)
ax.axis('off')
if __name__ == '__main__':
main()
|
c92a2df2126c90ba2ac46fc2a1d5560167a8e8228a54288850fcf53fd0e9184d | ['9e793e78ffea48e3b324e6e88bac0405'] | The Chow Test which is also incorporated in AUTOBOX actually dteremines if any of the parameters have changed ober time. If as you assert the last 2-3 years has a different ARIMA structure than the prior periods AUTOBOX will suggest data segmentation. If you want to pursue this feature contact the folks from Aautomatic Forecasting Systems. By the way I have written those procedures for them.
| 25edeb09ee336a67ea0ad7d39bdf509ff62753af2cb2814326ff6f35318fdc83 | ['9e793e78ffea48e3b324e6e88bac0405'] | If you knew a priori that certain weeks of the year or certain events in the year were possibly important you could form a Transfer Function that couild be useful. You might have to include some ARIMA structure to deal with short-term autoregressive structure AND/OR some Pulse/Level Shift/Local Trends to deal with unspecified deterministic series ( omitted variables ). If you would like to post all of your data I would be glad to demonstrate that for you thus providing ground zero help. Alternatively you can email it to me at <EMAIL_ADDRESS> and I will analyze it and post the data and the results to the list. Other commentators on this question might also want to do the same for comparative analytics.
|
4e37c9c21448c1004176ce3a7a093b773df03fd916f5f396d10eb7988685c6d0 | ['9e848e9304734beda1efdaa59c2e471b'] | ...actually, it looks like <PERSON> may finish about a full point ahead of <PERSON> in the popular vote, which means this poll was off by 4, not 3. So in theory a similar poll that had her winning by 3 points would have been **twice as accurate** as this one (off by only 2 points rather than 4). | 14dbd46e811b18e2fdb842325419b8f284a75714e7b2ce2ccc8f907345442b48 | ['9e848e9304734beda1efdaa59c2e471b'] | what i want to ask is, how does calling a binary from script cause crash? Also I am sure my binary is called by script as I can check the core is created due to my binary. so please suggest what are the factors created difference running a program on a shell prompt and running the same program from the shell script ? |
1c0980e41a39523f62465f6748f5974fcd1762f1152a85cdcd2a8317502bc73d | ['9e84d5f5895141cf995c9697a1ce2e4f'] | There are a number of things that could be wrong. Usually this error occurs when there is no .htaccess file present, or it's not configured correctly. (Keep in mind: if you new host is not running Apache, then you're not dealing with .htaccess altogether) It might also be that mod_rewrite is not set.
First thing to try though: set your permalinks back to default, or date and save it. Then set it back to pretty permalinks with %postname% and save it. Quite often this actually solves your issue in case the correct accessfile is actually present. :')
| cfd2bb99d4bc0b57f9d602c62ec294082f9d8b8f2a1acc14da6a8126a398aae0 | ['9e84d5f5895141cf995c9697a1ce2e4f'] | I had the same problem, and I noticed that infinite scroll does add a page number to each block that it loads. So I peeked at infinite.php to see how it's done. Basically it looks at the query to see which page/block we're on.
Then you can set the counter properly, like so:
$counter = $wp_query->current_post;
$page = $wp_query->get( 'paged' );
$counter = $page*7+$counter;
Or if you want to start with 0 on the extra loaded pages, because you already counted the first 7: (It's 7 because that's what the WordPress infinite scroll uses.)
$counter = $wp_query->current_post;
$page = $wp_query->get( 'paged' );
$counter = ($page - 1)*7+$counter;
You can probably think of an even nicer way of doing this...
|
ccce0bf5964945738fcc82a7df3dec6b0905ed71c75d28d3e490b9efb106a968 | ['9e982edd58cd4fd89d50c11eaab99113'] | I've encountered a problem when trying to define a recursive function which uses map over a zip.
Here is a simplified version of my code, firstly one that works
datatype bar = Bar "bar list"
function (sequential) bar_lub <IP_ADDRESS> "[bar,bar] ⇒ bar" ("_⊔b_" [30,60] 60)
where
"(Bar ts) ⊔b (Bar us) = Bar (map (λ(t1,t2). t1 ⊔b t2) (zip ts us))"
by pat_completeness auto
This is fine, and results in the termination goal of
1. ⋀ts us a b. (a, b) ∈ set (zip ts us) ⟹ P (a, b) ~ P (Bar ts, Bar us)
which is easy to prove given an appropriate P and ~.
My problem comes when I change the list to a list of pairs, as follows
datatype 'a foo = Foo "('a foo × 'a) list"
function (sequential) foo_lub1 <IP_ADDRESS> "['a foo, 'a foo] ⇒ 'a foo" ("_⊔_" [30,60] 60)
where
"(Foo ts) ⊔ (Foo us) = Foo (map (λ((t1,_), (t2,_)). (t1 ⊔ t2, undefined)) (zip ts us))"
by pat_completeness auto
Now, we get the termination goal
1. ⋀ts us t1 b1 t2 b2 xc. ((t1, b1), t2, b2) ∈ set (zip ts us) ⟹ P (t1, xc) ~ P (Foo ts, Foo us)
the variable xc has appeared, and is not related to anything. Ideally, I would expect to have the assumption xc = t2, and the proof would be simple.
Does anyone know why this is happening, and any ways to remedy it?
| e7e0fe31af515fede45850854f2a72281488861afe13cb8daf3099fcfd8757ed | ['9e982edd58cd4fd89d50c11eaab99113'] | The most immediate way of doing this that occurs to me is to set up a datatype for you modal language datatype fml = ..., and a satisfaction predicate sat :: ('w ⇒ 'w ⇒ bool) ⇒ 'w ⇒ fml ⇒ bool, and embed the logic in Isabelle. This is (essentially) the approach taken by <PERSON> and <PERSON> (<PERSON>'s Honour's Thesis; IJCAR Paper).
The downside to this approach is that it's a deep embedding, which means you would have to deal with variable binding and substitution yourself.
You could also declare that worlds and an accessibility relation exist, using typedecl and consts, and define 'lifted connectives' as functions which take a world, and return a boolean, e.g. TT ≡ λw. True and ◊φ ≡ λw. ∃v. (w R v) ∧ φ v (where R is defined by consts). This is the approach taken by <PERSON><IP_ADDRESS> ('w ⇒ 'w ⇒ bool) ⇒ 'w ⇒ fml ⇒ bool, and embed the logic in Isabelle. This is (essentially) the approach taken by Xu and Norrish (Xu's Honour's Thesis; IJCAR Paper).
The downside to this approach is that it's a deep embedding, which means you would have to deal with variable binding and substitution yourself.
You could also declare that worlds and an accessibility relation exist, using typedecl and consts, and define 'lifted connectives' as functions which take a world, and return a boolean, e.g. TT ≡ λw. True and ◊φ ≡ λw. ∃v. (w R v) ∧ φ v (where R is defined by consts). This is the approach taken by Christoph Benzmüller in this preprint on Gödel's Ontological Argument.
|
8010ccd0073ff36f0bd2c6b18e87bbe48cd7c1830514d0764e7dda90b9c70812 | ['9ea31598257d4de69de287de0b919e2e'] | I'm also new to Lucene.Net, but I do know that the Simple Analyzer omits any stop words, and indexes all tokens/works.
Here's a link to some Lucene info, by the way, the .NET version is an almost perfect, byte-for-byte rewrite of the Java version, so the Java documentation should work fine in most cases: http://darksleep.com/lucene/. There's a section in there about the three analyzers, Simple, Stop, and Standard.
I'm not sure how Lucene.Net handles word stemming, but this link, http://www.onjava.com/pub/a/onjava/2003/01/15/lucene.html?page=2, demonstrates how to create your own Analyzer in Java, and uses a PorterStemFilter to do word-stemming.
...[T]he Porter stemming algorithm (or "Porter stemmer") is a process for removing the more common morphological and inflexional endings from words in English
I hope that is helpful.
| 2a70ce26a12a0b3fee59d394d1d53bf60e3228a40c5df3262b45533ae5636111 | ['9ea31598257d4de69de287de0b919e2e'] | <PERSON> is right. How are you defining your URL to call this ajax script? It should not just call a file, you should use Wordpress `add_action` for your ajax function. So in js file make your call to WPs admin ajax URL and set data to your function name like `add_action('wp_ajax_my_function','my_function')` keep in mind there is also wp_ajax_nopriv if you're logged out. |
3c922a843f408c57e8a803714df9f22f04da8182aa2f4d3be0f470a6f960c2c0 | ['9ea53812a92c46629dc3a4471c20435c'] | I want use DialogBox in Adapter, when start application and click area of my mean shown FC error.
My Adapter codes :
public class newSMS_card_adapter extends
RecyclerView.Adapter<newSMS_card_adapter.ViewHolder> {
private static String[] mDataset;
static public Context context;
public newSMS_card_adapter(String[] myDataset) {
mDataset = myDataset;
}
@Override
public newSMS_card_adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.newsms_card_layout, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
// use and set objects
viewHolder.newSMS_sms.setText(mDataset[position].toString());
viewHolder.versionName=mDataset[position];
}
@Override
public int getItemCount() {
return mDataset.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView newSMS_sms, newSMS_count, newSMS_username, newSMS_hour, newSMS_date, newSMS_category;
public String versionName;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
newSMS_sms = (TextView) itemLayoutView.findViewById(R.id.sms_newsms_text);
newSMS_count = (TextView) itemLayoutView.findViewById(R.id.newSMS_count_text);
newSMS_username = (TextView) itemLayoutView.findViewById(R.id.newSMS_username_text);
newSMS_hour = (TextView) itemLayoutView.findViewById(R.id.newSMS_hour_text);
newSMS_date = (TextView) itemLayoutView.findViewById(R.id.newSMS_Date_text);
newSMS_category = (TextView) itemLayoutView.findViewById(R.id.newSMS_category_text);
newSMS_sms.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.show_sms__page);
//ImageView closeDialog_image = (ImageView) dialog.findViewById(R.id.addSMS_close_image);
}
});
}
}
}
Log Cat error :
09-20 21:43:34.909 9418-9418/com.tellfa.smsbox E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tellfa.smsbox, PID: 9418
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.Dialog.<init>(Dialog.java:160)
at android.app.Dialog.<init>(Dialog.java:137)
at com.tellfa.smsbox.adapters.newSMS_card_adapter$ViewHolder$1.onClick(newSMS_card_adapter.java:78)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
09-20 21:43:36.914 9418-9418/? I/Process﹕ Sending signal. PID: 9418 SIG: 9
please help me to fix it. tnx all dears <3
| d536ac04e821ece3197bcfe565b3b5d90d32f4e708356ec68fb1b75c55a2cdb6 | ['9ea53812a92c46629dc3a4471c20435c'] | i what use ImageView and set images from server, i use Volley library for connect to server and fetch data.
but when start Application and scroll items, show FC errors. my items has RecyclerView , CardView and custom ImageView.
My Adapter codes :
public class DataAdapter extends RecyclerView.Adapter {
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private List<newSMS_class> sms_list;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
private Bitmap bm;
private Context context;
public DataAdapter(List<newSMS_class> sms_list_use, RecyclerView recyclerView) {
sms_list = sms_list_use;
context = recyclerView.getContext();
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
@Override
public int getItemViewType(int position) {
return sms_list.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.newsms_card_layout, parent, false);
vh = new StudentViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progress_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
private Bitmap getImg(String url) {
RequestQueue queue = Volley.newRequestQueue(context);
ImageRequest ir = new ImageRequest("http://smsbox.tellfa.com/UploadUserImage/Cover/img_" + url + ".jpg", new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
bm = response;
}
}, 0, 0, null, null);
queue.add(ir);
//ir.setShouldCache(false);
return bm;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof StudentViewHolder) {
newSMS_class singleStudent = sms_list.get(position);
((StudentViewHolder) holder).sms_content_new.setText(singleStudent.getSms());
((StudentViewHolder) holder).sms_username.setText(singleStudent.getUsername());
((StudentViewHolder) holder).sms_count.setText(singleStudent.getCountsms());
((StudentViewHolder) holder).sms_category.setText(singleStudent.getCategory());
((StudentViewHolder) holder).sms_category.setTag(singleStudent.getCat_id());
((StudentViewHolder) holder).sms_date.setText(singleStudent.getDate());
((StudentViewHolder) holder).sms_hour.setText(singleStudent.getHour());
Bitmap b = getImg(singleStudent.getAvatar());
((StudentViewHolder) holder).sms_avatar.setImageBitmap(b);
((StudentViewHolder) holder).sms_class = singleStudent;
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
}
}
public void setLoaded() {
loading = false;
}
@Override
public int getItemCount() {
return sms_list.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
//
public static class StudentViewHolder extends RecyclerView.ViewHolder {
public TextView sms_content_new, sms_username, sms_count, sms_category, sms_date, sms_hour;
public ImageView sms_avatar;
public newSMS_class sms_class;
public StudentViewHolder(View v) {
super(v);
sms_content_new = (TextView) v.findViewById(R.id.sms_newsms_text);
sms_username = (TextView) v.findViewById(R.id.newSMS_username_text);
sms_count = (TextView) v.findViewById(R.id.newSMS_count_text);
sms_category = (TextView) v.findViewById(R.id.newSMS_category_text);
sms_date = (TextView) v.findViewById(R.id.newSMS_Date_text);
sms_hour = (TextView) v.findViewById(R.id.newSMS_hour_text);
sms_avatar = (ImageView) v.findViewById(R.id.users_avatar);
sms_content_new.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
final Dialog showSMS_dialog = new Dialog(v.getContext());
showSMS_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
showSMS_dialog.setContentView(R.layout.show_sms__page);
showSMS_dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
Window window = showSMS_dialog.getWindow();
window.setLayout(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
showSMS_dialog.setCancelable(false);
showSMS_dialog.show();
ImageView closeDialog_image = (ImageView) showSMS_dialog.findViewById(R.id.addSMS_close_image);
TextView sms_txt = (TextView) showSMS_dialog.findViewById(R.id.addSMS_smscontent_text);
ImageView avatar = (ImageView) showSMS_dialog.findViewById(R.id.addSMS_avatar_image);
ImageView copy = (ImageView) showSMS_dialog.findViewById(R.id.addSMS_toolBar_copy);
ImageView share = (ImageView) showSMS_dialog.findViewById(R.id.addSMS_toolBar_share);
avatar.setImageDrawable(sms_avatar.getDrawable());
sms_txt.setText(sms_content_new.getText());
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent();
intent2.setAction(Intent.ACTION_SEND);
intent2.setType("text/plain");
intent2.putExtra(Intent.EXTRA_TEXT, sms_content_new.getText());
v.getContext().startActivity(Intent.createChooser(intent2, "به یکی بفرست ;)"));
}
});
copy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) v.getContext().getSystemService(v.getContext().CLIPBOARD_SERVICE);
clipboard.setText(sms_content_new.getText());
Toast.makeText(v.getContext(), "کپی شد مشتیییی :))", Toast.LENGTH_SHORT).show();
}
});
closeDialog_image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showSMS_dialog.dismiss();
}
});
}
});
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
}
}
}
Logcat codes :
09-29 15:57:56.223 <PHONE_NUMBER>/com.tellfa.smsbox E/Adreno-GSL﹕ <gsl_memory_alloc_pure:2044>: GSL MEM ERROR: kgsl_sharedmem_alloc ioctl failed.
09-29 15:57:56.233 <PHONE_NUMBER>/com.tellfa.smsbox W/Adreno-GSL﹕ <sharedmem_gpumem_alloc_id:1498>: sharedmem_gpumem_alloc: mmap failed errno 12 Out of memory
09-29 15:57:56.233 <PHONE_NUMBER>/com.tellfa.smsbox E/Adreno-GSL﹕ <gsl_memory_alloc_pure:2044>: GSL MEM ERROR: kgsl_sharedmem_alloc ioctl failed.
09-29 15:57:56.236 <PHONE_NUMBER>/com.tellfa.smsbox W/Adreno-ES20﹕ <core_glTexImage2D:539>: GL_OUT_OF_MEMORY
09-29 15:57:56.277 <PHONE_NUMBER>/com.tellfa.smsbox E/OpenGLRenderer﹕ GL error: Out of memory!
09-29 15:57:56.288 <PHONE_NUMBER>/com.tellfa.smsbox W/libc﹕ pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
09-29 15:57:56.289 <PHONE_NUMBER>/com.tellfa.smsbox E/art﹕ Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"
09-29 15:57:56.289 <PHONE_NUMBER>/com.tellfa.smsbox D/AndroidRuntime﹕ Shutting down VM
09-29 15:57:56.319 <PHONE_NUMBER>/com.tellfa.smsbox E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tellfa.smsbox, PID: 13523
java.lang.OutOfMemoryError: pthread_create (1040KB stack) failed: Try again
at java.lang.Thread.nativeCreate(Native Method)
at java.lang.Thread.start(Thread.java:1063)
at com.android.volley.RequestQueue.start(RequestQueue.java:134)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:66)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at com.tellfa.smsbox.adapters.DataAdapter.getImg(DataAdapter.java:104)
at com.tellfa.smsbox.adapters.DataAdapter.onBindViewHolder(DataAdapter.java:130)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5138)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4433)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4326)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1955)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1364)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1327)
at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1155)
at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:1012)
at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:3777)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:549)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
please help me to fix it. big tnx <3
|
9228c915ff8864c05ba3ba33afe9e386ed0ac856b1b89055a5e942c0d8892744 | ['9ea62417b0374e2fb678e71dd1d140c6'] | Workaround for this problem is to place canvas into other panel which respect parent width like StackPanel:
<StackPanel Grid.Column="0"
Grid.Row="0"
Orientation="Horizontal">
<Canvas Background="Black"
Width="1600"
Height="35" />
</StackPanel>
or even when you place any item in first row second column, that item would be in foreground and canvas would be in background, hence not visible.
| c5de9a097d3df82ce587a915bbd91d552d82f1fcf89d298af51193f07ed192d5 | ['9ea62417b0374e2fb678e71dd1d140c6'] | I think in Stackpanel instead of setting Height you should set MaxHeight and VerticalAlignment property value should be Center instead of Bottom and that should do your work:
<DataTemplate x:Key="TileViewDT">
<DockPanel>
<StackPanel MaxHeight="40.5" DockPanel.Dock="Right" Margin="5,2,5,2" VerticalAlignment="Center">
<TextBlock x:Name="Name" TextWrapping="Wrap" Text="{Binding XPath=@Name}" Width="132" />
<TextBlock x:Name="Size" Foreground="DarkGray" TextWrapping="Wrap" Text="{Binding XPath=@Size}" />
</StackPanel>
<Image x:Name="Img" Source="BtnImg/Computer.png" Stretch="Fill" Margin="10,0,5,0" Width="48" Height="48"/>
</DockPanel>
</DataTemplate>
Hope it works !!!
|
332462de44d58ea7260520baeb54d2363d68923f201803ee6ffd40151314f912 | ['9ea7483f232b4381824429699eb8bfe0'] | Prova 3.0 http://www.prova.ws is nearing completion. It is, however, not just another Prolog but a mix of programming styles, particularly, useful for easy bi-directional Java integration, reactive agent programming, integration with ESB's, workflow logic, and event processing. This version is a complete rewrite from zero so some older features, like OWL integration, are missing, but are bound to return in the next revision.
| 718706a0af0fde0edf709941355ed9f83d745112ebbf7ec81d1ca0c3d43ddff2 | ['9ea7483f232b4381824429699eb8bfe0'] | Two other interesting projects to note related to coding in Abstract Syntax Tree's is Tree-Sitter which is now a part of the Atom text editor and Github. It parses your code real-time into an AST. This allows you to do some very interesting things, like something the creator of it calls "Extend Selection" where you can continue to click on one word and it will highlight the text related to higher and higher levels of the AST since it understands that structure.:
There is also the Unison programming language which doesn't store source code in text files. Instead, it parses the text files, takes out of all the details so you're left with a highly-abstracted version of your code, and then it hashes that. That "code" is then accessed by using the hash, not the file name. This leads to a lot of interesting benefits like no more builds, no dependency conflicts, and you can easily change names of variables/functions/etc without changing the codebase.
Both of these projects allow you to code at an abstraction level a little further away from the raw text and closer to the AST.
|
1260fec4087494e4125bb42a16c9654d308dec11989cd7512ced04ae33a9ac4c | ['9ebbbcfe97ec4130927e5c7c9b8e5ae6'] | I am using a GcmReceiver with a listener that extends GcmListenerService.
In my onMessageReceived method, I want to download a remote image (using Picasso lib) and once the image has been downloaded, post a notification to the user.
Code:
public class MainGcmListenerService extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
String urlImage = data.getString("image_url");
final Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) ...... // build a notification with the downloaded image as a logo
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notificationType.getValue(), mBuilder.build());
}
};
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
@Override
public void run() {
Picasso.with(context).load(urlImage)
.into(target);
}
});
This code works well most of the time, but sometimes the notification is not posted. I assume this is due to the fact that the GCM message thread gets killed before the download image task is finished. What would be a correct way to implement such a process in a GcmListenerService (downloading an image in onMessageReceived and then posting the notification once its finished)?
| 44852ee4709f9bbd3c67174aab2bdc4a370093f7f8a59a498674070ba0dbd762 | ['9ebbbcfe97ec4130927e5c7c9b8e5ae6'] | Once a minute I am running an update to my sqlite database using core data, by making a web request, parsing that request, and updating objects on my managed object context.
The JSON data returned from the webserver is stored in an NSDictionary:
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:operation.data options:kNilOptions error:&error];
I initialize an NSOperation instance with the dictionary stored as a member. The operation loops through the dictionary and update a NSManagedObjectContext, for example:
for (NSDictionary *item in self.dictionary) {
NSManagedObject *newItem = [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:self.context];
[newItem setValue:item[@"customerName"] forKey:@"contact_firstname"];
}
[self.context save:&error];
Looking at the instruments panel, I see that each update leaves few unreleased CFString objects:
The difference between the released and unreleased CFStrings can be shown by the refcount trace of each:
Released
Unreleased:
The retain (+1) made by [NSManagedObject(_NSInternalMethods) _newAllPropertiesWithRelationshipFaultsIntact__] prevents this object from being released. Since every update I delete all objects from the MSManagedObjectContext, I don't see any reason why these CFStrings should not be released.
What is the purpose of _newAllPropertiesWithRelationshipFaultsIntact__, and why does it retain some of my CFStrings?
|
abd092cd3c318fa1096afe4e4090887622df8ff7fc38f8cba46aace92291b9a2 | ['9ebeb4a9eeec418599874cf4deb0ac5f'] | I need to get index of from array of objects without using loop as per the key name using PHP. Here I am explaining my code below.
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));
$key = array_search('Jack', $arr);
echo $key;exit;
Here my code does not give any output. By using some key name I need the index of that object present inside array and also I dont want to use any loop. I need Is ther any PHP in build method so that I can get the result directly.
| 95b38f15abb12976792fe6b472b46bdb4f43a6028b2496168bfdb7686af4f503 | ['9ebeb4a9eeec418599874cf4deb0ac5f'] | I am getting the following error while using aggregate method in mongoDB.
Error:
Error: <PHONE_NUMBER>:14:33 - MongooseError: Callback must be a function, got [object Object]
at new MongooseError (/home/anil/Desktop/new/EdQart_Project/local/edqart-store-setup-api/node_modules/mongoose/lib/error/mongooseError.js:10:11)
at Function.Model.$handleCallbackError (/home/anil/Desktop/new/EdQart_Project/local/edqart-store-setup-api/node_modules/mongoose/lib/model.js:4604:11)
I am using mongoose with Node.js to retrieve the data from collection. I am explaining the query below.
const orders = await collection.aggregate(
[
{$match:filters},
{$sort:sort}
],
{allowDiskUse: true}
);
Here to avoid the sort limit issue I have used {allowDiskUse: true} and while fetching data I am getting that error. I need to resolve that issue.
|
40a1e5b58e5738a7ab879df391e1d5c0a6ec20dbff4e380387f77d063e408675 | ['9ec4ee165c9846b4a2d189d362f648c8'] | Here is the description of te function I am supposed to develop...give
a
Money
instance
that
rounds
the
monetary
amount
to
the
nearest
coin
(e.g.
NICKEL).
In
everyday
language
we
would
say
that
this
method
(function)
gives
back
change;
however,
it
does
not
change
the
calling
object
itself
but
rather,
returns
a
new
instance.
This
function
would
be
used
in
retail
in
Canada
to
give
back
a
monetary
amount
as
change
in
coins.
So I understand the return type will be a new instance aka object of Money and the parameters should be a money instance, but what else is this function supposed to do?
| 20b93b6489ff54159d277a3b880a025152a8bc718ce199268bf02df59d8e5a70 | ['9ec4ee165c9846b4a2d189d362f648c8'] | Trying to print out a polynomail i.e 10x^0+1*x^1 and 9*x^0+1*x^1 However the polynomials print out as
10x^0+1*x^1 +9*x^0+1*x^1, here is my for loop equation
for(int i=0; i<=p->deg; i++) {
if (p->coeffs[i]==0)
break; //dont want to print out any 0 constants
cout << p->coeffs[i] <<" * " << x << "^"<<i << " ";
if (p->coeffs[i]>0 && p->coeefs[i+1]!=0)
cout<< "+";
}
|
aec39d9f7ee24ce9f47c70dabae53016e226172e51d73375c1dc515c2a809942 | ['9ed6868c50e2436caa87fde7f398c9da'] | Individual made a (second) mortgage loan to another. The loan has been in default for many years. The bank (first mortgage holder) foreclosed on the property. The individual lender received a partial lump sum payment of $20K. The total loan amount was roughly $280K of which $150K was principal and accrued interest was $130K.
Is any of the $20K received taxable interest income?
| 010b05f8ef74ba74c797bbdfbf10a138370ccf3ed97fcd52c9fda40c00327924 | ['9ed6868c50e2436caa87fde7f398c9da'] | It appears, there is nothing wrong in what you're doing..
but there could be multiple reasons of why this is happening.
you could check the values of each one of you variables (Users UserID).
and note that tha contain function is case sensitive.. so also check the spelling of the name..
if you can provide the results of the variables we may be able to help you more.
|
9fc5dc717c540e51852430ab3183a47904a2d935dd634830a0f53c69cfa80bb2 | ['9edc8780fe9b4364babf098a79d71b24'] | As outlined in this documentation, the google-accounts daemon in compute-image-packages creates users and home directories for all users in the project that have SSH access after booting the new instances (these accounts are registered as SSH keys in the Compute Engine metadata).
The google-accounts daemon repeatedly polls the metadata server and creates home directories, UNIX accounts, and entries in ~/.ssh/authorized_keys to allow you to login.
You should either:
Option 1. Remove those users and home directories from the instance with SSH access and disable google-accounts-daemon service.
To do this, set accounts_daemon to false in the /etc/default/instance_configs.cfg file:
[Daemons]
accounts_daemon = false
Regenerate /etc/default/instance_configs.cfg configuration file:
$ sudo /usr/bin/google_instance_setup
Stop google-accounts-daemon service:
$ sudo systemctl stop google-accounts-daemon
and disable google-accounts-daemon service:
$ sudo systemctl disable google-accounts-daemon
It will prevent the GCE instance from adding accounts and the google-accounts-daemon won't start at boot.
Option 2. Switch to OS Login based SSH access to manage SSH access to Linux instances.
| e07397a0bac5d0867ae24a2b25bec09924efc8ca768bf6ca9a7ea6053a69782e | ['9edc8780fe9b4364babf098a79d71b24'] | You can change the Cloud Storage bucket/folders used by Cloud Dataprep for uploads, job runs, and temp storage by making sure you have created a bucket in your desired location, selecting the icon which displays the first initial of the account owner's username located in the bottom left corner, then selecting "Settings" from the drop-down menu. It will bring you to the User account's page and there you will be able to replace the old bucket for the new one.
|
47687e49ee6266a3afb1cf573182f9d70fb918fbb43635b78f6ca3871d1e13c1 | ['9ee67f09974143dcb1dd9963432e8634'] | First of all, sorry for my english :-)
Second, I want to run and debug my Spring application in a docker container. The container with the application starts up without any problem, I can reach the app from a browser.
I'm developing it in IntelliJ IDEA on Linux Mint and I would like to retrieve the debug informations from my container. But when I started the app in debug mode the IDEA tells me:
Cannot retrieve debug connection: java.net.MalformedURLException: unknown protocol: unix
Here's my Dockerfile:
FROM tomcat:8-jre8
RUN apt-get update -y && apt-get install -y \
curl \
vim
RUN rm -rfd /usr/local/tomcat/webapps/ROOT
RUN mkdir -p /usr/local/tomcat/conf/Catalina/localhost
RUN echo "<Context docBase=\"/usr/local/tomcat/webapps/ROOT\" path=\"\" reloadable=\"true\" />" >> /usr/local/tomcat/conf/Catalina/localhost/ROOT.xml
ENV JPDA_ADDRESS=8000
ENV JPDA_TRANSPORT=dt_socket
ENV JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=8000,suspend=n,server=y
EXPOSE 8000 8080
In the run configurations the port bindigs are correct, the app deploys successfully. Could someone help me? :-)
| 4d7e27655e359899e7bf8ab3fa31c669b25300c60bead5bf873b4d910430c9ff | ['9ee67f09974143dcb1dd9963432e8634'] | I think you need the client-go informers. Here's a good tutorial about them: https://firehydrant.io/blog/stay-informed-with-kubernetes-informers/
You can create an asynchronous event listener for the Pod in which your containers are running and then when one of a container status is change then the pod status is change also (updated, so you should listen to update events).
So you got the update event from your pod, after all you need get the Pod cointainers.
I hope you looking for this :)
|
9435a901c98f942c21c8f36eeec458f491d1644839784bf75ffecb809e430bc4 | ['9efa5747691441cc86e3dcc1b6c839eb'] | If you have VPS or Dedicated server on bluehost, try this manual from Bluehost FAQ:
https://my.bluehost.com/cgi/help/2383
Pretty sure, that you must manually import database (as it not included to git and can't upload automatically in mysql) and configure again wp-config.php. Also you don't say, what server you using with localhost, cause it can be different from bluehost config (for example apache / nginx / php version).
| 3b4216fb2e3569a3241e5817743568a3874ae709040d819fad32a4d9c264de96 | ['9efa5747691441cc86e3dcc1b6c839eb'] | I am trying to update title of wordpress single post via admin-ajax.php. Everything works great when I am directly load http://mysite.url//wp-admin/admin-ajax.php?action=myactionname * but when I am trying to load it from frontend (single post), variables doesn't send correctly.
I am using Wordpress 5, Php 7.2, Nginx
Inside plugin:
class AjaxUpdate {
public $postid;
public $new_title;
public function __construct($postid, $new_title) {
$this->postid = $postid;
$this->new_title = $new_title;
add_action('wp_ajax_myactionname', array( $this, 'do_updatepost'));
add_action('wp_ajax_nopriv_myactionname', array( $this, 'do_updatepost'));
add_action( 'wp_enqueue_scripts', array( $this, 'ajax_update_script'));
}
public function do_updatepost() {
echo 'It Work Updatepost';
$post_update = array(
'ID' => $this->postid,
'post_title' => $this->new_title,
);
wp_update_post( $post_update, $wp_error );
wp_die();
}
public function ajax_update_script() {
wp_enqueue_script('ajaxpost', plugins_url('plugname/scripts/ajaxpost.js'), array('jquery'));
wp_localize_script('ajaxpost', 'plugname', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('nonce-for-plugname'),
));
}
}
inside template page of single post:
$wpajaxupdate = new AjaxUpdate($postid, $new_title);
jQuery(document).ready(function ($) {
var data = {
action: 'myactionname',
nonce: plugname.nonce,
};
jQuery.post(plugname.ajaxurl, data, function (response) {
alert('Worked: ' + response + JSON.stringify(data));
});
});
If I am using this code inside plugin, set variables and load http://mysite.url//wp-admin/admin-ajax.php?action=myactionname everything works fine:
$wpajaxupdate = new AjaxUpdate($postid, $new_title);
What I am doing wrong? What is the correct way to update wp post title via ajax?
|
f7df5ecfe35e7d66c835f99cd88051b760bd5abddcea4969b074b149c3fe61b6 | ['9f22e827ee5e43df8d9983842e1226d4'] | I am reading about index of the Hodge-de Rham operator d$+$d$^*$, for a compact Riemannian manifold $M$, and its equality with the Euler characteristic of $M$. In the proof, which is an easy consequence of <PERSON> decomposition, there is usually stated the "obvious" fact that
$$
\text{Image}((\text{d} + \text{d}^*)^2) = \text{Image}((\text{d}^*\text{d} + \text{d}^*\text{d}) = \text{image}(\text{d}) + \text{image}(\text{d}^*).
$$
The inclusion of the LHS in the RHS is obvious. However, I cannot see why the opposite inclusion is true.
| aa270a4c32757198a1ab9337120fd32fb48a12129298c04fa4457c1dd8be1114 | ['9f22e827ee5e43df8d9983842e1226d4'] | Am I correct in reasoning that, from <PERSON> decomposition in the form $\Omega^k =$ d$\Omega^{k-1} \oplus $d$^* \Omega^{k+1} \oplus H^k$, the Laplacian must act as an isomorphism on d$\Omega^{k-1} \oplus $d$^* \Omega^{k+1}$, since $H^k = $ker$(\Delta)$, and so, its image is indeed d$\Omega^{k-1} \oplus $d$^* \Omega^{k+1}$? |
ca7b553ecd7bacecbf820678310d19bbaa8e4eed777fc6aebeb7313494016005 | ['9f28d926b08e46f480858af8b2648214'] | I solved this in a two-step fashion.
Formula for calculating elapsed day of fiscal year.
Formula for calculating fiscal week based off of elapsed days of fiscal year
This formula calculates the elapsed day of the fiscal year - for my purposes as of April 1. You'll need to tinker with the month value as fit for your purposes.
=date-DATE(YEAR(date)+(MONTH(date)<4)*-1,4,1)+1
The second formula I used took that elapsed day value and calculated it into a work week.
=ROUNDDOWN(((day_of_fiscal_year-1)/7),0)+1
The -1 in the second formula is to offset the elapsed day result and keep the week numbers aligned so that the 7th, 14th, 21st day results get pulled into the first, second and third weeks respectively. The +1 at the end prevents you from having a Week 0.
| 65883acb042d2823ff206b2e2d412b6355b5fef32ab70eaa0923d1c76df03830 | ['9f28d926b08e46f480858af8b2648214'] | 05AB1E, 3 bytes
<P<
Try it online!
This is of course only assuming that the greatest common denominator of the inputs (exchange rates) is 1, because otherwise this number is not well-defined.
Explanation:
The number we want to compute is called the Frobenius Number and can be calculated with the formula \$\operatorname{Frob}(a,b) = (a-1)(b-1) - 1\$.
< | Subtract 1 from each input
P | Take their product
< | Subtract 1
|
64dec32dd7105f90340e79ff5f8fd238789ce84dd2115708c06afdcd7e56915e | ['9f2b9ec319c141e9b8ef1f325f4344a8'] | There are a few ways to do it:
Redokun https://redokun.com (disclaimer: I’m a co-founder)
Export all the sentences in an Excel file, translate them and then reimport the sentences into the InDesign files.
Otherwise, there are a few (paid) tools (InPagina come to mind, but there are a few of them). There are also some solutions that save your document layout and information in a database and automatically create your InDesign document.
These solutions are very powerful, they are able to manage any changes you make and store your translations.
| 68793c0c1c040ccbf1e096ac695b232f7e68bbd3602c1df674243b310aa843a5 | ['9f2b9ec319c141e9b8ef1f325f4344a8'] | I think you can use any digital camera with good amount of pixels (12 should suffice). You also need to make sure that the object is fairly lit in case its steady, or well lit in case its moving.
Also, I don't think you need to take two different photos if you want to make use of the interactive zoom feature on the website. You just need to capture one image and use the compressed image for normal zoom & the high res image for the zoomed version.
Hope that helps!
|
6a276371cf13cbcb8580aeb7ec2371a8744daddf2bfb1e246fefd119eea5957b | ['9f363158a25a41b8bc8da7c5636210ba'] | As far as I understand, the whole trick is in the not-so-intuitive behavior of gamma and that it affects the value of option based on actual volatility (the 1/2*gamma*market_change^2 term). [This article](http://investorplace.com/2010/01/long-gamma-position/) was also quite good to explain the mechanics. And as [volcube](http://www.volcube.com/resources/options-articles/the-difference-between-long-gamma-and-short-gamma/) points out, the role of continuous delta-hedging is just to lock-in profits from the actual vol, otherwise rally of 5 points followed by drop of 5 points would earn nothing. | f82ad9ec2a9fe57104d5b249cfae90d29eab5065d7dcfc377a66b431c4ae5552 | ['9f363158a25a41b8bc8da7c5636210ba'] | I would like to do something in R that SAS can do using SAS's proc mixed (there is some way to do in STATA es well), namely fitting the so called Bivariate model from <PERSON> et al (2005). This model is a special mixed model where the variance depends on the study (see below). Googling and talking to some people familiar with the model did not yield a straightforward approach that is fast at the same time (i.e. a nice high level model fitting function). I am nevertheless sure, there is something fast in R that one can built on.
In a nutshell one is faced with the following situation: Given pairs of proportions $(p_1,p_2)$ in $[0,1]^2$ one would like to fit a bivariate normal to the logit-transformed pairs. Since the proportions come from a 2x2 table (i.e. binomial data) each logit transformed observed proportion has a variance estimate that is to be included in the fitting process, say $(s_1, s_2)$. So one would like to fit a bivariate normal to the pairs, where the covariance matrix $\Sigma$ depends on the observation, i.e.
$(\text{logit}(p_1),\text{logit}(p_2)) \sim N((mu_1, mu_2), \Sigma + S)$
where S is the diagonal matrix with $(s_1, s_2)$ and depends entirely on the data but varies from observation to observation. mu and Sigma are the same for all observation though.
Right now I am using a call to optim() (using BFGS) to estimate the five parameters ($\mu_1$, $\mu_2$, and three parameters for $\Sigma$). Nevertheless this is painfully slow, and especially unsuitable for simulation. Also one of my aims is to introduce regression coefficients for mu later, increasing the number of parameters.
I tried speeding up fitting by supplying starting values and I also thought about computing gradients for the five parameters. Since the likelihood becomes quite complex due to the addition of $S$, I felt the risk of introducting errors this way was too big and did not attempt it yet, nor did I see a way to check my calculations.
Is the calculation of the gradients typically worthwhile? How do you check them?
I am aware of other optimizer besides optim(), i.e. nlm() and I also know about the CRAN Task view: Optimization. Which ones a are worth a try?
What kind of tricks are there to speed up optim() besides reducing accuracy?
I would be very grateful for any hints.
|
496cd4622427c246751014c69e94c1424d61003809911a91403ec3a0bb32e1e3 | ['9f3c92688bdb46398e0ddc7b7b473aab'] | I have written an application program and what to get notified in this application if system date or time changed, the same way if user presses ctrl+c then OS sends sigkill signal. My requirement is to know if date or time change take place at any instance of time.
Dear friend, Can you please suggest me any technique to get notified in application for such events.
Thanks in advance to all.
| de229d52095394de94d41c005ea52c7fab78b3105a91261070255383125cf4ad | ['9f3c92688bdb46398e0ddc7b7b473aab'] | I know that we we call an overloaded function, compiler tries to match exact prototype and then goes for type promotion. But we it comes to return type, compiler does not goes for exact match and throws error. I am not sure the logic behind it. Dear friends, can u please help me here? Thanks in advance to all
|
245c050116fcb76c4c38a04c0073b53ee702338eaf4b962a155b7f69d20c163f | ['9f3e872137a342a893f30131b5f44f50'] | I understand and I agree with your comment. I will update and complete my question in the following days. This is not part of a problem sheet or homework, I was studying and wanted to prove the general case, which I couldn't find in the textbook I was following. | 81d9209df9d5e536480881a5e44c5e8abdca46f13a1b72ea11dd590b41b18401 | ['9f3e872137a342a893f30131b5f44f50'] | Given a Hilbert space $\mathbb{C}^N$ and the reduced dynamics $\Lambda(t)$ of the open quantum system, we can define the set of asymptotic states as
$$
\mathcal{A}=\left\{\tilde\rho \in \mathcal{S}(\mathbb{C}^N)\,|\,\exists\rho \in \mathcal{S}(\mathbb{C}^N)\; \text{such that}\; \lim_{t\rightarrow\infty} \Lambda(t)[\rho]=\tilde\rho \right\}\,,
$$
where by $\mathcal{S}(\mathbb{C}^N)$ I mean the set of quantum states ($\mathrm{Tr}\,\rho=1, \rho^\dagger=\rho, \rho\ge0$).
If the open system dynamics is relaxing, then there is only one steady-state $\rho_{ss}$ and this is the unique asymptotic state, so $\mathcal{A}$ has one element. However, in general $\mathcal{A}$ may have $\infty$ elements.
For example, for a pure dephasing channel, we have $\infty$ asymptotic states in the z-axis (if the coherence plane is the xy-plane) in the Bloch sphere.
So my question is:
Are there any particular reduced dynamics $\Lambda(t)$ for which we can say, for example, that $\mathcal{A}$ has 2 and only 2 different elements?
Thanks!
|
11d029174a5aabc009becef30a136b252d5cca7a756b1f44e960e41eb6e5c439 | ['9f41eadbf7b84bc39714f65317b60f3c'] | Just wanted to know how I can make a div with more vertices just like the picture below:
Is there any way to do that with css or JavaScript?
What I wanted to do is to add a text inside this orange shape, so the image that is on the top left area doesn't overlay the text.
| 8267bf3b39abca0cb8beec479ef717d72e56474b15d4555946367eb2443c4d44 | ['9f41eadbf7b84bc39714f65317b60f3c'] | I was making a new code where my objective was to make whatever key you press make my little "truck" go forward.
I was trying to do this by adding spaces to my string, which was my truck.
String truck = "<o><o>-<o>~|#|¬";
truck = new StringBuffer(truck).insert(0, " ").toString();
System.out.println(truck);
I would like to know how to do a "loop" on this, where it add spaces with the quantity of keys that you pressed.
Thanks for reading, have a nice day.
|
3e0e7b80cce0aa21a516f900461feb329ac636c2f65a427f35087cefef8cca8c | ['9f737b6b173446f99e05e69cd578815b'] | You can embed your data in the XMP tag within a JPEG (or EXIF or IPTC fields for that matter).
XMP is XML so you have a fair bit of flexibility there to do you own custom stuff.
It's probably not the simplest thing possible but putting your data here will maintain the integrity of the JPEG and require no "post processing".
You data will then show up in other imaging software such as PhotoShop, which may not be ideal.
| ab9337a38e06f4aed7e66f5d1f7ed07700b1501490a6f7ad503d2dc53221b0f5 | ['9f737b6b173446f99e05e69cd578815b'] | If you know the taxonomy name the plugin uses, you should be able to use the_terms pretty easily. You could basically plop this in between <?php foreach( $images as $image ): ?> and <?php endforeach; ?> where you want the terms to be displayed:
<?php the_terms($image->ID, 'YOUR_TAXONOMY_NAME'); ?>
If you want to get fancy, you could use get_the_terms which offers you a bit more control over how things are displayed.
|
3cd1c1281bc0aafee27b92c36607baa50bb31219870976f84d8f60550ca20694 | ['9f7d94d9a4f644979557e0062c6defdf'] | The best way to do this is to supply the ViewController to the view as a delegate, conforming to a protocol you create for it.
For instance, if you UIView is used to pick an image, then the delegate should have a method akin to:
(void)view:(UIView*)view choseImage:(UIImage*)image;
| 5749634f9f589d475c58492964821c1d8da2de9aa57a6668b102bb971d1621d1 | ['9f7d94d9a4f644979557e0062c6defdf'] | Assuming you want to catch the exception inside of MyBuffer<IP_ADDRESS>xsputn or inside of MyBuffer<IP_ADDRESS>_Xsgetn_s, you could wrap the code inside of the method in a try-catch block.
In my own custom LogFile class I inherit from std<IP_ADDRESS>streambuf, and redirect where the ostream goes, using cout.rdbuff(...). You must return the pointer to the default streambuff after your class is done with it, though. I've included a stripped down version of the class below:
class Logger : public std<IP_ADDRESS>streambuf
{
public:
std<IP_ADDRESS>streamsize xsputn (const char* s, std<IP_ADDRESS>streamsize n)
{
/* Your Code Here */
}
template <typename T>
friend Logger& operator<<(Logger& logger, const T& v);
Logger()
{
m_pPrevStreamBuffer = cout.rdbuf(this);
}
virtual ~Logger();
{
cout.rdbuf(m_pPrevStreamBuffer);
}
private:
std<IP_ADDRESS>streambuf* m_pPrevStreamBuffer;
String m_CurrentLine;
};
|
d7ce1ac57c42be31716172ced8281508243d1c4a49c8bd927bd9f15fa6fcbf06 | ['9f7ea843fe594bb39a8768549651a460'] | Thank you! I thought this would do the trick when I first read the description...but I cannot figure out how to compress a folder back into a CAB. My intention was to extract the corrupt CAB, replace the file that I suspect is causing the install to hang and then repackage - I don't think I can repackage a folder of files with this utility. | 2622660c2447df7fa64bd478036abf935dda70311c272c5f985393d9fc8ae54b | ['9f7ea843fe594bb39a8768549651a460'] | I’m trying to learn how to play the Pokémon tcg and can’t find an answer that makes sense online. My opponent used Cinccino’s Fluffy Tail attack, which does 30 damage, and also puts the defending Pokémon asleep.
Without a slew of cards that can wake up my defending Pokémon, I don’t understand how to defend against this kind of attack. They can just keep wicking 30 hp off my Pokémon, and I can’t attack back, turn after turn. It’s both frustrating and boring, as far as I understand the rules.
Is there any defense against this that doesn’t require me to have a very particular helper card handy?
|
f106172e7d4dd0952f37f6855088c21e2172b4296414ce420f8d3a545f141b6b | ['9fbc5385e665443cae50db0f2d1cecec'] | You can share the Spreadsheet directly with another user (needs to have edit permissions), that will give them access to the script (macros are stored as scripts). So a user with access to that same Sheet will have access to the macro you made.
If you want to only share the macros (in a way that can be reused in several separate Spreadsheets), you can build it into a library. To do this, you can take a look at this post which explains how to do just this.
| a6e147277d4cc2075f7a1f2ed598344487f04efead7798b1d4ccf11d790c5dbe | ['9fbc5385e665443cae50db0f2d1cecec'] | There does not seem to be a way to directly state that you want to set the response to "other". However, you can do it manually, and it shows how the pre-filled URL is crafted. I wrote some code (below) that will grab a list of items in a sheet (range B2:B4) which are supposed to be the responses to be pre-filled in "other.
The URLs will be logged, but you can use them how you please. Also, please keep in mind that this is only for the "other" question, the list where you get your data will pre-fill "other" regardless of what it says.
Try the following code:
function myFunction() {
var ss = SpreadsheetApp.getActive();
var formUrl = ss.getFormUrl(); // Use a form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
var formItem = items[0].asMultipleChoiceItem(); // The question
var id = formItem.getId().toString()
var otherResponse = ss.getRange("B2:B4").getValues();
for (var i = 0; i < otherResponse.length; i++){
var string = "__other_option__&entry." + id + ".other_option_response=" + otherResponse[i];
var other = formItem.createResponse(string);
var respWithOther = decodeURIComponent(form.createResponse().withItemResponse(other).toPrefilledUrl());
var firstId = respWithOther.substring(117, 127);
var finalUrl = respWithOther.substring(0, 151) + firstId + respWithOther.substring(161, respWithOther.length);
Logger.log(finalUrl);
}
}
|
c8ca166eebcc25029f1e9606b65e7a3bf5456c56ef615b35c06b5e2dfa66593e | ['9fe03da1e0284dbdac841cace10c8977'] | I am using Java with framework Spring and Liferay.
With liferay I know how to get a locale (object where there are some information: language, country...) but now I am in a java class without conection with liferay and I don't know how to get a locale object to get the language.
For example, I have the next method in a test class of my web page:
private void checkEnglishText(String contentXml) {
CarContentGenerator esCarGeneratorObject = new CarContentGenerator();
HashMap<String, CarContentVo> hm = esCarGeneratorObject.getCar(contentXml);
CarContentVo ccvo = hm.get("EPPA0418");
Assert.assertEquals(ccvo.getCarCodes(), "empress");
}
here I am calling to CarContentGenerator constructor, this constructor is it:
public CarContentGenerator() {
link = new LinkVo();
links = new ArrayList<LinkVo>();
itinerary = new ArrayList<LinkVo>();
lpackageId = new ArrayList<String>();
contentVo = new ContentVo();
mapCar = new HashMap<String, CarContentVo>();
this.locale = "en_US";
}
as you can see, I am giving the value "en_US" to the variable locale. "en_US" means that my page
will be showed in English and if I write "es_ES" it will be showed in Spanish, so.. my dought
is.. Do anyone know how to find out the language (in my case "en_US" or "es_EN") in which is my
web page? (get it from request or something)
| 91198ac2b598bfd72b10a84793eaf4574bc30806de55b627912279d702348579 | ['9fe03da1e0284dbdac841cace10c8977'] | Environment: Liferay 6.1
In my liferay-portlet.xml I have this cron job:
<scheduler-entry>
<scheduler-event-listener-class>com.shorex.b2b.web.billing.IndexJob</scheduler-event-listener-class>
<trigger>
<cron>
<cron-trigger-value>0 0 6 1/1 * ? *</cron-trigger-value>
</cron>
</trigger>
</scheduler-entry>
This expresion "0 0 6 1/1 * ? *" means that there is a process which will be execute once every day at 6:00:00.
The problem is that this process is been executed since 6:00:00 every 10 seconds. that is, at 6:00:00, 6:00:10, 6:00:20, 6:00:30...
Could anyone tell me why is it happening?
|
6144ab5d937d16ca7aef2f878e74300761ef3adce9c3ae8906f840a4f98624fe | ['9ff964bb5be5442ca83fe9ed6cf4fde8'] | Добрый день!
Мне необходимо реализовать сервис event broadcasting между бэкэндом и фронтендом. Соответственно, необходима библиотека с этим функционалом. Поддерживающиеся из коробки Pusher и Redis не устраивают по ряду причин. Подскажите, существуют ли альтернативы и если да, то можно, пожалуйста, ссылку на Github этих библиотек. Самое важное, чтобы можно было отловить с помощью Laravel Echo. Сложность значения не имеет.
Заранее благодарю.
| d74019378a02ca7858b0c000f1ad585c603d185371a9a7225fa8012a033850cf | ['9ff964bb5be5442ca83fe9ed6cf4fde8'] | You're putting on a lot of answers that they don't answer your question it might help if you said why they don't answer the question. Its worth noting that the monitor is not required by law to display what the software asks it to. It could for example change every third pixel to green, or invert them. So the reason that the monitor can "fuzzify" images is because enough customers wanted it, it could just as easily stretch the image but no-one wanted that, so they don't. So there are only 2 types of answer: how is this technically done, or why do people want this? |
d07abad0c324c4d8d3c11fc67105308d9474d3d6ce8e8c3b58c88dc4d5ebddcf | ['9ffe22ba80b8475d8d09b6c64fdde3cf'] | FaceBook's SDK doesn't allow that.. they've implemented the oauth login method so that the user don't need to give username and password to the application, user directly input the credentials in the web view and get authenticated via the fb servers. But in response app receives an access token which it can save and and use for future transactions and user don't need to enter his username or password again. This tutorial might be helpful in this regard:
http://www.raywenderlich.com/1488/how-to-use-facebooks-new-graph-api-from-your-iphone-app
Delegate methods are available in the SDK in which you can save the access token.
| 3577e1e5d83ecaca81ff5941f26233ff1f0135d44077f9ee5393c0d10298c358 | ['9ffe22ba80b8475d8d09b6c64fdde3cf'] | I wish to create multiple instances of UIView so i figured instead of creating new variables i'd allocate one UIView and then reallocate it again to create another UIView. Is this ok? Plus am I releasing the view properly or is the retain count of tempview is 2 after 2 allocations and a release just brings the retain count to 1?
NSMutableArray *array = [[NSMutableArray alloc] init];
UIView *tempview = [[UIView alloc] initWithFrame:CGRectMake(15, 30, 320, 460)];
[array addObject:tempView];
tempview = [[UIView alloc] initWithFrame:CGRectMake(15, 30, 320, 460)];
[array addObject:tempView];
[tempview release];
[array release];
|
4e01594686beda0ae91bee22d28a8e08d0621239b71cdb581f1e1b01af68fe93 | ['9fffa1d93e8c4b7283c6384a509ba1e6'] | I want to test a read from file and a write to file functions. My problem is that the functions don;t have any parameters. Until now i've tested this kind of fucntions only with the file as parameter. I've looked through other questins and found these: How to unit test a method that reads a given file, How to test write to file in Java? but they didn't really help me. The code i want ot test is:
public void loadData()
{
try(BufferedReader br=new BufferedReader(new FileReader(super.fileName))){
String line;
while((line=br.readLine())!=null){
String[] atributes=line.split(";");
if(atributes.length!=4)
throw new Exception("Linia nu este valida!");
Student t=new Student(atributes[0],atributes[1],atributes[2],atributes[3]);
super.save(t);
}
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void writeToFile() {
try (BufferedWriter br = new BufferedWriter(new FileWriter(super.fileName))){
super.entities.forEach(x -> {
try {
br.write(x.studentFileLine());
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Can anybody give me a hint about how to test this without the file parameter?
| cec8c09ced1506883b697791cd98bcd55d5657e57847f83110206feb9bf5900b | ['9fffa1d93e8c4b7283c6384a509ba1e6'] | I have a final exam in databases and as I was solving some sample questions I came across some problems.
I have a many to many relationship between 2 tables.
Player PlayerTournament Tournament
------- -------------------- -------------------
pk id_player fk id_player pk id_tournament
name fk id_tournament name
rank year city
country victories court_surface
tournament_type
What I have to do is:
1). List the players (name and country) who, in 2016, won at least one match in a clay tournament, but didn’t participate in any grass tournament.
2). List the players (name, country, total number of victories) with the greatest number of victories.
I was thinking of something like this:
1. SELECT P.NAME, P.COUNTRY
FROM Player P INNER JOIN PlayerTournament PT
ON P.ID_PLAYER= PT.ID_PLAYER
INNER JOIN Tournament T
ON T.ID_TOURNAMENT= PT.ID_TOURNAMENT
WHERE T.COURT_SURFACE="clay"
GROUP BY (something)
HAVING SUM(PT.VICTORIES)>=1
INTERSECT
(same select and inner joins)
WHERE T.COURT_SURFACE="grass"
GROUP BY (something)
HAVING COUNT(ID_PLAYER)=0
2.SELECT P.NAME, P.COUNTRY, SUM(PT.VICTORIES)
FROM Player P INNER JOIN PlayerTournament PT
ON P.ID_PLAYER= PT.ID_PLAYER
GROUP BY ...
HAVING sum of victories = max sum of victories
I don't know if the way i thought the problem is correct, I need help with the "having" statements.
|
1596b27b3c69d81fbfa0e2269edb320071ad3ea3bcde1422cd33306184de03eb | ['a008f3f173c74dd592328f10d51b640c'] | This is related to an earlier question I had asked about what sort of middleware one can use for developing a client/server app.
Among the options suggested, I was intrigued by zeroMQ and its capabilities.
Since morning, I have been researching on using zeroMQ for my application. However, since my client is a Adobe AIR/FLEX, I see a steep curve in using zeroMQ since there are no bindings available for actionscript.
Google search shows a popular client called STOMP that can be used for messaging in flex based applications but there doesn't seem to be any STOMP adapter for zeroMQ either.
This leaves me with other alternatives such as RabbitMQ or ActiveMQ (since they both seem to have STOMP adapters) as possible middleware choices.
How hard/easy it is to develop to stomp adapter for zeroMQ? I hardly found any documentation on writing an adapter. Or is it worth writing an adapter for zeroMQ than focus on, say, using RabbitMQ that supports STOMP.
Finally, what are other popular alternatives to STOMP for Flex on the client side and leverage zeroMQ on the middleware part.
Thanks
Dece
| 2602ec034ac70b2bfb611c3b7c7e14e3d8dd0b99dd5b94bfff7c3f2907720fc0 | ['a008f3f173c74dd592328f10d51b640c'] | I am developing a client/server application for which I am evaluating a few options for the communications layer.
As part of this communication framework, I am contemplating using google's protocol buffer (PB) for representation of the transport data instead of re-inventing my own binary structure.
Now coming on to the actual transport, I am wondering if one should use plain sockets to send/receive these binary messages or use some form of middleware. Using a middleware has certain obvious advantages over sockets. A few that I care about include: communication models - publish/subscribe, request/response and fail over.
On the other hand, using sockets has the advantage of low overhead compared to the middleware approach and will deliver better performance.
One can also think of using the RPC libraries available with protocol buffers (third party add-ons on google's protocol buffer wiki) to communicate between the client and the server. Though it abstracts from the low level socket, it still does not support the middleware features.
At the moment, my client is an Adobe Flex GUI and two server side processes (One java and another C++). In the future, the client and server side can potentially have other services developed in other languages as well such as .NET
What do the experts feel about these choices and from experience what works well without compromising on performance. Are there other alternatives that developers go with?
Thanks
Dece
|
d972834fda30428e398c2b923dc7977c8d2531f0f33793759dbbb305eabfdf68 | ['a0252daa9eca438296b03ecbab0f9da0'] | Found out that this behavior is by design. OpenLDAP has a global setting that controls the minimum length for a substring index. The default minimum number of characters that get indexed in a substring index is 2.
If you use online configuration (OLC), you will find the description of the setting in man slapd-config:
olcIndexSubstrIfMinlen: <integer>
Specify the minimum length for subinitial and subfinal indices. An attribute value must have at least this many characters in order to be processed by the indexing functions. The default is 2.
Or, if you use the traditional configuration method, you will find its description in man slapd.conf:
index_substr_if_minlen: <integer>
Specify the minimum length for subinitial and subfinal indices. An attribute value must have at least this many characters in order to be processed by the indexing functions. The default is 2.
The man pages additionally say:
Options described in this section apply to all backends, unless specifically overridden in a backend definition.
Does anyone know if this behavior can be overridden at the attribute level? It would be great if substring min and max lengths can be specified at a more granular level than global or per backend.
| 9fde6b49389f1b8a824f9e502a047eb58a26422f2a14c6e2e517f0ad161edd97 | ['a0252daa9eca438296b03ecbab0f9da0'] | I assume you are using the least square method (in linear regression) to find the best fitting straight line through a set of points representing the given training data.
You might define s as being the error associated to $y=a_0 +a_1x$ by:
$$s = \sum_{i=1}^n( y_i - (a_0 +a_1x_i))^2$$
You goal is to find $a_0$ and $a_1$ that minimize your error. In multivariate calculus, this requires to find the values of $a_0$ and $a_1$ such that:
$\frac{\partial s}{\partial a_0} =0$ and $\frac{\partial s}{\partial a_1} =0$
Differentiating $s(a_0,a_1)$ gives:
$$\frac{\partial s}{\partial a_0} = -2\sum_{i=1}^n( y_i - (a_0 +a_1x_i))$$
and,
$$\frac{\partial s}{\partial a_1} = 2\sum_{i=1}^n x_i( y_i - (a_0 +a_1x_i))$$
Setting $\frac{\partial s}{\partial a_0}=0$ and $\frac{\partial s}{\partial a_1}=0$ leads to:
$$\sum_{i=1}^n( y_i - (a_0 +a_1x_i))$$
and,
$$\sum_{i=1}^n x_i( y_i - (a_0 +a_1x_i))=0$$
By separating each term, you might rewrite your equations as follows:
$$(\sum_{i=1}^n x_i^2)a_1 + (\sum_{i=1}^n x_i)a_0 = \sum_{i=1}^n x_iy_i$$
and,
$$(\sum_{i=1}^n x_i)a_1 + (\sum_{i=1}^n 1)a_0 = \sum_{i=1}^n y_i$$
You have obtained your values of $a_0$ and $a_1$ that minimize the error and satisfy a linear equation which you can rewrite as the following matrix equation:
$$\begin{pmatrix}\sum_{i=1}^n x_i^2 & \sum_{i=1}^n x_i\\ \sum_{i=1}^n x_i & \sum_{i=1}^n 1 \\\end{pmatrix} \begin{pmatrix}a_1 \\ a_0 \\\end{pmatrix} = \begin{pmatrix}\sum_{i=1}^n x_iy_i \\ \sum_{i=1}^n y_i \\\end{pmatrix}$$
Let's denote the $2x2$ matrix M. You can show later that M is invertible as long as all the $x_i$ are not equal ( $det(M)\neq0$ ).
$$det(M) = (\sum_{i=1}^n x_i^2)(\sum_{i=1}^n 1) - (\sum_{i=1}^n x_i)(\sum_{i=1}^n x_i) = n(\sum_{i=1}^n x_i^2) - (\sum_{i=1}^n x_i)^2$$
thus,
$$\begin{pmatrix}a_1 \\ a_0 \\\end{pmatrix} = inv(\begin{pmatrix}\sum_{i=1}^n x_i^2 & \sum_{i=1}^n x_i\\ \sum_{i=1}^n x_i & \sum_{i=1}^n 1 \\\end{pmatrix})\begin{pmatrix}\sum_{i=1}^n x_iy_i \\ \sum_{i=1}^n y_i \\\end{pmatrix}$$
and,
$$inv(\begin{pmatrix}\sum_{i=1}^n x_i^2 & \sum_{i=1}^n x_i\\ \sum_{i=1}^n x_i & \sum_{i=1}^n 1 \\\end{pmatrix})=\frac{1}{det(M)}adj(M)$$
where,
$$adj(M)=\begin{pmatrix} \sum_{i=1}^n 1 & -\sum_{i=1}^n x_i\\ -\sum_{i=1}^n x_i & \sum_{i=1}^n x_i^2 \\\end{pmatrix}$$
refer to: https://en.wikipedia.org/wiki/Adjugate_matrix
Finally, your values of $a_0$ and $a_1$ are:
$$a_o = \frac{\sum_{i=1}^n x_i^2 \sum_{i=1}^n y_i - \sum_{i=1}^n x_i y_i \sum_{i=1}^n x_i}{n \sum_{i=1}^n x_i^2 - (\sum_{i=1}^n x_i)^2}$$
and,
$$a_1 = \frac{n \sum_{i=1}^n x_i y_i - \sum_{i=1}^n x_i \sum_{i=1}^n y_i}{n \sum_{i=1}^n x_i^2 - (\sum_{i=1}^n x_i)^2}$$
I hope this helps.
Cheers!
|
602aa31f34520b50b8dcf14a8b3f37fc58b5f8593ca40383eeacb629f15e18d4 | ['a0292c49b2914789ba829869e2e40b47'] | private void Enable(TextBox temp, String system)
{
if (File.Exists(temp.Text))
{
Properties.Settings.Default.system = temp.Text;
}
else
do something here;
}
Basically I'm trying to take a text box with some file path, check if it exists, if exists set the value of the Properties.Settings.Default.system to temp.text.
However I don't know how to use a variable name to reference the existing settings property.
Fairly new to this so any help is appreciated.
Thanks!
| 4eb9f60416e6c4772518ab5789c44cc9cb91283221bbc50948bcd7d6d8aba511 | ['a0292c49b2914789ba829869e2e40b47'] | Thanks to <PERSON> for getting me started and getting me thinking about this correctly. Ended up scripting it out manually without using RoboCopy or Xcopy as I could not get them to work exactly how I wanted to.
$target = "C:\\TestTemp"
foreach($item in (Get-ChildItem "C:\\OriginalDir\\This" -Recurse)){
if ($item.PSIsContainer -and ($item.Name -eq "obj" -or $item.Name -eq "bin")){
$tempPath = $target
$path = $item.FullName
$trimmed = $path.TrimStart("C:\\OriginalDir")
$pieces = $trimmed.Split("\\");
foreach($piece in $pieces){
$tempPath = "$tempPath\$piece"
New-Item -ItemType Directory -Force -Path "$tempPath"
if($piece -eq "Test" -or $piece -eq "Temp"){
Copy-Item -path $path\** -Destination $tempPath -Recurse -force
}
}
}
}
|
ca7a8dd6b97eda774d8dba312c68cffdd00d2291b9e1b86c5da8cd063c00810b | ['a038bdfef61542acbd411af615abd2e6'] | You must check application pool identity settings. Make sure your web application's appPool Identity is set ApplicationPoolIdentity and Managed Pipeline Mode should be Integrated.
Then check your web config system.webserver modules and enable this configuration on your application web config.
<system.webServer><modules runAllManagedModulesForAllRequests="true"> </modules></system.webServer>
| 1f58b4ee235c81f088d77dfca4043a9524cc692599179e4a10a7d5c73a022e33 | ['a038bdfef61542acbd411af615abd2e6'] | You can use jquery class selector instead of Id. if you give all transactionLines the same class name, you can access hover event for all transactionLines divs.
So you dont need foreach by this way.
transactionLine1
transactionLine2
...
<?php
echo "$('.yourClassNameHere').hover(
function() { $(this).css('background-color', 'yellow'); },
function() { $(this).css('background-color', 'transparent'); });";
echo "$('.yourClassNameHere').focusin(function()
{ $(this).css('background-color', 'red'); });";
echo "$('.yourClassNameHere').focusout(function()
{ $(this).css('background-color', 'transparent'); });";
?>
|
f6e80fd611f342b8fe2fe4824d92271745ffca2a66c7b603c4814ecab716eaae | ['a0472c14d16a43e9825b7e951eb36031'] | I just spent some time figuring out this issue as well and here is the solution that I found is most clean and uses Magento's XML-style abstractions to add the image column to the catalog_product_flat_1 table:
In config.xml:
<config>
<frontend>
<product>
<collection>
<attributes>
<image />
</attributes>
</collection>
</product>
</frontend>
</config>
Then reindex your flat catalog tables (Admin > Index Management > Select All + Reindex) and clear all Magento caches.
| cd7acfbf51f51867144afaefdb6422039feb0062a2c1536bc554e9d244eb02bf | ['a0472c14d16a43e9825b7e951eb36031'] | Try adding complete and error methods to the ajax call. This will help determine whether you are actually receiving a response.
For example:
$.ajax({
url:"<?php echo $this->getUrl('product.phtml') ?>",
dataType:'jsonp',
type:'post',
data:data,
success:function (jqXHR, textStatus) {
alert(textStatus);
},
error: function (jqXHR, textStatus) {
alert(textStatus);
},
complete: function (jqXHR, textStatus) {
alert(textStatus);
},
});
This may help you debug the problem better than a try catch statement.
|
d40a72109df70125af4c2eaaa11dac02872613f5e562f197b80db7874296fc3a | ['a04bfc033e3846f1aa9cb2ce6a33d180'] | Its just the cache problem.
Just follow these instructions:-
Press Ctrl+a then Ctrl+C then delete your all code of file and save the file.
Now just refresh your page.
After refresh press Ctrl+z and save the file
Now again refresh the page and see the results.
It Works...
| 3577a682354a23b6c47681919f488fdc0e3c992b39caa4f473b2bfc275897044 | ['a04bfc033e3846f1aa9cb2ce6a33d180'] |
Paste that code in function.php
function show_last_modified_date( $content ) {
$original_time = get_the_time('U');
$modified_time = get_the_modified_time('U');
if ($modified_time >= $original_time + 86400) {
$updated_time = get_the_modified_time('h:i a');
$updated_day = get_the_modified_time('F jS, Y');
$modified_content .= '<p class="last-modified">This post was most recently updated on '. $updated_day . '</p>';
}
$modified_content .= $content;
return $modified_content;
}
add_filter( 'the_content', 'show_last_modified_date' );
|
14fa3fc98c43cd9e8b0e2f376f9b4747ed57b347e617b687332d044e633e219a | ['a067c4d8f43345f19344301844126e6a'] | I'm using Oracle Database with UTF-16 encoding. The diacritics is correctly displayed when using directly cx_oracle client. Connection statement is like this:
cx_Oracle.connect(username, password, conn_str, encoding='UTF-16', nencoding='UTF-16')
However, now I'm building bigger application and I would like to use SQLalchemy in Flask.
Code looks like this:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
db.Model.metadata.reflect(db.engine)
class MyTable(db.Model):
__table__ = db.Model.metadata.tables['mytable']
for row in MyTable.query:
print(row.column_with_diacritics)
Output of the code above: aoe
But the column value in the database is: áóé
So my question is, how can pass arguments encoding='UTF-16', nencoding='UTF-16' to cx_oracle which sqlalchemy uses underhood?
Thank you for any advice or other workaround.
| b7a22567593c262315aaaf38bd82149f86d12e0988ec282071eaf315e01f661b | ['a067c4d8f43345f19344301844126e6a'] | it's a litle bit off-topic question but the answer would really help me.
Does anybody know the release date (year) of the first Pydev version? As far as I was able to find, I got year 2004. Is it correct? (I need it because of my Diploma Thesis)
|
dabeeb5839716df72c9cbdfa715d793ea281db79897c4fc4e7e0091d58c98177 | ['a06fdd592b224c8a9716b44661d514b7'] | document.write("<table>");
document.write("<tr>");
for (var i = 0; i < rs.Fields.Count ; i++)
{
document.write("<th style='color: #009900;'>" + rs.Fields(i).Name + "</th>");
}
document.write("</tr>");
while (!rs.EOF) {
document.write("<tr>");
for (var i = 0; i < rs.Fields.Count; i++)
{
document.write("<td >" + rs.Fields(i) + "</td>");
}
document.write("</tr>");
rs.movenext();
}
document.write("");
| 711966c9bc509e961758b409255349b1c3292c8562e5d96e9c914d1bc565e6f5 | ['a06fdd592b224c8a9716b44661d514b7'] | i have a codeunite i want when i run the codeunite the SoapUrl of my pages which i published as a web service show in a message;
my published objects Object id = 50000 and 50001 i just want to display SoapUrl in message.
below is the code i tried .
Var
WebService : Record Tenant Web Service;
Run()
WebService.FindSet;
IF WebService."Object ID" = 50000 THEN
BEGIN
MESSAGE('name %1', WebService.SoapUrl");
END;
But this code not working for me
|
98f9143d70822ed7a28b42c50b1c025e1091cda4bbae248109ed95682c2d2616 | ['a07d9f79cdfe4f9fb3e70696c575515f'] | My question is stated in the title.
I have a need to specify the content inset for specific rows. Reason for this is that i have to make a layout in which the first cell of the first section needs to occupy whole width of the screen, while first cell of the second section needs to have insets of left: 8, right: 8.
snapshot
Also, with inset set to 0 last cell in the section is positioned completely to the left of the screen. Any suggestions on that?
This is the code for calculating the size:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
collectionViewLayout.invalidateLayout()
if indexPath.section == 0 {
if indexPath.row == 0 {
return CGSize(width: self.view.frame.width, height: 100)
} else if indexPath.row == 1 || indexPath.row == 2 {
return CGSize(width: self.view.frame.width / 2 - 36, height: 50)
} else {
let size = CGSize(width: self.view.frame.width - 16, height: 50)
return size
}
} else {
if indexPath.row == 0 {
return CGSize(width: self.view.frame.width - 16, height: 100)
} else if indexPath.row == 1 || indexPath.row == 2 {
return CGSize(width: self.view.frame.width / 2 - 16, height: 50)
} else {
return CGSize(width: self.view.frame.width - 16, height: 50)
}
}
}
| a24aa03bdab7570393f6206b2621a0730ab521bf043b85f8c8ce2472491707c8 | ['a07d9f79cdfe4f9fb3e70696c575515f'] | I've managed to find the solution to this question by:
manually saving position of a header in:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CategoryNameReusableView", for: indexPath) as! CategoryNameReusableView
cell.nameLbl.text = sectionNames[indexPath.section]
if viewWithPosition.isEmpty { viewWithPosition.append(( name: cell.nameLbl.text!, position: cell.frame.origin.y))}
let x = isElementInArray(array: viewWithPosition, string: cell.nameLbl.text!)
if !x {
viewWithPosition.append((name: cell.nameLbl.text!, position: cell.frame.origin.y))
}
return cell
}
I am using an array of viewWithPosition tuples var viewWithPosition = [(name: String, position: CGFloat)](). It might have been the same if i saved only position of a cell, but since my cells have different text i used name parameter to check if the element already exists in the array. I used helper function:
fileprivate func isElementInArray(array: [ViewAndPosition], string: String) -> Bool {
var bool = false
for views in array {
if views.name == string {
bool = true
return bool
}
}
return bool
}
When i have initial positions i check if visible headers are misplaced:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let visibleHeadersInSection = collectionView.visibleSupplementaryViews(ofKind: UICollectionElementKindSectionHeader) as? [CategoryNameReusableView] {
for header in visibleHeadersInSection{
if let index = viewWithPosition.index(where: { (element) -> Bool in
element.name == header.nameLbl.text
}){
if header.frame.origin.y == viewWithPosition[index].position {
header.backgroundColor = UIColor.clear
} else {
header.backgroundColor = UIColor.white
}
}
}
}
}
At the moment it seems that there are no callbacks provided by Apple for this kind of situation. Hopefully this is also the solution for you.
|
a7db4e44351ceb1a553be4eeffb810a33d2a49d844d552f27c2a852228c0d66d | ['a07eac58277d44d199b10d45823b0eb5'] | I installed mongodb ( windows 32, storageEngine=mmapv1), it was working fine, I already created several DBs, inserted documents and collections. Surprisingly, when I was trying to connect today, it kept saying connect failedand emitting errno:10061I can't understand why. It's probably worth noting that last shutdown was unclean, so I tried Mongod –dbpath data\db --repair but nothing changed. Could you please help ?
| 877494e6144e5097be5d5296794e8b9729e4cc815cac5f4c4a078051cb78e35d | ['a07eac58277d44d199b10d45823b0eb5'] | I'm trying to apply SVM to my classification problem.
I have an issue with SVMClassify.
old_data=vi(5:10,:);
newData=vi(1,:);
svmStruct=svmtrain(old_data,groups(5:10),'Kernel_Function',@KFUN);
newClasses= svmclassify(svmStruvt, newData);
newClasses vector does'nt have same rows as newData matrix. I just can't understand why!
size_newClasses= size(newClasses);
returns size_newClasses= 6 rows and 1 column. Any help please?
|
c08ec0fcc9f273cbf12516966d2bee176071ad2be3918df56ab7905cb78fccfe | ['a08c31b568ae4a17858f98256d9a354b'] | Hello i just started using flux but it's still confusing me.
so i have a component named CoursePage in this i'm rendering courses and authors and they are fetched from the server separately, then i created two stores CourseStore and AuthorStore. The problem is i want my component to subscribe to these stores.
so is there a way a component to subscribe to two or more stores
| 126fdbb4f794b75c38e25deadd6505c5d81d6e8734fae558a104fd630ffa6d74 | ['a08c31b568ae4a17858f98256d9a354b'] | first of all you need to import these function in django.contrib.auth
from django.contrib.auth import authenticate, login
"""
from django.contrib.auth.models import User
don't need this import since authencate will directly
check if the user you trying to authencate exist in the User model
"""
def login(request):
if request.method== 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user is not None:
login(request, user)
return redirect("/")
else:
messages.info(request,'invalid credentials')
return redirect('login')
else:
return render(request,'login.html')
try these and let me know if that help
|
806b44366708176c3eab55def24e3e19eed8845602856010352bf2e4c2d6a697 | ['a096d8c154484ac4be0114c43d1148e6'] | Due to the rollback war between OP and editors (FYI: the edits were beneficial and should have been kept) I have rolled back to the acceptable version with some modifications and **locked this post** for a week to let everyone cool down. No more activity is accepted on this post in the interim until the lock expires. Go cool off, everyone. | 6e5c9f29268fc0ea38e15f483d50186259840009f911bab81ecdc338e4341680 | ['a096d8c154484ac4be0114c43d1148e6'] | @user447607 Then all you can do is wait - I would share the link, here, in a comment though so we can link to the existing bug in this answer, in case people want to status-check the state of this bug. (Note that if this were a Python 3 program, the error wouldn't exist, because `str` is Unicode by default in Python 3, and not a separate `unicode` variable type class.) |
149b962601e26bdf88bd05b450f90b0224f52d3139903572c19336632ed1e8e5 | ['a0a008025fb043d1b6fe32052aee77aa'] | So, I spent some time trying to achieve this and I have found that this setup works so well that I have decided to post it here in case it can help someone.
The integration with PyCharm (pro) works so well that you don't need any linux box or shell or ssh tunnel. PyCharm can see your WSL instance, it will automatically start it, and call your python interpreter when you will run your script.
Here is all the steps I have executed to complete my setup:
Install Debian WSL
Install and Setup a Debian instance from Microsoft Store
Then based on Pynini readme, here is what we need:
GCC > 4.8
Built OpenFST 1.7.3 built with ./configure --enable-grm and headers
A Python version: 2.7 or 3.6+ and headers
Install GCC
sudo apt update && sudo apt -y upgrade
sudo apt install build-essential # to install GCC and others build libs and tools
Install OpenFST
We need to install wget to be able to download openfst and pynini.
sudo apt install wget
cd /usr/local/src
sudo wget http://www.openfst.org/twiki/pub/FST/FstDownload/openfst-1.7.3.tar.gz
sudo tar -xvf openfst-1.7.3.tar.gz && sudo chown -R root:root openfst-1.7.3
cd openfst-1.7.3 && sudo ./configure --enable-grm
sudo make && sudo make install
Install Pynini
First we need to install Python
sudo apt install python3 python3-dev python3-pip python3-venv
Then download and build Pynini; sorry but I am addicted to virtual environments:
python3 -m venv ~/venv373; . ~/venv373/bin/activate;
cd /usr/local/src
sudo wget http://www.opengrm.org/twiki/pub/GRM/PyniniDownload/pynini-2.0.8.tar.gz
sudo tar -xvf pynini-2.0.8.tar.gz && sudo chown -R 1000:1000 pynini-2.0.8
cd /usr/local/src/pynini-2.0.8
sudo env PATH='$PATH'; python setup.py install;
And that's it, Pynini should be installed.
PyCharm integration
Please note that this integration with WSL is only available on PyCharm/IntelliJ Professional edition.
Here is the link on how to add you WSL python interpreter in PyCharm: https://www.jetbrains.com/help/pycharm/using-wsl-as-a-remote-interpreter.html
One screenshot from my IntelliJ where you can see the import pynini statement is recognized and auto-completion works as well.
| 5df9af238e57415affc4ce19dbbc8cd5f6cb105c8ca4a33de669f140fae96331 | ['a0a008025fb043d1b6fe32052aee77aa'] | First, a small word on how I have generated the event objects.
To make a reliable integration with the others java applications, I started from the JAXB event java classes used in the solution. I have converted them into schemas using schemagen and then converted the generated schemas into python classes using pyXB.
The result is that I have a module in python with an equivalent to the JAXB classes in the java solution. In the code below, I will assume that my_events is the module generated with pyXB.
import cx_Oracle
import my_events
ORACLE_QUEUE_NAME = "Q_MIG"
JMS_TEXT_MESSAGE_TYPE = "SYS.AQ$_JMS_TEXT_MESSAGE"
JMS_HEADER_TYPE = "SYS.AQ$_JMS_HEADER"
dsn = "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) (HOST=localhost)(PORT=1521))) " \
"(CONNECT_DATA = (SERVER = DEDICATED) (SID = MYSID)))"
with cx_Oracle.connect("MYUSER", "MYPASSWORD", dsn, encoding="UTF-8", nencoding="UTF-8") as con:
event = my_events.my_custom_event()
q = con.queue(ORACLE_QUEUE_NAME, con.gettype(JMS_TEXT_MESSAGE_TYPE))
payload = con.gettype(JMS_TEXT_MESSAGE_TYPE).newobject()
payload.HEADER = con.gettype(JMS_HEADER_TYPE).newobject()
# HEADER.TYPE must have the java class name
# have not checked yet how to get it from the pyxb class
payload.HEADER.TYPE = "MyCustomEvent"
payload.TEXT_VC = event.toxml("utf-8")
payload.TEXT_LEN = len(payload.TEXT_VC)
q.enqOne(con.msgproperties(payload=payload))
con.commit()
print("message enqueued.")
# dequeue the messages
print("\nDequeuing messages...")
queue = con.queue(ORACLE_QUEUE_NAME, con.gettype(JMS_TEXT_MESSAGE_TYPE))
queue.deqOptions.wait = cx_Oracle.DEQ_NO_WAIT
while True:
message = queue.deqOne()
if not message:
break
print(message.payload.TEXT_VC)
event = my_events.CreateFromDocument(message.payload.TEXT_VC)
con.commit()
print("\nDone.")
The CreateFromDocument is a utility method generated by pyXB to create new objects from serialized representations.
|
b5454bcd3b7ccaf9293b6670ed47995eccf1c0dba1d94a2255afab966e9682cf | ['a0a05c5056a242e4933c95e5e9125dad'] | I need to delete a folder from a blob container in Azure storage account. The folder structure is as follows:
container -> failed -> profiles
I am connecting to the container as follows:
CloudBlobClient blobClient = StorageAccountManager.getStorageAccount(ConnectionString));
var container = blobClient.GetContainerReference(container_name);
I am trying to refer to the specific folder as follows:
var blob = container.GetBlockBlobReference(failed + "/" + directory);
I also tried the follows ways:
((CloudBlob)blob).DeleteIfExists();
blob.DeleteIfExists();
blob.DeleteAsync();
but none of these are deleting the folder in my blob storage. Am I missing something or am I doing something wrong?
| e498c378e5178e66d29daf7b560ea3600baf2afa68baa12e2464be4dd16b970f | ['a0a05c5056a242e4933c95e5e9125dad'] | I am trying to gather all the possibilities through which I can import the data occasionally to OMS in Azure from Azure SQL database and Azure App Insights.
The only possibility that I could find is using the SQL Server connector for importing data from SQL server to OMS and using Application Insights connector for importing the data from App Insights to the OMS.
Please let me know if there are any other approaches available to achieve this.
|
5e26870e49b2f1eb2b67586bdac19c35f57c0dfce6d68f1e2653c41321768b44 | ['a0acfd45948a44fda485ce230bf15eea'] | I've a big calendar table to provide a overview of a planning.
I want to always scroll automatically on windowload to "this day", which col has the class .today.
I've already tried to work with JQuery scrollTo, scrollLeft and animate, but nothing works.
The table always start automatically 3 months before. (Now in July, it starts with April)
Here's a quick view of the table.
The "today col" is for example specified like this:
<col id='2018y7-31' class='today'> </col>
Does anyone know a solution to scroll onload to the/a specific day?
| 86e3f8eb736e999542bf5ef74bc46d148989591922e0fd17f31f94efa37976c5 | ['a0acfd45948a44fda485ce230bf15eea'] | I'm using node.js and pdf2json parser to parse a pdf file.
Currently it is working with a local pdf file.
But I'm trying to get a pdf-file through the URL/HTTP Module of node.js and I want to open this file to parse it.
Is there any possibility to parse/work with an online pdf?
let query = url.parse(req.url, true).query;
let pdfLink = query.pdf;
...
pdfParser.loadPDF(pdfLink + "");
So the url should be given through the url like: https://localhost:8080/?pdf=http://whale-cms.de/pdf.pdf
Is there any way to parse it within the online pdf/link?
Thanks in advance.
|
245d81214e8059f2e3f108c31428733eaa60020e5ea9444b23ed85d3e72790dc | ['a0b6b74c15b54a11b44617a470c35877'] | I am trying to extract some information from this site using beautifulsoup. I am familiar with extracting tags by class/attributes, but how can I extract the url from "tr data-url"?
import requests
import re
from bs4 import BeautifulSoup
url = "https://www.amcham.org.sg/events-list/?item%5Bdate_start%5D=07%2F05%2F2019&item%5Bdate_end%5D=09/17/2019#page-1"
webpage_response = requests.get(url)
webpage = webpage_response.content
soup = BeautifulSoup(webpage, "html.parser")
table = soup.find_all("tbody")
for i in table:
rows = i.find_all("tr")
for row in rows:
print(row)
<tr data-url="https://www.amcham.org.sg/event/8914">
<td class="date">July 09, 2019</td>
| d23d11ae4b990eda9e5fa64c4f586a6e34d1cf769e34fb9c7cffbbd8010c7965 | ['a0b6b74c15b54a11b44617a470c35877'] | How can I extract Commission I, Legislation Committee, Ad-Hoc Committee from tr?
<tr>
<td class="text-center">1</td>
<td class="hidden-xs"><a href="/en/anggota/detail/id/1319"><img class="img-responsive" src="/doksigota/photo/1319.jpg"/></a></td>
<td><a href="/en/anggota/detail/id/1319">PROF. DR. <PERSON>, MA</a><br/>National Democrat Party Faction<br/>ACEH I</td>
<td>Commission I<br/>Legislation Committee<br/>Ad-Hoc Committee</td> </tr
webpage_response = requests.get('http://www.dpr.go.id/en/anggota')
webpage = webpage_response.content
soup = BeautifulSoup(webpage, "html.parser")
tbody = soup.find("tbody")
for i in tbody:
print(i)
|
21940538458021b418dc096558bcab5fe6ae2685f638b93609d6f7cbff8cc940 | ['a0be02fc62ac41ae92b98aab97589cf9'] | We had the same issue with our project because we compress the response and remove comments. One workaround in order to avoid using a <div> or <span> for your foreach is to define your own <ko> element. If you do this, you will need to include the following script for IE8 and lower support:
<!--[if lt IE 9]>
<script>
document.createElement("ko");
</script>
<![endif]-->
| dbf2cba520d3b073ebaf1dd78671b36c241882bc8d110fad67c0b076ef557f35 | ['a0be02fc62ac41ae92b98aab97589cf9'] | I'm designing my 403 page and I can't seem to obtain the 'reason' string which I am populating on various forbidden pages to give a more relative response to the issue at hand. If I type ${response.reason} in the template, the whole page gets replaced with just the text of the response.
|
177a8470f5b9cf29c87cc2e3215a1b62512d2101c40e3a541dda1f3c1e945b6c | ['a0eec2477bb2423388d8314617244cba'] | I fixed this problem by restarting explorer.exe.
I think the issue I ran into was that I edited %PATH%, but explorer was using a stale version of it.
This will also happen if you already have a command window open when you edit an environment variable: the changes don't reflect in the window that is already open, only in new windows that are created.
| 61fe265c8d48735d97dbb3f98fe7282dec8307c5a4f9f96af4cfb6f894ae6e08 | ['a0eec2477bb2423388d8314617244cba'] | Пишу тесты для компоненты которая использует CKEditor.
TestBed.configureTestingModule({
imports: [FormsModule],
schemas: [NO_ERRORS_SCHEMA],
declarations: [DocumentEditComponent],
providers: [{provide: AppConfig, useValue: appConfig},
{provide: DocumentsService, useValue: documentsService},
{provide: NgbModal, useValue: modalService},
{provide: ActivatedRoute, useValue: activatedRoute},
{provide: BaThemeSpinner, useValue: loader},
{provide: PopupResultService, useValue: popupResultService},
],
})
fixture = TestBed.createComponent(DocumentEditComponent);
component = fixture.componentInstance;
При запуске теста вот такая ошибка. Есть идеи как имитирвоать его работу?
|
52e72a413261f69d3b443df8cfadcd1672d9aef0e2da96d91366136020cf11e6 | ['a0f6bd70ecc84c0c97f8be0ce6d6829d'] | I have a Linux server application that is using Kerberos for client authentication and client that needs to run on Windows. Kerberos tickets are issued by Windows Active Directory. Client authenticates successfully on server if I use MIT KfW 3.2.2. API for retrieving AS and TGS tickets from Kerberos server and store them in kerberos credentials store. But the problem with this approach is that user needs to input his credentials again.
The solution would be to access MS LSA store but this does not work. Neither does ms2mit.exe application. It does not matter if I run it as normal user or as administrator, or if I disable UAC completely.
This is why I would like to use SSPI on client to make the KRB_AP_REQ message which I would send to server. Is that possible. If yes how can it be done? IF no, what are my other options? Please note that server is already built and it would require significant effort to change it, therefore I would like to find a solution on windows.
| d3672e0c3edfa69cc4bc662090fb83dd41ac3e5a8163daaf514064b3a5e1f94e | ['a0f6bd70ecc84c0c97f8be0ce6d6829d'] | In c++ I am trying to build a portable server running on Linux and Windows and client running in Windows that will use MS Active Directory for authentication. After some research I decided that best way to go is use Kerberos. I decided to use MIT Kerberos v5 library due to BSD style licence.
But my problem is that I am completely unable to find good resource on working in Kerberos in C++. All examples that I found are just simple code snippets that fail to explain in enough details what input parameters to functions are and reference manuals (doxygen style) that briefly explains the function in question but does not provide enough information to understand the context where to use it.
In short, can you recommend good resource for C++ programmer that two weeks ago did not even know what Kerberos is?
|
de8d141a58d99ff8e0a610680578cc04b6a116fa579aa8281643124e03fcbd15 | ['a0ff40ad34284b05a5e4dca40bea1f6a'] | We were giving a this program in class and asked to try it our at home but it doesn't work, I'm guessing there is something wrong with the algorithm. Can someone help me out?
import java.awt.Graphics;
import javax.swing.JApplet;
public class rotationalTransformation extends JApplet {
int[] x=new int[3];
int[] y=new int[3];
int[][] tMatrix=new int[3][3];
int no_pts=3;
public void start()
{
x[0]= 10;
x[1]= 20;
x[2]= 30 ;
y[0]= 10;
y[1]= 30;
y[2]= 10 ;
}
public void paint(Graphics g)
{
try {
System.out.println("Before Rotation");
g.drawPolygon(x, y, no_pts);
matrixIdentity(tMatrix);
System.out.println("Identity Matrix Created");
rotation(60,10,10);
System.out.println("Rotating");
for(int a=0; a<3;a++)
{
for(int c=0; c<3;c++)
{
System.out.print(tMatrix[a][c] + " ");
}
System.out.println();
}
for(int a=0; a<3;a++)
{
System.out.println(x[a] + " " + y[a]);
}
transformPoints();
System.out.println("After Rotation");
g.drawPolygon(x, y, no_pts);
}
catch(Exception e){}
}
void matrixIdentity(int[][] m)
{int i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{ if(i==j)
{
m[i][j]=1;
}
else
m[i][j]=0;
}
}
void transformPoints()
{
int tmp;
for(int a=0; a<3;a++)
{
tmp=tMatrix[0][0]*x[a]+ tMatrix[0][1]*y[a]+tMatrix[0][2];
y[a]=tMatrix[1][0]*x[a]+tMatrix[1][1]*y[a]+tMatrix[1][2];
x[a]=tmp;
}
}
void rotation(double degree,int rx,int ry)
{ int a;
a = (int) (degree * 3.14/180);
tMatrix[0][0]= (int) Math.cos(a) ;
tMatrix[0][1]= (int) -Math.sin(a) ;
tMatrix[0][2]= (int) (rx*(1-Math.cos(a))+ ry*Math.sin(a));
tMatrix[1][0]= (int) Math.sin(a) ;
tMatrix[1][1]= (int) Math.cos(a);
tMatrix[1][2]= (int) (ry*(1-Math.cos(a))-rx*Math.sin(a));
}
}
It prints the original shape but does not print the rotated shape.
| bb7c0496e924dd41b598736edb8b586bf7c76f1858f31e53ddcccb555f8d13e9 | ['a0ff40ad34284b05a5e4dca40bea1f6a'] | We have been trying to create users in our Cognito User Pool but keep getting a rather weird error. The stack trace looks as follows:
{
"errorMessage": "Not Found",
"errorType": "UnknownError",
"stackTrace": [
"Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/json.js:48:27)",
"Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:105:20)",
"Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:77:10)",
"Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:683:14)",
"Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)",
"AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)",
"/var/task/node_modules/aws-sdk/lib/state_machine.js:26:10",
"Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)",
"Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:685:12)",
"Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:115:18)"
]
}
Here's our code which is executed in Lambda. The Lambda function itself is invoked by API Gateway without proxy integration.
const AWS = require('aws-sdk');
AWS.config.update({
region: "ap-south-1",
endpoint: "https://dynamodb.ap-south-1.amazonaws.com",
});
const docClient = new AWS.DynamoDB.DocumentClient();
const cispClient = new AWS.CognitoIdentityServiceProvider({
region: 'us-east-1'
});
const table = process.env.TABLE_NAME || "User_Info_Test";
exports.newDriverCreated = function (event, context) {
console.log('event: ', event);
// Get username, password
const username = event.username;
const password = event.password;
// Get first and last name
const firstName = event.name;
const lastName = event.family_name;
// Get phone number
const phone = event.phone;
const driverData = {
"TemporaryPassword": password,
"UserAttributes": [
{
"Name": "phone_number",
"Value": phone,
},
{
"Name": "first_name",
"Value": firstName,
},
{
"Name": "family_name",
"Value": lastName,
},
],
"Username": username,
"UserPoolId": 'user-pool-id',
"ValidationData": [
{
"Name": "phone_number",
"Value": phone
}
]
}
cispClient.adminCreateUser(driverData, (err, data) => {
if (err) {
console.error('adminCreateUser error: ', err);
context.done(err);
} else {
console.log('adminCreateUser data: ', data);
context.done(null, data);
}
});
}
The error occurs when we call the adminCreateUser() function. We have absolutely no clue what could be going wrong as we are really new to AWS as a whole.
Any help would be greatly appreciated.
Thanks.
|
fafe10589dad288fec7324c08d2f0a647eba8f1d08574128968ca8b65829104b | ['a100ac15c27b4ed5b0fe9404ee24fc4e'] | I am using Silverlight 4 and have a datagrid that allows users to sort the rows. On the sort column event the SelectionChanged event gets fired and the initial first row in the datagrid is selected. Is there anyway to not have the SelectionChanged event fired or is there away to have an onSort event to set the selectedItem to null?
| 7fb2b221ba1bd609ad36da47047af41c48199fddf3192ff2de05987d5d4c02fa | ['a100ac15c27b4ed5b0fe9404ee24fc4e'] | Hi <PERSON> my life saver!
It works!
Somehow I have never thought of GUI tools when it comes to Linux (bad perception).
However, after installing the driver labelled as "proprietary, tested", it popped out window saying “The system is running in low-graphics mode" (as in http://askubuntu.com/questions/141606/how-to-fix-the-system-is-running-in-low-graphics-mode-error) and the screen keep flashing. I enter console mode (ctrl+alt+F1) to reboot, after that everything just works perfectly until now. Will see what will happen after this. Thanks so much. |
eb2db1df1215b66dce536c3cd62568c3faca6f17bcab996cc6e786e633ec1831 | ['a1514393051f4955a52c3f19c03956e4'] | I want to say thanks to those who came up with suggestions, but I went the lazy way... I downloaded and installed AutoIt, and managed to make a reliably working exe with it in less than 10 minutes... still using a continuous loop to check for a change in display resolution, then--when it does--run a vbscript I'd already verified to work to update the wallpaper file and force refresh the desktop.
it almost looks like it's a feature-not-a-bug thing, this seemingly simple WMI query not working from a VB .Net Express executable.
| fbfda625039fa54f9324041072c66603734f0063b46520f7f34877b2fe11585c | ['a1514393051f4955a52c3f19c03956e4'] | I have a laptop that has both HDMI and VGA connectors; my TV is connected to the HDMI port (set at a resolution of 1600x900), and my desk monitor is connected to VGA (at an old-fashioned 1280x1024). The GPU does not allow for both external ports to be used simultaneously, so I end up having to switch between the one and the other, depending on whether I want to watch my shows and movies or sit behind the computer.
So far, so good... but (me being OCD about that stuff) I want to have a different wallpaper depending on the active config (laptop + TV or laptop + VGA), set by some script...
To catch the change between setups (Intel Graphics, using one of two preset profiles) I need something that monitors the active monitors for changes.
I've found a simple solution using SystemEvents.DisplaySettingsChanged, but this only works when I run the code from the VB.Net IDE. As soon as I compile and run the exe, the event doesn't seem to get triggered anymore.
I also tried a continuous loop using the Windows.Forms.Screen.AllScreen array, but the same applies: runs like a charm from within the IDE, but when compiled, it never detects the change.
Skeleton code for the first option (run as a console app):
Imports Microsoft.Win32
Imports System.Threading
Module Module1
Public Sub MyEH2(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("Display has changed")
' Actual code do change wallpaper comes here, natch
End Sub
Sub Main()
AddHandler SystemEvents.DisplaySettingsChanged, AddressOf MyEH2
While 1
Thread.Sleep(1000)
End While
End Sub
End Module
My question is: why does this work when started within the IDE, but not when compiled as an EXE? (In other words: why doesn't the compiled version detect the changes?)
I'm running Windows 7 Home Premium and using VB.Net 2012 (Express)
|
4c64b8ac18d402c31236c84703cfc5b36d5cfc798de8759dd6b91f8084baf66c | ['a15d402e01af4bc7a81cfe0212f9656d'] | I am writing an add-in for Word using the JS API.
My requirement is - do a search for a string, highlight the matching ranges (using font.highlightColor) - so far no problems.
But I also need to keep track of which ranges/texts have been highlighted, so that I can later programatically remove the highlights when the user clicks a button.
I have implemented similar functionality in a Google Docs Addon by using their Named Range feature. The range builder in that API lets you build a new range out of all the matching ranges, give it a name, and later find them by name.
How would I go about achieving this via the Word JS API?
| 35ce705281e5cdd61074ed43234ec6f8278a79cfba29080bfd5dd177377ab278 | ['a15d402e01af4bc7a81cfe0212f9656d'] | I am trying to add a new member to a MS Team, but I cannot get it to work.
It adds the new member to the group, but that's where it stops. It does not add the member to the team object.
This is what I am doing:
POST to 'groups/' + groupId + '/members/$ref' with the right data.
There is no error. It updates the group with the new member, but when I check the team, the new member is not there. What am I missing?
|
fb7bd6d2569f1ff74da417569b9caba8d421896b4c4993f00d8f9516a618ba0e | ['a164f8eac9994d5998ebdd13a7bf1b55'] | I am trying to use Font Awesome icons, the problem is that the size of fa-bed is 0X0 though the other icons are displayed properly.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="css/font-awesome.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<div class="col-sm-2 col-xs-3 col_pad col_pad_xs">
<i class="fa fa-plane" aria-hidden="true"></i><span>Flight</span>
</div>
<div class="col-sm-2 col-xs-3 col_pad col_pad_xs">
<i class="fa fa-bed" aria-hidden="true"></i><span>Hotel</span>
</div>
<div class="col-sm-2 col-xs-3 col_pad col_pad_xs">
<i class="fa fa-plane" aria-hidden="true"></i>
<span>+</span>
<i class="fa fa-bed" aria-hidden="true"></i>
<span style="margin-left: -5px;">Flight + Hotel
</span>
</div>
<div class="col-sm-2 col-xs-3 col_pad col_pad_xs">
<i class="fa fa-sun-o" aria-hidden="true"></i><span>Holidays</span>
</div>
</div>
</body>
</html>
Here is a screenshot of what I get:
| b2698e4003f7d1090cb519b1d2249ba9702bf37df347a2e3427419f0e05c44cf | ['a164f8eac9994d5998ebdd13a7bf1b55'] | I am exporting some data to Revit via API. The problem is that the result when having more than two elements meet at the same point is incorrect.
I have tried to edit the faces or the edges of the elements but it seems that they are read only and cannot be edited.
How to pass the correct geometry (faces & edges) to revit elements?
|
939cc6e8e9090a2aaf4a4588cfbb8f6ae6305126ffb3b413a88eb91ebe447a21 | ['a16dc8d7d7b640629e95e9c574c0a504'] | I would say: depends on what kind of architecture your app will have and how reliable it will need to be:
AWS Load Balancers does not provide instant (maybe real-time is a better word?)
auto-scale which is different of fail-over concept. It works with
health checks from time to time and have its small delay because it
is done via http requests (more overhead if you choose https).
You will have more points of failure if you choose more instances depending on architecture. To avoid it, your app will need to be async between instances.
You must benchmark and test more your application if you choose more
instances, to guarantee those bursts won't affect your app too much.
That's my point of view and it would be a very pleasant discussion between experienced people.
| 6a07b90488649d19fb49b4cd240cfff69dd70c4ff02fde47d87a66d1dd13cc83 | ['a16dc8d7d7b640629e95e9c574c0a504'] | I'm currently trying to require ace-builds (installed from bower) with webpack. Since it's a huge lib, I'm adding the whole folder to noParse option. I'm running webpack with -d option on terminal.
The problem is: when my code tries to require it, it is an empty object. Also, it's not loaded by the browser. Here are some information of what I'm doing:
My file:
// custom_editor.js
// ace-builds are aliased by ace keyword
var Ace = require('ace/ace'); // This is an empty Object when I'm debugging with breakpoints
Config file:
// webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
form: path.join(__dirname, 'static/main_files/form.js'),
vendor: [
'jquery',
'react',
'underscore',
'query-string',
'react-dnd',
'react-select-box'
]
},
output: {
path: path.join(__dirname, 'static/bundle'),
filename: '[name].bundle.js'
},
module: {
loaders: [{
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM'
}],
noParse: [
/ace-builds.*/
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
root: [
__dirname,
path.join(__dirname, 'static'),
path.join(__dirname, 'node_modules')
],
alias: {
jQueryMask: 'node_modules/jquery-mask-plugin/dist/jquery.mask',
twbsDropdown: 'node_modules/bootstrap-sass/assets/javascripts/bootstrap/dropdown',
'twbs-datetimepicker': 'node_modules/eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker',
ace: 'bower_components/ace-builds/src',
'select-box': 'node_modules/react-select-box/lib/select-box',
queryString: 'node_modules/query-string/query-string',
moment: 'node_modules/moment/moment'
}
},
plugins: [
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
};
It was not loaded on Chrome's Network panel
It is showing on Chrome's Sources panel (Don't know why because no ace.map file were loaded either)
Really running out of ideas of what I'm doing wrong here. Is there any good example that I can clone and test? (It can be another lib as well).
|
3e07c2663e52124e4b21b909a07e7e13a7faa5dbbe0bee8b3ddf4fb5c99c5647 | ['a17404f1596a4bc6a5ffb8d1fda0ef24'] | I implements an observer for a model's datas;
I have 2 activity, that share that datas. In my first activity I set the model like:
public void refreshValue (String id, Data data){
ConnectionModel.getInstance().updateConnection(data);
In the model the updateConnection is like:
public class ConnectionModel extends Observable{
//...
synchronized Connection getConnection() {
return connection;
}
void updateConnection(Data data){
synchronized (this) {
connection.setData(data);
}
setChanged();
notifyObservers();
}
}
In the second activity I set the observer like:
public class secondView extends AppCompatActivity implements Observer {
public void observe(Observable o) {
o.addObserver(this);
}
//...
public void refreshView(){
Connection connection = ConnectionModel.getInstance().getConnection();
heartRate.setText(connection.toString());
}
@Override
public void update(Observable o, Object arg) {
refreshView();
Log.d("update", "data is change");
}
I also tried to use LiveData with a ViewModel, but same result.
Where am I doing wrong?
Thanks a lot.
| e21db28b139d0f31b23c03418f5164328a865ce85bc2415fea91a45da660687e | ['a17404f1596a4bc6a5ffb8d1fda0ef24'] | I'm tring to download a pdf file inside a android web-view page. The problem is that the Web-view don't support the blob-link.
So I made a JavaScript interface, suggest by this answer
@JavascriptInterface
public void getBase64FromBlobData(String base64Data) throws IOException {
convertBase64StringToPdfAndStoreIt(base64Data);
}
public static String getBase64StringFromBlobUrl(String blobUrl){
if(blobUrl.startsWith("blob")){
return "javascript: var xhr = new XMLHttpRequest();" +
"xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true);" +
"xhr.setRequestHeader('Content-type','application/pdf');" +
"xhr.responseType = 'blob';" +
"xhr.onload = function(e) {" +
" if (this.status == 200) {" +
" var blobPdf = this.response;" +
" var reader = new FileReader();" +
" reader.readAsDataURL(blobPdf);" +
" reader.onloadend = function() {" +
" base64data = reader.result;" +
" Android.getBase64FromBlobData(base64data);" +
" }" +
" }" +
"};" +
"xhr.send();";
}
return "javascript: console.log('It is not a Blob URL');";
}
private void convertBase64StringToPdfAndStoreIt(String base64PDf) throws IOException {
String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
final File dwldsPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/report_" + currentDateTime + ".pdf");
byte[] pdfAsBytes = Base64.decode(base64PDf.replaceFirst("^data:application/pdf;base64,", ""), 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
if(dwldsPath.exists())
Toast.makeText(context, context.getApplicationContext().getString(R.string.download_success), Toast.LENGTH_LONG).show();
else
Toast.makeText(context, context.getApplicationContext().getString(R.string.download_failed), Toast.LENGTH_LONG).show();
}
But this don't work correctly, because when I load the url like:
String newUrl = JavaScriptInterface.getBase64StringFromBlobUrl(url);
webView.loadUrl(newUrl);
nothing happining. So I suppose that is the blob url parse inside the interface, becouse when I change this:
"xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true);"
to this
"xhr.open('GET', ' ', true);"
code works, but, obviusly, don't download the right pdf but a empty file.pdf.
Any advice?
thanks
|
a27269d5070f4b976cfda8c14f3b75a79d6be0754674f623f383ff6454dc2275 | ['a17b45d0b4e042d0a4e0beb43a1cb1ee'] | Two straight line are at right angles to one another, one of them touches the parabola $y^2=4a(x+a)$ and the other touches the parabola $y^2=4a'(x+a')$. Show that the point of intersection of the straight lines will lie on the straight line $x+a+a'=0$.
I tried to solve this problem, I find two tangents of two parabolas, then they meet at right angle,$(m_1.m_2=-1)$. But I can not find the result. Someone please help.
| 3f629d3b81937809aa06c84b5b14124e784ad014cc4c6b171cae5ebe914cafab | ['a17b45d0b4e042d0a4e0beb43a1cb1ee'] | I'm trying to install a software which comes with a shell script to install, and I need to run this in su because of some drivers it installs.
When I try to run this shell script with sudo:
➜ lab sudo ./xsetup
_xsetup: cannot connect to X server
And this is the error message I get in a dialog window when I try to run it with kdesu:
Cannot execute command ' ./xsetup'.
Thanks.
Btw, if anyone's interested, the software I'm trying to install is Xilinx.
|
f56521eb7df92132c9277c756d60927dfdd79b7887459fe4e20a415f70ccae7e | ['a17e57cc4e8d4fcca05fad33a6ddde58'] | I have a USB camera here that I am very familiar with and have worked with for a while. I can capture "still images" in OpenCV and with Gstreamer without problems. However one of the use cases for this camera involves a button on the camera itself to capture stills.
The camera has a "still pin" which I have wired up a button to. In Windows with DirectShow it works as you would expect. I have spent the past week in search of a way to replicate this behavior in Linux for my embedded project. So far I have not been able to find anything that I can make use of. It seems all the support for this feature is Windows only.
I have searched through the following:
V4l2 Documentation
OpenCV
Gstreamer
uvc-streamer
uvccapture
luvcview
I have also done USB sniffing on Windows which revealed a "capture begin" packet is sent. Though I have not found a way I can monitor the USB traffic from the camera during streaming. While capturing from the device, /dev/video0 is in use by V4l2 and I cannot read the bytes traveling on the bus. If there is a way I could read the raw data from the camera, I could also just handle a "still pin" button press in my application.
Any possible solutions/ideas are welcome at this point. I am out of ideas and web resources.
| f69804daedf73db1d6ec74f66ef42b848c3f56c4398548830848ae96202b3234 | ['a17e57cc4e8d4fcca05fad33a6ddde58'] | I have read all of the related questions with no success trying anything mentioned anywhere. I am new to cross-compiling and have been working on this for over a week with no progress. So please forgive me if you think I am stupid or have overlooked something.
So I have an application running in C++ that works great on my development computer running Ubuntu 14.04 x64. I am trying to cross compile for my Banana Pro running Lubuntu. Based on the documentation from <PERSON> I am supposed to cross compile using "arm-linux-gnueabihf-"
So far the farthest I have been able to get is to :
/usr/local/opencv-arm/usr/local/lib/libopencv_calib3d.so: file not recognized: File format not recognized
collect2: error: ld returned 1 exit status
I get this error regardless of what command I run, Here is a list of commands I have tried:
arm-linux-gnueabihf-g++ `arm-linux-gnueabihf-pkg-config arm-opencv --cflags` -Wall test.cpp -o vis-300 `arm-linux-gnueabihf-pkg-config arm-opencv --libs`
arm-linux-gnueabihf-g++ `pkg-config arm-opencv --cflags` -Wall test.cpp -o vis-300 `pkg-config arm-opencv --libs`
arm-linux-gnueabihf-gcc `pkg-config arm-opencv --cflags` -Wall test.cpp -o vis-300 `pkg-config arm-opencv --libs`
arm-linux-gnueabihf-g++ `pkg-config arm-opencv --cflags` test.cpp -o vis-300 `pkg-config arm-opencv --libs`
And there have been many more commands before those with different errors such as:
arm-linux-gnueabihf-gcc: error trying to exec 'cc1plus': execvp: No such file or directory
arm-linux-gnueabihf-cpp fatal error too many input files
I have tried with just normal arm-linux-gnueabihf-gcc/g++, 4.6, 4.7, and 4.8
I have built opencv making small changes for hf using these 2 guides and both produced the same results:
http://processors.wiki.ti.com/index.php/Building_OpenCV_for_ARM_Cortex-A8
http://www.ridgesolutions.ie/index.php/2013/05/24/building-cross-compiling-opencv-for-linux-arm/
and not included in either I install it using this command because it will conflict with my current x86_64 install:
sudo make install DESTDIR=/usr/local/opencv-arm
Also the above pkg-config lines point to my custom pkg config file named arm-opencv.pc
# Package Information for pkg-config
prefix=/usr/local/opencv-arm/usr/local
exec_prefix=${prefix}
libdir=
includedir_old=${prefix}/include/opencv
includedir_new=${prefix}/include
Name: OpenCV-arm
Description: Open Source Computer Vision Library
Version: 2.4.10
Libs: ${exec_prefix}/lib/libopencv_calib3d.so ${exec_prefix}/lib/libopencv_contrib.so ${exec_prefix}/lib/libopencv_core.so ${exec_prefix}/lib/libopencv_features2d.so ${exec_prefix}/lib/libopencv_flann.so ${exec_prefix}/lib/libopencv_gpu.so ${exec_prefix}/lib/libopencv_highgui.so ${exec_prefix}/lib/libopencv_imgproc.so ${exec_prefix}/lib/libopencv_legacy.so ${exec_prefix}/lib/libopencv_ml.so ${exec_prefix}/lib/libopencv_nonfree.so ${exec_prefix}/lib/libopencv_objdetect.so ${exec_prefix}/lib/libopencv_ocl.so ${exec_prefix}/lib/libopencv_photo.so ${exec_prefix}/lib/libopencv_stitching.so ${exec_prefix}/lib/libopencv_superres.so ${exec_prefix}/lib/libopencv_ts.a ${exec_prefix}/lib/libopencv_video.so ${exec_prefix}/lib/libopencv_videostab.so -lrt -lpthread -lm -ldl
Cflags: -I${includedir_old} -I${includedir_new}
Anyways I have tried a lot of stuff short of just installing everything on the board itself and compiling there. Any help is much appreciated and keep in mind I have never successfully cross-compiled before. I always give up and compile on the board.
|
990d8fe1e298ecd20b0a2e45105fffc691961a4499b6a613508b21bc4195e230 | ['a181ad01fa6343b5a12238cfb8dad830'] | We know that if M is an R-module, A,B,C are submodules of M and C is subset of A then $ A \cap (B+C) = (A \cap B) +C $
What if we use $ \oplus $ instead of +. Is it true to write that equation again? Or should we add more things to make it true for direct sum?
Thank you for any help.
| 4d3e023ab3d541a30917a91d379ab26ed8f652766aec5730a1b881909e43ebe5 | ['a181ad01fa6343b5a12238cfb8dad830'] | For modules we can say "External direct sum is associative and commutative up to isomorphism." If we are using internal direct sum I think we can say it is associative and commutative (They are equal not only isomorphic). Am I right? I tried to prove and didn't see any problem.
I mean I can say;
Let A,B,C are submodules of M then
$ M=A \oplus B \Rightarrow M=B \oplus A $
and
$ M=(A\oplus B)\oplus C \Rightarrow M=A \oplus(B\oplus C) $
Right?
|
d2cc0e0a40d341a73e8c1eb0573309b8a9488ce74707c6c3a1affbe5e63477f8 | ['a18aef9e5f32452abb663bb824601ef1'] | I would start by looking at your UV map. If you try using the color grid or UV preset textures (when you create a new texture) you should be able to see if your UV map makes sense, or if it's causing the issue.
If the UV map is the problem, you can probably just UV unwrap your object again. To make a flat UV map from above your object (which should work for your terrain), switch to edit mode with Tab, toggle to orthographic view with Ctrl+5, switch to top view with Ctrl+7, then select UV unwrap (or press U) > Project from View (Bounds).
| 18ad9626f3edabe730134b4b1ad4779f57e779b4fa348ae06370033ca6ec16a1 | ['a18aef9e5f32452abb663bb824601ef1'] | Guys, I am not a DBA, only a SQL developer. I am just asking all this as it's been going on for quite some time. Thanks for your comments, I will try to respond to all of them, even though for now I find it hard to follow (and it all seems pretty obvious for you). What is MP? |
13e688229852cc25394afc587022119aefd8471745e50ab837839405d7f4db62 | ['a1913eab5bf34e9384e5252fb2433861'] | set following in service model
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
<services>
<service name="SyncWebServices.Service1" behaviorConfiguration="">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basichttp" contract="SyncWebServices.Service1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="basichttp" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:25:00" sendTimeout="00:25:00" maxReceivedMessageSize="4294967296" transferMode="Streamed">
<readerQuotas maxDepth="4500000" maxStringContentLength="4500000" maxBytesPerRead="40960000" maxNameTableCharCount="250000000" maxArrayLength="4500000" />
<security mode="None">
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" httpHelpPageEnabled="true" />
<serviceThrottling maxConcurrentCalls="500" maxConcurrentSessions="500" />
</behavior>
</serviceBehaviors>
</behaviors>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
| 1daad420b50007e2aab62cb61bf938a9921766e24eb7bf703e771408a0f75bb9 | ['a1913eab5bf34e9384e5252fb2433861'] | hello i find out solution by using following i can get actual difference should it proper or not please suggest
public static DateTime ConvertToTheaterTimeZone(string TheaterTimeZone, DateTime Date)
{
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById(TheaterTimeZone);
DateTime targetTime = TimeZoneInfo.ConvertTime(Date, est);
return targetTime;
}
var hour = (item.Checkindate - ConvertToTheaterTimeZone("Eastern Standard Time", DateTime.Now)).TotalHours;
|
a5d700e2efb5d4e826baf76331b91a735beb7d59f0a853141a1eac7d11c55b32 | ['a19580f5196743d0aa002d2c1139a623'] | Kotlin code for sub data class like ImagesModel also parcelable used
data class MyPostModel(
@SerializedName("post_id") val post_id: String? = "",
@SerializedName("images") val images: ArrayList<ImagesModel>? = null
): Parcelable {
constructor(parcel: Parcel) : this(
parcel.writeString(post_id)
parcel.createTypedArrayList(ImagesModel.CREATOR)
)
override fun writeToParcel(parcel: <PERSON>, flags: Int) {
parcel.writeString(post_id)
parcel.writeTypedList(images)
}
}
| 6947edd13e96b6e0d9195029650a923ee74abee98176125cf91eeafe4c84e352 | ['a19580f5196743d0aa002d2c1139a623'] | Invalid image: ExifInterface got an unsupported image format file(ExifInterface supports JPEG and some RAW image formats only) or a corrupted JPEG file to ExifInterface.
This error showing in my app and might be problem of extension is not proper in Image URL. I have using the Glide library to load image and showing the error like ExifInterface supports JPEG and some RAW image formats only
After that I have cleared the cache and data from Application settings then it showing correct image but it showing the different log message as below
Load failed for http://myserverurl.com/web/image/product.template/7783/image_1920?unique=20201014051228 with size [146x156]
class com.bumptech.glide.load.engine.GlideException: Failed to load resource
There was 1 cause:
java.io.FileNotFoundException(https://myserverurl.com/web/image/product.template/7783/image_1920?unique=20201014051228)
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetching data failed, class java.io.InputStream, REMOTE
Below Image URL using in Glide
https://myserverurl.com/web/image/product.template/7783/image_1920?unique=20201014051228
Note: Above image url is reference purpose and not available in that server currently.
|
4eb937478b9f25a57ecf7a2d1adef1a59e6ed6020c4006eb5b8025e4b7dd1d3f | ['a19c1082435e4018830b293e95f9817a'] | there isn't a cpu temperature applet in the default list of panel applets, but there are applets to control cpu temperature in the repositories. I use one called cputemp or something along those lines, and I have both that and the cpu frequency scaling one installed on my panel as my cpu seems to overheat pretty easily (I think my fans may be defective ... or the laptop wasn't that well designed in general ... it's had overheating problems since the beginning, despite having it on a cooler).
Both applets have options for warnings etc. I haven't found a nice way to change the cpu frequency automatically depending on temperature ... but what I have done is make the system play a sound whenever the cpu temp exceeds 85 degrees ... at which point I remember I'm doing something CPU intensive (usually involving flash ... grrr), and I scale the CPU frequency down temporarily.
| 67198acc253cb4dd269c8e41c7560c616e6c68378886ceec6a706499e3b95c9b | ['a19c1082435e4018830b293e95f9817a'] | Your university may have specific guidelines as to how your thesis should be formatted (this is VERY common, actually - please consult the appropriate office at your school so there are no surprises). My university has the following ordering:
Title Page
Abstract
Dedication
Acknowledgements
Contributors and Funding Sources
Table of Contents
List of Figures/Tables
Nomenclature
Again, it depends on what your university says they want.
|
ea01a7dd1c9ef51c2224a2750030e5a6c932ac7e51bc3d711c0007d61f08c32f | ['a1afba0a563e4895a6af826e8a597cc8'] | You could use the Column mode (ALT + Mouseselect) to select only the part (column) you want.
This could be tricky if the product name length is very unequal.
An other way would be Find+Replace with a clever RegEx. Thats what I would do in your case.
As the product name is the first column, deleting everthing behind the comma should do the trick. So use this regex and replace with an empty string:
Find: ,[\w]*
Replace:
| 7594d15adf8a1fefd622b018486912b55dff3c96b4acc28f4c2d8b161b8ecfda | ['a1afba0a563e4895a6af826e8a597cc8'] | In a script you can do that like:
for line in ${ods-ksmutil key export --zone 231.72.212.in-addr.arpa --ds | grep "8 2"}
command ${echo $line | tr -s " " | cut -d " " -f 5-8}
done
That requires that the IFS is set to the newline character which it should be by default.
|
04271726a15cc142bde26b11af5ea0b89a77fab832d6f20e2ec2fb6f63a10a3a | ['a1d4bfba62f844288687d3f681745ca3'] | You should build your code with -Wall flag to compiler. At compile time it will then print:
main.c:9:15: warning: ‘coord1’ is used uninitialized in this function [-Wuninitialized]
This points you to the problem.
coord1 is a pointer type, that you assign to, but coord1 has no memory backing it until it is initialized. In the following snippet coord1 is initialized by allocating memory to store it's components. This gets rid of the segfault.
VECT coord1 = NULL;
coord1 = (VECT)malloc(sizeof(struct vector));
if (NULL == coord1)
{
fprintf(stderr, "Out of memory!\n");
exit(1);
}
coord1->x = 0.0012345;
coord1->y = 0.012345;
coord1->z = 0.12345;
In general, segfaults happen when a program accesses memory that the operating system has not allocated to it. Unintialized pointers usually point to address zero, which is not allocated to any program. Always use gcc -Wall when compiling, this will many times point to these potential problems. Helped me find it right away.
Also, you could have declared your VECT type to be typedef struct vector (a non-pointer type).
VECT coord1;
VECT* v_coord1 = &coord1;
v_coord1->x = 0.0012345;
v_coord1->y = 0.012345;
v_coord1->z = 0.12345;`
Also, variable naming conventions can help here as well.
struct vector{
double x;
double y;
double z;
};
typedef struct vector VECT;
typedef struct vector* pVECT;
| 0f89f781b87f0b3588dfbb01d1cf8ddc3bb3f13563e55fcaa214976ccd85f4d0 | ['a1d4bfba62f844288687d3f681745ca3'] | The following works for me with a gnome-terminal in Fedora and vim7.3.
Select the text you want, for instance using visual mode.
Press Ctrl-Shift-c
Then enter ESC followed by :shell
Once in the shell press Ctrl-Shift-v
If you also grab a newline when you copy it will execute as a shell command when you paste.
A side effect of this is that by doing :shell if you have vim configure to save .swp files, there will be one left in the current directory and the next time you edit the original file, you will need to deal with vim complaining about finding a swap file.
|
a9ccbdfd01fba1f6bf0f7d7a19f18afef8c73fd84723589760e3618125e86157 | ['a1d4e5bbbf4b4d7cbf2fb3918f737859'] | I'm trying to use rpmbuild to do the following.
I have a prebuilt project, about 100 files in a single directory, as a tar file. I want to create an RPM which will bundle those files, and when installed on a new machine using rpm -i, will unpack the files, create a directory under /usr/bin, and copy them into there. Finally, it should run a bash script file.
Running rpmbuild -bs creates an SRPM, but when I try to install that with rpm -i, nothing happens.
Running rpmbuild -bb runs all the steps - configure, build, install, etc, most of which I don't need. However, it does not create an RPM, and the install step is what I expected to happen on the target machine when I use rpm -i, not on the machine I'm trying to create the RPM on.
I think I'm missing something basic. Any hints?
| 5c4d1cd8c2b50f40965080aa634884d3ea7d3fdee11516854bf8a8aaf10fc000 | ['a1d4e5bbbf4b4d7cbf2fb3918f737859'] | I have want my .Net Linux service to start a bash shell script, which stops its parent service, while the script continues.
This can be done on straight Linux easily, with nohup and &.
It can be done in Windows .net, by writing a stub .exe or script which starts the persisting script, then stops its parent. In that case, the stub and the parent die, but the script the sub started continues.
However, in .net on Linux, this does not seem to work. My .net app can issue a shell command with nohup, but the sub-script - which is also started with nohup and &, and which is the one which is supposed the actual work, does not run.
The stub update1.sh, is run from the .net app with
nohup /usr/bin/myservice/update1.sh update.rpm &
It contains:
trap '' SIGTERM
trap '' SIGINT
nohup /usr/bin/myservice/update2.sh $1 &
update2.sh contains
trap '' SIGTERM
trap '' SIGINT
sudo systemctl stop myservice
yum -y localinstall $1
sudo systemctl start myservice
(the traps are intended to prevent the parent's shutting down from
stopping the child)
If I start update1.sh from the command line, while su'd to the service user account, with nohup and &, it works fine. The problem arises when I start up the stub from inside the .net app, with the same command line. It appears to be related to running in the .net managed code environment.
Any suggestions?
The goal is to take an .net app running on an unattended Centos server, and allow it to update and restart itself using 'yum -y localinstall' and a local RPM file (no, it can't go to a remote repository).
|
4ab8cc62810bb1b3c821ab018e9edc268124a65860cb776a11603a606204590d | ['a1e256f9c0c4430d9707b2a1ca153a1c'] | Yes, I think you can use Oracle APEX with Oracle XE for corporate applications, you can also use Oracle APEX Listener as your web server.
The only problem would be the hardware limits imposed on the XE edition:
"Oracle Database XE can be installed on any size host machine with any number of CPUs (one database per machine), but XE will store up to 11GB of user data, use up to 1GB of memory, and use one CPU on the host machine..."
But that should be enough to start, and when you start needing more resources you can also try Amazon on-demand DB instances "On-Demand DB Instances for the License Included model let you pay for compute capacity by the hour your DB Instance runs with no long-term commitments..."
| 8a2666428746207a523d72a095f0586d4582b54a47539bf05c60dd2d5aa6a3f5 | ['a1e256f9c0c4430d9707b2a1ca153a1c'] | Given the following source code:
namespace EventThreadLocal {
static thread_local std<IP_ADDRESS>unique_ptr<std<IP_ADDRESS>vector<EventInfo>> Stack;
static const EventInfo* Top()
{
auto stack = Stack.get();
if (!stack)
return nullptr;
if (stack->empty())
return nullptr;
return &(stack->back());
}
}
How can I inspect the contents of the static thread_local variable Stack on a heap dump?
My understanding is that the command !tls displays the thread local storage slots, but how can I know the appropriate slot index used by this variable?
|
6ef4c1874d2adfe4bce1ce179b8c45fa021e5a43a063c0449c0da2a4f8e7b9c3 | ['a1ed709944834fab9f8b30db57d54777'] | I believe I got it working the way you want :) The problem was that you were not checking the current class dynamically after change. Updated jsfiddle here.
$('.points').click(function () {
if($('.points').attr("class") === "points first") {
$('.points').removeClass('first').addClass('second');
$('.ten-points').fadeIn('slow').delay(2000).fadeOut('slow');
}else if($('.points').attr("class") === "points second") {
$('.points').removeClass('second').addClass('third');
$('.twenty-points').fadeIn('slow').delay(2000).fadeOut('slow');
}else if($('.points').attr("class") === "points third") {
$('.points').removeClass('third').addClass('first');
$('.no-points').fadeIn('slow').delay(2000).fadeOut('slow');
}
});
| a06f8e6430ff49d33632141deba96ccb8f4e1148641f0f03030f1361cd265e20 | ['a1ed709944834fab9f8b30db57d54777'] | How to get the amount of the free quota in my applications local storage?
I need to get the remaining storage amount in bytes, kilobytes, megabytes or in percentage. Also it would be nice to get some visual display of how much free quota I have in local storage.
Thanks!
Edit: Please note that this was "answer your own guestion" style post and therefore I cannot make better guestion. Focus on the answer because the guestion is in the title and there is not much more into that.
|
04e415394b0ed0a182f9c3ef811f09d6100821fbfd46c7e31b0f0fba023ff245 | ['a1f4099b33d7485b8d15f893bb3cc2ea'] | I'm following the Extending QgsTask example to create a custom QgsTask.
However, I don't want it to display the Task Complete notification* every time the task completes successfully.
Is it possible (preferably using PyQGIS) to suppress the "Task Complete" notification?
* In Windows 10 at least, the notification appears in the bottom right of the screen above the time (with a ding!).
| a3f13bd73b20224fe36f42c75466ab0e6be22fad1b9597d62b8ecf5ffd962027 | ['a1f4099b33d7485b8d15f893bb3cc2ea'] | I have a button in a QGIS (3.4.1) plugin that should: create a new project; set it's CRS to EPSG:4326', then import various maps.
However, when I run it for the first time after QGIS has loaded, the maps are show with their own CRS of EPSG:3857(confirmed in the bottom right of the GUI). If I click the button a second time/run the code again, the maps are shown in the intended CRS of EPSG:4326 (again, confirmed in the bottom right).
The minimum code I can find to replicate the behavior is below:
# Create new project
iface.newProject(promptToSaveFlag=False)
project = QgsProject.instance()
# Create map tile layer (which by default uses EPSG:3857)
map_uri = 'type=xyz&url=http://a.tile.openstreetmap.org/{z}/{x}/{y}.png'
raster_layer = QgsRasterLayer(map_uri, 'openstreetmap.org', 'wms')
if raster_layer.isValid():
project.addMapLayer(raster_layer)
# Set CRS to EPSG:4326
project.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
Copy/pasting into the Python console seems to have the same results (i.e. first time after QGIS has loaded it doesn't work, second time it does).
Is this a bug in QGIS?
Can anyone propose a workaround?
|
b631ebeb6bef47dee549fdaa78883bd4ac1518685ae34978e31062d43eca61d5 | ['a1f40aabf8604b60b5a7f8e9d60b2825'] | Variadic option. It prints «foo!bar!baz!foo!», as expected.
enum class foobar { foo, bar, baz };
void test() {}
template< typename F, typename... Fs >
void test( F Foo, Fs const&... args )
{
switch( Foo )
{
case foobar<IP_ADDRESS>foo:
std<IP_ADDRESS>cout << "foo!";
break;
case foobar<IP_ADDRESS>bar:
std<IP_ADDRESS>cout << "bar!";
break;
case foobar<IP_ADDRESS>baz:
std<IP_ADDRESS>cout << "baz!";
break;
}
test( args... );
}
int main() {
test( foobar<IP_ADDRESS>foo, foobar<IP_ADDRESS>bar, foobar<IP_ADDRESS>baz, foobar<IP_ADDRESS>foo );
}
| 641f19658703cee09ff02ae2ea51e19794e75c6f042752cdc101fd5283f14da3 | ['a1f40aabf8604b60b5a7f8e9d60b2825'] | To me this looks like a compiler bug: do you really need side effects from T{}? The whole construct of decltype((void)T{}) should discard zero-initialized T, allowing unevaluated side-effects — so what's the point of such side effect, if there are any? If you simplify it by just using void, or even omitting the whole second type, the problem goes away immediately (live demo on wandbox):
template<typename T, typename U = void>
struct Test
{
static const int value = 0;
};
template<typename T>
struct Test<T, void>
{
static const int value = 2;
};
template<typename T>
struct Test<T*, void>
{
static const int value = 1;
};
int main(){
std<IP_ADDRESS>cout << Test<int*>::value << "\n";
return 0;
}
Maybe there are some intricate details that I missed, but I tried many variants, including combinations of std<IP_ADDRESS>declval, std<IP_ADDRESS><IP_ADDRESS>value << "\n";
return 0;
}
Maybe there are some intricate details that I missed, but I tried many variants, including combinations of std::declval, std::result_of, alias templates, typedefs, none of which gave me anything meaningful. But if we move the decltype((void)T{}) part out:
template<typename T>
using wrap = decltype((void)T{});
template<typename T>
struct Test<T, wrap<T>>
{
static const int value = 2;
};
template<typename T>
struct Test<T*, wrap<T>>
{
static const int value = 1;
};
GCC yells: ambiguous template instantiation for 'struct Test<int*, void>'. Which for me is a sign of something going in the wrong direction.
|
a525f1707faa68000635d3bbcdd6287066b6e8f262ac75455fcd28265b4756ac | ['a1fd895033b84495bb810cf0cf3bf37c'] | I have a binary mask that originated from a piece-wise smooth curve. Each underlying curve segment is smooth, but connections between segments may or may not be smooth.
The mask is noisy so it might contain several pixels around the underlying curve. Image below shows an example of such input:
I want to estimate a fit to the underlying curve, given this input without any other prior knowledge, that will be able to provide both smooth and non-smooth connections.
I'm working in python so I tried several methods available there, such as numpy's polynomial fit, scipy's spline smoothing and pyqt-fit's non-parameteric regression, but was not able to get to the desired output. Here's a code example:
from imageio import imread
import random
import numpy as np
from scipy.interpolate import UnivariateSpline
import pyqt_fit.nonparam_regression as smooth
from pyqt_fit import npr_methods
from matplotlib import pyplot as plt
mask = imread(r'C:\mask.bmp')
ys, xs = np.where(mask)
# add tiny noise and sort - silly way to comply to UnivariateSpline's requirement of "x must be strictly increasing"
xs = np.array([x + random.random() * 1e-4 for x in xs])
sorter = np.argsort(xs)
xs = xs[sorter]
ys = ys[sorter]
# polynomial fit
p = np.poly1d(np.polyfit(xs, ys, 5))
# spline smoothing
spl = UnivariateSpline(xs, ys, k=3, s=1e9)
# non-parameteric regression
k = smooth.NonParamRegression(xs, ys, method=npr_methods.LocalPolynomialKernel(q=3))
k.fit()
plt.figure()
plt.imshow(mask, cmap='gray')
linexs = np.array(range(mask.shape[1]))
plt.plot(linexs, k(linexs), 'y', lw=1)
plt.plot(linexs, spl(linexs), 'g', lw=1)
plt.plot(linexs, p(linexs), 'b', lw=1)
plt.show()
For the parameters shown in this example, these fits both fail to capture the non-smooth connection on the left, as well as to provide a good fit for the "tail" on the right:
Expected results should behave like the red curve in the image below, where I expect the curve at location 1 to be non-smooth and at location 2 to be smooth.
I'd be happy to get a reference to a suitable algorithm. If there's also a python implementation, that would be a plus.
| 91e78af372cfc7fc64c440021a5753e7b2a3348f09ec185808344ae60213eaf9 | ['a1fd895033b84495bb810cf0cf3bf37c'] | I'm working with Matlab R2015a on Linux (Fedora OS).
The Matlab Editor shortcuts are defined as the default Windows shortcuts.
Some of them work OK (for example: ctrl+c , ctrl+s, ctrl+o) but some of them don't do anything (ctrl+F3 for searching the next appearance of a selection (while strangely Ctrl+Shift+F3 works OK for searching previous appearance of a selection), ctrl+d for opening a script/function..).
Any idea how to fix this?
|
4b2cc63c71a39af98793dc8ebc35ec63db8ab40ffe195ce25c80250b3b3a66b0 | ['a20a7aa2d6b74149b899cdf7f10082c1'] | You can go along two ways:
import numpy as np
M = np.array([[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3]])
mask = np.array([False,True,False,True,False,True])
true_locs = np.where(mask)[0]
# set True to False in the mask
mask[true_locs[2:]] = False
# OR just use the indeces directly
M[true_locs[:2],:]
| c71d7da1aadbef76c81aa007b376ff8416c6b3bb2a12430b08ec3e98b5eea822 | ['a20a7aa2d6b74149b899cdf7f10082c1'] | If you read in a csv-file, you can use the multi-select widget to select the columns you want to show:
import streamlit as st
import pandas as pd
# load csv
uploaded_file = st.file_uploader('upload')
# into dataframe
df = pd.read_csv(uploaded_file)
'## multi select'
cols = st.multiselect('select columns:', df.columns, default=[])
st.write('You selected:', cols)
# show dataframe with the selected columns
st.write(df[cols])
In the current version (v0.68.1) the file uploader is buggy. So if you get an error on rerun, consider downgrading to v0.66
|
2249f9302bf5ec3d2b045c2ca6c55d2385cad3ce0fdf561a9d7492a0f9e0520c | ['a20cc0f24d9d45f2a3ba8e7333ea6521'] | I try to get URL with inAppBrowser in ionic 4 for my instagram api. I build PWA and smartphone applications. . Why loadstart event
does not work when I build in PWA ?
I've already tried to get with in app browser plugin for ionic4 and with javascript (window.open() method).
In app Browser work when I build my IOS app.
That doesn't work when I build my PWA app/
//instagram API
let authUrl = `https://www.instagram.com/oauth/authorize/?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=token&scope=public_content`;
//create in app browser
var browser = this.iab.create(authUrl, '_blank');
//test loadstart event
browser.on('loadstart').subscribe(event => {
alert('loadstart');
alert(event.url);
}, err => {
alert("InAppBrowser loadstart Event Error: " + err);
});
//test loadstop event
browser.on('loadstop').subscribe(event => {
alert('loadstop');
alert(event.url);
}, err => {
alert("InAppBrowser loadstop Event Error: " + err);
});
}
PWA output :
loadstop
event.url == ""
IOS output :
loadstart
event.url == url
loadstop
event.url == ""
Thank you :)
| 355e9c9be353edeaf4d7bd50eeb0750bb6aaf539b45bdf9b6593d0db4d99d74d | ['a20cc0f24d9d45f2a3ba8e7333ea6521'] | I had a bug with symfony, I had to reinstall my vendor folder and since then I have a bug that I cannot fix.
Argument 3 passed to FOS\UserBundle\Doctrine\UserManager::__construct() must be an instance of Doctrine\Common\Persistence\ObjectManager, instance of Doctrine\ORM\EntityManager given, called in C:\wamp64\www\brouwers\var\cache\dev\ContainerMmxuCtr\srcApp_KernelDevDebugContainer.php on line 1664
Error on my browser
I have try to add : "doctrine/common":"^2.13" on my composer.json
The bug is still here ...
I don't know how to fix this.
Someone can help me ?
My composer.json
{
"type": "project",
"license": "proprietary",
"require": {
"php": "^7.1.3",
"ext-ctype": "*",
"ext-iconv": "*",
"friendsofsymfony/user-bundle": "^2.1",
"a2lix/translation-form-bundle": "^3.0",
"excelwebzone/recaptcha-bundle": "^1.5",
"doctrine/common":"^2.13",
"karser/karser-recaptcha3-bundle": "^0.1.8",
"knplabs/doctrine-behaviors": "^2.0",
"knplabs/knp-paginator-bundle": "^5.2",
"sensio/framework-extra-bundle": "^5.1",
"stof/doctrine-extensions-bundle": "^1.4",
"symfony/apache-pack": "^1.0",
"symfony/asset": "4.4.*",
"symfony/console": "4.4.*",
"symfony/dotenv": "4.4.*",
"symfony/expression-language": "4.4.*",
"symfony/flex": "^1.3.1",
"symfony/form": "4.4.*",
"symfony/framework-bundle": "4.4.*",
"symfony/http-client": "4.4.*",
"symfony/intl": "4.4.*",
"symfony/mailer": "4.4.*",
"symfony/monolog-bundle": "^3.1",
"symfony/orm-pack": "*",
"symfony/process": "4.4.*",
"symfony/security-bundle": "4.4.*",
"symfony/serializer-pack": "*",
"symfony/swiftmailer-bundle": "^3.4",
"symfony/translation": "4.4.*",
"symfony/twig-pack": "*",
"symfony/validator": "4.4.*",
"symfony/web-link": "4.4.*",
"symfony/webpack-encore-bundle": "^1.7",
"symfony/yaml": "4.4.*",
"twig/extensions": "^1.5",
"twig/extra-bundle": "^3.0",
"twig/twig": "^2.0"
},
"require-dev": {
"symfony/debug-pack": "*",
"symfony/maker-bundle": "^1.0",
"symfony/profiler-pack": "*",
"symfony/test-pack": "*"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"paragonie/random_compat": "2.*",
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php71": "*",
"symfony/polyfill-php70": "*",
"symfony/polyfill-php56": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "4.4.*"
}
}
}
Entity User :
<?php
// src/Entity/User.php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Assert\File(maxSize="2048k")
* @Assert\Image(mimeTypesMessage="Please upload a valid image.")
*/
protected $profilePictureFile;
// for temporary storage
private $tempProfilePicturePath;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
protected $profilePicturePath;
public function __construct()
{
parent::__construct();
// your own logic
$this->roles = array('ROLE_ADMIN');
$this->enabled = true;
}
public function getId(): ?int
{
return $this->id;
}
/**
* Asks whether the user is granted a particular role
*
* @return boolean
*/
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
/**
* Sets the file used for profile picture uploads
*
* @param UploadedFile $file
* @return object
*/
public function setProfilePictureFile(UploadedFile $file = null) {
// set the value of the holder
$this->profilePictureFile = $file;
// check if we have an old image path
if (isset($this->profilePicturePath)) {
// store the old name to delete after the update
$this->tempProfilePicturePath = $this->profilePicturePath;
$this->profilePicturePath = null;
} else {
$this->profilePicturePath = 'initial';
}
return $this;
}
/**
* Get the file used for profile picture uploads
*
* @return UploadedFile
*/
public function getProfilePictureFile() {
return $this->profilePictureFile;
}
/**
* Set profilePicturePath
*
* @param string $profilePicturePath
* @return User
*/
public function setProfilePicturePath($profilePicturePath)
{
$this->profilePicturePath = $profilePicturePath;
return $this;
}
/**
* Get profilePicturePath
*
* @return string
*/
public function getProfilePicturePath()
{
return $this->profilePicturePath;
}
/**
* Get the absolute path of the profilePicturePath
*/
public function getProfilePictureAbsolutePath() {
return null === $this->profilePicturePath
? null
: $this->getUploadRootDir().'/'.$this->profilePicturePath;
}
/**
* Get root directory for file uploads
*
* @return string
*/
protected function getUploadRootDir($type='profilePicture') {
// the absolute directory path where uploaded
// documents should be saved
return __DIR__.'/../../public/images/'.$this->getUploadDir($type);
}
/**
* Specifies where in the /web directory profile pic uploads are stored
*
* @return string
*/
protected function getUploadDir($type='profilePicture') {
// the type param is to change these methods at a later date for more file uploads
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'profilePicture';
}
/**
* Get the web path for the user
*
* @return string
*/
public function getWebProfilePicturePath() {
return '/'.$this->getUploadDir().'/'.$this->getProfilePicturePath();
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUploadProfilePicture() {
if (null !== $this->getProfilePictureFile()) {
// a file was uploaded
// generate a unique filename
$filename = md5(random_bytes(10));
$this->setProfilePicturePath($filename.'.'.$this->getProfilePictureFile()->guessExtension());
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*
* Upload the profile picture
*
* @return mixed
*/
public function uploadProfilePicture() {
// check there is a profile pic to upload
if ($this->getProfilePictureFile() === null) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getProfilePictureFile()->move($this->getUploadRootDir(), $this->getProfilePicturePath());
// check if we have an old image
if (isset($this->tempProfilePicturePath) && file_exists($this->getUploadRootDir().'/'.$this->tempProfilePicturePath)) {
// delete the old image
unlink($this->getUploadRootDir().'/'.$this->tempProfilePicturePath);
// clear the temp image path
$this->tempProfilePicturePath = null;
}
$this->profilePictureFile = null;
}
/**
* @ORM\PostRemove()
*/
public function removeProfilePictureFile()
{
if ($file = $this->getProfilePictureAbsolutePath() && file_exists($this->getProfilePictureAbsolutePath())) {
unlink($file);
}
}
}
fos_user.yaml
fos_user:
db_driver: orm # other valid values are 'mongodb' and 'couchdb'
firewall_name: main
user_class: App\Entity\User
from_email:
address: "<EMAIL_ADDRESS>"
sender_name: "<EMAIL_ADDRESS><IP_ADDRESS>__construct() must be an instance of Doctrine\Common\Persistence\ObjectManager, instance of Doctrine\ORM\EntityManager given, called in C:\wamp64\www\brouwers\var\cache\dev\ContainerMmxuCtr\srcApp_KernelDevDebugContainer.php on line 1664
Error on my browser
I have try to add : "doctrine/common":"^2.13" on my composer.json
The bug is still here ...
I don't know how to fix this.
Someone can help me ?
My composer.json
{
"type": "project",
"license": "proprietary",
"require": {
"php": "^7.1.3",
"ext-ctype": "*",
"ext-iconv": "*",
"friendsofsymfony/user-bundle": "^2.1",
"a2lix/translation-form-bundle": "^3.0",
"excelwebzone/recaptcha-bundle": "^1.5",
"doctrine/common":"^2.13",
"karser/karser-recaptcha3-bundle": "^0.1.8",
"knplabs/doctrine-behaviors": "^2.0",
"knplabs/knp-paginator-bundle": "^5.2",
"sensio/framework-extra-bundle": "^5.1",
"stof/doctrine-extensions-bundle": "^1.4",
"symfony/apache-pack": "^1.0",
"symfony/asset": "4.4.*",
"symfony/console": "4.4.*",
"symfony/dotenv": "4.4.*",
"symfony/expression-language": "4.4.*",
"symfony/flex": "^1.3.1",
"symfony/form": "4.4.*",
"symfony/framework-bundle": "4.4.*",
"symfony/http-client": "4.4.*",
"symfony/intl": "4.4.*",
"symfony/mailer": "4.4.*",
"symfony/monolog-bundle": "^3.1",
"symfony/orm-pack": "*",
"symfony/process": "4.4.*",
"symfony/security-bundle": "4.4.*",
"symfony/serializer-pack": "*",
"symfony/swiftmailer-bundle": "^3.4",
"symfony/translation": "4.4.*",
"symfony/twig-pack": "*",
"symfony/validator": "4.4.*",
"symfony/web-link": "4.4.*",
"symfony/webpack-encore-bundle": "^1.7",
"symfony/yaml": "4.4.*",
"twig/extensions": "^1.5",
"twig/extra-bundle": "^3.0",
"twig/twig": "^2.0"
},
"require-dev": {
"symfony/debug-pack": "*",
"symfony/maker-bundle": "^1.0",
"symfony/profiler-pack": "*",
"symfony/test-pack": "*"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"paragonie/random_compat": "2.*",
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php71": "*",
"symfony/polyfill-php70": "*",
"symfony/polyfill-php56": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "4.4.*"
}
}
}
Entity User :
<?php
// src/Entity/User.php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Assert\File(maxSize="2048k")
* @Assert\Image(mimeTypesMessage="Please upload a valid image.")
*/
protected $profilePictureFile;
// for temporary storage
private $tempProfilePicturePath;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
protected $profilePicturePath;
public function __construct()
{
parent<IP_ADDRESS>__construct();
// your own logic
$this->roles = array('ROLE_ADMIN');
$this->enabled = true;
}
public function getId(): ?int
{
return $this->id;
}
/**
* Asks whether the user is granted a particular role
*
* @return boolean
*/
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
/**
* Sets the file used for profile picture uploads
*
* @param UploadedFile $file
* @return object
*/
public function setProfilePictureFile(UploadedFile $file = null) {
// set the value of the holder
$this->profilePictureFile = $file;
// check if we have an old image path
if (isset($this->profilePicturePath)) {
// store the old name to delete after the update
$this->tempProfilePicturePath = $this->profilePicturePath;
$this->profilePicturePath = null;
} else {
$this->profilePicturePath = 'initial';
}
return $this;
}
/**
* Get the file used for profile picture uploads
*
* @return UploadedFile
*/
public function getProfilePictureFile() {
return $this->profilePictureFile;
}
/**
* Set profilePicturePath
*
* @param string $profilePicturePath
* @return User
*/
public function setProfilePicturePath($profilePicturePath)
{
$this->profilePicturePath = $profilePicturePath;
return $this;
}
/**
* Get profilePicturePath
*
* @return string
*/
public function getProfilePicturePath()
{
return $this->profilePicturePath;
}
/**
* Get the absolute path of the profilePicturePath
*/
public function getProfilePictureAbsolutePath() {
return null === $this->profilePicturePath
? null
: $this->getUploadRootDir().'/'.$this->profilePicturePath;
}
/**
* Get root directory for file uploads
*
* @return string
*/
protected function getUploadRootDir($type='profilePicture') {
// the absolute directory path where uploaded
// documents should be saved
return __DIR__.'/../../public/images/'.$this->getUploadDir($type);
}
/**
* Specifies where in the /web directory profile pic uploads are stored
*
* @return string
*/
protected function getUploadDir($type='profilePicture') {
// the type param is to change these methods at a later date for more file uploads
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'profilePicture';
}
/**
* Get the web path for the user
*
* @return string
*/
public function getWebProfilePicturePath() {
return '/'.$this->getUploadDir().'/'.$this->getProfilePicturePath();
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUploadProfilePicture() {
if (null !== $this->getProfilePictureFile()) {
// a file was uploaded
// generate a unique filename
$filename = md5(random_bytes(10));
$this->setProfilePicturePath($filename.'.'.$this->getProfilePictureFile()->guessExtension());
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*
* Upload the profile picture
*
* @return mixed
*/
public function uploadProfilePicture() {
// check there is a profile pic to upload
if ($this->getProfilePictureFile() === null) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getProfilePictureFile()->move($this->getUploadRootDir(), $this->getProfilePicturePath());
// check if we have an old image
if (isset($this->tempProfilePicturePath) && file_exists($this->getUploadRootDir().'/'.$this->tempProfilePicturePath)) {
// delete the old image
unlink($this->getUploadRootDir().'/'.$this->tempProfilePicturePath);
// clear the temp image path
$this->tempProfilePicturePath = null;
}
$this->profilePictureFile = null;
}
/**
* @ORM\PostRemove()
*/
public function removeProfilePictureFile()
{
if ($file = $this->getProfilePictureAbsolutePath() && file_exists($this->getProfilePictureAbsolutePath())) {
unlink($file);
}
}
}
fos_user.yaml
fos_user:
db_driver: orm # other valid values are 'mongodb' and 'couchdb'
firewall_name: main
user_class: App\Entity\User
from_email:
address: "bastien@no.com"
sender_name: "bastien@no.com"
Tks a lot
|
c8f9436c96206b2ae30a0815f46c997c510c5599d9cdefd91a431fa9fb6a10f3 | ['a210162a87c64bad90ec66d24ec8f6e5'] | If you want anybody (anonymous) to be able to access the Blob - you can put them into a container whose Public Access Level is set to Blob.
The documentation here shows how to do it through the portal and through code.
Then to share the URI of the Blob, use the CloudBlob.Uri property.
| 1b3430f01a4b22f67b7016ec64f444bcf8a138e8869707b0fbb82a7f093da5e4 | ['a210162a87c64bad90ec66d24ec8f6e5'] | I hope I'm not missing something here...
The URL you're using isn't the one that generates tokens for the Text-to-Speech API as documented here. (The "Oxford" that's referenced in your URL refers to the Project Oxford which Cognitive Services was formerly known as.)
Also, WebRequest is deprecated. Use the System.Net.Http package instead.
The code to invoke the new REST endpoint then would look something like:
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, "https://api.cognitive.microsoft.com/sts/v1.0/issueToken"))
{
request.Headers.Add("Ocp-Apim-Subscription-Key", "YOUR-KEY-HERE");
var response = await client.SendAsync(req);
var token = await response.Content.ReadAsStringAsync();
}
Finally, there are several client libraries that may get you around from writing any code to hit the REST services at all.
|
9f9bf0dbff18da4a95aafdabb908433823ed2d6c30e4db38d6154dcdb0abb144 | ['a21de59467a24a09ad4d5df9a7e3669d'] | If you have gmail, I recommend using the Gmail interface but also be sure to find the right extensions. Offline mail has been mentioned, but look to Checker Plus for Gmail This extension will make your experience better as it polls your accounts every few seconds and provides live notifications saving you the trouble of even keeping a tab of mail open.
| 7fed6793edb2f7e23bda3b47ecef60c1d3e28d9c800a20a457c59302fb23145c | ['a21de59467a24a09ad4d5df9a7e3669d'] | I'm not sure what those numbers mean. Pending sector count errors are caused by sectors that need to be remapped ([http://en.wikipedia.org/wiki/S.M.A.R.T.#Known_ATA_S.M.A.R.T._attributes](see this article)). As far as dealing with this, first you should update the disk firmware. This might stop the errors, but the problem could persist. If this is the case, second would be to clean wipe (use DBAN or `diskpart`) and see if the errors return. After those two, it might be time to invest in a new drive. |
7e61858da750abc98b90ea71150b176c70160467b8e0340f09d6e5e8ce3eed07 | ['a2255fb2e6a947c0be53fddbf9336fe9'] | Помогите разобраться в теоретических вопросах.
Я внутри своей компании разрабатываю ERP-систему, которая позволяет аккумулировать данные с производственных цехов и анализировать их. В качестве архитектуры системы я рассмотрел много вариантов и увидел, что многие системы реализуют так:
MVC - CORE WEB API - MYSQL
Правильно ли я понял функционал: MVC получается нужно для генерации интерфейса и получения данных от пользователя, а WEB API для получения данных из СУБД и обработки этих данных?
Можно ли на стороне клиента использовать целый спектр приложений UWP, Xamarin, MVC?
| eaf10938e24834afd37d29ce53b809c075d4cff1e117aff539cc8421f833031b | ['a2255fb2e6a947c0be53fddbf9336fe9'] | Есть 2 объекта, одним полем которого может являться List.
public class pDataStruct<T, O>
{
public String Name;
public T Tag;
public O Object;
}
Например полем Object такого объекта может являться List или просто bool. Как грамотно перегрузить Equals или сравнивать объекты по значению полей Tag и Object. Можно ли реализовать универсальную функцию сравнения, которая вызывала нужный Equals для сравнения полей по значению.
|
c0c125998c33ca55480031d8549572a36b937ecc4dfd9d093c5f04bd50ef968b | ['a22cd0540a784131998b55afbb400fe0'] | I'm trying to build a ROM for my phone (Xiaomi Mi A2 Lite) with SELinux enforcing. I've booted the phone successfully in permissive mode, however in the enforcing mode the Wi-fi won't work and SystemUI restarts every few minutes, displaying "Phone is starting..." instead of the launcher screen.
I used audit2allow to grab SELinux denials from my phone and added the output to the list of SELinux policies. However, when I try to compile the ROM, I get the following error:
device/xiaomi/daisy/sepolicy/daisy.te:224:ERROR 'unknown type qemu_hw_mainkeys_prop' at token ';' on line 75538:
allow platform_app qemu_hw_mainkeys_prop:file read;
After getting that error, I declared the type in my property.te file:
type qemu_hw_mainkeys_prop, property_type;
And after trying to compile the ROM again I get this:
device/xiaomi/daisy/sepolicy/property.te:3:ERROR 'Duplicate declaration of type' at token ';' on line 75576:
type qemu_hw_mainkeys_prop, property_type;
DT: https://github.com/tkchn/android_device_xiaomi_daisy/
| 759e40a4f1e2082041d3a5f0d36629f502cd7d730044d4e423317d81a7e831d5 | ['a22cd0540a784131998b55afbb400fe0'] | I'm trying to solve a problem with SystemUI's dimens.xml on my Pie-based ROM (it happens on stock as well).
Currently, when a notification arrives, it looks like
this (the notification icon is basically cropped from the left side).
The only thing that solves it is reducing rounded_corner_content_padding and status_bar_padding_start in SystemUI's dimens.xml. However, this also pushes the status bar edges way too close to the screen borders, which doesn't look pretty.
Is it possible to get rid of this part of the notification altogether? It seems redundant considering there are heads-up notifications already.
|
30d00b822ffb52dd9d0d7b6894f37883d24cff5b5df4ecadd5e562bfc43596d1 | ['a22f52cbffd84325bbc1f1c236ea471a'] | I have this function called numFunc(), which produces a numeric output.
I want to run this function 5 times and get the sum of all 5 outputs.
Here's what I've tried
function total(){
for (itr=1; itr<=5; itr++) //run the function 5 times
{
var numF = numFunc(); //store the output from the function in a variable
var sum = sum+numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();
But, what I get is the following output
3
3
3
3
3
NaN
What I want is the sum as a single value. How do I achieve this?
| 501338afa923ef240f5616dc6d9671b52e160829d8bfe5c583721eb5def7871b | ['a22f52cbffd84325bbc1f1c236ea471a'] | I have this code, where I run parseString()to extract some information from an xml file
function parseTime(){
var parser = new xml2js.Parser();
var data = fs.readFileSync('C:\\Temp\\tasks\\acis\\110-1100.sat\\110-1100.sat.response.xml', {encoding:'utf8'});
parser.parseString(data, function (err, result) {
var timeString = result.Message.Response[0].Events[0].MessageReportEvent[8].$.Message;
var fileTime = timeString.substr(13,20);
var filetimeVal = parseFloat(fileTime);
console.log(filetimeVal);
return filetimeVal;
});
};
What changes should I do to run parseString synchronously or is there a way to extract the xml data via a deifferent synchronous method
|
f5b1602f755ce2a8e42a70b63a0d381dd7b3018fd070fa2e51397afdd202434d | ['a235f604ea364fb681680f41e97b45e6'] | I am trying to delay validation of an custom textbox component. I only want to validate the input on blur. The existing component does not use ng-model inside the input but uses the ngModelController inside the controller of the custom component like so:
<input type="text" name="name" ng-required="true"/>
Can I still use ng-model-options onblur to delay the binding between the template and the controller?
If I'm using ngModelController inside component controller and not using ng-model inside the input element, can I still use ng-model-options in some way to delay input binding? Or is there another clever way to do this?
| a1e6d118b971d1d689913a7ec2cc3ac28c5e9f2f708930df469d384a7a433ef0 | ['a235f604ea364fb681680f41e97b45e6'] | I have a page of photos where I want to allow the user to click to enlarge that specific image into a bootstrap modal. How can I dynamically add each specific image to the modal on click..my html looks like this:
<div class="container fishing-picture-container">
<div ng-repeat="picture in fishingPictures" ng-if="$index % 3 == 0" class="row row-buffer">
<div class="col-md-4" ng-if="fishingPictures[$index].name">
<figure>
<img class="fishing-pics" ng-src="img/fishing/{{fishingPictures[$index].name}}" ng-click="showModal(fishingPictures[$index].name)" />
</figure>
</div>
<div class="col-md-4" ng-if="fishingPictures[$index + 1].name">
<figure>
<img class="fishing-pics" ng-src="img/fishing/{{fishingPictures[$index + 1].name}}" ng-click="showModal(fishingPictures[$index + 1].name)" />
</figure>
</div>
<div class="col-md-4" ng-if="fishingPictures[$index + 2].name">
<figure>
<img class="fishing-pics" ng-src="img/fishing/{{fishingPictures[$index + 2].name}}" ng-click="showModal(fishingPictures[$index + 2].name)" />
</figure>
</div>
</div>
</div>
<!-- Creates the bootstrap modal where the image will appear -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Image preview</h4>
</div>
<div class="modal-body">
<img src="" id="imagepreview">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
I was thinking I would call a function that would pass in the name of the image and then add that to the modal but doesn't seem to work. Does that seem to be the best way to go about it? Ideally, I would prefer to get a look similar to what it looks like when you click on the image in this link:
http://www.w3schools.com/howto/howto_css_modal_images.asp
|
63cb5155440eff5732207bcc9650c1230b9c55d108a03b0873b4e425202080af | ['a239ca839f5d44b3b6c1bf3cbfdb23dc'] | I've encountered the same problem and found a git repository of Azure samples for their computer vision service.
The relevant part is the Camera Capture module, specifically the Video Stream class.
You can see they've implemented a Queue that is being updated to keep only the latest frame:
def update(self):
try:
while True:
if self.stopped:
return
if not self.Q.full():
(grabbed, frame) = self.stream.read()
# if the `grabbed` boolean is `False`, then we have
# reached the end of the video file
if not grabbed:
self.stop()
return
self.Q.put(frame)
# Clean the queue to keep only the latest frame
while self.Q.qsize() > 1:
self.Q.get()
| 647e8135f69666f9350ef21206fd26d08fe49bb7c9e452aa6cddf0111af88d5e | ['a239ca839f5d44b3b6c1bf3cbfdb23dc'] | I'm running an experiment that include text documents that I need to calculate the (cosine) similarity matrix between all of them (to use for another calculation). For that I use sklearn's TfidfVectorizer:
corpus = [doc1, doc2, doc3, doc4]
vect = TfidfVectorizer(min_df=1, stop_words="english", use_idf=False)
tfidf = vect.fit_transform(corpus)
similarities = tfidf * tfidf.T
pairwise_similarity_matrix = similarities.A
The problem is that with each iteration of my experiment I discover new documents that I need to add to my similarity matrix, and given the number of documents I'm working with (tens of thousands and more) - it is very time consuming.
I wish to find a way to calculate only the similarities between the new batch of documents and the existing ones, without computing it all again one the entire data set.
Note that I'm using a term-frequency (tf) representation, without using inverse-document-frequency (idf), so in theory I don't need to re-calculate the whole matrix each time.
|
4479ea2c50e0e4e79eb3a0c4c9e4d52003138949e0337614f29c54a288e430b9 | ['a25683b99655436284a60077d96e8220'] | i have this link in a form :
<input type="file" class="multi" accept="doc|jpg|png|jpeg|tiff" maxlength="1" name="optionPhoto" id="optionPhoto" />
But if i want to upload a image i always want that a specific folder is opened.
for example : libs/uploads/
Now it depends when last folder is opened..
Any way i can do this in php or html ?
| b00156ba2e16bf563c712417d258c68445ff2593ebc8adebd8afc3ffcf58983d | ['a25683b99655436284a60077d96e8220'] | Oke after reading the documentation again http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
The ParamConverter only seems to work with request paramaters in the url for example a {id} parameter in the route.
It converts the {id} parameter to a object so it is required to have something like this in the route.
|
09c3031aa28f624f5b0fa06d202d33a6a40e9a5e4ff76513c4960e060a48897b | ['a261b63dde7d40cbb05f5d0cb540eb6f'] | I have tried changing the color of md-select underline with the following css:
md-input-container > md-select {
border-color: rgba(13, 148, 74, 0.82);
}
but it doesn't work.
Here is the html which contains the md-select which I want to customize:
<md-input-container>
<label>Items</label>
<md-select ng-model="selectedItem" md-selected-text="getSelectedText()" ng-required="true">
<md-optgroup label="items">
<md-option ng-value="item" ng-repeat="item in items">{{item}}</md-option>
</md-optgroup>
</md-select>
</md-input-container>
| 2e42cd6288e780bfe557db60b5339f9b87271c226c47b38d461ed99113b07906 | ['a261b63dde7d40cbb05f5d0cb540eb6f'] | I was wondering if there is a way of writing the appended function in a shorter way. The only difference between the code that's executed in the conditions is whether the datetime will be set to 00:00:00 (startOf('day')) or 23:59:59 (endOf('day')). This small difference led me to believe that there must be some way of dynamically setting the 3rd function call, but I don't know how.
function moveDateForOneMonth(date, type) {
if (type == 'startOf') {
return DateTime.fromJSDate(new Date(date))
.plus({ month: 1 })
.startOf('day')
.toMillis();
} else {
return DateTime.fromJSDate(new Date(date))
.plus({ month: 1 })
.endOf('day')
.toMillis();
}
}
The type parameter is either called with an argument 'endOf' or 'startOf', which corresponds to the name of the method that should be executed once .plus({month: 1}) is added to the date.
It'd be ideal if I could do something like:
function moveDateForOneMonth(date, type) {
return DateTime.fromJSDate(new Date(date))
.plus({ month: 1 })
.[type]('day')
.toMillis();
}
I apologise for my bad formatting and thank you for the answer in advance!
|
61d7df908df37c73ad9b8268fb1048f6fdbdc359c985c7fa311b08270edc0797 | ['a262ce7c3a714f1d80830a16ccd316d5'] | I would like to know what kind of data type this is, so I can decode it in PHP:
{s:31:"xperience_achievements_you_have";s:20:"You have %1$s points";s:26:"xperience_award_drawnin_of";s:69:"<b>%1$s</b> drawn-in of <a href="member.php?u=%2$s">%3$s</a> on %4$s.";s:26:"xperience_award_issued_for";s:68:"<b>%1$s</b> issued for <a href="member.php?u=%2$s">%3$s</a> on %4$s.";s:35:"xperience_award_issued_for_multiple";s:42:"<b>%1$s</b> issued for more than one user.";s:27:"xperience_award_issued_none";s:36:"<b>%1$s</b> has not yet been issued.";s:20:"xperience_awards_log";s:25:"Activity on issued Awards";s:28:"xperience_awards_used_fields";s:12:"Fields used:";s:17:"xperience_details";s:12:"Show details";s:14:"xperience_earn";s:11:"Earn Points";s:21:"xperience_earn_factor";s:6:"Factor";s:20:"xperience_earn_yours";s:5:"Yours";s:20:"xperience_gap_choose";s:16:"Give Away Points";s:27:"xperience_gap_choose_amount";s:66:"Enter the amount of points. They must be below the amount you have";s:26:"xperience_gap_choose_field";s:63:"Choose the category from where the points are being substracted";s:25:"xperience_gap_choose_user";s:49:"Type the name of the user who will receive points";s:23:"xperience_gap_give_away";s:9:"Give Away";s:18:"xperience_gap_more";s:31:"<a href="%1$s">Show more...</a>";s:18:"xperience_gap_text";s:156:"This is an automated message to inform you of a transfer to your Experience points.\r\n \r\n User [URL=%1$s]%2$s[/URL] has give away points to you:\r\n %3$s";s:19:"xperience_gap_title";s:46:"Experience: Notification of a Points Give Away";s:22:"xperience_gap_you_have";s:8:"You have";s:16:"xperience_groups";s:13:"Group Ranking";s:22:"xperience_groups_empty";s:17:"No Social Groups.";s:20:"xperience_groups_max";s:10:"Max Points";s:20:"xperience_groups_min";s:10:"Min Points";s:27:"xperience_groups_minmembers";s:96:"Only public and moderated Social Groups with at least %1$s members are included in this ranking.";s:17:"xperience_insight";s:18:"Insight Experience";s:26:"xperience_insight_featured";s:8:"Featured";s:20:"xperience_insight_sg";s:10:"Best Group";s:23:"xperience_insight_tipps";s:26:"Hints on collecting points";s:28:"xperience_insight_tipps_desc";s:77:"With Experience you can see how you progress compared to the whole Community.";s:28:"xperience_insight_tipps_earn";s:105:"Use the <a href="xperience.php?go=earn">Earn Points</a> feature to learn how you can collect points.<br/>";s:35:"xperience_insight_your_achievements";s:17:"Your Achievements";s:29:"xperience_insight_your_awards";s:11:"Your Awards";s:35:"xperience_most_achieved_achievement";s:25:"Most achieved Achievement";s:27:"xperience_most_active_user7";s:27:"This Week: Most Active User";s:36:"xperience_most_exclusive_achievement";s:26:"Most exclusive Achievement";s:25:"xperience_no_achievements";s:30:"No Achievements are available.";s:19:"xperience_no_awards";s:23:"No Awards are assigned.";s:23:"xperience_no_promotions";s:28:"No Users have been promoted.";s:28:"xperience_promotion_benefits";s:41:"Benefits you can get with this usergroup:";s:37:"xperience_promotion_benefits_assigned";s:21:"Assigned Permissions:";s:36:"xperience_promotion_benefits_revoked";s:20:"Revoked Permissions:";s:32:"xperience_promotion_benefits_set";s:47:"<i>%1$s</i> set from <b>%2$s</b> to <b>%3$s</b>";s:33:"xperience_promotion_benefits_sets";s:22:"Additional allowances:";s:27:"xperience_promotion_ingroup";s:21:"You are in this group";s:25:"xperience_promotion_jumps";s:59:"Promotions are possible to these usergroups and conditions:";s:30:"xperience_promotion_notingroup";s:32:"You are <i>not</i> in this group";s:25:"xperience_promotion_users";s:37:"%1$s Users promoted to this Usergroup";s:19:"xperience_recent_aa";s:41:"Recently assigned Awards and Achievements";s:25:"xperience_recent_activity";s:15:"Recent Activity";s:15:"xperience_stats";s:10:"Statistics";}
It looks like some kind of JSON but json_decode returns an empty string.
Thanks in advance.
| 185acd02a84ef1b97138d65c9e0a6338d8146378b2e07707a068bf736ab8c63c | ['a262ce7c3a714f1d80830a16ccd316d5'] | I had an issue where some of the above answers worked, but added a visible new line at the bottom - which was unacceptable, because the box had a background color. I fixed the justification with the code below:
jQuery:
$(".justify").each(function(index, element) {
var original_height = $(this).height();
$(this).append("<span style='display: inline-block;visibility: hidden;width:100%;'></span>");
$(this).height(original_height);
});
HTML:
<div class="justify" style="width:100px; background-color:#CCC">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
|
9795f169e23dc9b61818b77ea197541bc8eafbf66121a3ee7e3546ee27e1a58f | ['a26b778c27004b8083fc660a0bc99b1b'] | This works for me:
<?php
require ('facebook-sdk/autoload.php');
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\Entities\AccessToken;
use Facebook\GraphUser;
session_start();
?>
<html>
<head>
</head>
<body>
<div>Testing Notifications</div>
<?php
try {
FacebookSession<IP_ADDRESS>setDefaultApplication(
"{your_app_id}",
"{your_app_secret}"
);
$appSession = FacebookSession<IP_ADDRESS>newAppSession();
$request = new FacebookRequest(
$appSession,
'POST',
'/'. '{user_id}' .'/notifications',
array (
'href' => "index.php",
'template' => '{your_notification_text}',
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
echo 'Success?: ' . $graphObject->getProperty('success');
}catch(FacebookRequestException $ex) {
echo 'FacebookRequestException: ' . $ex->getMessage();
}catch(\Exception $ex) {
echo 'Exception' . $ex->getMessage();
}
?>
</body>
</html>
| 49ab6876cbef499e6809d70334c84f050948ffeec526c5997222d7e680b15244 | ['a26b778c27004b8083fc660a0bc99b1b'] | Thanks guys!
My approach:
<?php
session_start();
require ({your_php_sdk_path} . 'autoload.php');
use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
FacebookSession<IP_ADDRESS>setDefaultApplication({your_app_id},{your_app_secret});
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
}catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if (!is_null($session)) {
// Logged in
try {
//Get user name
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser<IP_ADDRESS>className());
$user_profile_name = $user_profile->getName();
//Get user picture
$request = new FacebookRequest(
$session,
'GET',
'/me/picture',
array (
'redirect' => false,
'height' => '135',
'width' => '135',
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
$user_profile_picture = $graphObject->getProperty('url');
} catch(FacebookRequestException $e) {
// When Facebook returns an error
} catch(Exception $e) {
// When validation fails or other local issues
}
}else{
//First time -> ask for authorization
$helper = new FacebookRedirectLoginHelper({your_canvas_url});
$login_url = $helper->getLoginUrl();
}
?>
And in your html put a javascript:
<script type="text/javascript">
if($login_url != null){
top.location.href = $login_url;
}
</script>
|
ce6084dcb3e9370a28455e29ad2521e49ad4411ec649f0510160cf15cfbec829 | ['a274bfd8269e400e9aa16fddae1b5efa'] | I created a WebView which loads google.com as test.
And at the bottom of the Layout ist a SeekBar.
If the Seekbar is changed to progress of 2 it shall for example load another page like stackoverflow.com.
If its progress is changed to 3,it shall load another page ( android.com)
My existing code is the following.
But I dont know how to fill the listener now.
Also with existing solutions it did not work.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView android:id="@+id/Viewing"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<SeekBar
android:id="@+id/seitenSwitcher"
android:layout_above="@+id/seitenSwitcher"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:max="15"
android:progress="0"
android:paddingLeft="4dip"
android:paddingRight="4dip"
/>
</RelativeLayout>
main.java
package testprojekt.homepageapp.application;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.SeekBar;
public class main extends Activity {
private WebView webv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webv = (WebView)findViewById(R.id.Viewing);
webv.setWebViewClient(new WebViewClient());
webv.getSettings().setJavaScriptEnabled(true);
webv.loadUrl("http://www.google.de");
}
public void onProgressChanged(SeekBar seitenSwitcher, int progress, boolean true) {
seitenSwitcher = (SeekBar) findViewById(R.id.seitenSwitcher);
seitenSwitcher.setOnSeekBarChangeListener(new sbListener());
}
}
sbListener.java
package testprojekt.homepageapp.application;
import android.widget.SeekBar;
public class sbListener implements SeekBar.OnSeekBarChangeListener {
???
}
| 31c8a08ef55616ffccfdd593bc318fa6daf97592a073442447644ee69034a9ce | ['a274bfd8269e400e9aa16fddae1b5efa'] | I have an Array of Websites in my code.
I added 2 buttons with the id button1 and button2.
They shall be used to navigate between the sites in Array.
private WebView webv;
private SeekBar seitenSwitcher;
private String[] websites = {
"000.htm",
"001.htm",
"002.htm",
"003.htm",
"004.htm",
"005.htm",
"006.htm",
"007.htm",
"008.htm",
"009.htm",
"010.htm",
"011.htm",
"012.htm",
"013.htm",
"014.htm",
"015.htm",
"016.htm",
};
public int pRog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webv = (WebView)findViewById(R.id.Viewing);
webv.setWebViewClient(new WebViewClient());
webv.getSettings().setJavaScriptEnabled(true);
webv.loadUrl(websites[0]);
pRog = 0;
Button button1= (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webv.loadUrl(websites[pRog--]);
pRog = pRog--; /** I can also leave this out and it works **/
}
});
Button button2= (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webv.loadUrl(websites[pRog++]);
}
});
The idea was that the int pRog is used to have the value of the string out of the array websites, which is currently shown.
And then with "pRog = pRog--" or "pRog = pRog++" change the value, to fit the currently shown string in the array.
It is working, but not as it should. I can go forward and backward, but the first touch of the button in the other way is not working.
Example:
I start at 000.htm, as you can see in the code.
First touch of button2. (nothing happens)
Second touch of button2. (webView loads 001.htm)
Third touch of button2. (webView loads 002.htm)
Fourth touch of button2. (webView load 003.htm)
First touch of button1. (webView loads 004.htm ! Instead of 002.htm)
Second touch of button1. (webView loads 003.htm ! now it is working.)
Touch of button2. (web View loads 002.htm ! Down instead of up)
Afterwards it also works again.)
It also works if i leave out pRog = pRog++ or --.
|
b7d2261a753160d1cbdccb4437a410350f0f42e05962aaa3350f17957a016d23 | ['a295b3e88a1d4ed3a276bfdcb462838c'] | I need bash script to count processes of SPECIFIC users or all users. We can enter 0, 1 or more arguments. For example
./myScript.sh root deamon
should execute like this:
root 92
deamon 8
2 users has total processes: 100
If nothing is entered as parameter, then all users should be listed:
uuidd 1
awkd 2
daemon 1
root 210
kklmn 6
5 users has total processes: 220
What I have till now is script for all users, and it works fine (with some warnings). I just need part where arguments are entered (some kind of filter results). Here is script for all users:
cntp = 0 #process counter
cntu = 0 #user counter
ps aux |
awk 'NR>1{tot[$1]++; cntp++}
END{for(id in tot){printf "%s\t%4d\n",id,tot[id]; cntu++}
printf "%4d users has total processes:%4d\n", cntu, cntp}'
| 8ee3cc4cf48eac3ce3a187bb942e8d99e293873e61d84c1a162f390c3277f978 | ['a295b3e88a1d4ed3a276bfdcb462838c'] | I am pretty new to tries. I found some solutions on net, but tries are defined in totally different way. I need solution for this type of trie.
What I need is function to print all words from trie in alphabetical order. As you can see, Insert and Search functions are done. Here is 2 header files, necessary for main code.
EntryType.h
#include <iostream>
using namespace std;
const int MAXLENGTH = 10;
class EntryType
{
public:
EntryType();
EntryType(char * key);
EntryType(EntryType & entry);
~EntryType();
bool operator== (const EntryType& item) const;
bool operator!= (const EntryType& item) const;
friend istream& operator>> (istream& is, EntryType& item);
friend ostream& operator<< (ostream& os, EntryType item);
void EntryKey(char word[]);
void PrintWord();
private:
char entryKey[MAXLENGTH];
};
ostream& operator<< (ostream& os, EntryType item)
{
os << item.entryKey;
return os;
}
EntryType<IP_ADDRESS>EntryType()
{
// empty instance constructor
}
EntryType::~EntryType()
{
// destructor
}
void EntryType<IP_ADDRESS>EntryKey(char word[])
{
for (int i = 0; i < 10; i++)
{
entryKey[i] = word[i];
}
}
void EntryType<IP_ADDRESS>PrintWord()
{
cout << entryKey << endl;
}
TrieType.h
#include <iostream>
#include <string>
#include "EntryType.h"
const int LETTERS = 26;
typedef char Key[MAXLENGTH];
struct Trienode
{
Trienode *branch[LETTERS];
EntryType *ref;
};
class TrieType
{
private:
Trienode * root;
public:
TrieType();
~TrieType();
TrieType(TrieType &originalTree);
void operator=(TrieType & originalTree);
void MakeEmpty();
void InsertTrie(Key newkey, EntryType *newentry);
EntryType * TrieSearch(Key target);
bool DeleteTrie(Key delkey);
void PrintTrie();
};
TrieType<IP_ADDRESS>TrieType()
{
root = NULL;
}
TrieType::~TrieType()
{
// destructor
}
TrieType<IP_ADDRESS>TrieType(TrieType &originalTree)
{
// constructor
}
EntryType *TrieType<IP_ADDRESS>TrieSearch(Key target)
{
int i;
Trienode * current = root;
for (i = 0; i < MAXLENGTH && current; i++)
if (target[i] == '\0')
break;
else
current =
current->branch[target[i] - 'a'];
if (!current)
return NULL;
else
if (!current->ref)
return NULL;
return current->ref;
}
Trienode *CreateNode()
{
int ch;
Trienode *newnode = new Trienode;
for (ch = 0; ch < LETTERS; ch++)
newnode->branch[ch] = NULL;
newnode->ref = NULL;
return newnode;
}
void TrieType<IP_ADDRESS><IP_ADDRESS>~EntryType()
{
// destructor
}
void EntryType::EntryKey(char word[])
{
for (int i = 0; i < 10; i++)
{
entryKey[i] = word[i];
}
}
void EntryType::PrintWord()
{
cout << entryKey << endl;
}
TrieType.h
#include <iostream>
#include <string>
#include "EntryType.h"
const int LETTERS = 26;
typedef char Key[MAXLENGTH];
struct Trienode
{
Trienode *branch[LETTERS];
EntryType *ref;
};
class TrieType
{
private:
Trienode * root;
public:
TrieType();
~TrieType();
TrieType(TrieType &originalTree);
void operator=(TrieType & originalTree);
void MakeEmpty();
void InsertTrie(Key newkey, EntryType *newentry);
EntryType * TrieSearch(Key target);
bool DeleteTrie(Key delkey);
void PrintTrie();
};
TrieType::TrieType()
{
root = NULL;
}
TrieType<IP_ADDRESS>~TrieType()
{
// destructor
}
TrieType::TrieType(TrieType &originalTree)
{
// constructor
}
EntryType *TrieType::TrieSearch(Key target)
{
int i;
Trienode * current = root;
for (i = 0; i < MAXLENGTH && current; i++)
if (target[i] == '\0')
break;
else
current =
current->branch[target[i] - 'a'];
if (!current)
return NULL;
else
if (!current->ref)
return NULL;
return current->ref;
}
Trienode *CreateNode()
{
int ch;
Trienode *newnode = new Trienode;
for (ch = 0; ch < LETTERS; ch++)
newnode->branch[ch] = NULL;
newnode->ref = NULL;
return newnode;
}
void TrieType::InsertTrie(Key newkey, EntryType *newentry)
{
int i;
Trienode *current;
if (!root)
root = CreateNode();
current = root;
for (i = 0; i < MAXLENGTH; i++)
if (newkey[i] == '\0')
break;
else
{
if (!current->branch[newkey[i] - 'a'])
current->branch[newkey[i] - 'a'] = CreateNode();
current = current->branch[newkey[i] - 'a'];
}
if (current->ref != NULL)
cout << "\nTried to insert a duplicate key." << endl;
else
current->ref = newentry;
}
|
6dfe072a13766449a9064189ac4c17f3b5705cebb4be753b9475a31a82263707 | ['a2962e40bd3e479ca46f22e546d2cb0b'] | parent component:
import React from "react";
import InputRow from "./InputRow";
const Bid: React.FunctionComponent = () => {
const inpVal = (d:string) => {
}
return (
<div style={{ display: "none" }} className="bid-container animated zoomIn" id="bid-modal">
<p>Mortage</p>
<div className="bid-row-container">
<p>Enter your bid</p>
<div className="bid-row">
<InputRow bid="Bid" inpVal={(inpVal: string)=>{console.log(inpVal)}} />
</div>
</div>
</div>
);
};
export default Bid;
child component:
import React from "react";
interface Props{
bid: string,
inpVal: (inpVal:string) => void;
}
const InputRow: React.FunctionComponent<Props> = (bid, inpVal) => {
return (
<div className="input-row">
<div>
<input type="text" onChange={(e) => { inpVal(e.target.value) }} />
<p>Rate</p>
</div>
<button className="bid-btn">{bid.bid}</button>
</div>
);
};
export default InputRow;
I am trying to pass the input value from the child component to the parent component but it is throwing error.
TypeError: inpVal is not a function.
| cc3b28025c079c603297f9cac167857779a57be32518ddfae8d936d6d9ee59f3 | ['a2962e40bd3e479ca46f22e546d2cb0b'] | i want to animate div box from left to righ and right to left.
suppose i have a 2 box with bootstrap classes`example :
<div class="container">
<div class="row">
<div class="col-md-6 id="leftToRight"></div>
<div class="col-md-6 id="RightToLeft"></div>
</div>
</div>
now i want to animate #leftToRight id from left to right and #RightToLeft from righ to left.
when scroll web page.
I see many website in which this type of animation is applied.
I am very curious to know how it is happen.
|
78377ddf3520893dc365343bf935c7b8774d748a93d49dd170a54aef6c60b3e8 | ['a2b0b629a56e451cbea790d013b25046'] | I Have a activity that opens the Camera by starting ACTION_IMAGE_CAPTURE Intent:
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
SimpleDateFormat dateformat = new SimpleDateFormat("ddMMyy");
File photo1 = new File(Environment
.getExternalStorageDirectory(), imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo1));
startActivityForResult(intent, 5);
After starting this intent it opens the image capture screen and sometimes after clicking on the capture button it doesn't return to my app (onActivityResult) it enforce me to take an image another time again, and it doen't close this screen only if i hit the back button.
I put a break point in OnActivityResult when debugging and it doen't stop in this method.
| a6ef94eed91a0d07049bd3e59ed580f7ea190df48b50585a0f25f98f28ebd6e2 | ['a2b0b629a56e451cbea790d013b25046'] | I'm using Apache commons Net library for FTP in my android app. and sometimes when using interrupted network or 2G network it doesn't send/download the file as expected.
I know that i have to check the boolean result of storeFile function in order to resend the file again and again...and sometime it sends corrupted files.
is there a library that uses Apache commons net library but it guarantees file sync process (including resuming, checking if the delivered file has the same size as the one in the client/server). is there any sync library that take care of all these checks for me.
the sync process doesn't have to be immediately. but with 100% guaranteed file delivery.
this issue does not happen when using WIFI.
|
da06130b09a167e4fb56b9dee541efcd901e3e60b4101794852a2d15da900ea5 | ['a2b0dc33821441ce8b2918dfb894d61c'] | Numpy's diff() function does what you ask.
Here is an example:
import numpy as np
a = np.arange(10) # this instantiates a numpy array containing values from 0 to 9
result = np.diff(a) # if you print this you'll see an array of 1 with length 9
If you want you can use slicing instead (I add this for all newbies, as an example of slicing), as follows:
result = a[1:] - a[:-1]
| a39738abc55ea373874021ebec8bd4e289e1accd4aafd5177adca9e654d2321d | ['a2b0dc33821441ce8b2918dfb894d61c'] | The following is a common function to sample from a probability vector
def sample(preds, temperature=1.0):
# helper function to sample an index from a probability array
preds = np.asarray(preds).astype('float64')
preds = np.log(preds) / temperature
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas)
Taken from here.
The temperature parameter decides how much the differences between the probability weights are weightd. A temperature of 1 is considering each weight "as it is", a temperature larger than 1 reduces the differences between the weights, a temperature smaller than 1 increases them.
Here an example using a probability vector on 3 labels:
p = np.array([0.1, 0.7, 0.2]) # The first label has a probability of 10% of being chosen, the second 70%, the third 20%
print(sample(p, 1)) # sample using the input probabilities, unchanged
print(sample(p, 0.1)) # the new vector of probabilities from which to sample is [ 3.54012033e-09, 9.99996371e-01, 3.62508322e-06]
print(sample(p, 10)) # the new vector of probabilities from which to sample is <PHONE_NUMBER>, <PHONE_NUMBER>, <PHONE_NUMBER>]
To see the new vector make sample return preds.
|
a9e40c0428d8e6e97961292077ce586dbed58d69e0b1db55354c80ff38566414 | ['a2b61e0b5b7a4c23a9fc7cf60b7bb8fa'] | This is so simple like if you are using hard values like setText="22sp.Now it might good your test mobile but good for every mobile screen so you have to create four folder
**hdpi,xhdpi,xxhdpi,xxxhdpi**
Copy the same file in these 4 folders and adjust it. when the app runs on any mobile Android framework automatically detects the screen and gets one of them.
Note: if you are using not hard values like matchparent etc then no need to create 4 duplicate files of that.
| 2795f403cc49c2609c81e34d072737ac7003c5b8fb3867cbca6c0494c51d5aa2 | ['a2b61e0b5b7a4c23a9fc7cf60b7bb8fa'] | What I recommend you is to go to files and select invalide and restart (you will find something like that).
If your problem has not been sort. Then uninstall the android studio but keep it in mind when you are uninstalling it only removes the setting, not the whole. The android studio asks you about this. So in this way within a few minutes you will be back to android studio and your AVD are also there.
|
80429ad90c57c3eb91bc7294aa5475ae166cbe2b3766815d9193f4887f112193 | ['a2bd0474370547e4bf5c80e85e2f6ec4'] | I thought this will be very simple but i think there is a bug when posting a variable from .ajax to a query. Is there any other way I ca get my result?
here is my jquery:
jQuery_1_4_2(document).ready(function()
{
jQuery_1_4_2('.mainfolder').live("click",function()
{
event.preventDefault();
var ID = jQuery_1_4_2(this).attr("id");
var dataString = 'folder_id='+ ID;
if(ID=='')
{
alert("Serious Error Occured");
}
else
{
jQuery_1_4_2.ajax({
type: "POST",
url: "display_folder.php",
data: dataString,
cache: false,
success: function(html){
jQuery_1_4_2(".right_file").prepend(html);
}
});
}
});
});
here is my display_folder.php
<?php
$folder_id = $_POST['folder_id'];
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>
Can anybody explain why this not work? i tried to echo $folder_id and it is working, but when you put it inside the query it is not working.
Note: This is not a dumb question where i forgot my connection of db. Thanks
| c07d3dd856cc2fa09a12416f80448ac957265fa52edc6ea002fdfd58ac8382f3 | ['a2bd0474370547e4bf5c80e85e2f6ec4'] | I just want to list all elements inside a div. If i have:
<div class="main_container">
<h1>Hello</h1>
<span>Hi</span>
<p>World</p>
</div>
I will want to have an ouput as a list of
h1
span
p
To have an idea, I am creating a DOM tree for my simple code snippet in my website. Please Help. Cheers!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.