text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Check to see if an event handler is attached to and event Add handler
if(!ClickHandled)
this.Click += (s, e) =>{ }
Remove handler:
if(ClickHandled)
this.Click -= (s, e) =>{ }
Is there a way to know if there is already an event handler attached to the control (and possibly get the list of them for example get the list of event handlers for click event)?
A: You can implement a class inherited from EventHandler. For this class you can implement any additional behavior you want. For instance, you can create a collection which will hold object-event maps and you can implement a method which searches for a given pair or pattern.
A: you can do this assuming you have access to source of class. Beware this way you are giving away the control of when to call all delegates to client of your class which is not a good idea. If you are not looking for the list of eventhandler but just want to know if event is subscribed.Probably you can use the other method which only tells whether click event is subscribed by anyone.
class MyButton
{
delegate void ClickHandler(object o ,EventArgs e);
public event ClickHandler Click;
......
public List<ClickHandler> ClickHandlerList
{
get
{
return ClickHandler.GetInovationList().Cast<ClickHandler>().ToList();
}
}
public bool IsClickEventSubcribed
{
get
{
return ClickHandler.GetInovationList().Cast<ClickHandler>().Any();
}
}
}
A: If the purpose of this is to stop sending signals to event listeners, wouldn't it be easier just wrap the sending by the check?
if (NotifyingEnabled)
{
SomeEvent.Raise(this);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35648181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generating packages by schema with wsimport and JAX bindings ignores Service classes I have a WSDL with multiple schemas and i'm trying to get wsimport to generate code into packages of my choice by schema. Using the -b option with a JAX-WS/JAX-B bindings file i managed to basically do that.
Only two classes are still generated into the default path: the service interface and the service implementation.
With the -p option on the other hand all the classes are generated into one package, but when i use that all the bindings defined in the external file are ignored.
What is the XPath for the service so that wsimport will generate those files into my packages?
I tried things like
<jaxws:bindings node="wsdl:definitions/wsdl:service"> ...
<jaxws:bindings node="wsdl:definitions/wsdl:binding"> ...
<jaxws:bindings node="wsdl:definitions/wsdl:portType"> ...
but neither had any effect.
Example:
<jaxws:bindings
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.0"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
wsdlLocation="myService.wsdl"
>
<!-- this works for schemas -->
<jaxws:bindings node="wsdl:definitions/wsdl:types/xsd:schema[@targetNamespace='http://org.com/service/1.0']" >
<jaxb:schemaBindings>
<jaxb:package name="com.myorg.service.v1" />
</jaxb:schemaBindings>
</jaxws:bindings>
<!-- the following does nothing -->
<jaxws:bindings node="wsdl:definitions/wsdl:service">
<jaxb:schemaBindings>
<jaxb:package name="com.myorg.service.v1" />
</jaxb:schemaBindings>
</jaxws:bindings>
</jaxws:bindings>
A: According to the JAX-WS specification, section 8.4.1, you don’t need an XPath to specify a package for JAX-WS classes like the service and port classes:
<jaxws:bindings wsdlLocation="http://example.org/foo.wsdl">
<jaxws:package name="com.acme.foo"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45062018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Script Reusability Need suggestions on -
I am new to selenium and implementing a POM based Robot framework. I need some suggestion on how to handle script changes in case if a functionality change that affects almost 15 scenario's.
Mostly the scripts are calling the page objects into an end to end scenario's, do we have any other approach to minimize the scripts changes?
A: If you're using Selenium with Python, you may be able to take advantage of the Page Object Model abilities of the SeleniumBase framework. Here's some code examples of that:
File 1 - google_objects.py:
class HomePage(object):
dialog_box = '[role="dialog"] div'
search_box = 'input[title="Search"]'
list_box = '[role="listbox"]'
search_button = 'input[value="Google Search"]'
feeling_lucky_button = """input[value="I'm Feeling Lucky"]"""
class ResultsPage(object):
google_logo = 'img[alt="Google"]'
images_link = "link=Images"
search_results = "div#center_col"
File 2 - google_test.py:
from seleniumbase import BaseCase
from .google_objects import HomePage, ResultsPage
class GoogleTests(BaseCase):
def test_google_dot_com(self):
self.open("https://google.com/ncr")
self.type(HomePage.search_box, "github")
self.assert_element(HomePage.list_box)
self.assert_element(HomePage.search_button)
self.assert_element(HomePage.feeling_lucky_button)
self.click(HomePage.search_button)
self.assert_text("github.com", ResultsPage.search_results)
self.assert_element(ResultsPage.images_link)
(Example taken from the SeleniumBase samples/ folder)
As seen above, reusable selectors/objects from File 1 are used in File 2, and could also be reused in many other files as well.
Here's a longer example, test_page_objects.py, which puts methods into page objects:
from seleniumbase import BaseCase
class GooglePage:
def go_to_google(self, sb):
sb.open("https://google.com/ncr")
def do_search(self, sb, search_term):
sb.type('input[title="Search"]', search_term + "\n")
def click_search_result(self, sb, content):
sb.click('a[href*="%s"]' % content)
class SeleniumBaseGitHubPage:
def click_seleniumbase_io_link(self, sb):
link = '#readme article a[href*="seleniumbase.io"]'
sb.wait_for_element_visible(link)
sb.js_click(link)
sb.switch_to_newest_window()
class SeleniumBaseIOPage:
def do_search_and_click(self, sb, search_term):
if sb.is_element_visible('[for="__search"] svg'):
sb.click('[for="__search"] svg')
sb.type('form[name="search"] input', search_term)
sb.click("li.md-search-result__item h1:contains(%s)" % search_term)
class MyTests(BaseCase):
def test_page_objects(self):
search_term = "SeleniumBase GitHub"
expected_text = "seleniumbase/SeleniumBase"
GooglePage().go_to_google(self)
GooglePage().do_search(self, search_term)
self.assert_text(expected_text, "#search")
GooglePage().click_search_result(self, expected_text)
SeleniumBaseGitHubPage().click_seleniumbase_io_link(self)
SeleniumBaseIOPage().do_search_and_click(self, "Dashboard")
self.assert_text("Dashboard", "main h1")
This provides a lot of different possibilities for script reusability.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70601786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting the list of modified fields in kendo grid? I have a kendo grid where editing is enabled.
I'm trying to:
*
*catch the event that is executed when a field is modified within the
grid.
*Get the list of fields (or cells) modified within the grid row.
Thanks
A: http://demos.telerik.com/kendo-ui/grid/editing-inline
This should get you where you need to go.
A: I have actually found what I needed.
The event I was looking for is save
It is fired after the item is edited, when the item is being saved. This is where I need to plug in my code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27988114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: SCNCamera.exposureOffset not working in iOS13 SCNCamera.wantsHDR is true. Yet any changes to SCNCamera.exposureOffset are not visible on iOS13 devices. But it is working perfectly fine on iOS12.
if let camera = self.sceneView.pointOfView?.camera {
camera.exposureOffset = -5
}
A: You said absolutely right, if someone wanna use exposureOffset instance property in SceneKit, he/she needs to activate a wantsHDR property at first:
var wantsHDR: Bool { get set }
In real code it might look like this:
sceneView.pointOfView!.camera!.wantsHDR = true
sceneView.pointOfView!.camera!.exposureOffset = -5
But there's a bug in iOS 13 and iOS 13 Simulator. However, if you disable allowsCameraControl, exposureOffset works fine.
sceneView.allowsCameraControl = false
Here's how exposureOffset changes from -2 to 2:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59133410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement undo function for HTML canvas using JavaScript? I am making a paint app in HTML using JavaScript and Flask-Python. Currently, I am able to draw lots of pencil drawings and shapes like rectangles/circles without any problem. The following functionality that I am trying to implement for this application is a undo function.
I store the strokes and the canvas drawing data in a JS object in the following manner:
canvas_data = { "pencil": [], "line": [], "rectangle": [], "circle": [], "eraser": [], "last_action": -1 };
All of the key names should be self-explanatory except last_action. I use this last_action variable to know the last category used by the user so that I can later use this information to implement the undo function.
var canvas = document.getElementById("paint");
var ctx = canvas.getContext("2d");
var pi2 = Math.PI * 2;
var resizerRadius = 8;
var rr = resizerRadius * resizerRadius;
var width = canvas.width;
var height = canvas.height;
var curX, curY, prevX, prevY;
var hold = false;
ctx.lineWidth = 2;
var fill_value = true;
var stroke_value = false;
var canvas_data = {
"pencil": [],
"line": [],
"rectangle": [],
"circle": [],
"eraser": [],
"last_action": -1
};
// //connect to postgres client
// var pg = require('pg');
// var conString = "postgres://postgres:database1@localhost:5432/sketch2photo";
// client = new pg.Client(conString);
function color(color_value) {
ctx.strokeStyle = color_value;
ctx.fillStyle = color_value;
}
function add_pixel() {
ctx.lineWidth += 1;
}
function reduce_pixel() {
if (ctx.lineWidth == 1) {
ctx.lineWidth = 1;
} else {
ctx.lineWidth -= 1;
}
}
function fill() {
fill_value = true;
stroke_value = false;
}
function outline() {
fill_value = false;
stroke_value = true;
}
function reset() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas_data = {
"pencil": [],
"line": [],
"rectangle": [],
"circle": [],
"eraser": [],
"last_action": -1
};
}
// pencil tool
function pencil(data, targetX, targetY, targetWidth, targetHeight) {
canvas.onmousedown = function(e) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
hold = true;
prevX = curX;
prevY = curY;
ctx.beginPath();
ctx.moveTo(prevX, prevY);
};
canvas.onmousemove = function(e) {
if (hold) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
draw();
}
};
canvas.onmouseup = function(e) {
hold = false;
};
canvas.onmouseout = function(e) {
hold = false;
};
function draw() {
ctx.lineTo(curX, curY);
ctx.stroke();
canvas_data.pencil.push({
"startx": prevX,
"starty": prevY,
"endx": curX,
"endy": curY,
"thick": ctx.lineWidth,
"color": ctx.strokeStyle
});
canvas_data.last_action = 0;
}
}
// line tool
function line() {
canvas.onmousedown = function(e) {
img = ctx.getImageData(0, 0, width, height);
prevX = e.clientX - canvas.offsetLeft;
prevY = e.clientY - canvas.offsetTop;
hold = true;
};
canvas.onmousemove = function linemove(e) {
if (hold) {
ctx.putImageData(img, 0, 0);
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(curX, curY);
ctx.stroke();
canvas_data.line.push({
"startx": prevX,
"starty": prevY,
"endx": curX,
"endY": curY,
"thick": ctx.lineWidth,
"color": ctx.strokeStyle
});
ctx.closePath();
canvas_data.last_action = 1;
}
};
canvas.onmouseup = function(e) {
hold = false;
};
canvas.onmouseout = function(e) {
hold = false;
};
}
// rectangle tool
function rectangle() {
canvas.onmousedown = function(e) {
img = ctx.getImageData(0, 0, width, height);
prevX = e.clientX - canvas.offsetLeft;
prevY = e.clientY - canvas.offsetTop;
hold = true;
};
canvas.onmousemove = function(e) {
if (hold) {
ctx.putImageData(img, 0, 0);
curX = e.clientX - canvas.offsetLeft - prevX;
curY = e.clientY - canvas.offsetTop - prevY;
ctx.strokeRect(prevX, prevY, curX, curY);
if (fill_value) {
ctx.fillRect(prevX, prevY, curX, curY);
}
canvas_data.rectangle.push({
"startx": prevX,
"starty": prevY,
"width": curX,
"height": curY,
"thick": ctx.lineWidth,
"stroke": stroke_value,
"stroke_color": ctx.strokeStyle,
"fill": fill_value,
"fill_color": ctx.fillStyle
});
canvas_data.last_action = 2;
}
};
canvas.onmouseup = function(e) {
hold = false;
};
canvas.onmouseout = function(e) {
hold = false;
};
}
// circle tool
function circle() {
canvas.onmousedown = function(e) {
img = ctx.getImageData(0, 0, width, height);
prevX = e.clientX - canvas.offsetLeft;
prevY = e.clientY - canvas.offsetTop;
hold = true;
};
canvas.onmousemove = function(e) {
if (hold) {
ctx.putImageData(img, 0, 0);
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
ctx.beginPath();
ctx.arc(Math.abs(curX + prevX) / 2, Math.abs(curY + prevY) / 2, Math.sqrt(Math.pow(curX - prevX, 2) + Math.pow(curY - prevY, 2)) / 2, 0, Math.PI * 2, true);
ctx.closePath();
ctx.stroke();
if (fill_value) {
ctx.fill();
}
canvas_data.circle.push({
"startx": prevX,
"starty": prevY,
"radius": curX - prevX,
"thick": ctx.lineWidth,
"stroke": stroke_value,
"stroke_color": ctx.strokeStyle,
"fill": fill_value,
"fill_color": ctx.fillStyle
});
canvas_data.last_action = 3;
}
};
canvas.onmouseup = function(e) {
hold = false;
};
canvas.onmouseout = function(e) {
hold = false;
};
}
// eraser tool
function eraser() {
canvas.onmousedown = function(e) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
hold = true;
prevX = curX;
prevY = curY;
ctx.beginPath();
ctx.moveTo(prevX, prevY);
};
canvas.onmousemove = function(e) {
if (hold) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
draw();
}
};
canvas.onmouseup = function(e) {
hold = false;
};
canvas.onmouseout = function(e) {
hold = false;
};
function draw() {
ctx.lineTo(curX, curY);
var curr_strokeStyle = ctx.strokeStyle;
ctx.strokeStyle = "#ffffff";
ctx.stroke();
canvas_data.pencil.push({
"startx": prevX,
"starty": prevY,
"endx": curX,
"endy": curY,
"thick": ctx.lineWidth,
"color": ctx.strokeStyle
});
canvas_data.last_action = 4;
ctx.strokeStyle = curr_strokeStyle;
}
}
// Function to undo the last action by the user
function undo_pixel() {
// Print that function has been called
console.log("undo_pixel() called");
// Print the last action that was performed
console.log(canvas_data.last_action);
switch (canvas_data.last_action) {
case 0:
case 4:
console.log("Case 0 or 4");
canvas_data.pencil.pop();
canvas_data.last_action = -1;
break;
case 1:
//Undo the last line drawn
console.log("Case 1");
canvas_data.line.pop();
canvas_data.last_action = -1;
break;
case 2:
//Undo the last rectangle drawn
console.log("Case 2");
canvas_data.rectangle.pop();
canvas_data.last_action = -1;
break;
case 3:
//Undo the last circle drawn
console.log("Case 3");
canvas_data.circle.pop();
canvas_data.last_action = -1;
break;
default:
break;
}
// Redraw the canvas
redraw_canvas();
}
// Function to redraw all the shapes on the canvas
function redraw_canvas() {
// Redraw all the shapes on the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw the pencil data
canvas_data.pencil.forEach(function(p) {
ctx.beginPath();
ctx.moveTo(p.startx, p.starty);
ctx.lineTo(p.endx, p.endy);
ctx.lineWidth = p.thick;
ctx.strokeStyle = p.color;
ctx.stroke();
});
// Redraw the line data
canvas_data.line.forEach(function(l) {
ctx.beginPath();
ctx.moveTo(l.startx, l.starty);
ctx.lineTo(l.endx, l.endy);
ctx.lineWidth = l.thick;
ctx.strokeStyle = l.color;
ctx.stroke();
});
// Redraw the rectangle data
canvas_data.rectangle.forEach(function(r) {
ctx.beginPath();
ctx.rect(r.startx, r.starty, r.width, r.height);
ctx.lineWidth = r.thick;
ctx.strokeStyle = r.color;
if (r.fill) {
ctx.fillStyle = r.fill_color;
ctx.fillRect(startx, starty, width, height);
}
ctx.stroke();
});
// Redraw the circle data
canvas_data.circle.forEach(function(c) {
// "startx": prevX, "starty": prevY, "radius": curX - prevX, "thick": ctx.lineWidth, "stroke": stroke_value, "stroke_color": ctx.strokeStyle, "fill": fill_value, "fill_color": ctx.fillStyle
ctx.beginPath();
ctx.arc(c.startx, c.starty, c.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.stroke();
if (c.fill) {
ctx.fillStyle = c.fill_color;
ctx.fill();
}
});
}
$("#paint1").mousedown(function(e) {
handleMouseDown(e);
});
$("#paint1").mouseup(function(e) {
handleMouseUp(e);
});
$("#paint1").mouseout(function(e) {
handleMouseOut(e);
});
$("#paint1").mousemove(function(e) {
handleMouseMove(e);
});
html {
min-width: 1500px;
position: relative;
}
#toolset {
width: 100px;
height: 340px;
position: absolute;
left: 0px;
top: 50px;
background: #35d128;
}
#paint {
position: absolute;
left: 130px;
top: 50px;
}
#colorset {
position: absolute;
left: 0px;
top: 450px;
width: 300px;
}
#title {
position: absolute;
left: 500px;
}
#penciltool {
background: #358128;
color: #f3f3f3;
width: 80px;
height: 25px;
border: 1px solid #33842a;
-webkit-border-radius: 0 15px 15px 0;
-moz-border-radius: 0 15px 15px 0;
box-shadow: rgba(0, 0, 0, .75) 0 2px 6px;
}
#linetool {
background: #358128;
color: #f3f3f3;
width: 80px;
height: 25px;
border: 1px solid #33842a;
-webkit-border-radius: 0 15px 15px 0;
-moz-border-radius: 0 15px 15px 0;
box-shadow: rgba(0, 0, 0, .75) 0 2px 6px;
}
#rectangletool {
background: #358128;
color: #f3f3f3;
width: 80px;
height: 25px;
border: 1px solid #33842a;
-webkit-border-radius: 0 15px 15px 0;
-moz-border-radius: 0 15px 15px 0;
box-shadow: rgba(0, 0, 0, .75) 0 2px 6px;
}
#circletool {
background: #358128;
color: #f3f3f3;
width: 80px;
height: 25px;
border: 1px solid #33842a;
-webkit-border-radius: 0 15px 15px 0;
-moz-border-radius: 0 15px 15px 0;
box-shadow: rgba(0, 0, 0, .75) 0 2px 6px;
}
#erasertool {
background: #358128;
color: #f3f3f3;
width: 80px;
height: 25px;
border: 1px solid #33842a;
-webkit-border-radius: 0 15px 15px 0;
-moz-border-radius: 0 15px 15px 0;
box-shadow: rgba(0, 0, 0, .75) 0 2px 6px;
}
#resettool {
background: #358128;
color: #f3f3f3;
width: 80px;
height: 25px;
border: 1px solid #33842a;
-webkit-border-radius: 0 15px 15px 0;
-moz-border-radius: 0 15px 15px 0;
box-shadow: rgba(0, 0, 0, .75) 0 2px 6px;
}
<html>
<head>
<title>Paint App</title>
</head>
<body>
<p style="text-align:left; font: bold 35px/35px Georgia, serif;">
PaintApp
<div align="right">
<link rel="stylesheet" type="text/css" href="style.css">
<body onload="pencil(`{{ data }}`, `{{ targetx }}`, `{{ targety }}`, `{{ sizex }}`, `{{ sizey }}`)">
<p>
<table>
<tr>
<td>
<fieldset id="toolset" style="margin-top: 3%;">
<br>
<br>
<button id="penciltool" type="button" style="height: 15px; width: 100px;" onclick="pencil()">Pencil</button>
<br>
<br>
<br>
<button id="linetool" type="button" style="height: 15px; width: 100px;" onclick="line()">Line</button>
<br>
<br>
<br>
<button id="rectangletool" type="button" style="height: 15px; width: 100px;" onclick="rectangle()">Rectangle</button>
<br>
<br>
<br>
<button id="circletool" type="button" style="height: 15px; width: 100px;" onclick="circle()">Circle</button>
<br>
<br>
<br>
<button id="erasertool" type="button" style="height: 15px; width: 100px;" onclick="eraser()">Eraser</button>
<br>
<br>
<br>
<button id="resettool" type="button" style="height: 15px; width: 100px;" onclick="reset()">Reset</button>
</fieldset>
</td>
<td>
<canvas id="paint" width="500vw" height="350vw" style="border: 5px solid #000000; margin-top: 3%;"></canvas>
</td>
</tr>
</table>
</p>
<fieldset id="colorset" style="margin-top: 1.8%;">
<table>
<tr>
<td><button style="height: 15px; width: 80px;" onclick="fill()">Fill</button>
<td><button style="background-color: #000000; height: 15px; width: 15px;" onclick="color('#000000')"></button>
<td><button style="background-color: #B0171F; height: 15px; width: 15px;" onclick="color('#B0171F')"></button>
<td><button style="background-color: #DA70D6; height: 15px; width: 15px;" onclick="color('#DA70D6')"></button>
<td><button style="background-color: #8A2BE2; height: 15px; width: 15px;" onclick="color('#8A2BE2')"></button>
<td><button style="background-color: #0000FF; height: 15px; width: 15px;" onclick="color('#0000FF')"></button>
<td><button style="background-color: #4876FF; height: 15px; width: 15px;" onclick="color('#4876FF')"></button>
<td><button style="background-color: #CAE1FF; height: 15px; width: 15px;" onclick="color('#CAE1FF')"></button>
<td><button style="background-color: #6E7B8B; height: 15px; width: 15px;" onclick="color('#6E7B8B')"></button>
<td><button style="background-color: #00C78C; height: 15px; width: 15px;" onclick="color('#00C78C')"></button>
<td><button style="background-color: #00FA9A; height: 15px; width: 15px;" onclick="color('#00FA9A')"></button>
<td><button style="background-color: #00FF7F; height: 15px; width: 15px;" onclick="color('#00FF7F')"></button>
<td><button style="background-color: #00C957; height: 15px; width: 15px;" onclick="color('#00C957')"></button>
<td><button style="background-color: #FFFF00; height: 15px; width: 15px;" onclick="color('#FFFF00')"></button>
<td><button style="background-color: #CDCD00; height: 15px; width: 15px;" onclick="color('#CDCD00')"></button>
<td><button style="background-color: #FFF68F; height: 15px; width: 15px;" onclick="color('#FFF68F')"></button>
<td><button style="background-color: #FFFACD; height: 15px; width: 15px;" onclick="color('#FFFACD')"></button>
<td><button style="background-color: #FFEC8B; height: 15px; width: 15px;" onclick="color('#FFEC8B')"></button>
<td><button style="background-color: #FFD700; height: 15px; width: 15px;" onclick="color('#FFD700')"></button>
<td><button style="background-color: #F5DEB3; height: 15px; width: 15px;" onclick="color('#F5DEB3')"></button>
<td><button style="background-color: #FFE4B5; height: 15px; width: 15px;" onclick="color('#FFE4B5')"></button>
<td><button style="background-color: #EECFA1; height: 15px; width: 15px;" onclick="color('#EECFA1')"></button>
<td><button style="background-color: #FF9912; height: 15px; width: 15px;" onclick="color('#FF9912')"></button>
<td><button style="background-color: #8E388E; height: 15px; width: 15px;" onclick="color('#8E388E')"></button>
<td><button style="background-color: #7171C6; height: 15px; width: 15px;" onclick="color('#7171C6')"></button>
<td><button style="background-color: #7D9EC0; height: 15px; width: 15px;" onclick="color('#7D9EC0')"></button>
<td><button style="background-color: #388E8E; height: 15px; width: 15px;" onclick="color('#388E8E')"></button>
</tr>
<tr>
<td><button style="height: 15px; width: 80px" onclick="outline()">Outline</button>
<td><button style="background-color: #71C671; height: 15px; width: 15px;" onclick="color('#71C671')"></button>
<td><button style="background-color: #8E8E38; height: 15px; width: 15px;" onclick="color('#8E8E38')"></button>
<td><button style="background-color: #C5C1AA; height: 15px; width: 15px;" onclick="color('#C5C1AA')"></button>
<td><button style="background-color: #C67171; height: 15px; width: 15px;" onclick="color('#C67171')"></button>
<td><button style="background-color: #555555; height: 15px; width: 15px;" onclick="color('#555555')"></button>
<td><button style="background-color: #848484; height: 15px; width: 15px;" onclick="color('#848484')"></button>
<td><button style="background-color: #F4F4F4; height: 15px; width: 15px;" onclick="color('#F4F4F4')"></button>
<td><button style="background-color: #EE0000; height: 15px; width: 15px;" onclick="color('#EE0000')"></button>
<td><button style="background-color: #FF4040; height: 15px; width: 15px;" onclick="color('#FF4040')"></button>
<td><button style="background-color: #EE6363; height: 15px; width: 15px;" onclick="color('#EE6363')"></button>
<td><button style="background-color: #FFC1C1; height: 15px; width: 15px;" onclick="color('#FFC1C1')"></button>
<td><button style="background-color: #FF7256; height: 15px; width: 15px;" onclick="color('#FF7256')"></button>
<td><button style="background-color: #FF4500; height: 15px; width: 15px;" onclick="color('#FF4500')"></button>
<td><button style="background-color: #F4A460; height: 15px; width: 15px;" onclick="color('#F4A460')"></button>
<td><button style="background-color: #FF8000; height: 15px; width: 15px;" onclick="color('FF8000')"></button>
<td><button style="background-color: #FFD700; height: 15px; width: 15px;" onclick="color('#FFD700')"></button>
<td><button style="background-color: #8B864E; height: 15px; width: 15px;" onclick="color('#8B864E')"></button>
<td><button style="background-color: #9ACD32; height: 15px; width: 15px;" onclick="color('#9ACD32')"></button>
<td><button style="background-color: #66CD00; height: 15px; width: 15px;" onclick="color('#66CD00')"></button>
<td><button style="background-color: #BDFCC9; height: 15px; width: 15px;" onclick="color('#BDFCC9')"></button>
<td><button style="background-color: #76EEC6; height: 15px; width: 15px;" onclick="color('#76EEC6')"></button>
<td><button style="background-color: #40E0D0; height: 15px; width: 15px;" onclick="color('#40E0D0')"></button>
<td><button style="background-color: #9B30FF; height: 15px; width: 15px;" onclick="color('#9B30FF')"></button>
<td><button style="background-color: #EE82EE; height: 15px; width: 15px;" onclick="color('#EE82EE')"></button>
<td><button style="background-color: #FFC0CB; height: 15px; width: 15px;" onclick="color('#FFC0CB')"></button>
<td><button style="background-color: #7CFC00; height: 15px; width: 15px;" onclick="color('#7CFC00')"></button>
</tr>
<tr>
<td><label>Line Width</label></td>
<td><button id="pixel_plus" type="button" onclick="add_pixel()" style="width: 25px;">+</button></td>
<td><button id="pixel_minus" type="button" onclick="reduce_pixel()" style="width: 25px;">-</button></td>
<td><button id="undo" type="button" onclick="undo_pixel()" style="width: 75px;">Undo</button></td>
</tr>
</table>
<br>
</fieldset>
<script src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="script.js"></script>
</body>
</html>
Here's what I tried:
*
*First, I made an undo_pixel() function that uses the last_action variable to pop the last element entered in the respective stack of the previous action
*Then I redrew the canvas using a redraw_canvas() function that clears the canvas and then redraws it using all the data points stored in the canvas_data object.
But what this is causing some unexpected behaviour that I cannot understand entirely. This is what's happening:
Sketch before undo:
Sketch after undo:
I think this is maybe because straight lines are being drawn between all the points being looped through, but I am not exactly sure how else to go about it. How do I correctly implement the redraw/undo function?
A: The immediate problem, causing the fan shape you observe, is caused by startx and starty remaining the same for each object entry in canvas_data.pencil array. This is because, startx and starty are assigned the values held in prevX and prevY, but these were set in the mousedown event listener and are not updated in the mousemove event listener.
This is fixed as follows:
Firstly, although not strictly necessary for funtion, remove the references to prevX and prevY from the mousedown event listener in the pencil function and set ctx.moveTo(curX, curY) - this is a little less confusing because the mousedown is where the draw begins from:
// inside pencil function;
canvas.onmousedown = function(e) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
hold = true;
ctx.beginPath();
ctx.moveTo(curX, curY); // prev -> cur;
};
Next, in the mousemove listener, add lines to update prevX and prevY:
// inside pencil function;
canvas.onmousemove = function(e) {
if (hold) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
draw();
prevX = curX; // new
prevY = curY; // new
}
};
These changes form the correct data object array with each object's startx and starty value now being set to the previous object's endx and endy value, as required.
However, there's another immediate problem: the undo_pixel function only fully executes on the first click to remove the last object of the pencil array (causing the last sliver of line captured by the last mousemove event to disappear as intended), but subsequent clicks (to remove successive parts of the line) are aborted.
I'm assuming the undo_pixel function is intended to remove a sliver for each click rather than the entire pencil line (see later if not).
The reason for the process to be aborted is because of resetting the canvas_data.last_action flag inside undo_pixel:
canvas_data.last_action = -1`
Because there is no case block in the switch statement for -1, nothing happens on subsequent clicks of the undo button;
Instead, the case block for the pencil should be:
case 4:
canvas_data.pencil.pop();
canvas_data.last_action = 4; // not -1;
break;
You have to leave it at 4 until another action is selected to undo or until the whole pencil line is removed and then move to the object drawn immediately before the lencil line (for which you will need to keep track of the order in which items were drawn).
I've made a working snippet with the above suggestions. You'll need to display it full page as the preview window is too small to see the line while you click the undo button. If you draw a short pencil sqiggle and repeatedly press the undo button, you'll see the line being 'undrawn'.
(I had to delete some of your other functions as I exceeded the allowed character limit for an answer)
var canvas = document.getElementById("paint");
var ctx = canvas.getContext("2d");
var pi2 = Math.PI * 2;
var resizerRadius = 8;
var rr = resizerRadius * resizerRadius;
var width = canvas.width;
var height = canvas.height;
var curX, curY, prevX, prevY;
var hold = false;
ctx.lineWidth = 2;
var fill_value = true;
var stroke_value = false;
var canvas_data = {
"pencil": [],
"line": [],
"rectangle": [],
"circle": [],
"eraser": [],
"last_action": -1
};
// //connect to postgres client
// var pg = require('pg');
// var conString = "postgres://postgres:database1@localhost:5432/sketch2photo";
// client = new pg.Client(conString);
function color(color_value) {
ctx.strokeStyle = color_value;
ctx.fillStyle = color_value;
}
function add_pixel() {
ctx.lineWidth += 1;
}
function reduce_pixel() {
if (ctx.lineWidth == 1) {
ctx.lineWidth = 1;
} else {
ctx.lineWidth -= 1;
}
}
function fill() {
fill_value = true;
stroke_value = false;
}
function outline() {
fill_value = false;
stroke_value = true;
}
function reset() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas_data = {
"pencil": [],
"line": [],
"rectangle": [],
"circle": [],
"eraser": [],
"last_action": -1
};
}
// pencil tool
function pencil(data, targetX, targetY, targetWidth, targetHeight) {
//prevX = 0; // new
//prevY = 0; // new
canvas.onmousedown = function(e) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
hold = true;
ctx.beginPath();
ctx.moveTo(curX, curY); // prev -> cur;
};
canvas.onmousemove = function(e) {
if (hold) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
draw();
prevX = curX; // new
prevY = curY; // new
}
};
canvas.onmouseup = function(e) {
hold = false;
};
canvas.onmouseout = function(e) {
hold = false;
};
function draw() {
ctx.lineTo(curX, curY);
ctx.stroke();
canvas_data.pencil.push({
"startx": prevX,
"starty": prevY,
"endx": curX,
"endy": curY,
"thick": ctx.lineWidth,
"color": ctx.strokeStyle
});
canvas_data.last_action = 0;
}
}
function undo_pixel() {
switch (canvas_data.last_action) {
case 0:
case 4:
canvas_data.pencil.pop();
canvas_data.last_action = 4; // not -1;
break;
case 1:
//Undo the last line drawn
console.log("Case 1");
canvas_data.line.pop();
canvas_data.last_action = -1;
break;
case 2:
//Undo the last rectangle drawn
console.log("Case 2");
canvas_data.rectangle.pop();
canvas_data.last_action = -1;
break;
case 3:
//Undo the last circle drawn
console.log("Case 3");
canvas_data.circle.pop();
canvas_data.last_action = -1;
break;
default:
break;
}
redraw_canvas();
}
function redraw_canvas() {
// Redraw all the shapes on the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw the pencil data
canvas_data.pencil.forEach(function(p) {
ctx.beginPath();
ctx.moveTo(p.startx, p.starty);
ctx.lineTo(p.endx, p.endy);
ctx.lineWidth = p.thick;
ctx.strokeStyle = p.color;
ctx.stroke();
});
// Redraw the line data
canvas_data.line.forEach(function(l) {
ctx.beginPath();
ctx.moveTo(l.startx, l.starty);
ctx.lineTo(l.endx, l.endy);
ctx.lineWidth = l.thick;
ctx.strokeStyle = l.color;
ctx.stroke();
});
}
<html>
<head>
<title>Paint App</title>
<script src="main.js" defer></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<body>
<p style="text-align:left; font: bold 35px/35px Georgia, serif;">
PaintApp
</body>
</body>
<div align="right">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<body onload="pencil(`{{ data }}`, `{{ targetx }}`, `{{ targety }}`, `{{ sizex }}`, `{{ sizey }}`)">
<p>
<table>
<tr>
<td>
<fieldset id="toolset" style="margin-top: 3%;">
<br>
<br>
<button id="penciltool" type="button" style="height: 15px; width: 100px;" onclick="pencil()">Pencil</button>
<br>
<br>
<br>
<button id="linetool" type="button" style="height: 15px; width: 100px;" onclick="line()">Line</button>
<br>
<br>
<br>
<button id="rectangletool" type="button" style="height: 15px; width: 100px;" onclick="rectangle()">Rectangle</button>
<br>
<br>
<br>
<button id="circletool" type="button" style="height: 15px; width: 100px;" onclick="circle()">Circle</button>
<br>
<br>
<br>
<button id="erasertool" type="button" style="height: 15px; width: 100px;" onclick="eraser()">Eraser</button>
<br>
<br>
<br>
<button id="resettool" type="button" style="height: 15px; width: 100px;" onclick="reset()">Reset</button>
</fieldset>
</td>
<td>
<canvas id="paint" width="500vw" height="350vw" style="border: 5px solid #000000; margin-top: 3%;"></canvas>
</td>
</tr>
</table>
</p>
<fieldset id="colorset" style="margin-top: 1.8%;">
<table>
<tr>
<td><button style="height: 15px; width: 80px;" onclick="fill()">Fill</button>
<td><button style="background-color: #000000; height: 15px; width: 15px;" onclick="color('#000000')"></button>
<td><button style="background-color: #B0171F; height: 15px; width: 15px;" onclick="color('#B0171F')"></button>
<td><button style="background-color: #DA70D6; height: 15px; width: 15px;" onclick="color('#DA70D6')"></button>
<td><button style="background-color: #8A2BE2; height: 15px; width: 15px;" onclick="color('#8A2BE2')"></button>
<td><button style="background-color: #0000FF; height: 15px; width: 15px;" onclick="color('#0000FF')"></button>
<td><button style="background-color: #4876FF; height: 15px; width: 15px;" onclick="color('#4876FF')"></button>
<td><button style="background-color: #CAE1FF; height: 15px; width: 15px;" onclick="color('#CAE1FF')"></button>
<td><button style="background-color: #6E7B8B; height: 15px; width: 15px;" onclick="color('#6E7B8B')"></button>
<td><button style="background-color: #00C78C; height: 15px; width: 15px;" onclick="color('#00C78C')"></button>
<td><button style="background-color: #00FA9A; height: 15px; width: 15px;" onclick="color('#00FA9A')"></button>
<td><button style="background-color: #00FF7F; height: 15px; width: 15px;" onclick="color('#00FF7F')"></button>
<td><button style="background-color: #00C957; height: 15px; width: 15px;" onclick="color('#00C957')"></button>
<td><button style="background-color: #FFFF00; height: 15px; width: 15px;" onclick="color('#FFFF00')"></button>
<td><button style="background-color: #CDCD00; height: 15px; width: 15px;" onclick="color('#CDCD00')"></button>
<td><button style="background-color: #FFF68F; height: 15px; width: 15px;" onclick="color('#FFF68F')"></button>
<td><button style="background-color: #FFFACD; height: 15px; width: 15px;" onclick="color('#FFFACD')"></button>
<td><button style="background-color: #FFEC8B; height: 15px; width: 15px;" onclick="color('#FFEC8B')"></button>
<td><button style="background-color: #FFD700; height: 15px; width: 15px;" onclick="color('#FFD700')"></button>
<td><button style="background-color: #F5DEB3; height: 15px; width: 15px;" onclick="color('#F5DEB3')"></button>
<td><button style="background-color: #FFE4B5; height: 15px; width: 15px;" onclick="color('#FFE4B5')"></button>
<td><button style="background-color: #EECFA1; height: 15px; width: 15px;" onclick="color('#EECFA1')"></button>
<td><button style="background-color: #FF9912; height: 15px; width: 15px;" onclick="color('#FF9912')"></button>
<td><button style="background-color: #8E388E; height: 15px; width: 15px;" onclick="color('#8E388E')"></button>
<td><button style="background-color: #7171C6; height: 15px; width: 15px;" onclick="color('#7171C6')"></button>
<td><button style="background-color: #7D9EC0; height: 15px; width: 15px;" onclick="color('#7D9EC0')"></button>
<td><button style="background-color: #388E8E; height: 15px; width: 15px;" onclick="color('#388E8E')"></button>
</tr>
<tr>
<td><button style="height: 15px; width: 80px" onclick="outline()">Outline</button>
<td><button style="background-color: #71C671; height: 15px; width: 15px;" onclick="color('#71C671')"></button>
<td><button style="background-color: #8E8E38; height: 15px; width: 15px;" onclick="color('#8E8E38')"></button>
<td><button style="background-color: #C5C1AA; height: 15px; width: 15px;" onclick="color('#C5C1AA')"></button>
<td><button style="background-color: #C67171; height: 15px; width: 15px;" onclick="color('#C67171')"></button>
<td><button style="background-color: #555555; height: 15px; width: 15px;" onclick="color('#555555')"></button>
<td><button style="background-color: #848484; height: 15px; width: 15px;" onclick="color('#848484')"></button>
<td><button style="background-color: #F4F4F4; height: 15px; width: 15px;" onclick="color('#F4F4F4')"></button>
<td><button style="background-color: #EE0000; height: 15px; width: 15px;" onclick="color('#EE0000')"></button>
<td><button style="background-color: #FF4040; height: 15px; width: 15px;" onclick="color('#FF4040')"></button>
<td><button style="background-color: #EE6363; height: 15px; width: 15px;" onclick="color('#EE6363')"></button>
<td><button style="background-color: #FFC1C1; height: 15px; width: 15px;" onclick="color('#FFC1C1')"></button>
<td><button style="background-color: #FF7256; height: 15px; width: 15px;" onclick="color('#FF7256')"></button>
<td><button style="background-color: #FF4500; height: 15px; width: 15px;" onclick="color('#FF4500')"></button>
<td><button style="background-color: #F4A460; height: 15px; width: 15px;" onclick="color('#F4A460')"></button>
<td><button style="background-color: #FF8000; height: 15px; width: 15px;" onclick="color('FF8000')"></button>
<td><button style="background-color: #FFD700; height: 15px; width: 15px;" onclick="color('#FFD700')"></button>
<td><button style="background-color: #8B864E; height: 15px; width: 15px;" onclick="color('#8B864E')"></button>
<td><button style="background-color: #9ACD32; height: 15px; width: 15px;" onclick="color('#9ACD32')"></button>
<td><button style="background-color: #66CD00; height: 15px; width: 15px;" onclick="color('#66CD00')"></button>
<td><button style="background-color: #BDFCC9; height: 15px; width: 15px;" onclick="color('#BDFCC9')"></button>
<td><button style="background-color: #76EEC6; height: 15px; width: 15px;" onclick="color('#76EEC6')"></button>
<td><button style="background-color: #40E0D0; height: 15px; width: 15px;" onclick="color('#40E0D0')"></button>
<td><button style="background-color: #9B30FF; height: 15px; width: 15px;" onclick="color('#9B30FF')"></button>
<td><button style="background-color: #EE82EE; height: 15px; width: 15px;" onclick="color('#EE82EE')"></button>
<td><button style="background-color: #FFC0CB; height: 15px; width: 15px;" onclick="color('#FFC0CB')"></button>
<td><button style="background-color: #7CFC00; height: 15px; width: 15px;" onclick="color('#7CFC00')"></button>
</tr>
<tr>
<td><label>Line Width</label></td>
<td><button id="pixel_plus" type="button" onclick="add_pixel()" style="width: 25px;">+</button></td>
<td><button id="pixel_minus" type="button" onclick="reduce_pixel()" style="width: 25px;">-</button></td>
<td><button id="undo" type="button" onclick="undo_pixel()" style="width: 75px;">Undo</button></td>
</tr>
</table>
<br>
</fieldset>
<script src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src=" {{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
Note about intended undo function
If I have misunderstood and the undo action is supposed to remove the entire last pencil shape for a single click, you have to change the way the pencil object array is structured.
At present, the array is structured like this:
[
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
},
// more data objects for each mousemove captured;
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
}
]
this means that removing the last object (which your .pop in case 4 does) removes only the sliver of the pencil line captured during the last mousemove event. This is ok if you want to fine tune a line (I think that's a good feature, and assuemed it you wanted it that way) but causes a problem if more than one separate pencil line is drawn. If there are two pencil lines, they are merged into one inside the pencil data array.
To deal with this you would have to re-structure the pencil array to hold descrete inner arrays for each line like this:
[
// first line array:
[
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
},
// more data objects for each mousemove captured;
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
}
],
// more line arrays;
// last line array:
[
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
},
// more data objects for each mousemove captured;
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
}
]
] // end of pencil array;
Under this structure, .pop will remove a whole line (which may be what you intended). It will also solve a bug where currently a redraw will join any separate lines into one line.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71718111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Async search with jquery, ajax and json I'm working on a project for school. in this project, I have to make an async search bar to search data in a table in CodeIgniter, and this has to be done with JSON. The async search is working, but I don't think the way I'm doing it is with JSON. I would appreciate some help on how to do this with JSON.
Jquery in my view : `
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"<?php echo base_url(); ?>ajaxsearch/fetch",
method:"POST",
data:{query:query},
success:function(json){
$('#result').html(json);
}
})
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
`
Controller : `
class Ajaxsearch extends CI_Controller {
function index()
{
$this->load->view('ajaxsearch');
}
function fetch()
{
$output = '';
$query = '';
$this->load->model('ajaxsearch_model');
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$data = $this->ajaxsearch_model->fetch_data($query);
$output .= '
<div class="table-responsive">
<table class="table table-striped">
<tr>
<th scope="row" >Channel Number</th>
<th scope="row">Channel Name</th>
</tr>
';
if($data->num_rows() > 0)
{
foreach($data->result() as $row)
{
$output .= '
<tr>
<td>'.$row->nr.'</td>
<td>'.$row->naam.'</td>
</tr>
';
}
}
else
{
$output .= '<tr>
<td colspan="5">No Data Found</td>
</tr>';
}
$output .= '</table>';
echo $output;
}
}`
Model :
`
<?php
class Ajaxsearch_model extends CI_Model
{
function fetch_data($query)
{
$this->db->distinct('nr');
$this->db->select("*");
$this->db->from("kanalen");
if($query != '')
{
$this->db->like('naam', $query);
}
$this->db->order_by('nr', 'DESC');
return $this->db->get();
}
}
?>`
Error on line 51 : Error
A: If you create the data as an array in your controller, then pass it back with json_encode() and render the output on the client-side, I think it is more what you are looking for. I excluded the Model, because it doesn't need to change, and the unchanged part of your jquery is omitted before/after the ...
Javascript:
...
function load_data(query)
{
$.ajax({
url:"<?php echo base_url(); ?>ajaxsearch/fetch",
method:"POST",
data:{query:query},
success:function(json){
handleOutput(json);
}
});
}
function handleOutput(json) {
var output = '<div class="table-responsive"><table class="table table-striped"><tr><th scope="row" >Channel Number</th><th scope="row">Channel Name</th></tr>';
if (json.length == 0) { // if no data is returned
output += '<tr><td colspan="5">No Data Found</td</tr>';
} else { // if data isn't returned
json.forEach(function(row) {
output += '<tr><td>'+row['nr']+'</td><td>'+row['naam']+'</td></tr>';
}
}
output += '</table></div>';
$('#result').html(output);
}
...
Controller:
class Ajaxsearch extends CI_Controller {
function index()
{
$this->load->view('ajaxsearch');
}
function fetch()
{
$query = '';
$this->load->model('ajaxsearch_model');
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$data = $this->ajaxsearch_model->fetch_data($query);
$retval = array();
if($data->num_rows() > 0)
{
$retval[] = array(
"nr" => $row->nr,
"naam" => $row->naam
);
}
return json_encode($retval);
}
}
Note: I condensed your code a bit. Hopefully, it is still easily read/understandable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50728235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I add multiple series to a Razor Helper Chart? http://www.asp.net/webmatrix/tutorials/7-displaying-data-in-a-chart goes over how to create simple charts and they are working, but I can't seem to figure out how to add two data series (from two separate DB queries) to the same chart.
A: Have you tried calling the AddSeries() method twice, once for each database?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4868590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Redux store is updating but the components not re-rendering I wrote this code a few months ago for learning rtk etc.
Now I installed react 18 for checking new features and try to use them, but my code is not working.
Here is my code. After adding todos and trying to change App or TodosList components you can see changes.
What is wrong with this code?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71676492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Debounce function does not reduce stutter with heavy computations I have some sliders, that when changed runs a fairly heavy computation function.
This results in some heavy stuttering when dragging the slider, and a generally bad experience overall.
So my idea was to use debouncing, so that if the last computation have not finished, it will be discarded and a new one with the latest input value will start instead.
The problem is that my debounce function only works if the computation takes less time than the animation frame request, and I don't know how I would make it cancel the currently running operation if it's not finished when the next value is being set.
function debounce(callback) {
let handle;
return function debounced(...args) {
return new Promise(resolve => {
if (handle !== undefined) {
cancelAnimationFrame(handle);
}
const delayed = () => {
resolve(callback.apply(this, args));
handle = undefined;
};
handle = requestAnimationFrame(delayed);
});
};
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49857819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring Data JPA Unidirectional OneToOne Mapping does not persist I have a Client datatype (representing a customer) which has a principal of type Person and a contact of type Contact (for contact details).
The Client datatype (with the mappings) is:
@Entity
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Access(AccessType.PROPERTY)
private Long id;
@Column(unique = true, updatable = false)
private String nk;
@Min(10000000000L)
private Long abn;
private String name;
@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
@JoinColumn(name = "person_id")
private Person principal;
@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
@JoinColumn(name = "contact_id")
private Contact contact;
public Client() {
this.nk = UUID.randomUUID().toString();
}
// remaining constructors, builders and accessors omitted for brevity
}
Using the Contact as an example (Person is structured the same way)
@Entity
public class Contact {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String phone;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String mobile;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String fax;
@OneToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@JoinColumn(name = "address_id")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Address address;
private String email;
public Contact() {
}
// remaining constructors, builders and accessors omitted for brevity
}
The Address datatype is also a unidirectional mapping. I could show Person and Address, but I'm pretty sure that nothing new will be understood from them.
Unfortunately, Client is twice the subject of a ManyToOne relationship with Aircraft, through owner and operator fields. I say unfortunately, because it complicates my question. The Aircraft datatype is as follows:
@Entity
public class Aircraft {
@Id
private String registration;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "casa_code")
private Casa casa;
private String manufacturer;
private String model;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-d")
private LocalDate manufacture;
@ManyToOne(cascade={CascadeType.PERSIST}, fetch = FetchType.EAGER)
private Client owner;
@ManyToOne(cascade={CascadeType.PERSIST}, fetch = FetchType.EAGER)
private Client operator;
private String base;
@OneToOne(cascade={CascadeType.ALL})
@JoinColumn(name = "airframe_id")
private Airframe airframe;
@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name = "ac_registration")
private Set<Prop> props;
@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name = "ac_registration")
private Set<Engine> engines;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-d")
private LocalDate lastUpdated;
public Aircraft() {
}
// remaining constructors, builders and accessors omitted for brevity
}
The controller method resposible for the save:
@RestController
@RequestMapping("/api")
public class AircraftController {
private static final Logger LOG = LoggerFactory.getLogger(AircraftController.class);
private AircraftService aircraftService;
@Autowired
public AircraftController(AircraftService aircraftService) {
this.aircraftService = aircraftService;
}
@Secured("ROLE_ADMIN")
@PostMapping(value="/maintainers/{mid}/aircrafts", produces = "application/json")
@ResponseStatus(value = HttpStatus.CREATED)
Response<Aircraft> create(@PathVariable("mid") Long mid, @RequestBody Aircraft request) {
return Response.of(aircraftService.create(request));
}
}
The service method:
public interface AircraftService {
Aircraft create(Aircraft aircraft);
// other interface methods omitted for brevity
@Service
class Default implements AircraftService {
private static final Logger LOG = LoggerFactory.getLogger(AircraftService.class);
@Autowired
AircraftRepository aircraftRepository;
@Transactional
public Aircraft create(Aircraft aircraft) {
LOG.debug("creating new Aircraft with {}", aircraft);
if (aircraft.getOwner() != null && aircraft.getOwner().getNk() == null) {
aircraft.getOwner().setNk(UUID.randomUUID().toString());
}
if (aircraft.getOperator() != null && aircraft.getOperator().getNk() == null) {
aircraft.getOperator().setNk(UUID.randomUUID().toString());
}
return aircraftRepository.save(aircraft);
}
}
}
and, finally, the repository:
@Repository
public interface AircraftRepository extends JpaRepository<Aircraft, String> {
}
When I supply the following JSON:
{
"registration":"VH-ZZZ",
"casa":null,
"manufacturer":"PITTS AVIATION ENTERPRISES",
"model":"S-2B",
"manufacture":"1983-01-2",
"owner":{
"id":null,
"nk":"84f5f053-82dd-4563-8158-e804b3003f3b",
"abn":null,
"name":"xxxxx, xxxxx xxxxxx",
"principal":null,
"contact":{
"id":null,
"phone":null,
"address":{
"id":null,
"line3":"PO Box xxx",
"suburb":"KARAMA",
"postcode":"0813",
"state":"NT",
"country":"Australia"
},
"email":null
}
},
"operator":{
"id":null,
"nk":"edfd3e41-664c-4832-acc5-1c04d9c673a3",
"abn":null,
"name":"xxxxx, xxxxx xxxxxx",
"principal":null,
"contact":{
"id":null,
"phone":null,
"address":{
"id":null,
"line3":"PO Box xxx",
"suburb":"KARAMA",
"postcode":"0813",
"state":"NT",
"country":"Australia"
},
"email":null
}
},
"base":null,
"airframe":{
"id":null,
"acRegistration":null,
"serialNumber":"5005",
"hours":null
},
"props":[
{
"id":null,
"acRegistration":"VH-ZZZ",
"engineNumber":1,
"make":"HARTZELL PROPELLERS",
"model":"HC-C2YR-4CF/FC8477A-4",
"casa":null,
"serialNumber":null,
"hours":null
}
],
"engines":[
{
"id":null,
"acRegistration":"VH-ZZZ",
"engineNumber":1,
"make":"TEXTRON LYCOMING",
"model":"AEIO-540",
"casa":null,
"serialNumber":null,
"hours":null
}
],
"lastUpdated":"2018-12-16"
}
To this test:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("embedded")
@EnableJpaRepositories({ "au.com.avmaint.api" })
@AutoConfigureMockMvc
public class AircraftControllerFunctionalTest {
private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
private HttpMessageConverter mappingJackson2HttpMessageConverter;
@TestConfiguration
static class ServiceImplTestContextConfiguration {
@Bean
public CasaFixtures casaFixtures() {
return new CasaFixtures.Default();
}
@Bean
public ModelFixtures modelFixtures() {
return new ModelFixtures.Default();
}
@Bean
public MaintainerFixtures maintainerFixtures() {
return new MaintainerFixtures.Default();
}
@Bean
public AircraftFixtures aircraftFixtures() {
return new AircraftFixtures.Default();
}
}
@Autowired
private WebApplicationContext context;
@Autowired
private MockMvc mvc;
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private ModelFixtures modelFixtures;
@Autowired
private MaintainerFixtures maintainerFixtures;
@Autowired
private AircraftFixtures aircraftFixtures;
Maintainer franks;
@Autowired
void setConverters(HttpMessageConverter<?>[] converters) {
this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream()
.filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter)
.findAny()
.orElse(null);
assertNotNull("the JSON message converter must not be null",
this.mappingJackson2HttpMessageConverter);
}
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
franks = maintainerFixtures.createFranksMaintainer();
}
@After
public void tearDown() {
maintainerFixtures.removeFranks(franks);
aircraftFixtures.killAircraft(aircrafts);
UserAndRoleFixtures.killAllUsers(userService, roleService);
}
@Test
public void doCreate() throws Exception {
File file = ResourceUtils.getFile("classpath:json/request/vh-zzz.json");
String json = new String(Files.readAllBytes(file.toPath()));
mvc.perform((post("/api/maintainers/{mid}/aircrafts", franks.getId())
.header(AUTHORIZATION_HEADER, "Bearer " + ModelFixtures.ROOT_JWT_TOKEN))
.content(json)
.contentType(contentType))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.payload").isNotEmpty())
.andExpect(jsonPath("$.payload.registration").value("VH-ZZZ"))
.andExpect(jsonPath("$.payload.manufacturer").value("PITTS AVIATION ENTERPRISES"))
.andExpect(jsonPath("$.payload.model").value("S-2B"))
.andExpect(jsonPath("$.payload.manufacture").value("1983-01-2"))
.andExpect(jsonPath("$.payload.owner.id").isNotEmpty())
.andExpect(jsonPath("$.payload.owner.nk").isNotEmpty())
.andExpect(jsonPath("$.payload.owner.contact").isNotEmpty())
.andExpect(jsonPath("$.payload.operator.id").isNotEmpty())
.andExpect(jsonPath("$.payload.operator.nk").isNotEmpty())
.andExpect(jsonPath("$.payload.operator.contact").isNotEmpty())
;
}
}
I have found that the two ManyToOne mappings in Aircraft are persisted, but the OneToOne mappings are not. Basically these two expectations fail:
.andExpect(jsonPath("$.payload.owner.contact").isNotEmpty())
.andExpect(jsonPath("$.payload.operator.contact").isNotEmpty())
I have tried a few Cascade options, such as ALL, MERGE etc and it looks like my example is pretty much like others out there. I realise that this is slightly unusual in that Address, Person and Contact do not contain references back to their parents, but I would have thought that this is the point of a unidirectional relationship. Does anyone know how to persist these?
UPDATE - On the create method in the AircraftService, I have tried saving the owner and operators separately with:
@Transactional
public Aircraft create(Aircraft aircraft) {
if (aircraft.getOwner() != null && aircraft.getOwner().getNk() == null) {
aircraft.getOwner().setNk(UUID.randomUUID().toString());
} else if (aircraft.getOwner() != null) {
if (aircraft.getOwner().getPrincipal() != null) {
LOG.debug("saving principal");
Person person = personRepository.save(aircraft.getOwner().getPrincipal());
aircraft.getOwner().setPrincipal(person);
}
if (aircraft.getOwner().getContact() != null) {
Contact contact = contactRepository.save(aircraft.getOwner().getContact());
aircraft.getOwner().setContact(contact);
}
}
if (aircraft.getOperator() != null && aircraft.getOperator().getNk() == null) {
aircraft.getOperator().setNk(UUID.randomUUID().toString());
if (aircraft.getOperator().getPrincipal() != null) {
Person person = personRepository.save(aircraft.getOperator().getPrincipal());
aircraft.getOperator().setPrincipal(person);
}
if (aircraft.getOperator().getContact() != null) {
Contact contact = contactRepository.save(aircraft.getOperator().getContact());
aircraft.getOperator().setContact(contact);
}
}
return aircraftRepository.save(aircraft);
}
I did this on the supposition that JPA doesn't know what to do with references to objects that don't exist yet.
But no change.
Other than saving the Contact and Person ids, this change makes no difference to the save repository, which still fails to link the Client to either the Contact or Person. Do I have to save the Contact and Person in a separate transaction, and then save the Client?
This is killing me: what's going on?
A: The issue was that I needed CascadeType.MERGE on the Aircraft entity:
@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
private Client owner;
@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
private Client operator;
Essentially, when JSON is input to a create operation, it appears to be indistinguishable from a MERGE operation (where a new entity is created and put under management, unlike PERSIST) and so a MERGE operation is passed into Client, not PERSIST (as I would have expected). This is why Person and Contact were not being persisted. I still don't understand why JSON input is being treated like a merge though - it doesn't make sense.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53806029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error passing array as parameter - Java A program I'm modifying is supposed to use a drawing panel to randomly move a square, starting from the center, either left or right and use an array to tally the position it moves to while the square stays on screen (the panel is 400 x 400 and the square is 10 x 10, so there are only 40 possible positions it can move to) After the square goes off screen, I have to print a histogram that shows how many times the square moved to that index (i.e if the square moved from the x coordinate of 200 to 190, index 19 would get a tally) Here is my code:
import java.awt.*;
import java.util.*;
public class RandomWalkCountSteps {
// DrawingPanel will have dimensions HEIGHT by WIDTH
public static final int HEIGHT = 100;
public static final int WIDTH = 400;
public static final int CENTER_X = WIDTH / 2;
public static final int CENTER_Y = HEIGHT / 2;
public static final int CURSOR_DIM = 10;
public static final int SLEEP_TIME = 25; // milliseconds
public static void main( String[] args ) {
DrawingPanel panel = new DrawingPanel( WIDTH, HEIGHT );
Random rand = new Random();
walkRandomly( panel, rand );
}
public static void walkRandomly( DrawingPanel panel, Random rand ) {
Graphics g = panel.getGraphics();
int[] positionCounts = new int[ WIDTH / CURSOR_DIM ];
// start in center of panel
int x = CENTER_X;
int y = CENTER_Y;
// Draw the cursor in BLACK
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
// randomly step left, right, up, or down
while ( onScreen( x, y ) ) {
panel.sleep( SLEEP_TIME );
// Show a shadow version of the cursor
g.setColor(Color.GRAY);
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
if ( rand.nextBoolean() ) { // go left
x -= CURSOR_DIM;
}
else { // go right
x += CURSOR_DIM;
}
positionCounts[ x / CURSOR_DIM ]++;
histogram(positionCounts, x, y);
// draw the cursor at its new location
g.setColor(Color.BLACK);
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
}
}
public static boolean onScreen( int x, int y ) {
return 0 <= x && x < WIDTH
&& 0 <= y && y < HEIGHT;
}
public static void histogram(int[] positionCounts, int x, int y) {
if (onScreen(x, y) == false) {
for (int i = 0; i < WIDTH / CURSOR_DIM; i++) {
System.out.print(i + ": ");
for (int j = 1; j <= positionCounts[i]; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
My problem was that I couldn't find a good place to initialize the array so that it wouldn't re-initialize every time I passed the x coordinate to the histogram method. Now that I thought I had it in the right place, I get this error message on both calls to histogram in the method walkRandomly "error: method histogram in class RandomWalkCountSteps cannot be applied to given types;" I'm fairly new to java and programming in general, so there's probably something I'm missing regarding arrays as parameters. Thanks in advance.
A: histogram takes two parameters, positionCounts of type int[] and x of type int. In walkRandomly, you call histogram twice: once with an argument positionCounts of type int[] and once with an argument x of type int. That’s why the compiler complains that the method ”cannot be applied to given types”: the method histogram(int[], int) can’t be applied to (called with) the given types, i.e., histogram(int[]) and histogram(int).
I’m not sure what you’re trying to do with this code, but I’d guess that you want remove the first call and change the second call (inside of the while loop) to histogram(positionCounts, x).
(You’ve edited your code, so my answer doesn’t make much sense.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36019234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Skip character from beginning of file I am reading a file by character but I want to skip number of character from the beginning of file. For example this is the content of file:
Hello. Read content by character
FileInputStream fis = new FileInputStream(file);
int skipNumberOfCharacter = 12;
char readCharacter;
int ch;
while ((ch = fis.read()) != -1) {
readCharacter = (char) ch;
System.out.print(readCharacter);
}
When file process it should remove first 12 character from the content and should return out put as:
content by character
A: There is a skip method in BufferedReader.
Probably you would like to have look at it.
BufferedReader#skip (long)
A: use fis.skip(12);
Or create a counter
int count = 12;
while (..) {
count--;
if (count > 0) continue;
// your code
}
A: You should be able to just do:
fis.read(new byte[12]);
A: Loop over fis.read() by skipNumberOFCharacter.
for(int i = 0; i < skipNumberOfCharacter; i++) fis.read();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11019614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Programmatically Installing Windows Service from Application I currently have a windows service that needs to run in the background while a main application I have written handles UI and other tasks. I install and maintain the GUI application using ClickOnce Deployment and would like to find a way to bundle my Windows Service in as well.
They are in separate projects at the moment since I was still learning how to use the Windows Service.
My question is, is it possible given MyService.exe that I install and start MyService.exe from MyApp.exe? I can assume that I have access to InstallUtil.exe and could write a script to install and run it manually, but I would like a cleaner solution if there is one.
The only resources I've found all seem to assume I want to have the Service install itself, which is not the case.
A: In general, ClickOnce can't be used to install services. There is typically a lack of permissions, but also the location is incorrect, etc. For details, see MSDN on Choosing Between ClickOnce and Windows Installer for more details.
If you want to install a service, you should do a traditional installation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24834977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android SupportMapFragment Error inflating fragment class Happy New Year All,
New with implementing Fragments in Android (and I have seen similar posts but I have not been able to get an answer for my problem), so here goes:
I wish to use SupportMapFragment (referenced from the support library v4) and I have created a class that extends FragmentActivity, called TripSummary.java:
package com.project.locationapp;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import android.os.Bundle;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class TripSummary extends android.support.v4.app.FragmentActivity {
private GoogleMap mMap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, LocationService.class);
stopService(intent);
setContentView(R.layout.activity_trip_summary);
createMap();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_trip_summary, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Content?
return super.onOptionsItemSelected(item);
}
private void createMap(){
//if a map has not already been instantiated it'll return null
if(mMap == null){
//instantiate map
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
//check it has been instantiated
if(mMap != null){
Toast.makeText(this, "map done", Toast.LENGTH_SHORT)
.show();
//Manipulate map here (add coordinates/polylines from trip etc etc.)
}
}
}
}
Which gets a layout from activity_trip_summary.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tripSummary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@string/trip_summary"
tools:context=".Start" />
<TextView
android:id="@+id/tripDetails"
android:layout_below="@id/tripSummary"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@string/awaiting_location"
tools:context=".Start" />
<Fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_below="@id/tripDetails"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
AndroidManifest.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.project.locationapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<permission
android:name="com.project.locationapp.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.project.locationapp..permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.project.locationapp.Start"
android:label="@string/title_activity_start" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.project.locationapp.LocationService" />
<activity
android:name="com.project.locationapp.TripSummary"
android:label="@string/title_activity_trip_summary" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.project.locationapp.Start" />
</activity>
<activity
android:name="com.project.locationapp.ViewTrips"
android:label="@string/title_activity_view_trips" >
</activity>
<activity
android:name="com.project.locationapp.TripDetail"
android:label="@string/title_activity_trip_detail" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="<-- My Key -->"/>
</application>
</manifest>
The problem I am having in that each time I try to load the activity TripSummary, I get a 'Sorry! stopped unexpectedly' dialog and the app crashes.
LogCat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.locationapp/com.project.locationapp.TripSummary}: android.view.InflateException: Binary XML file line #24: Error inflating class Fragment
I am referencing the google-play-services_lib library (which is also in my workspace) and I also have a copy of android-support-v4.jar in /libs directory within my project.
If you know an answer to my problem, please share!
Thanks in advance.
A: Please replace:
<Fragment
with:
<fragment
Also, you can get rid of the redundant/incorrect namespace declarations in that element.
Also also, in the future, post the complete stack trace, not just part of one line, to make it easier for people to help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14113987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php exec() responding differently from windows 8 metro app I wanted to change the tile icons for desktop applications in the new windows 8 start menu.
So they would fit in with the other metro apps.
I made a simple metro app that calls a simple localhost php file
<?php
// check if the chrome is in the task list
exec('tasklist /FI "IMAGENAME eq chrome.exe" 2>NUL | find /I /N "chrome.exe">NUL');
// get a return value I can check
$runing = exec('if "%ERRORLEVEL%"=="0" echo Programm is running');
if ($runing === 'Programm is running'){
// the program is open already
echo $runing;
} else {
// the program is not running and should be opened
exec('C:\Users\Gerdy\AppData\Local\Google\Chrome\Application\chrome.exe');
}
?>
If I launch this file from chrome it echos "Programm is running".
That's great!
If I launch it from windows start and Chrome is not running, Chrome does not start.
If I exclude the if statement and just run.
exec('C:\Users\Gerdy\AppData\Local\Google\Chrome\Application\chrome.exe');
From the start menu.
It will open a new Chrome window regardless of if chrome is already open.
So I guess my question is :
What can I do that will allow my php file to check if chrome is open and if it is not , to open it?
This model actually works for any other program just not browsers.
My best guess is that it has do less with my commands and more to do with chrome itself.
It could be a target that I need to add, I don't know.
A: You can use Windows Management Instrumentation:
If you have not used wmic before you should install it by running wmic from cmd.exe.
It should then say something like:
WMIC Installing... please wait.
After that wmic is ready for use:
function getProcessId( $imagename ) {
ob_start();
passthru('wmic process where (name="'.$imagename.'") get ProcessId');
$wmic_output = ob_get_contents();
ob_end_clean();
// Remove everything but numbers and commas between numbers from output:
$wmic_output = preg_replace(
array('/[^0-9\n]*/','/[^0-9]+\n|\n$/','/\n/'),
array('','',','),
$wmic_output );
if ($wmic_output != '') {
// WMIC returned valid PId, should be safe to convert to int:
$wmic_output = explode(',', $pids);
foreach ($wmic_output as $k => $v) { $wmic_output[$k] = (int)$v; }
return $wmic_output;
} else {
// WMIC did not return valid PId
return false;
}
}
// Find out process id's:
if ($pids = getProcessId( "chrome.exe" )) {
foreach ($pids as $pid) {
echo "Chrome.exe is running with pid $pid";
}
} else {
echo "Chrone.exe is not running";
}
I have not tested this and just wrote it out of my head so there might be some fixing and you should check wmic's output by running it from commandline with same args to see if preg_replace() is doing it right (get pid from wmic's output).
UPDATE:
Tested and it seems that wmic does not return any status codes so updated my php function to reflect this bahavior.
UPDATE:
Now it handles multiple processes too and returns all pids as indexed array or false when no process running.
About WMI:
Windows Management Instrumentation is very powerful interface and so is wmic commandline tool. Here is listed some of WMI features
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9763006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Android ListView Replycating its values I am trying to delete my database child while LongItemClick using the following code. Remove procedure is working fine. But when I try to long press its replicating the ListView again and again. I didn't added any code for that in my setOnItemLongClickListener. Why its happening like this. I couldn't able to find from where its happening.
private void showList() {
Bundle bundle = getIntent().getExtras();
final String retrievedName = bundle.getString("Name");
final String retrievedMonth = bundle.getString("Month");
customerList = findViewById(R.id.customerlistView);
progress = findViewById(R.id.progress_bar_cust_load);
progress.setVisibility(View.VISIBLE);
customerArray.clear();
customerList.invalidateViews();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(retrievedName);
DatabaseReference NameRef = ref.child(retrievedMonth);
NameRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
final String name = postSnapshot.getKey();
customerArray.add(name);
customerList.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, customerArray));
progress.setVisibility(View.INVISIBLE);
}
if(customerArray.size()==0){
progress.setVisibility(View.INVISIBLE);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("name", "load:onCancelled", databaseError.toException());
}
});
customerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
progress.setVisibility(View.VISIBLE);
customerList.invalidateViews();
final String selectedFromList =(customerList.getItemAtPosition(position).toString());
Bundle bundle = getIntent().getExtras();
final String retrievedName = bundle.getString("Name");
final String retrievedMonth = bundle.getString("Month");
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference retrieveStatus = ref.child(retrievedName).child(retrievedMonth).child(selectedFromList).child("status");
retrieveStatus.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String status=dataSnapshot.getValue(String.class);
String ID= FirebaseAuth.getInstance().getUid();
DatabaseReference details_edit=ref.child(retrievedName).child(retrievedMonth).child(selectedFromList).child("status");
details_edit.setValue("Dropped");
DatabaseReference status_db = FirebaseDatabase.getInstance().getReference().child(ID)
.child("Customer Status").child("Dropped").child(selectedFromList);
Map statusPost = new HashMap();
statusPost.put("name", selectedFromList);
status_db.setValue(statusPost);
if(!status.equals("Dropped")){
assert ID != null;
DatabaseReference remove = ref.child(ID).child("Customer Status")
.child(status).child(selectedFromList);
remove.removeValue();
}else {
}
progress.setVisibility(View.INVISIBLE);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return true;
}
});
}
A: Okay I think the problem is this:
1) You use a Value Event to listen to the data (keep in mind that this listener is very active).
2) Then when you long click you update a certain value in the database.
3) Because the ValueEventListener is very active it will respond to the change, and re populate the list.
Okay this is my analysis according to your code.
Possible Solution:
Try to listen once when you populate data.
So instead of this in the (showList() method):
NameRef.addValueEvent......
use this:
NameRef.addListenerForSingleValueEvent(.....)
Hope it helps fix the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51012107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to properly parse out error code from lambda response in openapi api-gateway I am setting up an endpoint for a lambda in api-gateway using openapi. This lambda will need to be be able to return 400/500 error codes for internal errors/bad requests. To this end I have tried to format the x-amazon-apigateway-integration section of the openapi json document for this endpoint as follows:
"x-amazon-apigateway-integration": {
...
"responses": {
".*statusCode\\\":400.*": {
"statusCode": "400",
"responseTemplates": {
"application/json": "#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage'))) \n{ \"message\" : \"$errorMessageObj.message\"}"
}
}
}
}
The raw output from my lambda (i.e. before transformations) looks like this:
"{\"statusCode\":400,\"message\":\"Invalid request parameters\"}"
My expectation would be that the final response would have an error code of 400 and the object returned to my client would be
{
"message": "Invalid request parameters"
}
But I am getting the full untransformed response object back with a response code of 200 (the default). I have referenced this aws-blog-post which towards the bottom has the regex I am attempting to use. It passes a regex-parser So I am not understanding why I am still getting the default response back. I am using openapi v3. What is is that I am missing here?
A: I figured it out. In the lambda you need to throw an error with the response code you want parsed out. If you simply return it assumes correct execution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58458992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Exception has occurred. _TypeError (type '_InternalLinkedHashMap' is not a subtype of type 'List') in flutter using getx I AM TRYTING TO GET LIST OF ALL ITEMS FROM REST API USING GETX BUT THIS ERROR IS BEING THROWN ON FORM LOAD "Exception has occurred. _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List')" I DON'T KNOW WHY
HERE IS MY MODEL FILE
import 'dart:convert';
import 'package:foodello/model/ShowListing.dart';
import 'package:http/http.dart' as http;
class ApiManager {
static Future getShowList() async {
String baseURL = 'https://westmarket.herokuapp.com/api/v1';
String userId = '62f4ecf82b6e81e77059b332';
String url = baseURL + '/user/:$userId/products';
final response = await http.get(Uri.parse(url));
List jsonResponse = json.decode(response.body);
return jsonResponse.map((item) => ShowList.fromJson(item)).toList();
}
}
HERE IS MY API FILE
import 'dart:ffi';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:foodello/model/ShowListing.dart';
import 'package:get/get.dart';
import 'package:foodello/services/apiManager.dart';
class HomeController extends GetxController {
var showlist = <ShowList>[].obs;
@override
void onInit() {
fetchShowList();
super.onInit();
}
void fetchShowList() async {
var post = ApiManager.getShowList();
if (post != null) {
showlist.value = await post;
}
}
}
HERE IS MY HOME PAGE WHERE I'M CALLING THE DATA
Obx(
() => Expanded(
child: ListView.builder(
itemCount: controller.showlist.length,
itemBuilder: (BuildContext context, index) {
var singlePost = controller.showlist[index];
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
height: 200,
width: 100,
child: Column(
children: [
Text(singlePost.products.data[index].name),
Text(singlePost.products.data[index].price
.toString()),
Text(singlePost
.products.data[index].initialQuantity
.toString()),
Text(singlePost.products.data[index].soldQuantity
.toString()),
],
),
import 'dart:convert';
ShowList showListFromJson(String str) => ShowList.fromJson(json.decode(str));
String showListToJson(ShowList data) => json.encode(data.toJson());
class ShowList {
ShowList({
required this.products,
});
Products products;
factory ShowList.fromJson(Map<String, dynamic> json) => ShowList(
products: Products.fromJson(json["products"]),
);
Map<String, dynamic> toJson() => {
"products": products.toJson(),
};
}
class Products {
Products({
required this.message,
required this.success,
required this.statusCode,
required this.data,
});
String message;
bool success;
int statusCode;
List<Datum> data;
factory Products.fromJson(Map<String, dynamic> json) => Products(
message: json["message"],
success: json["success"],
statusCode: json["statusCode"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"message": message,
"success": success,
"statusCode": statusCode,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
required this.id,
required this.name,
required this.price,
required this.initialQuantity,
required this.soldQuantity,
required this.createdAt,
required this.updatedAt,
required this.v,
});
String id;
String name;
int price;
int initialQuantity;
int soldQuantity;
DateTime createdAt;
DateTime updatedAt;
int v;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["_id"],
name: json["name"],
price: json["price"],
initialQuantity: json["initialQuantity"],
soldQuantity: json["soldQuantity"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"_id": id,
"name": name,
"price": price,
"initialQuantity": initialQuantity,
"soldQuantity": soldQuantity,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"__v": v,
};
}
A: Seeing the error i assume that ShowList.fromJson requires a list but the code written is passing a map.. you can try like this
List jsonResponse = json.decode(response.body);
return ShowList.fromJson(jsonResponse);
You havecreated a method to convert the data
showListFromJson(String str)
This can be used directly to set the data like
ShowList _showList = showListFromJson(response.body);
A: json.decode returns either dynamic or List<dynamic>
If your response.body is List of items do it as follows
final jsonResponse = json.decode(response.body) as List<dynamic>;
return jsonResponse.map((e) => ShowList.fromJson(e as Map<String, dynamic>)).toList();
A: The error means the api is returning a map instead of the list your are expecting, so the first thing you have to do is to print your response.body to be sure of whats coming from the api
I have tested the api it seems the message it's returning is this:
{
"result": "Unauthorized, Access Denied",
"status": 401
}
which means the api is missing an authorization token
so try this:
static Future getShowList() async {
try {
String baseURL = 'https://westmarket.herokuapp.com/api/v1';
String userId = '62f4ecf82b6e81e77059b332';
String url = baseURL + '/user/:$userId/products';
final response = await http.get(
Uri.parse(url),
headers: {
'Authorization': '<your token>'
},
);
if(response.statusCode == HttpStatus.ok) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((item) =>
ShowList.fromJson(item)).toList();
} else {
//throw/return an error here
}
} catch(e) {
// throw/return an error here
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73341017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: convert array to multiple object based on options array? I have an array of object and each object has mutiple options, how to covert the it to multiple objects based on the options count?
Input:
var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}]
const res = Object.values(arr.reduce((acc,{name, options})=>{
acc[name] = acc[name] || {name, options: []};
acc[name].options.push(options);
return acc;
}, {}));
console.log(res)
.as-console-wrapper { max-height: 100% !important; }
Expected Output:
[{name: "audio", options:{name:'true', value: 'T'}},
{name: "audio", options:{name:'false', value: 'F'}},
{name: "audio", options:{name:'yes', value: 'Y'}},
{name: "video", options:{name:'true', value: 'T'}},
{name: "video", options:{name:'yes', value: 'Y'}},
{name: "video", options:{name:'false', value: 'F'}},
{name: "call", options:{name:'true', value: 'T'}},
{name: "call", options:{name:'No', value: 'N'}},
{name: "call", options:{name:'false', value: 'F'}}]
A: You can do this with a flat map
const arr = [{"name":"audio","options":[{"name":"true","value":"T"},{"name":"false","value":"F"},{"name":"yes","value":"Y"}]},{"name":"video","options":[{"name":"true","value":"T"},{"name":"false","value":"F"},{"name":"yes","value":"Y"}]},{"name":"call","options":[{"name":"true","value":"T"},{"name":"false","value":"F"},{"name":"yes","value":"Y"}]}]
const res = arr.flatMap(({ options, ...props }) =>
options.map(options => ({ ...props, options })))
console.log(res)
.as-console-wrapper { max-height: 100% !important; }
This creates an array of arrays for each options in the collection and then flattens it to produce a one-dimensional array.
The spread syntax lets you merge any top-level properties (like name) into each option result
A: You need a nested loop over the options array to split them into separate array elements.
var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}]
const res = [];
arr.forEach(({
name,
options
}) => options.forEach(option => res.push({
name,
options: option
})));
console.log(res)
A: Use Array.map to create the converted elements, then use
Array.flat to flatten the 2D array.
var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}]
let output = arr.map(it => {
return it.options.map(option => {
return {name:it.name,options:option}
})
}).flat()
console.log(output);
Edit:
As @mplungjan mentioned this is identical to using Array.flatMap.
var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}]
let output = arr.flatMap(it => {
return it.options.map(option => {
return {name:it.name,options:option}
})
});
console.log(output);
A: var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}]
const newArr = arr.reduce((acc, cur) => {
acc = [...acc, ...cur.options.map(option => {
return {
...cur,
options: option,
}
})];
return acc;
}, []);
A: You can use map function to resolve your query.
var arr = [
{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
{name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}]
let result = [];
arr.map(a => {
a.options.map(o => {
result.push({ name: a.name, options: { ...o }
});
});
});
console.log(result)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69204290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Print number without spaces using java.util.logging? I am currently using Vertx's default logging tool : java.utils.logging.
I have a variable defined as follow : private static int port = 8600;
This line :
logger.info("Server is now listening on port {0}", port);
gives the following output :
[2018-05-29 16:00:54] [INFOS ] Server is now listening on port 8 600
I find the space in 8 600 disturbing, as ports are usually not written with spaces.
How can I make my logger print port number as : 8600 and not 8 600?
Thanks in advance.
A: Try to use {0,number,#} instead of {0}.
Edit: More info: https://docs.oracle.com/javase/8/docs/api/java/text/MessageFormat.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50586493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Onscreen angle of 3D vector My math is too rusty to figure this out. I want to derive the onscreen angle (the angle as seen on the 2d screen) of a 3d vector.
Given the x and y rotation of a vector (z rotation is zero and doesn't mstter), what does the angle on screen look like?
We know when y is zero and x is positive, the angle is 90. When y is zero and x is negative the angle is -90. When y is 90, for any value of x, the angle is 180. When y is -90, for any value of x, the angle is 0.
So what the formula here so I can derive the angle for the other values of x and y rotation?
A: The problem, as stated, doesn't make sense. If you're holding z to zero rotation, you've converted a 3D problem to 2D already. Also, it seems the angle you're measuring is from the y-axis which is fine but will change the ultimate formula. Normally, the angle is measured from the x-axis and trigometric functions will assume that. Finally, if using Cartesian coordinates, holding y constant will not keep the angle constant (and from the system you described for x, the angle would be in the range from -90 to 90 - but exclusive of the end points).
The arctangent function mentioned above assumes an angle measured from the x-axis.
A: Angle can be calculated using the inverse tangent of the y/x ratio. On unity3d coordinated system (left-handed) you can get the angle by,
angle = Mathf.Rad2Deg * Mathf.Atan(y/x);
A: Your question is what will a 3-d vector look like.
(edit after posted added perspective info)
If you are looking at it isometrically from the z-axis, it would not matter what the z value of the vector is.
(Assuming a starting point of 0,0,0)
1,1,2 looks the same as 1,1,3.
all x,y,z1 looks the same as any x,y,z2 for any values of z1 and z2
You could create the illusion that something is coming "out of the page" by drawing higher values of z bigger. It would not change the angle, but it would be a visual hint of the z value.
Lastly, you can use Dinal24's method. You would apply the same technique twice, once for x/y, and then again with the z.
This page may be helpful: http://www.mathopenref.com/trigprobslantangle.html
Rather than code this up yourself, try to find a library that already does it, like https://processing.org/reference/PVector.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28165291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to count all the products that belongs to category(slug) Laravel 8 I am a beginner in Laravel. I need a little help.
I have an index.blade.php file which displays all the category names. When I click on on it will generate the slug link where I have all the products that in the category. So I would like to count only those products that is belongs to category's slug and display the number on the index.blade.php. Thanks for the help.
Route::get('view-category/{slug}', [ProductsController::class,'viewcategory']);
productsController:
public function viewcategory($slug){
if(Category::where('slug', $slug)->exists()){
$category = Category::where('slug', $slug)->first();
$products = Products::where('cateId', $category->id)->where('status','1')->get();
return view('admin.products.display', compact('category','products'));
}
else{
return redirect('/dashboard')->with('status',"Slug does not exist");
}
}
category Model:
class Category extends Model
{
use HasFactory;
protected $table = "categories";
protected $fullable = [
'name',
'slug',
'description',
'status',
'popular',
];
public function products(){
return $this->belongsTo(Products::class, 'id', 'cateId');
}
}
index.blade.php:
<thead>
<tr>
<th></th>
<th>Product Name</th>
<th>Category</th>
<th>Sub Category</th>
<th>Variations</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach($category as $item)
<tr>
<td class="control" tabindex="0"></td>
<td>{{$item->products->productName}}</td>
<td>{{$item->name}}</td>
<td>{{$item->subCategory}}</td>
<td>{{$item->counter}}</td>
<td></td>
<td></td>
</tr>
@endforeach
</tbody>
</table>
A: You can still call relationships inside your blade files, so if you have a products relationship setup correctly, you only need to change your index blade to this
<td>{{$item->products()->count()</td>
If you have categories that don't have any products put this in your blade to check before showing the count (Its an if else statement just inline)
<td>{{$item->products ? $item->products()->count() : 'N/A'}}</td>
A: in your blade file add this line before your foreach
@if( $category->posts->count() )
//your @foreach code here
@endif
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68531756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: is it possible to change UITableView section title background color as title, possible to do it?
A: You will need to use
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *v = [[UIView alloc] init];
[v setBackgroundColor:[UIColor blackColor]];
return [v autorelease];
}
This was free-handed so forgive any typos, etc..
UPDATE: This only works for 'grouped' tables. Is your table grouped, or normal?
A: Yes. Customize the HeaderInSection using the method in UITableViewDelegate Protocol:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
As it returns a UIView, you can set it to anything you like or just
[UIView setBackgroundColor:UIColor];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/968964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to stop function with interval if div count exceeds 5 in jQuery? Even when there are 5+ divs on screen it keeps going, any way to fix this?
if ($('div').length > 5) {
// Do nothing
} else {
window.setInterval(function(){
$(document).ready(function() {
$('body').append('<div>' + (Math.floor(Math.random() * 9) + 0) + '</div>');
});
}, 1000);
}
A: It sounds like what you want is to clear the interval timer when 5 are created so you would need to check again inside the interval timer code also
Something like:
var timer= window.setInterval(function(){
if ($('div').length > 5){
clearInterval(timer)
}else{
$('body').append('<div>' + (Math.floor(Math.random() * 9) + 0) + '</div>');
}
}, 1000);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41913522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Multiple OnTouchListeners on Buttons and also Buttons with OnClickListeners in Android Studio I am trying to create a max bench press calculator for a project for school. I am very new to coding and can not figure out why this is not working. The plus and menus weight buttons never work. I did have it working before with an OnClickListener and OnLongClickListener. I just want the OnTouchListeners to keep adding weight as long as the button is held down.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button plusreps;
private Button menusreps;
private Button Calculate;
private Button plus;
private Button menus;
private TextView textView;
private TextView textView2;
private TextView textView3;
int reps;
int Maxint;
double Max;
double weight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
textView2 = (TextView) findViewById(R.id.textView2);
textView3 = (TextView) findViewById(R.id.textView3);
plusreps = (Button) findViewById(R.id.button5);
menusreps = (Button) findViewById(R.id.button4);
menus = (Button) findViewById(R.id.button3);
plus = (Button) findViewById(R.id.button2);
Calculate = (Button) findViewById(R.id.button);
Calculate.setOnClickListener(this);
reps = 0;
weight = 100;
textView.setText("" + String.valueOf(weight));
textView2.setText("" + String.valueOf(reps));
plus.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent mEvent1) {
if (mEvent1.getAction() == MotionEvent.ACTION_DOWN)
startIncreasingWeight();
else if (mEvent1.getAction() == MotionEvent.ACTION_UP)
stopIncreasingWeight();
return false;
}
private void stopIncreasingWeight() {
textView.setText("" + String.valueOf(weight));
}
private void startIncreasingWeight() {
weight = weight++;
textView.setText("" + String.valueOf(weight));
}
});
menus.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent mEvent) {
if (mEvent.getAction() == MotionEvent.ACTION_DOWN)
startDecreasingWeight();
else if (mEvent.getAction() == MotionEvent.ACTION_UP)
stopDecreasingWeight();
return false;
}
private void stopDecreasingWeight() {
textView.setText("" + String.valueOf(weight));
}
private void startDecreasingWeight() {
weight = weight--;
textView.setText("" + String.valueOf(weight));
}
});
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button4:
if (reps > 1){
textView2.setText("" + String.valueOf(reps - 1));
reps = reps - 1;
}
else {
textView2.setText("" + String.valueOf(reps));
}
break;
case R.id.button5:
textView2.setText("" + String.valueOf(reps + 1));
reps = reps + 1;
break;
case R.id.button:
Max = reps * weight * 0.0333 + weight;
int Maxint = (int) Math.round(Max);
textView3.setText("Your max is: " + String.valueOf(Maxint));
break;
}
}}
A: put this:
plusreps.setOnClickListener(this);
menusreps.setOnClickListener(this);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35560589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Vaadin popup should show and hide in the click event makes no appear popup Having a
public void buttonClick(ClickEvent event) {
MyPopup popup = new MyPopup();
getWindow().addWindow(popup);
log.warn("Added POPUP");
//lot of method calling here then
getWindow().removeWindow(popup);
log.warn("Removed Popup");
}
I would expect to show a popup window and after some milisecundom (after the expensive method calls) it should hide itself. The log says :
2014-02-19 15:26:51 WARN xyzClass:82 - Added POPUP
2014-02-19 15:26:51 WARN xyzClass:135 - Removed Popup
But the truth is that there is no popup showing here.
If i only show it, and not remove it later (the popup will show)
public void buttonClick(ClickEvent event) {
MyPopup popup = new MyPopup();
getWindow().addWindow(popup);
log.warn("Added POPUP");
//lot of method calling here then
log.warn("Removed Popup");
}
My main reason for this i want to achieve a glasspanel/loading screen functionality @ Vaadin, and not had found better solution yet. Any solution/description why the popup not shown up i would appreciate
A: Just do not have time to render it. You add it and immediately remove.
Try this approach, for example:
private MyPopup popup;
public void buttonClick(ClickEvent event) {
Thread workThread = new Thread() {
@Override
public void run() {
// some initialization here
getWindow().removeWindow(popup);
}
};
workThread.start();
popup = new MyPopup();
getWindow().addWindow(popup);
}
A: Depending on Vaadin version you can make use of ICEPush plugin (Vaadin 6) or built-in feature called Server Push (Vaadin 7).
public void buttonClick(ClickEvent event) {
MyPopup popup = new MyPopup();
getWindow().addWindow(popup);
log.warn("Added POPUP");
// start background thread with ICEPush or ServerPush
}
// Background thread in a separate class
// update UI accordingly when thread finished the job
getWindow().removeWindow(popup);
log.warn("Removed Popup");
Thanks to it you can move your time-consuming operations to another class thus decouple your business logic from the presentation layer. You can find examples of usage in the links above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21883502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: can't get pixels[] from an PImage in processing js i've been trying to run the following code using processing.js however it just gets me a grey window. I think it's because its not accessing correctly to the image pixels[].
PImage img;
void setup() { // this is run once.
size(600, 400);
img=loadImage("http://c.tadst.com/gfx/600x400/int-mountain-day.jpg?1");
}
void draw() { // this is run repeatedly.
int dimension = (img.width*img.height);
img.loadPixels();
for (int i=0; i < dimension; i+=2) {
img.pixels[i] = color(0, 0, 0);
}
img.updatePixels();
image(img, 0, 0);
}
the code is running here http://sketchpad.cc/sp/pad/view/ro.TExeW6NhoU8/rev.163
A: I don't know exactly why it doesn't work on processing.js.
However, you are doing the image processing (drawing the black stripes) each time the draw() function is called, this seems unnecessary and might be too intensive for the browser.
Remember that the setup() function gets called once when the sketch starts whereas the draw() function gets called in an infinite loop while the sketch is running (it stops when you close the sketch).
So basically do the image processing once in the setup() function and then draw the processed image in the draw() function (you don't need to, you could draw the image also in the setup() function).
Looking at your other examples at http://sketchpad.cc/sp/pad/view/ro.TExeW6NhoU8/rev.163 this code might do:
PImage img;
void setup() { // this is run once.
size(600, 400);
img=loadImage("http://c.tadst.com/gfx/600x400/int-mountain-day.jpg?1");
img.loadPixels();
int dimension = (img.width*img.height);
for (int i=0; i < dimension; i+=2) {
img.pixels[i] = color(0, 0, 0);
}
img.updatePixels();
}
void draw() { // this is run repeatedly. It only draws the image again and again.
image(img, 0, 0);
}
A: I've been dealing with this very issue. The problem appears to be that the documentation is just flat out wrong.
I was doing almost exactly what you show above with the same result, but it turns out that this is the way you have to do it:
var pixels = bg.pixels.toArray();
for(var i=0;i<pixels.length;++i){
pixels[i] = color(0);
}
bg.pixels.set(pixels);
JSFiddle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17108355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to clone part of a List? Is it possible to clone just part of a List<T>?
Example:
List<string> myoriginalstring = new List<string>();
myoriginalstring.Add("Tyrannosaurus");
myoriginalstring.Add("Amargasaurus");
myoriginalstring.Add("Mamenchisaurus");
I want to clone myoriginalstring to another list but just from index 1 to index 2.
Is that possible? Changes in the second List<string> should be reflected in first and vice-versa.
UPDATE
Thanks for the answers so far. It seems I didn't express myself correctly.
Actually I don't want to copy or clone. I need to create a new list (which will be some part of the original one); and when I change something (some value) in my new list, the original should be also changed the same way. (The lists should be identical all the time, just the new list will be some part of the original).
Hopefully that is clearer.
A: You can create a ListSlice<T> class that represents a slice of an existing list. The slice will behave as a read-only list and because it keeps a reference to the original list you are not supposed to add or remove elements in the original list. This cannot be enforced unless you implement your own list but I will not do that here.
You will have to implement the entire IList<T> interface including the IEnumerator<T> you need for enumerating the slice. Here is an example:
class ListSlice<T> : IList<T> {
readonly IList<T> list;
readonly Int32 startIndex;
readonly Int32 length;
public ListSlice(IList<T> list, Int32 startIndex, Int32 length) {
if (list == null)
throw new ArgumentNullException("list");
if (!(0 <= startIndex && startIndex < list.Count))
throw new ArgumentException("startIndex");
if (!(0 <= length && length <= list.Count - startIndex))
throw new ArgumentException("length");
this.list = list;
this.startIndex = startIndex;
this.length = length;
}
public T this[Int32 index] {
get {
if (!(0 <= index && index < this.length))
throw new ArgumentOutOfRangeException();
return this.list[this.startIndex + index];
}
set {
if (!(0 <= index && index < this.length))
throw new ArgumentOutOfRangeException();
this.list[this.startIndex + index] = value;
}
}
public Int32 IndexOf(T item) {
var index = this.list.IndexOf(item);
return index == -1 || index >= this.startIndex + this.length
? -1 : index - this.startIndex;
}
public void Insert(Int32 index, T item) { throw new NotSupportedException(); }
public void RemoveAt(Int32 index) { throw new NotSupportedException(); }
public Int32 Count { get { return this.length; } }
public Boolean IsReadOnly { get { return true; } }
public void Add(T item) { throw new NotSupportedException(); }
public void Clear() { throw new NotSupportedException(); }
public Boolean Contains(T item) { return IndexOf(item) != -1; }
public void CopyTo(T[] array, Int32 arrayIndex) {
for (var i = this.startIndex; i < this.length; i += 1)
array[i + arrayIndex] = this.list[i];
}
public Boolean Remove(T item) { throw new NotSupportedException(); }
public IEnumerator<T> GetEnumerator() {
return new Enumerator(this.list, this.startIndex, this.length);
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
class Enumerator : IEnumerator<T> {
readonly IList<T> list;
readonly Int32 startIndex;
readonly Int32 length;
Int32 index;
T current;
public Enumerator(IList<T> list, Int32 startIndex, Int32 length) {
this.list = list;
this.startIndex = startIndex;
this.length = length;
}
public T Current { get { return this.current; } }
Object IEnumerator.Current {
get {
if (this.index == 0 || this.index == this.length + 1)
throw new InvalidOperationException();
return Current;
}
}
public Boolean MoveNext() {
if (this.index < this.length) {
this.current = this.list[this.index + this.startIndex];
this.index += 1;
return true;
}
this.current = default(T);
return false;
}
public void Reset() {
this.index = 0;
this.current = default(T);
}
public void Dispose() {
}
}
}
You can write an extension method to make it easier to work with slices:
static class ListExtensions {
public static ListSlice<T> Slice<T>(this IList<T> list, Int32 startIndex, Int32 length) {
return new ListSlice<T>(list, startIndex, length);
}
}
To use the slice you can write code like this:
var list = new List<String> {
"Tyrannosaurus",
"Amargasaurus",
"Mamenchisaurus"
};
var slice = list.Slice(1, 2);
slice[0] = "Stegosaurus";
Now list[1] as well as slice[0] contains "Stegosaurus".
A: Assuming you really did mean clone and not copy...
List<string> myoriginalstring = new List<string> { "Tyrannosaurus", "Amargasaurus", "Mamenchisaurus" };
List<string> myCloneString = myoriginalstring.GetRange(1, myoriginalstring.Count() -1 );
A: On the first glance, it seems as if
var list2 = myoriginalstring.SkipWhile((str, i)=>!(i>=1 && i<=2)).ToList();
list2[1]="Stegosaurus";
would be the solution. But it is not, because list2 is a independent list which contains its own elements. The code above works, but it replaces only the element in the (new) list2, not in myoriginalstring.
As you pointed out, this is not what you wanted to do.
Solution
Unlike other languages like C, you don't have access to pointers directly in C#.
Hence, the solution is more complex. Instead of using strings directly, you need to create an object, like the following:
public class Dino
{
public string Value { get; set; }
public object[] Parent { get; set; }
public int ParentIndex;
}
Then, create some helper extension methods, like so:
public static class Extensions
{
public static Dino AsDino(this string name)
{
return new Dino() {Value=name};
}
public static Dino AsDino(this string name, object[] reference, int parentIndex)
{
return new Dino() {Value=name, Parent=reference, ParentIndex=parentIndex };
}
public static Dino Replace(this object item, Dino replacementItem)
{
replacementItem.ParentIndex=((Dino)item).ParentIndex;
replacementItem.Parent=((Dino)item).Parent;
((Dino)item).Parent[replacementItem.ParentIndex]=replacementItem;
return replacementItem;
}
}
With those helpers, you can do it:
// create array with 3 elements
var myoriginalstring = new object[3];
// fill in the dinosours and keep track of the array object and positions within
myoriginalstring[0]="Tyrannosaurus".AsDino(myoriginalstring, 0);
myoriginalstring[1]="Amargasaurus".AsDino(myoriginalstring, 1);
myoriginalstring[2]="Mamenchisaurus".AsDino(myoriginalstring, 2);
// get a subset of the array
var list2 = myoriginalstring.SkipWhile((str, i)=>!(i>=1 && i<=2)).ToList<object>();
// replace the value at index 1 in list2. This will also replace the value
// in the original array myoriginalstring
list2[1].Replace("Stegosaurus".AsDino());
The trick is, that the Dino class keeps track of its origin (the array myoriginalstring) and the position within it (i.e. its index).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26495500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Running docker command in azure docker VM I'm a trying to setup a docker enabled linux VM on azure. I have a VM created with the docker extension by using azure cross platform command line tool. however i have 2 issues right now
*
*When I ssh into the VM and try to run the docker command (ex docker images), it returns the following error.
FATA[0000] Get http:///var/run/docker.sock/v1.18/images/json: dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?
*I am only able to run the docker command against the vm remotely (docker --tls images ...something like this). According to their documentation the "azure create docker vm" command will create the certificate for the server to use. How do I connect from a remote on a different machine? where can I find the generated certificate and how to use it for remote access?
A: Once the software is installed, you can start using it. However, you may encounter the following two issues the first time you attempt to run docker commands:
docker
FATA[0000] Get http: ///var/run/docker.sock/v1.18/images/json: dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?
And the other error is:
docker
FATA[0000] Get http: ///var/run/docker.sock/v1.18/containers/json: dial unix /var/run/docker.sock: permission denied. Are you trying to connect to a TLS-enabled daemon without TLS?
The reason is, you need to start the Docker service first. Moreover, you must run the technology as root, because Docker needs access to some rather sensitive pieces of the system, and interact with the kernel. That's how it works.
systemctl start docker
Now we can go crazy and begin using Docker.
This is the original
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29888243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: XCode 7: xcdatamodeld doesn’t exist After updating to XCode 7 in order to support iOS9 I had the following build error
error: Cannot read bundle contents (Error Domain=NSCocoaErrorDomain Code=260 "The folder “VoIP.xcdatamodeld” doesn’t exist.
Build target myTitle of project myTitle with configuration Debug
DataModelCompile Build/Products/Debug-iphoneos/myTitle.app/
/Users/myself/MyDev/m1/app/VoIP/VoIP/VoIP.xcdatamodeld
cd /Users/myself/MyDev/m1/app/app/iPhone
export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Applications/Xcode.app/Contents/Developer/usr/bin/momc --sdkroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk
--iphoneos-deployment-target 7.0 --module myTitle /Users/myself/MyDev/m1/app/VoIP/VoIP/VoIP.xcdatamodeld
/Users/myself/MyDev/m1/app/app/iPhone/Build/Products/Debug-iphoneos/myTitle.app/
/Users/myself/MyDev/m1/app/VoIP/VoIP/VoIP.xcdatamodeld:: error: Cannot
read bundle contents (Error Domain=NSCocoaErrorDomain Code=260 "The
folder “VoIP.xcdatamodeld” doesn’t exist." UserInfo=0x7fd0f350f990
{NSFilePath=/Users/myself/MyDev/m1/app/VoIP/VoIP/VoIP.xcdatamodeld,
NSUserStringVariant=(
Folder ), NSUnderlyingError=0x7fd0f350f940 "The operation couldn’t be completed. (OSStatus error -43.)"})
How can I resolve it?
The only reference about this file in my project is this one (in the .project file)
/* Begin XCVersionGroup section */
449367DE1338E89100DB4AC9 /* myTitle.xcdatamodeld */ = {
isa = XCVersionGroup;
children = (
449367DF1338E89100DB4AC9 /* VoIP.xcdatamodel */,
);
currentVersion = 449367DF1338E89100DB4AC9 /* VoIP.xcdatamodel */;
name = myTitle.xcdatamodeld;
path = ../../../../VoIP/VoIP/VoIP.xcdatamodeld;
sourceTree = "<group>";
versionGroupType = wrapper.xcdatamodel;
};
/* End XCVersionGroup section */
No idea how it came from and why it worked w/o problems in previous xcode versions.
A: I had the same issue when I stashed a new Model and unfortunately the selected solution did not work for me. What worked for me was: find the model file in your project folder in Finder ("ModelNameHere.xcdatamodeld"); right-button click and select "Show Package Contents". You will see all versions of the Model - delete the one that was not supposed to exist.
A: Check Compile Sources under Build Phases for your Target setting described in the below image.
I saw all the resources carefully and found one resource without any path (an unknown resource, I don't know how it appeared there..). Remove it from there, clean the product and run.
The above was the only reason in my case..
Hope it helps you !!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32868017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Objected Oriented Programming in SWI-Prolog I read somewhere that you can think of modules as objects in Prolog. I am trying to get my head around this, and if it a good way to code.
If I have two files, one defining a class dog and then another one that uses this class to make two dog objects.
:- module(dog,
[ create_dog/4,bark/1 ]).
create_dog(Name,Age,Type,Dog):-
Dog = dog(name(Name),age(Age),type(Type)).
bark(Dog):-
Dog = dog(name(_Name),age(_Age),type(Type)),
Type = bassethound,
woof.
bark(Dog):-
Dog = dog(name(_Name),age(_Age),type(Type)),
Type \= bassethound,
ruff.
woof:-format("woof~n").
ruff:-format("ruff~n").
second file
use_module(library(dog)).
run:-
dog:create_dog('fred',5,bassethound,Dog),
forall(between(1,5,_X),
dog:bark(Dog)
),
dog:create_dog('fido',6,bloodhound,Dog2),
dog:bark(Dog2).
This makes a dog object Dog which is a basset hound and makes it bark 5 times,
I then make another dog object Dog2 which is a bloodhound and make this also bark. I understand that in oop you have objects that have behaviours and state. So I now have two objects with different behaviours based on their own states but at the moment I am storing the state of the objects in the Dog variables where they can be seen by the code in the main program. Is there a way to hide the state of the objects i.e to have private variables?
For example I might want to have a way of storing the state has_barked for each dog object, which would be true if it has barked earlier in the program and false otherwise, then change the behaviour of bark/1 based on this.
Also how would you handle inheritance and overriding methods etc?
Any pointer to readings welcomed. Thank you.
A: Just an example of one of the possible reimplementations of your sample code in Logtalk. It uses prototypes for simplicity but it still illustrates some key concepts including inheritance, default predicate definitions, static and dynamic objects, and parametric objects.
% a generic dog
:- object(dog).
:- public([
create_dog/3, bark/0, name/1, age/1
]).
create_dog(Name, Age, Dog) :-
self(Type),
create_object(Dog, [extends(Type)], [], [name(Name),age(Age)]).
% default definition for all dogs
bark :-
write(ruff), nl.
:- end_object.
:- object(bassethound,
extends(dog)).
% bark different
bark :-
write(woof), nl.
:- end_object.
:- object(bloodhound,
extends(dog)).
:- end_object.
% support representing dogs as plain database facts using a parametric object
:- object(dog(_Name,_Age,_Type),
extends(dog)).
name(Name) :-
parameter(1, Name).
age(Age) :-
parameter(2, Age).
bark :-
parameter(3, Type),
[Type::bark].
:- end_object.
% a couple of (static) dogs as parametric object proxies
dog(fred, 5, bassethound).
dog(fido, 6, bloodhound).
% another static object
:- object(frisbee,
extends(bloodhound)).
name(frisbee).
age(1).
:- end_object.
Some sample queries:
$ swilgt
...
?- {dogs}.
% [ /Users/foo/dogs.lgt loaded ]
% (0 warnings)
true.
?- bassethound::bark.
woof
true.
?- bloodhound::bark.
ruff
true.
?- bassethound::create_dog(boss, 2, Dog).
Dog = o1.
?- o1::bark.
woof
true.
?- {dog(Name, Age, Type)}::bark.
woof
Name = fred,
Age = 5,
Type = bassethound ;
ruff
Name = fido,
Age = 6,
Type = bloodhound.
?- dog(ghost, 78, bloodhound)::(bark, age(Age)).
ruff
Age = 78.
?- forall(between(1,5,_X), {dog(fred,_,_)}::bark).
woof
woof
woof
woof
woof
true.
Some notes. ::/2 is the message sending control construct. The goal {Object}::Message simply proves Object using the plain Prolog database and then sends the message Message to the result. The goal [Object::Message] delegates a message to an object while keeping the original sender.
A: Prolog modules can be trivially interpreted as objects (specifically, as prototypes). Prolog modules can be dynamically created, have a name that can be regarded as their identity (as it must be unique in a running session as the module namespace is flat), and can have dynamic state (using dynamic predicates local to the module). In most systems, however, they provide weak encapsulation in the sense that you can usually call any module predicate using explicit qualification (that said, at least one system, ECLiPSe, allows you to lock a module to prevent breaking encapsulation this way). There's also no support for separating interface from implementation or having multiple implementations of the same interface (you can somehow hack it, depending on the Prolog module system, but it's not pretty).
Logtalk, as mentioned in other answers, is a highly portable object-oriented extension to Prolog supporting most systems, including SWI-Prolog. Logtalk objects subsume Prolog modules, both from a conceptual and a practical point-of-view. The Logtalk compiler supports a common core of module features. You can use it e.g. to write module code in Prolog implementations without a module system. Logtalk can compile modules as objects and supports bi-directional calls between objects and modules.
Note that objects in Logic Programming are best seen as a code encapsulation and code reuse mechanism. Just like modules. OO concepts can be (and have been) successfully applied in other programming paradigms, including functional and logic. But that doesn't mean necessarily bringing along imperative/procedural concepts. As an example, the relations between an instance and its class or between a prototype as its parent can be interpreted as specifying a pattern of code reuse instead of being seen from a dynamic/state point-of-view (in fact, in OOP languages derived from imperative/procedural languages, an instance is little more than a glorified dynamic data structure whose specification is distributed between its class and its class superclasses).
Considering your sample code, you can recode it easily in Logtalk close to your formulation but also in other ways, the most interesting of them making use of no dynamic features. Storing state (as in dynamic state) is sometimes necessary and may even be the best solution for particular problems (Prolog have dynamic predicates for a reason!) but should be used with care and only when truly necessary. Using Logtalk doesn't change (nor intends to change) that.
I suggest you look into the extensive Logtalk documentation and its numerous programming examples. There you will find how to e.g. cleanly separate interface from implementation, how to use composition, inheritance, specialize or override inherited predicates, etc.
A: Logtalk is effectively the prominent object oriented Prolog available today. Paulo made it available as a pack, so installing should be very easy.
Modules are not really appropriate for object orientation. They are more similar to namespaces, but without nesting. Also, the ISO standard it's a bit controversy.
SWI-Prolog v7 introduced dicts, an extension that at least handles an historical problem of the language, and make available 'fields' by name, and a syntax for 'methods'. But still, no inheritance...
edit
I've added here a small example of object orientation in SWI-Prolog. It's an evolution of my test application about creating genealogy trees.
Comparing the genealogy.pl sources, you can appreciate how the latest version uses the module specifier, instead of the directive :- multifile, and then can work with multiple trees.
You can see, the calling module is passed down the graph construction code,
and have optional or mandatory predicates, that gets called by module qualification:
make_rank(M, RPs, Rp-P) :-
findall(G, M:parent_child(P, G), Gs),
maplist(generated(M, Rp, RPs), Gs).
optional predicates must be called like
...
catch(M:female(P),_,fail) -> C = red
...
Note that predicates are not exported by the applicative modules. Exporting them, AFAIK, breaks the object orientation.
==========
Another, maybe more trivial, example of of object orientation, it's the module pqGraphviz_emu, where I crafted a simple minded replacement of system level objects.
I explain: pqGraphviz it's a tiny layer - written in Qt - over Graphviz library. Graphviz - albeit in C - has an object oriented interface. Indeed, the API allows to create relevant objects (graphs, nodes, links) and then assign attributes to them. My layer attempts to keep the API most similar to the original. For instance, Graphviz creates a node with
Agnode_t* agnode(Agraph_t*,char*,int);
then I wrote with the C++ interface
PREDICATE(agnode, 4) {
if (Agnode_t* N = agnode(graph(PL_A1), CP(PL_A2), PL_A3))
return PL_A4 = N;
return false;
}
We exchange pointers, and I have setup the Qt metatype facility to handle the typing... but since the interface is rather low level, I usually have a tiny middle layer that exposes a more applicative view, and it's this middle level interface that gets called from genealogy.pl:
make_node(G, Id, Np) :-
make_node(G, Id, [], Np).
make_node(G, Id, As, Np) :-
empty(node, N0),
term_to_atom(Id, IdW),
N = N0.put(id, IdW),
alloc_new(N, Np),
set_attrs(Np, As),
dladd(G, nodes, Np).
In this snippet, you can see an example of the SWI-Prolog v7 dicts:
...
N = N0.put(id, IdW),
...
The memory allocation schema is handled in allocator.pl.
A: Have a look at logtalk. It is kind of an object-oriented extension to Prolog.
http://logtalk.org/
A: the PCE system in SWI-Prolog is also an option for OOP in Prolog. It's usually associated with xpce, the GUI system, but it's actually a general purpose class based OO system.
A: Nowadays, SWI prolog has dicts which interact with the modules in a nice way. See The SWI prolog manual page on dicts, especially section 5.4.1.1: User defined functions on dicts.
This allows you to define things that look exactly like methods, up to returning values (unusual but very useful in Prolog).
Unlike discussed in some of the other answers, I personally find the logic programming and OOP paradigms to be orthogonal to each other: it definitely doesn't hurt to be able to structure your logic code using the OOP modularity...
A: There is something called context.pl implemented as part of another, unrelated project. Unlike Logtalk, it doesn't require compilation, but it definitely has only a fraction of Logtalk's features:
Context is an object-oriented programming paradigm for Prolog. It implements
contexts (namespaces), classes and instances. It supports various inheritance
mechanisms. Access to member predicates is regulated through public/protected
& private meta-predicates. We enable declarative static typing of class data
members.
/.../
CONTEXT implements a declarative contextual logic programming paradigm
that aims to facilitate Prolog software engineering. Short
description:
*
*We split up the global Prolog namespace into contexts, each having
their own facts and rules.
*We create a meta-language allowing you to declare metadata about
facts and rules in a context.
*We implement Classes and Instances, Public, Protected and Private
meta-predicates. We implement (Multiple) inheritance and cloning.
We implement operators enabling interaction with context.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28154041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Calling an undefined array element is showing a value of another defined element When calling an undefined element of an array, it is showing me a value of another defined element.
Example of array structure:
$array = array(
'a' => array(
'b' => 'c'
)
);
When using echo command on $array['a']['b']['x'] it is showing me value of 'c'. Why this happens I really don't understand since $array['a']['b']['x'] is not defined.
And then when I try to add another value by using command $array['a']['b']['x'] = 'y';
It is rewriting the value of $array['a']['b'] to 'y'
Somehow I really don't understand this behaviour, can someone explain how is that possible? And how then I will be able to create a new string value at $array['a']['b']['x'] = 'xyz' to not override $array['a']['b']?
A: It is actually not related to arrays at all. This is a string problem.
In PHP you can access and modify characters of a string with array notation. Consider this string:
$a = 'foo';
$a[0] gives you the first character (f), $a[1] the second and so forth.
Assigning a string this way will replace the existing character with the first character of the new string, thus:
$a[0] = 'b';
results in $a being 'boo'.
Now what you do is passing a character 'x' as index. PHP resolves to the index 0 (passing a number in a string, like '1', would work as expected though (i.e. accessing the second character)).
In your case the string only consists of one character (c). So calling $array['a']['b']['x'] = 'y'; is the same as $array['a']['b'][0] = 'y'; which just changes the character from c to y.
If you had a longer string, like 'foo', $array['a']['b']['x'] = 'y'; would result in the value of $array['a']['b'] being 'yoo'.
You cannot assign a new value to $array['a']['b'] without overwriting it. A variable can only store one value. What you can do is to assign an array to $array['a']['b'] and capture the previous value. E.g. you could do:
$array['a']['b'] = array($array['a']['b'], 'x' => 'xyz');
which will result in:
$array = array(
'a' => array(
'b' => array(
0 => 'c',
'x' => 'xyz'
)
)
);
Further reading:
*
*Arrays
*Strings
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5803726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can the user of proftpd change the password themself not by admin? I have read all the command on ftp which contains no command to change passwd.
I am a user of proftpd ,how can change my password after logining into proftpd by myself not by admin?
User can change it's own password in ssh service ,not by admin,it is convenient.
A: As far as i know ProFTPD does not contain its own users, but rather uses external resources to authenticate. That means that if you want to edit a user (or it's password) you need to edit whatever source ProFTPD authenticated that user against (i.e. /etc/passwd, PAM, LDAP, etc).
This, unfortunately for you, means that you can not edit your password from within an FTP session, but rather have to access the server via SSH or similar to change it.
More info can be found in the documentation: http://www.proftpd.org/docs/howto/Authentication.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31960863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Large Memory (Data Size) Collection Very often I have to use objects from the java.util.collection package, objects that conform to the the Map and Set interfaces.
When I insert several million tuples or entities into these objects (HashMap, TreeMap, etc) their performance, both insertion and look-up slow to a crawl.
I have devised, derived classes which are essentially compositions of the classes in java.util.collection that scale better in performance.
I was wondering if there is an open source equivalent of the java.util.collections package that is optimized for handling large amounts of data.
A: For better performing collections libraries, try trove. But, in general, you want to tackle these kinds of issues by streaming, or another form of lazy loading, such that you can do things like aggregation without loading the entire dataset into memory.
You could also use a key value store like Redis or CouchDB for storing this data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13214006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: json-c: Simplest way to access a value from a subarray {
"name":"John Doe",
"dob":"2005-01-03",
"scores":
{
"math":
{
"lowest":65,
"highest":98
},
"english":
{
"lowest":75,
"highest":80
},
"history":
{
"lowest":50,
"highest":85
}
}
}
What is the simplest way to access the highest math score in the above JSON object with json-c?
Is it possible to use something similar to json_object_object_get (jsonobj, "scores.math.highest") ?
If not, do I have to retrieve each individual array to get to the highest score? ie. Get scores, then get math and finally get highest?
Thanks!
A: Looking at the JSON-C docs it doesn't appear to have an easy way to drill down into the structure. You'll have to do it yourself. Something like this:
struct json_object *json_object_get_with_keys(
struct json_object *obj,
const char *keys[]
) {
while( keys[0] != NULL ) {
if( !json_object_object_get_ex(obj, keys[0], &obj) ) {
fprintf(stderr, "Can't find key %s\n", keys[0]);
return NULL;
}
keys++;
}
return obj;
}
Pass it a null terminated array of keys and it will drill down (or return null).
const char *keys[] = {"scores", "math", "highest", NULL};
struct json_object *obj = json_object_get_with_keys(top, keys);
if( obj != NULL ) {
printf("%s\n", json_object_to_json_string(obj));
}
Instead, use JSON-Glib. It has JSONPath which will be more familiar, you can use $.scores.english.highest.
JsonNode *result_node = json_path_query(
"$.scores.english.highest",
json_parser_get_root(parser),
&error
);
if( error != NULL ) {
fprintf(stderr, "%s", error->message);
exit(1);
}
/* It returns a node containing an array. Why doesn't it just return an array? */
JsonArray *results = json_node_get_array(result_node);
if( json_array_get_length( results ) == 1 ) {
printf("highest: %ld\n", json_array_get_int_element(results, 0));
}
else {
fprintf(stderr, "Couldn't find it\n");
}
It's a little awkward to use, but you can make that easier with some wrapper functions to take care of the scaffolding and error handling.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42310054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS bottom: 0; position: absolute; parent position: relative; not working At this page I have the navigation menu .slider-btm underneath the head image ("Branding, Print, Websites & Movies, Displays & Signage") with:
.slider-btm {
position: absolute;
width: 100%;
bottom: 0;
height: 60px;
z-index: 10;
}
and parent:
<div class="slider-outer-wrapper" style="position:relative">
yet the navigation menu .slider-btm is not at the bottom of the screen. I see the following:
I wish to have this menu at the bottom like the menu at the bottom of brand.insightdesign.com.au
Help appreciated.
A: In an ultra-basic way, that website (that you have removed from your question) would have the container measure the height of your window and attach the height of the window to the header(container) and then absolute position the menu to the bottom of this container (see code for a very rough example)
.container {
background:red;
position:relative;
height:100vh;
}
li {
list-style:none;
float:left;
}
.menu {
position:absolute;
bottom:0;
width:100%;
background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div class="container">
<div class="menu">
<ul>
<li>Link</li>
<li>Link</li>
<li>Link</li>
<li>Link</li>
</ul>
</div>
</div>
<h1>This is more content</h1>
If you need anything further explaining, let me know.
--- UPDATE ---
Instead of using JavaScript to work out the height of your browser window, simply add height:100vh to the container height. This will match the container height to the browser height, give you the same outcome (just through CSS rather than JavaScript - with the added positive of that this you won't have to assign this to an on resize in case the user resizes their screen). I have updated the code above.
--- FURTHER UPDATE ---
Thanks, by moving .slider-btm out of .slider-outer-wrapper container, this should resolve your issue so that .slider-btm can sit at the bottom of your container which is 100vh.
A: You want to have the bar fixed at the bottom of the screen, also while scrolling?
Use position: fixed
.slider-btm {
position: fixed;
width: 100%;
bottom: 0;
height: 60px;
z-index: 10;
}
A: i think the issue is the the different screen resolution of the devices , add this line to the "slider-outer-wrapper" class
.slider-outer-wrapper{
position: relative;
height: 100%;
}
you have added max-height property , please remove it
after removing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50170590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AWS LightSail RDS - How Much RAM Do I Need I'm just setting up a hight availability WordPress network and I need to decide how much RAM I need for the database instance. On a web server you run "top" and find out how much RAM is being used per MySql process and then look in your config file and look at the maximum number of processes that are allowed to run.
How do you calculate how much RAM you will need on a High availability MySQL database running in AWS LightSail? The plans seem very light on RAM. For example a $20 webserver gets 4GB of RAM whereas a $60 database server get 1GB of RAM. Why is this and how many processes will 1GB run?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67062350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Monitoring Java from within Java I want to write a simple visualization of a Java program by displaying the program's method calls as branches of a tree. This could be done quite simply by having the program itself tell the visualization what it is doing, but I want to be able to do this with any Java method/class and not just the ones I modify to do so.
What I need is the ability to watch the methods a program calls and what methods are called within that method and so on. Obviously, stack traces provide exactly this functionality:
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9)
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)
So I thought about having the program I want to monitor run in a thread and then just look at that thread's stack. However, the thread class does not really support this. It only supports printing the current stack.
Now I, of course, thought of simply changing the PrintStream of the System class so the thread would print its stack into my PrintStream, but this feels kind of wrong.
Is there a better way to do this? Are there any pre-existing classes/methods I can use?
Also, I'm currently downloading the Java source code, to check how exactly the thread class prints its stack so I could maybe subclass thread and imitate the dumpStack() method with my own getStack() method.
A: Look also at VisualVM, shipped with latest Java releases.
A: Oh shoot, looking through the source code I noticed the thread class has a method public StackTraceElement[] getStackTrace(), it just wasn't in the documentation I was reading. Now I feel dumb.
So yeah, that seems to be the solution.
A: One approach might be to use something like BCEL to preprocess the target bytecode to insert calls to your own code on every method entry and exit (probably best to do exit by wrapping the whole method in a try/finally block, to catch exception exits). From this, you can deduce the call tree exactly as it happens.
A: You could use AspectJ for that. Have a look at this description of exactly your use case.
A: Have a look at the ThreadMXBean class -- it my provide what you need. Essentially, you:
*
*call ManagementFactory.getThreadMXBean() to get an instance of ThreadMXBean;
*call getAllThreadIds() on the resulting ThreadMXBean to enumerate current threads;
*call getThreadInfo() to get the top n stack trace elements from a given list of threads.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1617271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: cURL error Couldn't resolve host 'Bearer' I'm trying to connect to the Adobe Analytics found here
I've managed to generate an auth token using the below request:
curl -i -v "https://api.omniture.com/token" -u 'my-user' -d "grant_type=client_credentials"
I then copy the whole object thats returned which looks something like this:
{
"access_token": "some-really-long-access-token",
"expires_in": 3600,
"token_type": "bearer",
"scope": "livestream",
"success": true
}
and paste it into the following cURL:
curl --location --compressed --header “Authorization: Bearer [{"access_token":"some-really-long-access-token","expires_in":3600,"token_type":"bearer","scope":"livestream","success":true}]” [https://livestream.adobe.net/api/1/stream/myendpoint]
The error i'm getting is:
Couldn't resolve host 'Bearer'
I'm fairly new to cURL so not sure if there is an obvious error here? Will most likely be down to the way i'm sending the data over...
EDIT
After the answer written below this is the error message i'm getting:
curl: (6) Couldn't resolve host 'Bearer'
curl: (6) Couldn't resolve host 'some-really-long-auth-key
invalid authorization header
A: Okay, the part you need to pass in the header is the "some-really-long-access-token"
Example:
curl --compressed --header "Authorization: Bearer some-really-long-access-token" "https://livestream.adobe.net/api/1/stream/myendpoint"
So just pay attention to the encoding on the ".
*
*“ is not the same as "
*When copying / pasting from HTML, Rich text, or something other than a code block, it's best to check this
Edit:
Your question is tagged php, but your examples are using the command line, therefore, ensure your command is formatted using the following points:
First and foremost:
*
*The examples on the Adobe Developer Connection page also showing arguments inside [square brackets], for example:
Other general things to check:
*
*A header is passed like this: -H "Header-name: Header-Value"
*
*Therefore, if my access token was 29035-97v657zyr8qk966y143k2v0p365460xbd1pvk9p6
Then my header arguments would be this:
*
*-H "Authorization: Bearer 29035-97v657zyr8qk966y143k2v0p365460xbd1pvk9p6"
*You can explicitly specify the url to cURL using --url. I don't usually do this because it shouldn't be necessary if everything is correct, but it may help refine the error message.
*
*So my URL arguments would be this:
*
*--url "https://livestream.adobe.net/api/1/stream/myendpoint"
*Be sure as described above NOT to use LEFT AND RIGHT DOUBLE QUOTATION MARK “ and ”, but the standard " found on the computer keyboard. The standard " is what the shell uses to contain arguments
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44067382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Android: Difference between canvas.drawBitmap and BitmapDrawable.draw? When I want to draw a BitmapDrawable to a Canvas in Android, there are two possibilities that do the same and I don't know which one to prefer:
*
*Using canvas.drawBitmap() and extract the Bitmap from the drawable using getBitmap()
*Using drawable.draw(canvas), passing the canvas as an argument to the drawable.
I'm using the first option now, but it seems completely arbitrary as I can't see any difference.
Thanks for your answers
A: Never do option number 1 the way you do it. Instead of creating a bitmap out of a drawable every time you want to draw it, create a bitmap in the first place. That is, don't create a Drawable if you are going to draw a bitmap. Create a bitmap like this:
mBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.myImage);
mBitmap = Bitmap.createScaledBitmap(mBitmap, width, height, true);
And this is something you do just once. After that, just draw like you do (canvas.drawbitmap()).
As for option number 2, you are doing it correctly.
Now, there are some differences.
Option 1 is faster to draw and usually good for background images. There is a significant change to FPS depending on if you draw a bitmap or drawable. Bitmaps are faster.
Option 2 is the way to go if you need to things like scaling, moving and other kinds of manipulations of the image. Not as fast but there's no other option if you want to do any of those things just mentioned.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6681108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: GET direct_messages using url in Twitter There is a requirement in an application in which we use only URL to access information on twitter. We cannot use twitter API for that. I have a reference URL : https://dev.twitter.com/docs/api/1/get/direct_messages/sent but it is not working as it needs authentication.
Is there some other way to access it using URL only? I want to list all Direct messages of an account on twitter in my application.
A: If it requires Authentication then the only way you'll be able to "get" it using GET is to authenticate the user. Otherwise you'll see an error code in the response. Recent changes were made in the applications permission model for Direct Messages.
Lean More Here
Your going to need some code besides a URL to send, receive and validate authentication tokens.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7156043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find potential largest circle I have a set of 2D points and I want to find the potential largest empty circle. By that, I don't mean to code the Largest Empty Circle algorithm.
Here's an image trying to explain my words.
As you can see, there are points inside that circle, so what I want is an algorithm that given that set of 2D points, could compute that circle.
That set of points represents a wall of a sewer which contains a hole. The problem is that this hole may be corked, may contain some dirt at one or more sides of the circle. So, when you laser detect that part, you don't obtain a perfect circle, but kind of a semicircle. What I want to find is the original hole, the clean hole, when there is no dirt. When I say potential, I mean the original hole. In the image, the green circle is the original hole and the points inside that circle are some kind of dirt. The final purpose of this is to decide whether the hole is clean or dirty (Detecting how many points are inside that green circle and decide how dirty it is)
Another example of how it is supposed to be in real life:
Here you can see that the hole has dirt in the bottom part (could be any side of the hole), so when you laser detect it, you don't obtain the circle, but a bunch of points with the upper part of the circle as empty. What I want is from that set of points where you can only see the upper part of the circle empty, reconstruct the original hole, as it was when clean.
Plus, I attach two images of the point cloud, from two different perspectives, so you can know what I am working with.
A: I would find the bounding box of hole and then inspect the sides. find the one that is not linear but curved instead and set that as circle border. Then fit circle to that side only. For more info see:
*
*fitting ellipses
*Finding holes in 2d point sets
A: If you can scale the coordinates in order to draw the point into an image, here is a solution:
*
*Draw the points into an image
*Compute the distance map using all the points as a source point.
*Then, each pixel will contain the distance to the closets point. So the pixel with the highest value will be the center of the largest circle, and the pixel value will be the circle radius.
*Find the closest points to the circle center.
*Find the circle passing by all theses points (Hough?). The solution might not be unique.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36450042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why does "1 in range(2) == True" evaluate to False? I came across this expression, which I thought should evaluate to True but it doesn't.
>> s = 1 in range(2)
>> s == True
>> True
Above statement works as expected but when this:
1 in range(2) == True
is executed, it evaluates to False.
I tried searching for answers but couldn't get a concrete one. Can anyone help me understand this behavior?
A: 1 in range(2) == True is an operator chain, just like when you do 0 < 10 < 20
For it to be true you would need
1 in range(2)
and
range(2) == True
to be both true. The latter is false, hence the result. Adding parenthesis doesn't make an operator chaining anymore (some operators are in the parentheses), which explains (1 in range(2)) == True works.
Try:
>>> 1 in range(2) == range(2)
True
Once again, a good lesson learned about not equalling things with == True or != False which are redundant at best, and toxic at worst.
A: Try to write
(1 in range(2)) == True
It has to do with parsing and how the expression is evaluated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48944267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Compare string and integer in same if statement I have a program that takes input from the user. I want to display an invalid option message if the input is a string or it is not a number between 1 to 4. I want to check all these 3 conditions in a single if statement.
ask_option = input("Your option: ")
if int(ask_option) != int and (int(ask_option) < 1 or int(ask_option) > 4):
print("Not a valid option")
I feel the int(ask_option) != int is incorrect. But is it possible to fulfill all these 3 in a single if statement?
My code fulfills the criteria to choose between 1-4 but doesn't work to check string input. Please help
A: input() will always return a string unless you explicity convert it. So using ask_option = int(input("Your option: ")) will already satisfy checking if ask_option is an integer as an exception will be raised otherwise.
As for evaluating the integer, you can accomplish this in a single line such as:
if not 1 <= ask_option <= 4:
print("Not a valid option")
A: If you try to convert string input into an int, the program will throw ValueError.
ask_option = input("Your option: ")
try:
val = int(ask_option)
if val <= 1 or val => 4:
print("Not a valid option!")
except ValueError:
print("Not a valid option!")
A: ask_option = input("Your option: ")
if len(ask_option) != 1 or ask_option < '1' or ask_option > '4':
print("Not a valid option")
else:
print( "valid option")
Edit:
OP: "I want to display an invalid option message if the input is a string or it is not a number between 1 to 4."
Therefore we need to accept values ranging from 1 - 4
We know that input() accepts everything as a string
so in the if statement
first condition: len(ask_option) != 1
We invalidate any string whose length is not equal to 1 ( since we need to accept values ranging from 1-4 which are of a length 1 )
And now we are left to deal with the input value whose length is just 1 which could be anything and will be checked with the next 2 conditions.
second and third condition: ask_option < '1' or ask_option > '4'
We do string comparison ( which is done using their ASCII values )
more on string comparison: String comparison technique used by Python
I would not recommend using this approach since it's hard to tell what it does on the first look, so it's better if you use try except instead as suggested in other answers.
See this solution as just a different approach to solve OP's problem ( but not recommended to implement. )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64420636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Capture optional Group I want to capture the values of some keys which may be optional, specifically consider the string below
@Foo1:dog|a=5|b=6|c=10|d=12|e=2
@Foo2:cat|a=12|c=10|d=11|e=123
@Foo1:bat|a=213123|b=10
@Foo3:pet|c=346
Now I want to capture the strings between @ and :, : and |, and the value of keys b, d which may be optional.
I should the following captured
Foo1, dog, 6, 12
Foo2, cat, 11
Foo1, bat, 10
Foo3, pet
I am using this regex
^@(\w+):(\w+).*(?:b=(\d+)).*(?:d=(\d+)) but it only works when both b and d are present.
A: You may use
^@(\w+):(\w+)(?:.*?\|b=(\d+))?(?:.*?\|d=(\d+))?
See the regex demo
Details
*
*^ - start of string
*@ - a @ char
*(\w+) - Group 1: one or more word chars
*: - a colon
*(\w+) - Group 2: one or more word chars
*(?:.*?\|b=(\d+))? - an optional non-capturing group matching any 0+ chars other than line break chars, as few as possible, then |b= and then capturing 1+ digits into Group 3
*(?:.*?\|d=(\d+))? - an optional non-capturing group matching any 0+ chars other than line break chars, as few as possible, then |d= and then capturing 1+ digits into Group 4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62083951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is the std::shared_ptr the same as adding "SharedPtr" to the name of a class when declaring a variable? I encountered a somewhat odd "shared pointer" usage. As far as I know, shared pointers are written out as
std::shared_ptr<void()> pointy(fun, del);
However, I have a case where I have an interface IGenericResult (which all different result-classes implement). I found a place where it simply has "SharedPtr" added to the end of the name. Like this;
IGenericResultSharedPtr result = databasePointer->getLatestResult();
result->getTimestamp(); // Example of usage
It doesn't seem as if there is any defined class/interface/header/anything named IGenericResultSharedPtr so I can only assume it's something built into C++ (currently using version C++11 I think).
Is this the same thing as the std::shared_ptr (and if it is, how would I declare it in the std syntax)? If it's not the same thing, what differences are there?
A: There is no such thing as "if the type name is XYZSharedPtr, it is instead std::shared_ptr<XYZ>" inbuilt into C++.
The authors of the code created a type alias somewhere, either
using IGenericResultSharedPtr = std::shared_ptr<IGenericResult>;
or
typedef std::shared_ptr<IGenericResult> IGenericResultSharedPtr;
(or possibly wrapped in a macro - who knows). Ask your IDE to find the definition :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58875399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I build an un-ordered list dynamically from json data How do I modify this function that dynamically builds a drop down list so that I could build an un-ordered list dynamically from json data.
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$.each(jsonData, function (i, j) {
document.index.spec_list.options[i] = new Option(j.options);
});
});});
</script>
*spec_list* is id of drop down i.e. 'select' here & options i.e. in (j.options) is the field in table which data is received as json. I have 'msg' only table field now which data is to be used to dynamically populate 'ul id="msg"'.
A: So it sounds like you want to append li elements to an existing ul with the ID "msg", where the content of each li comes from the .msg property of each entry in the jsonData:
jQuery.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
var markup;
markup = [];
jQuery.each(jsonData, function (i, j) {
// Note: Be sure you escape `msg` if you need to; if it's already
// formatted as HTML, you're fine without as below
markup.push("<li>");
markup.push(j.msg);
markup.push("</li>");
});
jQuery('#msg').append(markup.join(""));
});
Here's a working example. (See the "off-topic" comment below; the working example uses one of the tricks mentioned.)
Or if the new lis should replace the existing ones in the ul, use
jQuery('#msg').html(markup.join(""));
...instead of append.
Either way, that uses the well-known "build it up in an array and then join it" idiom for building up markup, which is almost always more efficient (in JavaScript implementations) than doing string concatenation. (And building up the markup first, and then applying it with a single DOM manipulation call [in this case via jQuery] will definitely be more efficient than adding each li individually).
If you're not concerned about efficiency (this is showing the result of an Ajax call, after all, and if you know there are only a couple of lis to append...), you could do it like this:
jQuery.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
var ul;
ul = jQuery('#msg');
// If you want to clear it first: ul.empty();
jQuery.each(jsonData, function (i, j) {
// Note: Be sure you escape `msg` if you need to; if it's already
// formatted as HTML, you're fine without as below
ul.append("<li>" + j.msg + "</li>");
});
});
...but if you're dealing with a lot of items, or if you were doing this in something that happened frequently, you're probably better off with the build-it-up version.
Off-topic: Your original code mixes using the jQuery symbol and the $ symbol. Probably best to stick to one or the other, so I went with jQuery above. If you're not using noConflict, or if you're doing one of the nifty tricks for using noConflict but still being able to use $, you can safely change the above over to using $ throughout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4296844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Devise already_authenticated flash message persists for more than 1 redirect In my routes.rb file, I defined the root path like this:
root 'users/sessions#new'
Then, in my ApplicationController, I have logic to redirect like this:
def after_sign_in_path_for(user)
return dashboard_path if user.normal_user?
employee_dashboard_path
end
After signing in as a normal user, navigating to the root path (i.e. localhost:3000), I'm redirected to the dashboard_path as expected. However, when I click on an item on the dashboard and go to the item's show page, I see this flash message:
You are already signed in.
I'm confused, because shouldn't the flash message be flushed out after redirecting to the dashboard_path? I found out if I add code to display the flash message on the dashboard page, the flash message won't show up on the item's show page. The way I'm showing flash message is just simply this:
<div class="alert alert-success" role="alert">
<%= flash[:notice] %>
</div>
I know if I go to the devise.en.yml file and remove the already_authenticated message, the flash won't show up, but I don't want to do that because I do want to show this message for another type of user. Am I doing something wrong? Why does the flash message persist onto the item's show page and won't disappear after redirecting to the dashboard? Thanks for your help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55425747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python: Split string by pattern My question is a variation to this one. I can't seem to figure this one out.
given = "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq"
expected = ["{abc, xyz}", "123", "{def, lmn, ijk}", "{uvw}", "opq"]
As in the above example, an item in the expected could be a {..., ...} or just another string.
Many thanks in advance.
A: I think the following regexp fit the job. Howevever you don't have to have nested curly bracket (nested curly bracket can't be parsed using regular expression as far as I know)
>>> s= "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq"
>>> re.findall(r",?\s*(\{.*?\}|[^,]+)",s)
['{abc, xyz}', '123', '{def, lmn, ijk}', '{uvw}', 'opq']
A: given = "{abc,{a:b}, xyz} , 123 , {def, lmn, ijk}, {uvw}, opq"
#expected = ["{abc, xyz}", "123", "{def, lmn, ijk}", "{uvw}", "opq"]
tmp_l = given.split(',')
tmp_l = [i.strip() for i in tmp_l]
result_l = []
element = ''
count = 0
for i in tmp_l:
if i[0] == '{':
count += 1
if i[-1] == '}':
count -= 1
element = element + i + ','
if count == 0:
element = element[0:-1]
result_l.append(element)
element = ''
print str(result_l)
this one can handle nested curly bracket, although it seems not so elegant..
A: Does the following not provide you with what you are looking for?
import re
given = "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq"
expected = re.findall(r'(\w+)', given)
I ran that in Terminal and got:
>>> import re
>>> given = "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq"
>>> expected = re.findall(r'(\w+)', given)
>>> expected
['abc', 'xyz', '123', 'def', 'lmn', 'ijk', 'uvw', 'opq']
A: You can use the below regex to do that. Rest is same as the similar link you provided.
given = "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq"
regex = r",?\s*(\{.*?\}|[^,]+)"
print re.findall(regex,given)
OP: ['{abc, xyz}', '123', '{def, lmn, ijk}', '{uvw}', 'opq']
Just import the re module. and do the same as the link says.
It will match anything inside the curly braces { } and any string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21423877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Upgraded Azure Function cannot test from the portal We had a Azure Function with Timer Trigger which was develop using function version 3.0 and .NET 3.1. This function is running on Windows App Service Plan on Azure. So, I have upgraded it to function version 4.0 and .NET 6.0 using below steps:
Upgrade your local project
The following changes are required in the .csproj XML project file:
*
*Change the value of PropertyGroup.TargetFramework to net6.0.
*Change the value of PropertyGroup.AzureFunctionsVersion to v4.
*Replace the existing ItemGroup.PackageReference list with the following ItemGroup:
Image
After you make these changes, your updated project should look like the following example:
Image
*Upgrade the local.settings.json file
Image
*Run the function app locally and verify the functionality.
Upgrade your function app in Azure
*
*Run below command to set the FUNCTIONS_EXTENSION_VERSION application setting to ~4 on your function app in Azure.
az functionapp config appsettings set --settings FUNCTIONS_EXTENSION_VERSION=~4 -g <RESOURCE_GROUP_NAME> -n <APP_NAME>
*Change the .NET version of the function app. If you're function app is hosted on Windows, run below command.
az functionapp config set --net-framework-version v6.0 -g <RESOURCE_GROUP_NAME> -n <APP_NAME>
However, I cannot test or see the function.json file from Azure Portal.
A: I have taken the .NET 3.1 Azure Function Project with Timer Trigger in the VS 2022 IDE:
Published the .NET Core 3.1 Azure Functions Project to Azure Function App in the Azure Portal and then changed the FUNCTIONS_EXTENSION_VERSION to 4 using Azure CLI Command by following this MS Doc:
Running locally after migration to V4-.NET 6:
Then, deployed the migrated project to the Azure Function App and tested as shown below:
A: I was able to find the reason for the issue by running "Diagnose and solve problems" from Azure portal.
The issue was related to the function name. My function name length was more than 32 characters long. By default, the Host ID is auto-generated from the Function App name, by taking the first 32 characters. If you have multiple Function Apps sharing a single storage account and they're each using the same Host ID (generated or explicit), that can result in a Host ID collision. For example, if you have multiple apps with names longer than 32 characters their computed IDs may be the same. Consider two Function Apps with names myfunctionappwithareallylongname-eastus-production and
myfunctionappwithareallylongname-westus-production
that are sharing the same storage account. The first 32 characters of these names are the same, resulting in the same Host ID myfunctionappwithareallylongname being generated for each(Please refer https://github.com/Azure/azure-functions-host/wiki/Host-IDs#host-id-collisions for more information).
So, to solve the issue, I just rename the function name on Azure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75154249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ethereum mining - amount actually mined is Im trying my luck on ethereum mining with this, can someone tell me how much ethereum I have mined and how to cash it :)
https://github.com/angelomilan/ethereum-guides/blob/master/GPU-cloud_mining.md
> eth.getBalance(eth.coinbase).toNumber();
5000000000000000000
> web3.fromWei(eth.getBalance(eth.coinbase), "ether")
5
What is 5000000000000000000 and what is 5 ?
A: 5000000000000000000 is your balance in wei, which represents 5 ethers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48659091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: button onclick replace hours and minutes, JavaScript Can any body help me, the button replace hours and minutes (HH:MM) onclick.
<button id="pressbtn1" onclick="getElementById('pressbtn1').innerHTML=Date()">Press</button>
A: Use .getHours() and .getMinutes() like...
<html>
<button id="pressbtn1" onClick="show()">Press</button>
<script>
function show()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
document.getElementById("pressbtn1").innerHTML = h+":"+m;
}
</script>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58051468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to specify taskExecutor in publishSubscribe() How to "translate" the following XML configuration to the equivalent Spring integration java-dsl?
<int:publish-subscribe-channel id="channel" task-executor="myex">
</int:publish-subscribe-channel>
<task:executor id="myex" pool-size="10"></task:executor>
I've read the DSL Reference Guide, but still can't figure it out.
A: MessageChannels chapter points out to the MessageChannels factory. So, <publish-subscribe-channel> XML config translates to Java config like:
@Bean
public MessageChannel channel() {
return MessageChannels.publishSubscribe(myExecutor()).get();
}
Although you can reach the same just with raw Java config:
@Bean
public MessageChannel channel() {
return new PublishSubscribeChannel(myExecutor());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38276996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: hide and show a dynamic created UL list with Jquery? Well, as the question says, Im found a code that makes the UL list show and hide with Jquery.
Here is a link on jsFiddle and when I made a UL list directly on the HTML it works but not if I add it dynamically with javascript. http://jsfiddle.net/p2v0ka1s/4/
The problem I found is that the Jquery creates classnames that is called and changed by clicking, and those classnames doesnt apply to my dynamic UL list and I dont know why. Can you please help me?
Here is my code that creates it dynamically and the test of jquery that doesnt work. http://jsfiddle.net/aytnt4bL/1/ The Jquery code is at the button of the javascript code (I added it there, but I have it as a separate sourcefile in my computer.
I add the code here in the text too, so you can see it!
It works perfect with non-dynamic UL list so there is my issue, to make it work with my dynamic created UL list. Thanks!
$(function() {
$('.contactlist').click(function(e) {
e.stopPropagation();
var sub = $('> ul', this);
if(sub.length) {
if(sub.is(':visible')) {
sub.hide();
sub.removeClass('open');
} else {
$('.contactlist .open').hide().removeClass('open');
sub.show();
sub.parents('ul:not(.contactlist)').addClass('open').show();
sub.addClass('open');
}
}
});
});
Thanks for your help!
A: You need to use event delegation for attaching events to dynamically added elements:
$('body').on('click','.contactlist',function(e) {
e.stopPropagation();
var sub = $('> ul', this);
if(sub.length) {
if(sub.is(':visible')) {
sub.hide();
sub.removeClass('open');
} else {
$('.contactlist .open').hide().removeClass('open');
sub.show();
sub.parents('ul:not(.contactlist)').addClass('open').show();
sub.addClass('open');
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26689416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React input field doesn't see value changing When i picking date, event doesn't see anything, nothing happened, i cannot extract my value from input field. What **** ? Is it problem React or Datepicker? In datepicker manual nothing say about that, http://t1m0n.name/air-datepicker/docs/index.html
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
dueDate: 'Date and time'
}
}
componentDidMount(){
this.initDatepicker();
}
initDatepicker(){
$(this.refs.datepicker).datepicker();
}
render(){
return (
<div>
<h3>Choose date!</h3>
<input
value={this.state.dueDate}
type='text'
onChange={event => console.log(event)}
ref='datepicker'
/>
</div>
)
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css" rel="stylesheet"/>
<div id="app"></div>
A: You bound the input field value to the state property dueDate. Now if you want to modify it, you have to refresh the state property on input field change, therefore:
onChange={event => this.setState({dueDate: event.target.value})}
A: You wrote a controlled component. You set a state value to input element. If the state changes, your input value change. So you change the code below like,
// input element
<input value={this.state.dueDate} onChange={this.handleDueDate}/>
// handleDueDate method
handleDueDate(event){
this.setState({
dueDate: event.target.value
})
}
If you change your code looks like, its works fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44865423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: After insert Node to XML formating I add a new node to an existing XML but the format is not well.
Original XML is:
<xml xmlns:xi="http://www.w3.org/2001/XInclude">
<vars>
....
I tried to insert before "vars" and the result is
<xml xmlns:xi="http://www.w3.org/2001/XInclude">
<TCafe initvalue="1" type="int"/><vars>
But I expect
<xml xmlns:xi="http://www.w3.org/2001/XInclude">
<TCafe initvalue="1" type="int"/>
<vars>
My code is simple:
var xmlDoc = new DOMParser().parseFromString(dataRegelWerk);
if(allok == false){
var root = xmlDoc.documentElement;
var varselem = xmlDoc.getElementsByTagName('vars')[0];
var newEle = xmlDoc.createElement('TCafe');
var att1 = xmlDoc.createAttribute("initvalue");
att1.value = "1";
var att2 = xmlDoc.createAttribute("type");
att2.value = "int";
newEle.setAttributeNode(att1);
newEle.setAttributeNode(att2);
root.insertBefore(newEle, varselem);
}
var myFile = serializer.serializeToString(xmlDoc);
Do I understand something wrong with insertBefore? or is this a good XML formatting and I just expect a wrong thing?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58875607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript MVC Framework for building reusable components on a non-SPA site We have an existing Genealogy site which is not a single-page app, and over the years we've created a number of jQuery plugins for doing things such as typeahead, various modal-based utilities, and components that are reusable around the site. We aren't doing a single-page app because we are a content publisher, and we're not yet confident that search engines will reliably index these in our use case.
We are now looking at adding some more complex widgets that have multi-view modal flows. An example for our Genealogy site is that there are numerous cases where a user must select a Person record from a pool of records they are following OR optionally, create a new one.
For example, say you are viewing a person record want to change the family tree relationships on a person. You click on a link and a modal appears allowing you to edit their relationships. We were envisioning a modal flow that looks like this:
*
*View 1 (Index): A management page that lists current relationships, along with an "Add Person" pulldown that allows you to select a relationship type (Parent, Spouse, Child, Sibling)
*View 2 (Add a person): We show a text input field with typeahead support. As the user types, we look through the pool of people on their graph and try to make a match. If they match something in typeahead, we can capture that and send that back to the parent app.
*View 3 (Search for matches): The user may have just missed the typeahead results - so allow the API to see if there are any potential matches in their graph. Allow the user to choose a match, and send this back. If there are no matches, they can click "These are not my person"
*View 4 (Create person): If we couldn't find a matching person in their graph, this is a completely new person. Give them a form to give details about the person.
I'm at a loss for what might be the best solution for this. I've looked into EmberJS and AngularJS, and folks in both those communities suggested that if you're not building a single-page app, it's not worthwhile using these frameworks.
Can anyone point me in the right direction? I can't be unique in this use case!
A: I have built several mini-SPA apps using both Knockout.js and Ember.js. There are a lot of good reasons for serving a mini-Single-Page-Application rather than converting your entire app, mainly that client-side code doesn't do everything better.
In my experience, both Angular and Ember.js are very useable without making your whole app client-side. Ember gives you some very useful tools for making "widgets".
For example, if I want my Ember application to render on a part of my server-side page, I can do this:
var App = Ember.Application.create({
// Set the rootElement property to the div that I want my ember app to render inside
rootElement: "#your-root-element",
Resolver: Ember.DefaultResolver.extend({
resolveTemplate: function(parsedName) {
// Override this method to make this app look for its templates in a subdirectory
}
}),
});
// Don't render the app on any page by default
App.deferReadiness();
// Instead, check to see if the #rootElement is present on the page before rendering.
$(document).ready(function() {
if ( $(App.get('rootElement')).length > 0 ) {
App.advanceReadiness();
}
});
I'm sure you can do similarly with Angular.js. I prefer Ember for the following reasons:
*
*A genuine class/mixin system. This is really helpful when you want to share code: it should be very familiar to anyone who is used to working on the server side.
*Very flexible templating.
*Clear separation of concerns, allowing many different views and such to be handled elegantly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21197574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Connecting GitHub Account and SourceTree with SSH I am on a Windows 10 laptop with git version 2.20.1.windows.1 and Sourcetree version 3.0.17. I am using the System Git (I don't have the Embedded Git downloaded, so there isn't any interference there).
I am trying to add my GitHub account to Sourcetree for easier cloning of repos (so I don't have to use HTTPS links for each one), and I am not able to see any of the repos once the account is added. I have tried using both OAuth and basic, and also tried using OpenSSH, as suggested in this SO post (this is also the only way I could get Sourcetree to link with my Bitbucket account).
Unfortunately it is not working, but when I open Git Bash and type ssh -T git@github.com I receive a message acknowledging I have connected my account to git on my laptop. It also doesn't work adding the account via HTTPS (OAuth or basic).
Does anyone have a suggestion, as this is slowing my migration of some projects to GitHub?
A: Check your SourceTree Git settings, and make sure your are using the System Git, not the embedded one.
Otherwise, your local Git installation (which does connect to GitHub) would be ignored.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54777335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can I cancel out gravity only with gyro and magnetometer? On a device I want to detect a range of forces: small forces (Minimum around 0.01g) but also stronger forces like 0.1g - 0.15g.
This device will have different positions in 3d space so in order to detect the small forces I have to know its angle in order to be able to subtract 1g. Because the device can have a random position (angle position).
What I did so far: I used the MPU6050 and used a complementary filter with accel. and gyro.
It's something like:
agnleX_k+1 = 0.98*(angle_k + deltaT * gyro_k+1) + 0.02*angle_acc_k+1;
angle_acc is the angle calculated from the accel. sensor. Something like:
arctan(accelX / sqrt(accelX^2 + accelY^2 + accelZ^2 + ))
So I am interested in:
forceX_k+1 = accelX_k+1 - 1g*sin(agnleX_k+1)
The problem is:
If I want to detect a small force coming in very fast, let's say on accelX_k+1 I would want to detect a Change from 0g to 0.01g or more but in a very small time range. The problem is that my calculated angle would then also be influenced by this small and fast change of the accel. sensor although the angle haven't really changed.
I think I would have to do the angle calculation independent of the accel. sensor. Can I do something like a complementary filter with gyro and magnetometer? Would that work the same as my filter described above but just with the mag. sensor instead? Or how would you do that? I was thinking about using MPU9250.
A: You stated using MPU6050, which contains both an accelerometer and a gyrosocpe. You could use them independantly - get acceleration from the accelerometer and get angles from the gyroscope, and then use the angles to compensate for rotation. There is no need for the angle to depend on your accelerometer.
A: Using DMP library fromJeff Rowberg will do the work for you.
it can compensate gravity acceleration internally way faster that Arduino code.
Link to github
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40830641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Issue while printing the decimal values when reading from excel using java In Excel I have these decimal values:
TS
BS
5.60
4.10
10.00
10.00
10.00
10.00
10.00
10.00
While parsing, it shows different values:
TS
BS
0.1375
0.85
0.0125
0.7125
0.0125
0.8125000000000001
0.0125
0.7875000000000001
I need to print the exact values.
Here is the code:
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext())
{
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch (cell.getCellType())
{
case STRING:
System.out.print(cell.getStringCellValue() + "\t\t\t");
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
System.out.print(dateFormat.format(cell.getDateCellValue()) + "\t\t\t");
} else {
System.out.print(cell.getNumericCellValue() + "\t\t\t\t");
}
break;
default:
}
}
System.out.println("");
}
I'm using Apache POI-4.1.1.
Could please someone help me with this?
A: g00se is right. My issue is solved. I had to parse the values from formula.
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext()) {
Row row = itr.next();
//iterating over each column
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
CellType cellType = cell.getCellType();
if (cell.getCellType() == CellType.FORMULA) {
switch (cell.getCachedFormulaResultType()) {
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING:
System.out.print(cell.getRichStringCellValue() + "\t\t");
break;
}
}
switch (cell.getCellType()) {
case STRING:
//field that represents string cell type
System.out.print(cell.getStringCellValue() + "\t\t");
break;
case NUMERIC:
//field that represents number cell type
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); System.out.print(dateFormat.format(cell.getDateCellValue()) + "\t\t");
}
else {
double roundOff = Math.round(cell.getNumericCellValue() * 100.0) / 100.0;
System.out.print(roundOff + "\t\t");
}
break;
case BLANK:
break;
default:
}
}
System.out.println("");
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68755486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use empty list as fill value for Series.fillna I need to change the NaN values the column 'FocusColumn' to empty lists.
I tried to do it like this:
df['FocusColumn'].fillna([],inplace=True)
But it throws me the following error:
337 if validate_scalar_dict_value and isinstance(value, (list, tuple)):
338 raise TypeError(
339 '"value" parameter must be a scalar or dict, but
340 f'you passed a "{type(value).__name__}"'
341 )
TypeError: "value" parameter must be a scalar or dict, but you passed a "list"
What is the correct way to do it?
A: Looks like you can work around this by supplying a dict to Series.fillna.
>>> df
FocusColumn
0 NaN
1 1.0
2 NaN
>>> df['FocusColumn'].fillna({i: [] for i in df.index})
0 []
1 1
2 []
Name: FocusColumn, dtype: object
Notes:
*
*Surprisingly, this only works for Series.fillna.
*For large Series with few missing values, this might create an unreasonable amount of throwaway empty lists.
*Tested with pandas 1.0.5.
A: You could try the following:
import pandas as pd
import numpy as np
df = pd.DataFrame({'FocusColumn': [1, 2, 3, 4, np.NaN, np.NaN, np.NaN, np.NaN], 'Column1': [1, 2, 3, 4, 5, 6, 7, 8], 'Column2': [7, 8, 6, 5, 7, 8, 5, 4]})
df['FocusColumn'] = df['FocusColumn'].apply(lambda x: [] if np.isnan(x) else x)
print(df)
Output:
FocusColumn Column1 Column2
0 1 1 7
1 2 2 8
2 3 3 6
3 4 4 5
4 [] 5 7
5 [] 6 8
6 [] 7 5
7 [] 8 4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62684835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: React Buttons change color from parent component I'm learning react and making a simple quiz where the div changes color based on if the solution is correct or not, but I want to reset the color when the "Next" or "Previous" question is selected from the parent component. I tried creating a prop called clearColor and when that is true reset the color from within the component but this isn't quite working. I was wondering how to best go about this? Because I am so new to react I wasn't even quite sure what to google so any help is appreciated!
class Button extends React.Component {
constructor(props) {
super(props);
this.state = this.getInitialState();
}
componentWillMount() {
this.initialState = this.state
}
getInitialState = () => ({
bgColor: ""
})
resetState = () => {
if (this.props.clearColor) {
this.setState(this.initialState)
}
}
boxClick = (e) => {
if (this.props.isCorrect) {
this.setState({
bgColor: "#9ef0bc"
})
} else {
this.setState({
bgColor: "#f56342"
})
}
}
render() {
return (
<div className="boxClickCss"
style={{backgroundColor: this.state.bgColor}}
onClick={this.boxClick}>{this.props.name}</div>
);
}
}
function Quiz() {
const questions = [
{
questionText: 'What is the capital of France?',
answerOptions: [
{ answerText: 'New York', isCorrect: false },
{ answerText: 'London', isCorrect: false },
{ answerText: 'Paris', isCorrect: true },
{ answerText: 'Dublin', isCorrect: false },
],
},
{
questionText: 'Who is CEO of Tesla?',
answerOptions: [
{ answerText: 'Jeff Bezos', isCorrect: false },
{ answerText: 'Elon Musk', isCorrect: true },
{ answerText: 'Bill Gates', isCorrect: false },
{ answerText: 'Tony Stark', isCorrect: false },
],
},
{
questionText: 'The iPhone was created by which company?',
answerOptions: [
{ answerText: 'Apple', isCorrect: true },
{ answerText: 'Intel', isCorrect: false },
{ answerText: 'Amazon', isCorrect: false },
{ answerText: 'Microsoft', isCorrect: false },
],
},
{
questionText: 'How many Harry Potter books are there?',
answerOptions: [
{ answerText: '1', isCorrect: false },
{ answerText: '4', isCorrect: false },
{ answerText: '6', isCorrect: false },
{ answerText: '7', isCorrect: true },
],
},
];
const [currentQuestion, setCurrentQuestion] = React.useState(0);
const [clearColor, setClearColor] = React.useState(false)
const nextClicked = () => {
setClearColor(true);
const nextQuestion = currentQuestion + 1;
if (nextQuestion < questions.length) {
setCurrentQuestion(nextQuestion);
}
};
const previousClicked = () => {
setClearColor(true)
if (currentQuestion <= 0) {
setCurrentQuestion(0);
} else {
const nextQuestion = currentQuestion - 1;
setCurrentQuestion(nextQuestion);
}
}
return (
<div className='quiz'>
<div className='app'>
<div className='question-section'>
<div className='question-count'>
<span>Question {currentQuestion + 1}</span>/{questions.length}
</div>
<div className='question-text'>{questions[currentQuestion].questionText}</div>
</div>
<div className='answer-section'>
{questions[currentQuestion].answerOptions.map((answerOption) => (
<Button name={answerOption.answerText} isCorrect={answerOption.isCorrect} clearColor={clearColor} />
))}
</div>
</div>
<br></br>
<div className='buttons'>
<button className="prev" onClick={() => previousClicked()}>Previous</button>
<button className="next" onClick={() => nextClicked()}>Next</button>
</div>
</div>
);
}
ReactDOM.render(
<Quiz />,
document.getElementById('root')
);
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
font-family: "Verdana", cursive, sans-serif;
color: #014650;
}
body {
background-color: #014650;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.app {
display: flex;
justify-content: space-evenly;
}
.score-section {
display: flex;
font-size: 24px;
align-items: center;
}
/* QUESTION/TIMER/LEFT SECTION */
.question-section {
width: 100%;
position: relative;
}
.question-count {
margin-bottom: 20px;
}
.question-count span {
font-size: 28px;
}
.question-text {
margin-bottom: 12px;
}
.timer-text {
background: rgb(230, 153, 12);
padding: 15px;
margin-top: 20px;
margin-right: 20px;
border: 5px solid rgb(255, 189, 67);
border-radius: 15px;
text-align: center;
}
/* ANSWERS/RIGHT SECTION */
.answer-section {
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.boxClickCss {
width: 80%;
font-size: 16px;
color: #014650;
background-color: white;
border-radius: 15px;
display: flex;
padding: 5px;
justify-content: flex-start;
align-items: center;
border: 5px solid #234668;
cursor: pointer;
margin-top: 15px;
}
.boxClickCss:hover {
background-color: #6A939A;
}
button {
width: 100%;
font-size: 16px;
color: #7BC8C3;
background-color: #252d4a;
border-radius: 15px;
display: flex;
padding: 5px;
justify-content: flex-start;
align-items: center;
border: 5px solid #234668;
cursor: pointer;
margin-top: 15px;
}
.correct {
background-color: #2f922f;
}
.incorrect {
background-color: #ff3333;
}
button:hover {
background-color: #555e7d;
}
button:focus {
outline: none;
}
button svg {
margin-right: 5px;
}
.buttons {
display: flex;
justify-content: space-between;
}
.prev {
width: 30%;
text-align: center;
}
.next {
width: 30%;
text-align: center;
}
.quiz {
background-color: #DEF2F0;
width: 450px;
min-height: 200px;
height: min-content;
border-radius: 15px;
padding: 20px;
box-shadow: 10px 10px 42px 0px rgba(0, 0, 0, 0.75);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-
dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
<!-- This div's content will be managed by React. -->
</div>
I also have a codepen here if that is easier to work with: https://codepen.io/mayagans/pen/mdOypGG?editors=1111 I tried looking into lifting up state so I can change the bgColor in the parent component but I'm not sure that is react-y? Any help on how to tackle this appreciated!
A: You need to lsiten to props changes during componentDidUdpate like this, to check:
componentDidUpdate() {
if (this.props.clearColor && this.state.bgColor) {
this.setState(this.initialState)
}
}
Moving the state up is reacty and you could be using that.
I would recommend that or moving it into a context.
Also maybe look into function components, which will be the main way to write react in the future.
A: This is how I would do it. I would just lift all the state up to Quiz component. Also would keep boxClick function in Quiz component and pass it to Button component. And I am colouring the button only which title match currently selected answer using setAnswer hook.
const Button = ({answer, name, bgColor, isCorrect, boxClick, setAnswer}) => {
return (
<div className="boxClickCss"
style={{backgroundColor: (answer === name) && bgColor}}
onClick={(e) => {
boxClick(isCorrect)
setAnswer(name)
}}>
{name}
</div>
)
}
const Quiz = () => {
const questions = [
{
questionText: 'What is the capital of France?',
answerOptions: [
{ answerText: 'New York', isCorrect: false },
{ answerText: 'London', isCorrect: false },
{ answerText: 'Paris', isCorrect: true },
{ answerText: 'Dublin', isCorrect: false },
],
},
{
questionText: 'Who is CEO of Tesla?',
answerOptions: [
{ answerText: 'Jeff Bezos', isCorrect: false },
{ answerText: 'Elon Musk', isCorrect: true },
{ answerText: 'Bill Gates', isCorrect: false },
{ answerText: 'Tony Stark', isCorrect: false },
],
},
{
questionText: 'The iPhone was created by which company?',
answerOptions: [
{ answerText: 'Apple', isCorrect: true },
{ answerText: 'Intel', isCorrect: false },
{ answerText: 'Amazon', isCorrect: false },
{ answerText: 'Microsoft', isCorrect: false },
],
},
{
questionText: 'How many Harry Potter books are there?',
answerOptions: [
{ answerText: '1', isCorrect: false },
{ answerText: '4', isCorrect: false },
{ answerText: '6', isCorrect: false },
{ answerText: '7', isCorrect: true },
],
},
];
const [currentQuestion, setCurrentQuestion] = React.useState(0);
const [bgColor, setbgColor] = React.useState('')
const [answer, setAnswer] = React.useState('')
const boxClick = isCorrect => {
if(isCorrect) {
setbgColor("#9ef0bc")
} else {
setbgColor("#f56342")
}
}
const nextClicked = () => {
const nextQuestion = currentQuestion + 1;
if (nextQuestion < questions.length) {
setCurrentQuestion(nextQuestion);
}
};
const previousClicked = () => {
if (currentQuestion <= 0) {
setCurrentQuestion(0);
} else {
const nextQuestion = currentQuestion - 1;
setCurrentQuestion(nextQuestion);
}
}
return (
<div className='quiz'>
<div className='app'>
<div className='question-section'>
<div className='question-count'>
<span>Question {currentQuestion + 1}</span>/{questions.length}
</div>
<div className='question-text'>{questions[currentQuestion].questionText}</div>
</div>
<div className='answer-section'>
{questions[currentQuestion].answerOptions.map((answerOption) => (
<Button name={answerOption.answerText} isCorrect={answerOption.isCorrect} boxClick={boxClick} bgColor={bgColor} setAnswer={setAnswer} answer={answer} />
))}
</div>
</div>
<br></br>
<div className='buttons'>
<button className="prev" onClick={() => previousClicked()}>Previous</button>
<button className="next" onClick={() => nextClicked()}>Next</button>
</div>
</div>
);
}
ReactDOM.render(
<Quiz />,
document.getElementById('root')
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65985142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ruby compatibility error encoding I'm having a problem. Let's look:
C:\temp> ruby script.rb
script.rb => Powershell output
puts "ę" => ę #irb \xA9
puts "\xA9" => ▯
puts "ę"=="\xA9" => false
input = $stdin.gets.chomp => input=="ę"
puts "e#{input}e" => eęe
puts "ę"==input => false
puts "ę#{input}" => Encoding::Compatibility Error Utf8 & CP852
irb => #command line in ruby
puts "ę"=="\xA9" => true
input = $stdin.gets.chomp => input=="ę"
puts "ę"==input => true && "\xA9"==input => true
puts "ę#{input}" => ęę
It looks like powershell's input uses other font for all special characters than ruby and notepad++(?). Can i change that so it will work when i type in prompt(when asked) and does not show an error?
Edit: Sorry for misdirection. I added invoke and specified that file has extension ".rb" not ".txt"
Edit2: Ok, I've researched some more information and I've been trying do some encoding(UTF8) to a variable. Somethin' strange occured.
puts "ę#{input.encoding}" => ęCP852
puts "\xA9" => UTF-8
Encoding to CP852 has revealed that encoding pass on bytes. I learned that value of "ę"=20+99=119, "ą" = 20 + 85, 20 = C4
Ok. got it ".encoding" - shows what encoding i use. And that resolve this problem.
puts "ę#{input.encode "UTF-8"}" => ęę
Thanks everyone for your input.
A: If your input in prompt( either cmd or powershell) is causing problems due to incompatibility of using differents encodings just try to encode it via methods in script.encode "UTF-8" #in case of Ruby language If you dont know what methods do that just google your_language_name encoding
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37029914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to configure Database Driver Location(s) in a Nifi process when Nifi is runing on a Kuberntes pod I have deployed Nifi on Kubernetes using cetic/helm-nifi helm chart. I have to insert log data to a MySQL database using a PutDatabaseRecord process. To do that, inside of PutDatabaseRecord process, I have to configure Database Connection URL, Database Driver Class Name & Database Driver Location(s).
As the Database Driver Location, I downloaded the connector jar (https://dev.mysql.com/downloads/connector/j/) inside the pod and configured the location of the MySQL connector jar file inside the PutDatabaseRecord process. In that way, if the pod is getting restart, I have to download connector manually inside the pod again. It is not a recommended way to do that. Appreciate if you can suggest a solution for this.
A: It would be really helpful to see your Kubernetes configuration, but overall you can use ConfigMaps for this purpose - as it is standard Kubernetes resource for storing configuration data. It is described in more details here.
Below is the example of ConfigMap, where MySQL connector jar file is mounted to the pod:
containers:
- name: container
volumeMounts:
- name: config
mountPath: /usr/local/mysql-connector-java.jar
volumes:
- name: config
configMap:
name: config-map
items:
- key: mysql-connector-java.jar
path: mysql-connector-java.jar
But ConfigMap will work for you only if you are storing the connector jar file, which size is not exceeding 1 MiB.
Otherwise, there is one more option - mounting a persistent volume with a MySQL connector jar file - as described here and here. The jar file will be copied to the pod once persistent volume is mounted into it - and it can be re-mounted to the pod after its restart/re-creation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71050188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Integrate custom java web application with MS dynamics CRM Currently we have custom java application which is connected to salesforce CRM via canvas integration. Now we need to integrate with MS dynamics CRM.
Could you please tell me high level steps? how authentication will happen when control come from dynamics to custom application? Is there any canvas integration / iframe like thing in ms dynamics?
A: The best thing for a non .Net Application is to use the Dynamics 365 WebApi
It supports all common types of CRM Instances (On-Premise, Online) and authentication Methods:
*
*OAuth (2)
*Office365
*AD
*etc...
You can than look for existing projects on the web. (Like this guide for example)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45583873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: QScrollArea not scaling to the window I'm trying to use a QScrollArea in order to be able to put a lot of widgets on the same window. Unfortunately, the QWidget containing the QScrollAea (which is central) is not scaling to the size of the window, which makes it... not like I want... I tried different things but I can't fix it... any idea?
QWidget *central = new QWidget(this);
QScrollArea *scroll = new QScrollArea(this);
QVBoxLayout *vLayout = new QVBoxLayout(central);
this->setCentralWidget(central);
central->setLayout(vLayout);
//vect is not empty
for (elt t : vect)
{
vLayout->addWidget(new TweetDisplay(elt, t));
}
//If I remove those three lines, everything is displayed but of course, I can't scroll.
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
scroll->setWidget(central);
scroll->setWidgetResizable(true);
Picture for reference:
A: Instead of setting the central widget to central you should try using scroll as your central widget. Thus, the proper line would be:
this->setCentralWidget(scroll);
Remember the scroll area uses central as the widget it contains already, so setting it as the central widget doesn't actually make sense.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40947003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SSIS export to Excel template - keep row height I have a following excel 2007 template (.xlsx):
I have set up an SSIS process to copy that template and populate the first two columns with data as the file will be printed and then signed by order recipients. Everything is going well except for one thing - after the process populates the template with data, the cells don't retain their size - making signature cells too small.
Any ideas on how to force excel to keep the cell heights ?
A: One idea would be to create a macro that runs when the workbook is opened and it sets the row height using the Range.RowHeight property, here:
https://msdn.microsoft.com/en-us/library/office/ff193926.aspx
A: If anyone ever has a similar issue, I managed to find a workaround. Instead of using SSIS I'm using SSRS where I keep the cell height by adding an "invisible (white text on white background) column at the end. I set up an SSRS subscription to automatically export the data and send as an Excel.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42704887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Interfaces With generic factory i'm trying to do fancy stuff like this:
i have following code:
public interface IMyInterface
{
void Method1();
}
public interface IClassFactory
{
object GetObject();
}
public interface IGenericClassFactory<T> where T: IMyInterface
{
T GetObject();
}
public class MyClass : IMyInterface
{
public void Method1()
{
Console.WriteLine("Medota 1");
}
}
public class MyFactory : IClassFactory
{
public object GetObject()
{
return new MyClass();
}
}
public class MyGenericFactory<T> : IGenericClassFactory<T> where T : IMyInterface, new()
{
public T GetObject()
{
// T t = new T();
//return t;
//var ctor = typeof(T).GetConstructor(new Type[0]);//1] { typeof(int) });
//if (ctor != null)
//{
// return (T)ctor.Invoke(new object[0]); // new object[1] { 5});
// //return Activator.CreateInstance<T>(); //to samo co wyzej tylko nie jest bezpieczne
//}
//throw new InvalidOperationException("T nie posiada domyślnego konstruktora");
// return Activator.CreateInstance<T>(); //bez parametrów
// return (T)Activator.CreateInstance(typeof(T), 5, "EOG", new object()); // z parametrami
return new T();
}
}
static void Main(string[] args)
{
IClassFactory factory;
factory = new MyFactory();
IGenericClassFactory<IMyInterface> genFactory;
genFactory = new MyGenericFactory<MyClass>(); //Do not compile!
MyClass obj = genFactory.GetObject() as MyClass;
obj.Method1();
Console.ReadKey();
}
I can do this like:
IGenericClassFactory<IMyInterface> genFactory;
genFactory = new MyGenericFactory<MyClass>();
//so i can chose object to create
but i think it is pointless because i want to have Factory of more then one object.
Can u help me?
Thx in advance
A: You should not make your factory class generic but the method GetObject should be generic:
public T GetObject<T>() where T: IMyInterface, new()
Then:
static void Main(string[] args)
{
var factory = new MyFactory();
var obj = factory.GetObject<MyClass>();
obj.Method1();
Console.ReadKey();
}
So all in all you should get rid of your generic code and simply modify your MyFactory class
public class MyFactory : IClassFactory
{
public T GetObject<T>()
{
//TODO - get object of T type and return it
return new T();
}
}
By the way - I am not sure what is the purpose of having this generic implementation? Does it make any sense from the perspective of the usage of Factory pattern?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21627742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Trouble pulling events between 2 dates in Codeigniter / PHP I have created an events calendar with codeigniters calendar class which you can view here: Events Calendar
I have it set up where the events are showing up on the calendar and when you click "view events" on a particular day, all the events with that start date pull up and are shown in a modal window.
Well... the problem is that unless its the START DATE of a particular event, the modal window details don't pull up. I know this is because i'm saying in my query to pull events where the start date equals a certain date...
I'm kind of stumped on how to modify this to say, "pull all records where this day is ANYWHERE BETWEEN the start and end date of the event.
Do I need to run a while loop or something and loop through each day of the month? Any ideas on an easier way to do this are appreciated.
the start and end dates are set up as 'Y-m-d H:i:s' in the database and the $query_date variable being passed in is 'Y-m-d', which i change to the same format in the first few lines of the function.
function get_list_events($query_date) {
$start_date_start = date('Y-m-d H:i:s', strtotime($query_date.' 00:00:00'));
$start_date_end = date('Y-m-d H:i:s', strtotime($query_date.' 23:59:59'));
$this->db->where('active', 1);
$this->db->where("start_date BETWEEN '$start_date_start%' AND '$start_date_end%'", NULL, FALSE);
$query = $this->db->get('events');
$data = array();
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'title' => $row->title,
'description' => $row->description,
'cost' => $row->cost,
'image' => $row->image,
'start_date' => $row->start_date,
'end_date' => $row->end_date,
'venue' => $row->venue,
'venue_address' => $row->venue_address,
'venue_city' => $row->venue_city,
'venue_state' => $row->venue_state,
'venue_zipcode' => $row->venue_zipcode,
'contact_name' => $row->contact_name,
'contact_email' => $row->contact_email,
'contact_phone' => $row->contact_phone,
'contact_website' => $row->contact_website,
'create_date' => $row->create_date,
'active' => $row->active,
);
}
return $data;
}
A: I guess your start_date column has the DATETIME or the TIMESTAMP data type. If that isn't true, please update your question.
There's a common trap in date-range processing in all kinds of SQL, due to the fact that when you compare a pure DATE with a DATETIME, they hardly ever come out equal. That's because, for example, DATE('2011-07-1') means the same thing as 2011-07-01 00:00:00.
So you need
start_date >= '$start_date_start'
AND start_date < '$start_date_end' + INTERVAL 1 DAY
instead of what you have, which is
start_date BETWEEN '$start_date_start%' AND '$start_date_end%' /*wrong!*/
The second clause with the < ... + INTERVAL 1 DAY picks up all possible times on the last day of your interval.
Edit Now that you've disclosed that you have two DATETIME columns, called start_date and end_date, it sounds like you're looking for items which start on or before a specific date, and end on or after that same date. Try something like this:
WHERE DATE(start_date) <= DATE('$specific_date')
AND DATE(end_date) >= DATE('$specific_date')
The trick on queries like this is to spend the majority of your time thinking through and specifying the results you want. If you do this, the SQL is often perfectly obvious.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22990825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set cvxpy n-dim variable first value? I'm a beginner at python and I try to use cvxpy library for my optimization project. I try to change the first value of my n dimensional variable But I get an AttributeError
import cvxpy as cp
S = cp.Variable(100)
S[0].value=320000
output:AttributeError: can't set attribute
It works for 1-dim variable
import cvxpy as cp
S = cp.Variable()
S.value=320000
Thanks in advance
A: The 'Variable' object does not support item assignment. You may enforce your requirement as a constraint:
import cvxpy as cp
S = cp.Variable(100) # Define your variables
objective = ... # Define your objective function
constraints = [] # Create an array of constraints
constraints.append(S[0]==320000) # Make your requirement a constraint
# Add more constraints
prob = Problem(objective, constraints) # Define your optimization problem
prob.solve(verbose=True) # Solve the problem
print(S.value)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62299396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google maps javascript example not working I am using the example from the google maps website.
https://developers.google.com/maps/documentation/javascript/tutorial
I am posting the entire code below. I get a blank screen - nothing seems to show up either on firefox or chrome. Can anyone suggest what is going on?
Thank you,
-VJ
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
A: Ok so i figured out the problem. I was saving the code in an html file using wordpad and saving it in format Unicode. When I saved the file using notepad and format ANSI, everything is ok. Took me the entire morning to figure this out!!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16448562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Display Google Map Direction instructions in different languages I am using Google Map service. Now I integrated Google Map Direction into my application, but all direction instructions are English.
Anyone know the way to translate it into other languages? (e.g Vietnamese). You can see the site: maps.google.com, when you use your own language, all the direction instructions are translated into your language. That's what I need.
Thanks :)
A: The directions service will either use the browser's configured language or you can specify the language to use when loading the API.
From the API docs:
Textual directions will be provided using the browser's preferred
language setting, or the language specified when loading the API
JavaScript using the language parameter. (For more information, see
Localization.)
A: Just specify your language using the language parameter when loading the API:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en-US"></script>
See full list of supported languages here : https://developers.google.com/+/web/api/supported-languages
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9512421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: UICollectionView load image cannot get correct cell swift 3 My UICollectionView is fetching images in cellForItemAt. After I upgrade to swift 3, some images are not showing when I scroll very fast. Here is my code in cellForItemAt:
if (imageNotInCache) {
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
if let thumb = imageFromPathAndCacheIt(path) {
DispatchQueue.main.async {
let updateCell = collectionView.cellForItem(at: indexPath) as! MyCustomCell? {
updateCell.imageView.image = thumb
}
}
}
The problem is, sometimes I get updateCell as nil even it is on the screen (probably because scroll to fast).
I know we can add reloadData after adding the image, just like: Swift 3: Caching images in a collectionView, but I don't want to call reload so many times.
Thank you for interested in this question. Any ideas would be very appreciated!
A: There's definitely a compromise between accessing and manually updating the cell view content, and calling reloadData on the whole collection view that you could try.
You can use the func reloadItems(at: [IndexPath]) to ask the UICollectionView to reload a single cell if it's on screen.
Presumably, imageNotInCache means you're storing image in an in-memory cache, so as long as image is also accessible by the func collectionView(UICollectionView, cellForItemAt: IndexPath), the following should "just work":
if (imageNotInCache) {
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
if let thumb = imageFromPathAndCacheIt(path) {
DispatchQueue.main.async {
self.collectionView.reloadItems(at: [indexPath])
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41152727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamically generate GraphQL schema One of my application requires Graphql schema that can have fields added & resolved on the fly based on the data. for example need something like
type Data {
email: [String]!
col1 :[Int]!
col2: [Int]!
...col3:
}
where col1 == nameOfColumnOne, col2=nameOfColumnTwo etc will & be added based on the data and possibly set on the fly.
I am kind of stuck on this and will appreciate some help on this one please.
A: Couldn't you just have a resolver columns that resolves a list of these columns that will grow over time? It makes more sense to me. I don't believe that you can achieve this modeling that you want.
you would have a type Column which defines what a column is supposed to be, and have:
type Data {
email: [String]!
columns: [Column]!
}
Hope it helps you :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53094033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Alternative to using PHP-GMP to populate two column table A page is using the PHP GNU Multiple Precision (GMP) to determine how many rows should end up in each column. While the code works, we would like to migrate the application to a new host that does not support the PHP5-GMP module. That said, what might be the best alternative to generating and populating a two column table that may not always have an even number of results? Further the table design is probably not the best so I am open to alternatives.
The code below taken from here gets us close but since it uses mysql_fetch_array, it places the items like:
a b
c d
instead of
a c
b d
Is there a way to have it display in the first example?
Newer code:
<head>
<style>
.container { width: 400px; float: left; }
.container .item { width: 50%; float: left; height: someFixedHeight; }
</style>
</head>
<?php
mysql_select_db("database",$db);
$cat= $_GET["cat"];
echo '<div class="container">';
$q = mysql_query("SELECT * FROM name WHERE Field4 = '$cat'",$db);
while ($res = mysql_fetch_array($q)){
echo '<div class="item">' . $res['Field1'] . '</div>';
}
echo '</div>';
?>
Original code:
<div id="bit-list" align="center" >
<table class="list" width="600" border="0" align="center">
<tr>
<td width="300" height="72" valign="top" border="1">
<div align="left">
<?php
$result = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);
$d3 = gmp_div_q("$num_rows", "2", GMP_ROUND_PLUSINF);
$i = 1;
$result8 = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
while ($myrow3 = mysql_fetch_row($result8))
{
if ($i <= gmp_strval($d3))
{
echo "<p>";
echo '<a href="detail.php?';
echo 'page=';
echo "$myrow3[2]";
echo '&';
echo 'pnum=';
echo "$myrow3[6]";
echo '">';
echo "$myrow3[1]";
echo "</p>";
$i = $i + 1;
}
else
{
}
}
?>
</div></td>
<td width="300" valign="top" border="1">
<div align="left">
<?php
$result = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);
$d4 = gmp_div_q("$num_rows", "2", GMP_ROUND_MINUSINF);
$d3 = gmp_div_q("$num_rows", "2", GMP_ROUND_PLUSINF);
$j = 1;
$result18 = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
while ($myrow3 = mysql_fetch_row($result18))
{
if ($j <= gmp_strval($d3))
{
$j=$j+1;
}
else
{
echo "<p>";
echo '<a href="detail.php?';
echo 'page=';
echo "$myrow3[2]";
echo '&';
echo 'pnum=';
echo "$myrow3[6]";
echo '">';
echo "$myrow3[1]";
echo "</p>";
$j = $j + 1;
}
}
?>
</div>
</td>
</tr>
</table>
</div>
A: If i read well, you use gmp_div_q for rounding only? Then, you should check round().
The only case, that round() cannot cover is GMP_ROUND_ZERO, but you don't use that (and you could cover it with a simple if).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16590561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TFS2013 Web Access - Configuration for Stakeholders We use TFS2013 on premise. A request came up that when using Web Access, some members with Stakeholder access should only have limited rights when opening work items.
They should be able to edit Description, Acceptance Criteria, etc fields, but others should be read-only, such as Iteration, State, etc.
The only option I saw was about tags Create tag definition option under
Security >> Permissions, but that's not enough for me.
One idea was Customizing a process template, but this seems to be thin ice as our team doesn't have any experience with it and the things to avoid list is quite long.
The best workaround approach so far is to reference the TFS ClientLibrary from Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\ and create a custom website which implements only the required features (for example when opening a work item, State would be a Label instead of a DropDownList).
The drawback of this solution is that it would keep the whole WebAccess portal hidden, including its nice features.
So my question in short: is there a way to make certain fields read-only on the work item form for stakeholder members?
UPDATE
Eventually I went towards Template Customization using TFS Power Tools 2013. Now I have to following problem:
Applying rules for certain fields work just fine, but in case the field type is TreePath, saving the template gives the following error
TF26062: Rule '< READONLY for="[Global]\Stakeholders" />' is not
supported for the field 'System.AreaPath'.
There were validation errors. Continuing to save may cause the file to
become unloadable, do you want to continue?
According to this answer from 2009: "there are some particular fields which can't be applied rules for"
Any suggestions how to go on?
A: You can choose the work item types to make some fields read only.
You will never need to be careful to not mark field read only that are needed for adding items. That would include area and iteration. Use witadmin.exe to export the desired work item and add read only clauses only for those in the stakeholder group.
You would be better with a permissive model. Allow everything and tell them what bout to change. Then have an alert for changes to those fields by stakeholders.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29028335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Is custom membership provider the thing that really worth to follow? After long tries to get answer to my question "Should I write custom MembershipProvider implementation or make my own custom system?" on SO I decided that it's not so bad to go MembershipProvider's way and start writing my membership provider. But at the time I feel some trouble.
For instance, in my system there's no user names. The emails are user names. So the CreateUser method should look like this:
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
bool userExists = GetUser(email);
if (userExists) {
status = MembershipCreateStatus.DuplicateEmail;
return null;
}
bool? tryExists = regTryExists(email);
if (tryExists.HasValue && tryExists.Value && !userExists)
{
UserRepository.CreateUser(email, password);
status = MembershipCreateStatus.Success;
return GetUser(email);
}
return null;
}
Also, thus I don't need GetUserNameByEmail,FindUsersByName methods:
public override string GetUserNameByEmail(string email)
{
return email;
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
So here I don't need username, passwordQuestion, passwordAnswer, isApproved arguments.
Also, in my system there is no user questions, so I don't need such methods as
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
return false;
}
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
And this is just a part of waste and cumbersome membership system. It's not so realiable as I want.
So the question is Is it really worth to go with MembershipProvider? Could you please bring me over? Is there good advantages for MembershipSystem that makes it really value system?
A: Using the MembershipProvider essentially boils down to the "build or buy" decision any developer (or dev mgr) has to make: build it from scratch, or buy off-the-shelf (or in this case, use a pre-existing tool).
With that in mind... admittedly, the MembershipProvider isn't perfect - it's a bit clunky, and probably has too much (or too little) of what you'll need - but it's 85% of the way there for most implementations. And as alluded to by others, building your own authentication system from scratch just isn't worth the time or effort. This is a solved problem; use your development energy to solve more urgent and relevant business problems, not re-inventing the wheel!
Remember this axiom: unless you can gain a direct competitive advantage from developing something from scratch, you are (usually) better off using an existing tool for the job (buy, don't build).
A: Some advantages of the ASP.NET membership provider API:
*
*You don't have to reinvent the wheel. New comers on your project will be familiar with a well-known API.
*There are already implementations (SQL Server, Active Directory mostly) available you can re-use or start from.
*It's visually integrated with ASP.NET (Login Controls, etc.)
*You can use the built-in ASP.NET administration tool to create users & roles (it's in fact a good way to check your provider works fine, as it should work with the tool)
*It can be integrated with the .NET (not only ASP.NET) Identity / Principal classes, and can be used to support the PermissionAttribute system (with the associated Role Provider). Although it technically lives in System.Web.dll, you can in fact use it in non-web systems.
*One last thing but quite interesting: you can also use ASP.NET membership providers in WCF services
A: Well MembershipProvider is indeed useful. The complete ASP.Net security infrastructure is build around it. Lot of the control can directly interact with this infrastructure such as Login, LoginStatus. So it does have it's advantage.
But it also has it's fair share of problem due to its fat interface. It's breaking the interface segregation principle and hence is a little cumbersome to use. I believe the advantages outweigh the penalty we pay here. So as long there are simple workarounds there are no harms using it. Building your own security infrastructure is not a trivial task either.
A: It sounds like the default MembershipProvider does everything you need it to do.
Therefore I would definitely recommend creating a UserBusinessclass that wraps the MembershipProvider and only exposes the features you use.
This makes it easy to use the great features of the MembershipProvider but also simplifies the interface for your needs.
A: I used custom provider first but now switched out completely.
I kept just a principle where things like when to lock user, how to hash password, etc
I was fine with custom provider until I needed multi-tenant support with different databases. And last drop was my attempt to unit test WCF service that used membership provider. Now I have my MembershipService and life is good. I still have data structure almost identical to original, but in .NET I use my code
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8426969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ruby on rails on bigrock hosting I am using bigrock hosting
i want to learn ror
i have putty access with ssh
what i have done is
rails new appname -d mysql
Using # Set by Administrator # Ruby on Rails support depends on this script # Do NOT modify unless you know what you're doing export GEM_HOME=/home/user/ruby/gems export GEM_PATH=$GEM_HOME:/opt/ruby/lib/ruby/gems/1.9.1 export PATH=$GEM_HOME/bin:/opt/ruby/bin:$PATH from /home/user/.railsrc
i am getting error
run bundle install
/home/user/ruby/gems/gems/bundler-1.7.2/lib/bundler.rb:302: warning: Insecure world writable dir /home/user/public_html/apps in PATH, mode 040777
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies...
Using rake 10.4.2
Using i18n 0.7.0
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/opt/ruby/bin/ruby extconf.rb
creating Makefile
make
compiling generator.c
make: execvp: gcc: Permission denied
make: *** [generator.o] Error 127
Gem files will remain installed in /home/user/ruby/gems/gems/json-1.8.2 for inspection.
Results logged to /home/user/ruby/gems/gems/json-1.8.2/ext/json/ext/generator/gem_make.out
An error occurred while installing json (1.8.2), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.2'` succeeds before bundling.
run bundle exec spring binstub --all
/home/user/ruby/gems/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/user/public_html/apps in PATH, mode 040777
/home/user/ruby/gems/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/user/public_html/app in PATH, mode 040777
Warning: You're using Rubygems 1.8.23 with Spring. Upgrade to at least Rubygems 2.1.0 and run `gem pristine --all` for better startup performance.
* bin/rake: spring inserted
* bin/rails: spring inserted
bundle install will cause this error
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies...
Using rake 10.4.2
Using i18n 0.7.0
/home/user/ruby/gems/gems/bundler-1.7.2/lib/bundler.rb:302: warning: Insecure world writable dir /home/user/public_html/apps in PATH, mode 040777
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/opt/ruby/bin/ruby extconf.rb
creating Makefile
make
compiling generator.c
make: execvp: gcc: Permission denied
make: *** [generator.o] Error 127
Gem files will remain installed in /home/user/ruby/gems/gems/json-1.8.2 for inspection.
Results logged to /home/user/ruby/gems/gems/json-1.8.2/ext/json/ext/generator/gem_make.out
An error occurred while installing json (1.8.2), and Bundler cannot continue.
Make sure that gem install json -v '1.8.2' succeeds before bundling.
please help me to run a app in bigrock hosting
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28903916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it necessary to pre-defined variables in prepared statement? I have the following prepared statement:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user LIKE ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $user, $pass, $first, $last, $type, $email);
$stmt->fetch();
$stmt->close();
}
if ($pass === $filtered_form['pass']) {
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
$_SESSION['first'] = $first;
$_SESSION['last'] = $last;
$_SESSION['email'] = $email;
$_SESSION['type'] = $type;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
however Visual Studio says there is a problem that the variables $id, $user, $pass, $first, $last, $type, $email are not defined. I added the variables like this:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user LIKE ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$id = "";
$user = "";
$pass = "";
$first = "";
$last = "";
$type = "";
$email = "";
$stmt->bind_result($id, $user, $pass, $first, $last, $type, $email);
$stmt->fetch();
$stmt->close();
}
if ($pass === $filtered_form['pass']) {
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
$_SESSION['first'] = $first;
$_SESSION['last'] = $last;
$_SESSION['email'] = $email;
$_SESSION['type'] = $type;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
And the problem goes away. Upon reviewing the PHP documentation, I cant find examples where the variables must be defined first, yet visual studio still shows it as an error. Any idea why this is?
A: Nope, it is not necessary when variables are passed by reference, which is the case here. So it's Visual Studio who is wrong here.
However, you are using obsoleted techniques here, and can get rid of these false positive warnings and reduce the amount of code at once:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user = ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
if ($row and password_verify($filtered_form['pass'], $row['pass']) {
$_SESSION['user'] = $row;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
as you can see, get_result() gives you a much better result (pun not intended) than store_result(), letting you to store the user information in a single variable, so it won't litter the $_SESSION array.
And num_rows() proves to be completely useless (as it always happens).
An important note: you should never ever store passwords in plain text. Alwas shore a hashed password instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62709494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use selectindexchange to show or hide a dropdown/combo box in powershell I am trying to create a GUI that has several combo boxes. I want to keep 2 of them hidden until a selection is made in another.
The account type combo is blank - both are hidden
Combobox account type select "Clinical" and the Division combo box appears
combobox account type "MSO" selected and the Department Combobox appears
Here is the code
##Type of account drop down
$acctype = New-Object System.Windows.Forms.Label
$acctype.Text = "Account Type"
$acctype.Location = New-Object System.Drawing.Point(10,140)
$acctype.Size = New-Object System.Drawing.size(100,20)
$form.Controls.Add($acctype)
#Acctype Dropdown
$cbacctype = New-Object System.Windows.Forms.Combobox
$cbacctype.Width = 200
$cbacctype.Location = New-Object system.drawing.point(120,140)
$cbacctype.Items.Add("Clinical")
$cbacctype.Items.Add("MSO")
##################################################################################################
## Location drop down
##location text
$loc = New-Object System.Windows.Forms.Label
$loc.Text = "Location"
$loc.Location = New-Object System.Drawing.Point(10,230)
$loc.Size = New-Object System.Drawing.size(100,20)
$form.Controls.Add($loc)
#location Dropdown
$cbloc = New-Object System.Windows.Forms.Combobox
$cbloc.Width = 200
$cbloc.Location = New-Object system.drawing.point(120,230)
###################################################################################################
## Provider/Divison selection - if possabile make only visiable when account type "Clinical" selected
##division text
$division = New-Object System.Windows.Forms.Label
$division.Text = "Division"
$division.Location = New-Object System.Drawing.Point(10,260)
$division.Size = New-Object System.Drawing.size(100,20)
$form.Controls.Add($division)
#Division Dropdown
$cbdivision = New-Object System.Windows.Forms.Combobox
$cbdivision.Width = 200
$cbdivision.Location = New-Object system.drawing.point(120,260)
###################################################################################################
## MSO Department Drop Down - if possabile make only visiable when account type "MSO" selected
##department text
$depart = New-Object System.Windows.Forms.Label
$depart.Text = "Department"
$depart.Location = New-Object System.Drawing.Point(10,290)
$depart.Size = New-Object System.Drawing.size(100,20)
$form.Controls.Add($depart)
#Department Dropdown
$cbdepart = New-Object System.Windows.Forms.Combobox
$cbdepart.Width = 200
$cbdepart.Location = New-Object system.drawing.point(120,290)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72876733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Lex's incorrect algorithm for lookahead operators In "modern compiler implementation in Java" by Andrew Appel he claims in an exercise that:
Lex has a lookahead operator / so that the regular expression abc/def matches abc only when followed by def (but def is not part of the matched string, and will be part of the next token(s)). Aho et al. [1986] describe, and Lex [Lesk 1975] uses, an incorrect algorithm for implementing lookahead (it fails on (a|ab)/ba with input aba, matching ab where it should match a). Flex [Paxson 1995] uses a better mechanism that works correctly for (a|ab)/ba but fails (with a warning message on zx*/xy*. Design a better lookahead mechanism.
Does anyone know the solution to what he is describing?
A: "Does not work how I think it should" and "incorrect" are, not always the same thing. Given the input
aba
and the pattern
(ab|a)/ab
it makes a certain amount of sense for the (ab|a) to match greedily, and then for the /ab constraint to be applied separately. You're thinking that it should work like this regular expression:
(ab|a)(ab)
with the constraint that the part matched by (ab) is not consumed. That's probably better because it removes some limitations, but since there weren't any external requirements for what lex should do at the time it was written, you cannot call either behavior correct or incorrect.
The naive way has the merit that adding a trailing context doesn't change the meaning of a token, but simply adds a totally separate constraint about what may follow it. But that does lead to limitations/surprises:
{IDENT} /* original code */
{IDENT}/ab /* ident, only when followed by ab */
Oops, it won't work because "ab" is swallowed into IDENT precisely because its meaning was not changed by the trailing context. That turns into a limitation, but maybe it's a limitation that the author was willing to live with in exchange for simplicity. (What is the use case for making it more contextual, anyway?)
How about the other way? That could have surprises also:
{IDENT}/ab /* input is bracadabra:123 */
Say the user wants this not to match because bracadabra is not an identifier followed by (or ending in) ab. But {IDENT}/ab will match bracad and then, leaving abra:123 in the input.
A user could have expectations which are foiled no matter how you pin down the semantics.
lex is now standardized by The Single Unix specification, which says this:
r/x
The regular expression r shall be matched only if it is followed by an occurrence of regular expression x ( x is the instance of trailing context, further defined below). The token returned in yytext shall only match r. If the trailing portion of r matches the beginning of x, the result is unspecified. The r expression cannot include further trailing context or the '$' (match-end-of-line) operator; x cannot include the '^' (match-beginning-of-line) operator, nor trailing context, nor the '$' operator. That is, only one occurrence of trailing context is allowed in a lex regular expression, and the '^' operator only can be used at the beginning of such an expression.
So you can see that there is room for interpretation here. The r and x can be treated as separate regexes, with a match for r computed in the normal way as if it were alone, and then x applied as a special constraint.
The spec also has discussion about this very issue (you are in luck):
The following examples clarify the differences between lex regular expressions and regular expressions appearing elsewhere in this volume of IEEE Std 1003.1-2001. For regular expressions of the form "r/x", the string matching r is always returned; confusion may arise when the beginning of x matches the trailing portion of r. For example, given the regular expression "a*b/cc" and the input "aaabcc", yytext would contain the string "aaab" on this match. But given the regular expression "x*/xy" and the input "xxxy", the token xxx, not xx, is returned by some implementations because xxx matches "x*".
In the rule "ab*/bc", the "b*" at the end of r extends r's match into the beginning of the trailing context, so the result is unspecified. If this rule were "ab/bc", however, the rule matches the text "ab" when it is followed by the text "bc". In this latter case, the matching of r cannot extend into the beginning of x, so the result is specified.
As you can see there are some limitations in this feature.
Unspecified behavior means that there are some choices about what the behavior should be, none of which are more correct than the others (and don't write patterns like that if you want your lex program to be portable). "As you can see, there are some limitations in this feature".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9050134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Xpath to click on Eye Icon In my application, i have to perform click operation on an Eye icon to view the documents but i am unable to generate proper xpath to locate that icon.
Below is the image of HTML code.I am unable to copy paste the code hence attaching the image.
<div title="" class="dragItem row " id="DocSelected-1" draggable="true" type="11" data-content="Salary Slips" data-draggable="item" document-required="1" state="notVerified" accountid="0">
<span class="col-xs-10 dl-no-padding">
Salary Slips
</span>
<i class="document-icon-eye dl-padding-right-10 pull-right" aria-hidden="true" onclick="openValidDoc('DocSelected-1')">
</i>
</div>
Below is the code tried but i am no such element error.
IWebElement salaryeyeicon = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span/span/i"));
salaryeyeicon.Click();
(OR)
IWebElement salaryeyeicon = driver.FindElement(By.XPath("//div[@id='DocSelected-1']//span[@class='col-xs-10 dl-no-padding']//i[@class='document-icon-eye dl-padding-right-10 pull-right']"));
salaryeyeicon.Click();
Kindly suggest the right way to locate the element.
A: The problem with your first xpath is probably that the i element is not nested in any span elements.
Maybe it is not necessary to specify the full path to the element, because it's class document-icon-eye is more or less sufficient identificator in your concrete scenario. You could use something like this:
//div[@id='DocSelected-1']//i[contains(@class, 'document-icon-eye')]
I suggest you to use the built in xpath search tool in the browser developer tools. Pasting the candidate xpath in the search field (Ctrl + F in the Elements view) will quickly show you if the xpath provided will work properly. Probably this could save you a lot of time from successive trial and error compilations and executions of your code.
After the edit the correct versions of your xpaths would be:
//div/i
//div[@id='DocSelected-1']//i[@class='document-icon-eye dl-padding-right-10 pull-right']
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62781542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Symfony2 Docrine ODM: dynamic collection name I'm using MongoDB Doctrine ODM on a Symfony 2 project. In the documents classes the mapping metadata are specified by annotations.
For example:
/**
* @MongoDB\Document(collection="statistiche")
*/
The collection name in this way is hardcoded. I want to have dynamical collection name parameter, that can be readed from global parameters.yml Symfony file (and, consequently, can be configured by user). How can I perform this goal? Thanks.
A: Then don't use the annotation but use yaml from your metadata definition.
Documentation and Example
But be aware that every metadata definition (be it per annotation, yaml or whateever) usually is loaded only once and cached for performance reasons in production.
That means that you usually have to clear your cache to use an updated metadata definition.
Another issue to consider is when you rename an already existing document/attribute. This might require some migration activities to avoid unexpected behaviour.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40784385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Laravel 5.6 how to read text file line by line Without Laravel I can use simple code to read text file by line:
$file = fopen("whatever/file.txt", "r") or exit("Unable to open file!");
while(!feof($file)) {
echo fgets($file). "<br>";
}
fclose($file);
With Laravel this simple thing becomes overwhelming due to local file storage location.
I.e. I can get file contents with Storage::get('whatever/file.txt') method, but how to get just a file and then read it in a loop?
I've tried to use File::get('whatever/file.txt') method but get an error: File does not exist at path.
How to read file from local storage (not public) line by line with Laravel?
A: You can get your file like this:
$file = fopen(storage_path("whatever/file.txt"), "r");
This will result in a path similar to this
'/var/www/storage/whatever/file.txt' or '/var/www/foo/storage/whatever/file.txt' if you are serving multiple websites from the same server, it will depend on your setup, but you get the gist of it. Then you can read your file;
while(!feof($file)) {
echo fgets($file). "<br>";
}
fclose($file);
A: You need to know where your file lives. You also need a path to get there.
E.g., if your file is located in the storage folder, you could do
File::get(storage_path('whatever/test.txt'));
dd($contents);
A: Laravel v 9.0 update
File::lines('whatever/file.txt')->each(function ($line) {
$this->info($line);
}
A: $files = ExamFile::where('exam',$code)->get();
foreach ($files as $file)
{
$content = fopen(Storage::path($file->url),'r');
while(!feof($content)){
$line = fgets($content);
echo $line."<br>";
}
fclose($content);
}
You can use it like this. It works for me.
A: Hope it will help
File::get(storage_path('whatever/file.txt'));
A: So confusing!
My file was in the folder storage/app/whatever/file.txt but Laravel storage("whatever/file.txt") method recognizes it as storage/whatever/file.txt path.
As I said before it is overwhelming and confusing a lot.
So, fopen('storage/app/whatever/file.txt') works for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53008105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Make round edged button in WPF I want to make my button round edged. My button code is as follows:-
<Button Grid.Column="1" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" HorizontalAlignment="Center" BorderThickness="1" Foreground="White" FontFamily="Arial,Helvetica,sans-serif" Width="85" Background="#6F933D" BorderBrush="#48671E" CommandParameter="11" Command="{Binding AuditCommand}" Visibility="{Binding ViewModel.IsCompleteAccessible}" Margin="38,0,60,0" Height="24" VerticalAlignment="Bottom">Complete</Button>
Please Help.
Thanks
A: Try this
<Window.Resources>
<Style x:Key="test" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="ButtonBorder" CornerRadius="10" BorderThickness="1" BorderBrush="Gray" Background="LightGray">
<ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Content="Button" Style="{StaticResource test}" Margin="0,137,0,0" />
<Grid>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31066071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: getting detailed SQL logs from Heroku Cedar Stack What exactly needs to happen in order to get detailed SQL logs out of heroku cedar?
On our dev platform the log trail gives us lots of information including insite into the SQL which is being executed by activerecord. In production the information is much less detailed.
What do i need to do to get this SQL information when i run
heroku logs --tail
Is there a setting i need to send to heroku or something i need to put into my rails code?
Thanks!
A: Heroku's Logplex contains all logging statements from your application - there is no filtering of any kind.
By default, Rails does not log SQL statements in production so you'll need to bump your log level in production.rb to a level that is more suitable.
http://guides.rubyonrails.org/debugging_rails_applications.html#log-levels
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11136905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: apache server serving index.html instead of index.php, after changing the file preference inside the dir.conf file I changed the file preference inside the dir.conf file:
$sudo nano /etc/apache2/mods-enabled/dir.conf
<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>
This means that index.php will get first preference, right?
In /var/www/html i have two files i.e index.html and index.php.
But when i visit my ip_address in my browser, the index.html is being served instead of index.php. Am i missing out something?
A: Change your dir.conf file :
<IfModule mod_dir.c>
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64633737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regex JavaScript overlapping matches If I have a string like fooba and I want to catch both foo and fooba how can I do? If I use foo|fooba it cathes only the first foo and not fooba.
A: Use lookaheads (zero-width assertion) for both patterns:
(?=(foo))(?=(fooba))
RegEx Demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30942010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to download bitbucket code to new machine I am using git and my code is in bitbucket. I changed my laptop. I want to know the steps to set up entire thing in my new laptop. By the way, I am using ubuntu, ubuntu commands will be helpful.
Thanks.
A: Use git clone and clone from your bitbucket repository.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17019500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: A query on asynchronous response for Servlet request In context of Servlet request/response I read somewhere that:
Using a different thread to do work required by a request will, as you expect, allow the response to be sent immediately.
I am just wondering when a Servlet thread is handing over the actual processing to another thread then that means that it does not have the expected response with it at that point of time anyways, then what is the value in sending the immediate but meaningless response back to the browser?
Could someone please give me a valuable usecase for it.
A: That quote is talking about a scenario where you can return a meaningful response without actually finishing all the work required by the request. For instance you might upload a file to be processed and respond immediately with a processing ID, but pass the processing to another thread. Later on the client could make another request with that ID to find out if processing completed.
An asynchronous servlet scenario would hand off processing to another thread to do the work while blocking the request. But the blocked request would not tie up a servlet request thread during processing like a normal synchronous servlet request.
Suppose you had a single threaded processor and 10 requests were made at the same time. With a synchronous servlet that waited for the processing to finish, you'd have 10 blocked request threads + 1 processor thread. But with an asynchronous servlet, you'd have 0 blocked threads + 1 processor thread. That's a pretty significant gain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30767092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Chrome Extension null TypeError So I have a chrome extension that checks for an update of programs via an xml document. However i get this error when I open a new tab:
Error in event handler for 'tabs.onActivated': Cannot call method 'getElementsByTagName' of null TypeError: Cannot call method 'getElementsByTagName' of null
at isUpdateAvailable (chrome-extension://bdhjocmpiogdmlfpbpppiffcjbonbocg/background.js:16:17)
at chrome-extension://bdhjocmpiogdmlfpbpppiffcjbonbocg/background.js:84:5
at chrome.Event.dispatch (event_bindings:237:41)
at Object.chromeHidden.Event.dispatchJSON (event_bindings:151:5
Code:
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp;
}
function isUpdateAvailable(type, build) {
var buildNumber = localStorage["version" + build + type];
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + build + "/view/latest-" + type + "/");
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("title")[0];
var y = x.childNodes[0];
var txt = y.nodeValue;
if(txt == buildNumber) {
return true;
}
xml.close();
return false;
}
function notify(type, build) {
window.webkitNotifications.createNotification('icon.png', getTitle(type, build), getDescription(type, build));
}
function getTitle(type, build) {
var title;
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + type + "/view/latest-" + build + "/");
var xmlDoc=xml.responseXML;
var name=xmlDoc.getElementsByTagName("name")[0];
var version=xmlDoc.getElementsByTagName("version")[0];
title+=name;
title+=" version ";
title+=version;
title+=" is out!";
xml.close();
return title;
}
function getDescription(type, build) {
var desc;
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + type + "/view/latest-" + build + "/");
var xmlDoc=xml.responseXML;
var name=xmlDoc.getElementsByTagName("name")[0];
desc+="There is a new update for ";
desc+=name;
desc+=". You can download it here: ";
var downloadLink;
get_short_url(long_url, function(short_url) {downloadLink=short_url;});
desc+=downloadLink;
xml.close();
return desc;
}
function get_short_url(long_url, func) {
var login = "kezz101";
var api_key = "R_d68d87d13b42412a56be9bd9711c4dc4";
$.getJSON("http://api.bitly.com/v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url
},
function(response) {
func(response.data.url);
}
);
}
chrome.tabs.onActivated.addListener(function() {
var type = localStorage["type"];
var build = localStorage["build"];
if(!type) {
type = "rb";
}
if(!build) {
build = "craftbukkit";
}
if(isUpdateAvailable(type, build)) {
notify(type, build);
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + type + "/view/latest-" + build + "/");
var xmlDoc=xml.responseXML;
localStorage["version" + build + type] = xmlDoc.getElementsByTagName("build_number")[0];
xml.close();
}
});
A: You are using synchronous Ajax, which has been disabled for extensions and apps. You should instead use asynchronous Ajax with a callback passed into loadXMLDoc:
function loadXMLDoc(dname, callback) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname);
xhttp.onload = function() {
callback(xhttp);
}
xhttp.send();
}
function isUpdateAvailable(type, build, callback) {
var buildNumber = localStorage["version" + build + type];
loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + build + "/view/latest-" + type + "/", function(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("title")[0];
var y = x.childNodes[0];
var txt = y.nodeValue;
if(txt == buildNumber) {
callback(true);
} else {
xml.close();
callback(false);
}
});
}
...
chrome.tabs.onActivated.addListener(function() {
var type = localStorage["type"];
var build = localStorage["build"];
if(!type) {
type = "rb";
}
if(!build) {
build = "craftbukkit";
}
isUpdateAvailable(type, build, function(isAvail) {
if(isAvail) {
notify(type, build);
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + type + "/view/latest-" + build + "/", function(xml) {
var xmlDoc=xml.responseXML;
localStorage["version" + build + type] = xmlDoc.getElementsByTagName("build_number")[0];
xml.close();
});
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11923511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MPI - sending and receiving rows of matrix I am making program, where will be 2-4 processes in MPI with C language. In elimination I am sending each row below actual row to different processes by cyclic mapping.
e.g. for matrix 5 * 6, when there is active row 0, and 4 processes, I am sending row 1 to process 1, row 2 to the process 2, row 3 to the process 3 and row 4 to the process 1 again. In theese processes I want to make some computation and return some values back to the process 0, which will add theese into its original matrix. My question is, which Send and Recv call should I use?
There is some theoretical code:
if(master){
for(...)
//sending values to other processes
}
for(...)
//recieving values from other processes
}
}else{//for other non-master processes
recieve value from master
doing some computing
sending value back to master
}
If I use only simple blocking send, I don't know what will happen on process 1, because it gets row 1 and 4, and before I will cal recv in master, my value in process 1 - row 1 will be overwritten by row 4, so I will miss one set of data, am I right? My question on therfore, what kind of MPI_Send should I use?
A: You might be able to make use of nonblocking if, say, proc 1 can start doing something with row 1 while waiting for row 4. But blocking should be fine to start with, too.
There is a lot of synchronization built into the algorithm. Everyone has to work based on the current row. So the recieving processes will need to know how much work to expect for each iteration of this procedure. That's easy to do if they know the total number of rows, and which iteration they're currently working on. So if they're expecting two rows, they could do two blocking recvs, or launch 2 nonblocking recvs, wait on one, and start processing the first row right away. But probably easiest to get blocking working first.
You may find it advantageous even at the start to have the master process doing isends so that all the sends can be "launched" simulataneously; then a waitall can process them in whatever order.
But better than this one-to-many communication would probably be to use a scatterv, which one could expect to proceed more efficiently.
Something that has been raised in many answers and comments to this series of questions but which I don't think you've ever actually addressed -- I really hope that you're just working through this project for educational purposes. It would be completely, totally, crazy to actually be implementing your own parallel linear algebra solvers when there are tuned and tested tools like Scalapack, PETSc, and Plapack out there free for the download.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5530168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: When does the write() system call write all of the requested buffer versus just doing a partial write? If I am counting on my write() system call to write say e.g., 100 bytes, I always put that write() call in a loop that checks to see if the length that gets returned is what I expected to send and, if not, it bumps the buffer pointer and decreases the length by the amount that was written.
So once again I just did this, but now that there's StackOverflow, I can ask you all if people know when my writes will write ALL that I ask for versus give me back a partial write?
Additional comments: X-Istence's reply reminded me that I should have noted that the file descriptor was blocking (i.e., not non-blocking). I think he is suggesting that the only way a write() on a blocking file descriptor will not write all the specified data is when the write() is interrupted by a signal. This seems to make at least intuitive sense to me...
A: write may return partial write especially using operations on sockets or if internal buffers full. So good way is to do following:
while(size > 0 && (res=write(fd,buff,size))!=size) {
if(res<0 && errno==EINTR)
continue;
if(res < 0) {
// real error processing
break;
}
size-=res;
buf+=res;
}
Never relay on what usually happens...
Note: in case of full disk you would get ENOSPC not partial write.
A: You need to check errno to see if your call got interrupted, or why write() returned early, and why it only wrote a certain number of bytes.
From man 2 write
When using non-blocking I/O on objects such as sockets that are subject to flow control, write() and writev() may write fewer bytes than requested; the return value must be noted, and the remainder of the operation should be retried when possible.
Basically, unless you are writing to a non-blocking socket, the only other time this will happen is if you get interrupted by a signal.
[EINTR] A signal interrupted the write before it could be completed.
See the Errors section in the man page for more information on what can be returned, and when it will be returned. From there you need to figure out if the error is severe enough to log an error and quit, or if you can continue the operation at hand!
This is all discussed in the book: Advanced Unix Programming by Marc J. Rochkind, I have written countless programs with the help of this book, and would suggest it while programming for a UNIX like OS.
A: Writes shouldn't have any reason to ever write a partial buffer afaik. Possible reasons I could think of for a partial write is if you run out of disk space, you're writing past the end of a block device, or if you're writing to a char device / some other sort of device.
However, the plan to retry writes blindly is probably not such a good one - check errno to see whether you should be retrying first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/694188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How refresh a listView inside SherlockFragment? I have a listView inside a SherlockFragment, but I can not update the listView on screen when I make any changes to the Adapter. I tried: adapter.notifyDataSetChanged(), but without success. Thank's.
A: You should be updating the underlying dataset that is passed to the adapter before calling notifyDatasetChanged();
EG:
For ArrayAdapter in a ListActivity
("arraylist" is the ArrayList you've used to back your ArrayAdapter)
arraylist.add(data);
arrayadapter = this.getListAdapter();
arrayadapter.notifyDatasetChanged();
A: Personally, everytime user like press refresh button i repopulate listView initializing Cursor again.
Like this: calling this function...
public void repopulateListView(){
cursor = dbHelper.fetchAll();
columns = new String[] {
DBAdapter.KEY_NAME,
DBAdapter.KEY_DATE,
DBAdapter.KEY_VOTE,
DBAdapter.KEY_CREDIT
};
to = new int[] {
R.id.one,
R.id.two,
R.id.three,
R.id.four
};
dataAdapter = new SimpleCursorAdapter(
getActivity(), R.layout.YOUR_ID,
cursor,
columns,
to,
0)
{
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
final View row = super.getView(position, convertView, parent);
}
}
}
...from Refresh onClick:
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.refresh:{
repopulateListView();
break;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18602457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTTP:TIMEOUT error through mule request connector but api working through postman I am using mule-4. I am trying to integrate a third-party API(confidential). It is working from the postman and is returning responses within 1 second.
When I wrote a request connector for the same in mule, The API kept giving a timeout exception.
I increased the response timeout to 2 minutes then also got the same error i.e. timeout exceeded.
Please help.
EDIT 1:
I was able to reproduce this issue on postman. SO postman is adding Connection:keep-alive header by default and when this particular header is added then the API gives response within seconds but when this header is missing then the API gives a timeout error.
A: You are not really providing too much details of the issue. I can give some generic guidelines:
*
*Ensure that there is network connectivity. If you are testing Postman and Mule from the same computer it is probably not an issue.
*Ensure host, port and certificates (if using TLS) are the same. Pointing an HTTPS request to port 80 could cause a timeout sometimes.
*Enable HTTP Wire logging in Mule and compare with Postman code as HTTP to identify any significant difference between the requests. For example: headers, URI, body should be the same, except probably for a few headers. Depends on the API. This is usually the main cause for differences between Postman and Mule, when the request are different.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70201096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Maven : How to avoid version appended to a war file in Maven? I am using Maven as the build file , this is my below settings for the war file name to be generated
I am using Maven version 2.2.1
<artifactId>TataWeb</artifactId>
<packaging>war</packaging>
<version>1.0</version>
So its actually generating a war file with this name TataWeb-1.0
But i want the war file name to be only TataWeb .
Please let me know how can i avoid the version appeneded to the war file name ??
Thank you .
A: You should use your artifactid, rather than hard-coding the file name.
<build>
<finalName>${project.artifactId}</finalName>
</build>
A: Just add this to your pom.xml:
<build>
<finalName>TataWeb</finalName>
</build>
A: well, its not the Maven Way. Maven does have a version attribute.. use it.
A: You can avoid the version appeneded to the war file name by doing a "clean compile package" instead of "clean install".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10548553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Yii2 SwiftMailer sending email via remote smtp server (gmail) I want to send emails via my gmail account.
My mailer config:
[
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,//set this property to false to send mails to real email addresses
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'my@gmail.com',
'password' => 'pass',
'port' => '587',
'encryption' => 'tls',
],
]
I wrote command MailController:
<?php
namespace app\commands;
use yii\console\Controller;
use Yii;
/**
* Sanding mail
* Class MailController
* @package app\commands
*/
class MailController extends Controller
{
private $from = 'my@gmail.com';
private $to = 'to@gmail.com';
public function actionIndex($type = 'test', $data = null)
{
Yii::$app->mailer->compose($type, ['data' => $data])
->setFrom($this->from)
->setTo($this->to)
->setSubject($this->subjects[$type])
->send();
}
}
When I'm trying to run: php yii mail
I get: sh: 1: /usr/sbin/sendmail: not found
But why it requires sendmail if I want just SMTP connection to smtp.gmail.com?
A: Yii2 Has different config files for web and console works. So you need to config both of them. Regarding this issue, I had to make mail config file (for example mailer.php) and include it in both config files (web.php & console.php) like:
'components' => [
...
'mailer' => require(__DIR__ . '/mailer.php'),
...
],
A: I think you have configured the mailer wrongly. Because it is still using the default mail function. From the documentation the configuration should be like below. The mailer should be inside components.
'components' => [
...
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'username',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
],
],
...
],
One more suggestion is to use port "465" and encryption as "ssl" instead of port "587", encryption "tls".
A: Might be useful for someone as reference:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'username',
'password' => 'password',
'port' => 587,
'encryption' => 'tls',
'streamOptions' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
]
],
]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29592790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Google Charts API, AnnotatedTimeline: properly setup several series and scales I am using a Google Charts' AnnotatedTimeline which contains three different series.
The first series has its own scale. The second and third should have the same scale as they represent the same kind of data.
The thing is I can only get the scales to be associated to one series at a time. Here's how I'm currently drawing the chart:
chart.draw(chartData, {scaleType: 'allmaximized', scaleColumns:[0, 1], displayExactValues: true, dateFormat: 'dd MMMM yyyy'});
This way, the first series has its own scale on the left, which is good. The second scale, however, is computed using only the second series' values, so the third series is misplaced on the chart. Changing the method to:
chart.draw(chartData, {scaleType: 'allmaximized', scaleColumns:[0, 1, 2], displayExactValues: true, dateFormat: 'dd MMMM yyyy'});
adds a third scale in the middle of the graph for the third series, which is not what I want.
Is there a way to group series 2 and 3 to get the same scale for both?
A: I see what you're trying to do now. You want to have only 2 axes, 1 that will correspond to the values in columns 0/1, and the other corresponding to column 2. I threw this example together (feel free to copy-paste in to google playground):
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Sold Pencils');
data.addColumn('string', 'title1');
data.addColumn('string', 'text1');
data.addColumn('number', 'Sold Pens');
data.addColumn('string', 'title2');
data.addColumn('string', 'text2');
data.addColumn('number', 'Sold Erasers');
data.addColumn('string', 'title3');
data.addColumn('string', 'text3');
data.addRows([
[new Date(2008, 1 ,1), 30000, null, null, 40645, null, null, 100, null, null],
[new Date(2008, 1 ,2), 14045, null, null, 20374, null, null, 120, null, null],
[new Date(2008, 1 ,3), 55022, null, null, 50766, null, null, 70, null, null],
[new Date(2008, 1 ,4), 75284, null, null, 14334, 'Out of Stock', 'Ran out of stock on pens at 4pm', 100, null, null],
[new Date(2008, 1 ,5), 41476, 'Bought Pens', 'Bought 200k pens', 66467, null, null, 110, null, null],
[new Date(2008, 1 ,6), 33322, null, null, 39463, null, null, 130, 'Eraser Boom', 'People dig erasers']
]);
var annotatedtimeline = new google.visualization.AnnotatedTimeLine(
document.getElementById('visualization'));
annotatedtimeline.draw(data, {'displayAnnotations': true, scaleType: 'allmaximized', scaleColumns:[0, 2]});
}
This shows column 0/1 on the left-side scale, and column 2 on the right-side scale.
A: Get the same scale for both series 2 and 3 ?
Looks like the only way is to "hack" it. You could do it by adding two rows of fake values at the end (or start) of the series.
Get the max and min values for series 2 and 3 in variables max2, max3, min2, min3.
Then append two rows of (fake) values :
row1 = last value of series 1, Max(max2, max3), Max(max2, max3)
row2 = last value of series 1, Min(min2, min3), Min(min2, min3)
You need to set also option scaleType:'allmaximized' and your series 2 and 3 will be perfectly aligned.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14383134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: In Chrome packaged apps v2 how to check if the window is maximized? I created a frameless window using the new Google Chrome packaged apps, v2
I created the minimize, maximize, and close buttons and hocked them to the appropriate JavaScript functions and have them working.
I don’t know who to check if the window is already maximized in JavaScript, any ideas?
The following example is showing how to minimize a window, it took me some time to understand it and implement it, and it works.
https://github.com/GoogleChrome/chrome-app-samples/blob/master/frameless-window/style.css
The maximize button have to restore the window if maximized, and if you double click the window title bar it maximized but I don’t get any events.
A: This is currently not possible. Bug 134068 is filed for querying the properties of a window, and bug 134070 is filed for getting events when they change.
A: Seems to be possible now that those mentioned bugs were fixed in the last few weeks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12716621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.