text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
SPA apps, and server synchronisation, best practices
I am developing a SPA application in Angularjs to load data into my database.
I have a Django back end with tastypie providing a REST interface.
I am trying to populate a flowcell object, which is made up of 8 lane elements. Each lane may contains multiple libraries (say 5 or 6 on average).
Flowcell
Lane 1
library 1
library 2
library 3
Lane 2
library 5
Lane 3
library 6
library 7
etc.....
So at the moment when I add a new library to a lane object, I POST the details to the server then refresh the lane's library list with a GET request, and the display refreshes.
This ensures that the server data and the display data are synchronised. However, it does add a delay while each Lane contacts the server and refreshes itself.
So is it considered better to add a number of libraries to each lane in the client side, then update them together - this will give a smoother user experience, but the display may not reflect exactly what is in the database? (I can imagine this may cause errors if the two get too far out of synch).
Or is it considered better to do what I am currently doing - update multiple small changes, sending more requests to the server, but ensuring the data between the client and the server are consistent?
A:
I think you're on the right track. Taking the approach of being more granular in your updates will be better.
Primarily, it will create the feeling of less delay for the client. If the changes are small and are fired off when an element is changed, unless the network is really slow, each change should be fast and almost undetectable by the client.
The only thing I would say is that you might not need to do another GET after your POST of changed data. Unless this is some type of shared data model across many users and sessions, if the client makes an update and the POST goes through, the client holds the correct set of data so the additional GET isn't necessary.
| {
"pile_set_name": "StackExchange"
} |
Q:
conditional either or validation in asp.net mvc2
In my registration page I have land line phone number and mobile number fields.
I need to ensure that the user needs to add at least one phone number either the land line or mobile.
How do I do this?
Thanks
Arnab
A:
You could write a custom validation attribute and decorate your model with it:
[AttributeUsage(AttributeTargets.Class)]
public class AtLeastOnePhoneAttribute: ValidationAttribute
{
public override bool IsValid(object value)
{
var model = value as SomeViewModel;
if (model != null)
{
return !string.IsNullOrEmpty(model.Phone1) ||
!string.IsNullOrEmpty(model.Phone2);
}
return false;
}
}
and then:
[AtLeastOnePhone(ErrorMessage = "Please enter at least one of the two phones")]
public class SomeViewModel
{
public string Phone1 { get; set; }
public string Phone2 { get; set; }
}
For more advanced validation scenarios you may take a look at FluentValidation.NET or Foolproof.
| {
"pile_set_name": "StackExchange"
} |
Q:
The empty set contains irrationals only.
Is the above statement true; because we can not find any rational in it.
Or false; because it does not contain any irrational.
Also is the statement: "The elements of the empty set are irrationals and no element in it is rational." true, being vacuous?
A:
Yes the statement is true. It can be rephrased as if $x \in \emptyset$ then $x \in \mathbb Q^c$. Since the hypothesis $x\in \emptyset$ is false the statement as a whole is by definition true.
Another way to think about this is that the statement "if $x \in \emptyset$ then $x \in \mathbb Q^c$" is that same as saying that $\emptyset$ is a subset of $\mathbb Q^c$ which is also vacuously true.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamically creating Checkboxes while not knowing the number of them in Android studio
I am trying to create a user registration activity in Android Studio, where the Manager registers the employees and selects the actions the employee is allowed to do.
I have done the registration in PHP and looks like this:
<?php foreach ($action_item as $key => $value):?>
<input type="checkbox" name="actions[]" value="<?php echo $value['ID_action'] ?>"><?php echo $value['Action_Name'] ?><br>
<?php endforeach; ?>
The actions are stored in the "Actions" table. And the code inserts their IDs in the "Employee_has_action" table with the structure(Id_EHA, ID_employee, ID_action). I know how to insert to and retrieve data from online DB with json, so the question is how to (if possible) dynamically make several (number of retrieved database rows from Action table) checkboxes through code and give them the retrieved values?
Or any other better options where at user register the manager selects multiple data and they get inserted to DB?
Thanx in advance.
A:
My first choice would be to present the information in a RecyclerView and have an item layout (xml) with the checkbox already there.
But if you want to dinamically create the checkboxes, you can:
1) In the layout you will be using include a holder for the checkboxes (a parent) with an id you can findViewById() from the program to appendView() them upon creation.
2) Create the checkboxex in a loop (0 to 4 in your 5 actions example) and give them an id (See View.generateViewId() to get an Id that doesn't collide with other existing ones).
You will also have to create and set the LayoutParams for each checkbox (different instance for each checkbox). The LayoutParams you will have to set will depend on the layout where you are putting the checkboxes.
And finally add the checkbox to the view with parent.appendView().
As a last step you may need to ivalidate() the parent or call requestLayout() on the parent view.
More or less this is how it should go.
| {
"pile_set_name": "StackExchange"
} |
Q:
passing django request object to celery task
I have a task in tasks.py like so:
@app.task
def location(request):
....
I am trying to pass the request object directly from a few to task like so:
def tag_location(request):
tasks.location.delay(request)
return JsonResponse({'response': 1})
I am getting an error that it can't be serialized i guess? How do I fix this? trouble is I have file upload objects as well .. its not all simple data types.
A:
Because the request object contains references to things which aren't practical to serialize — like uploaded files, or the socket associated with the request — there's no general purpose way to serialize it.
Instead, you should just pull out and pass the portions of it that you need. For example, something like:
import tempfile
@app.task
def location(user_id, uploaded_file_path):
# … do stuff …
def tag_location(request):
with tempfile.NamedTemporaryFile(delete=False) as f:
for chunk in request.FILES["some_file"].chunks():
f.write(chunk)
tasks.location.delay(request.user.id, f.name)
return JsonResponse({'response': 1})
| {
"pile_set_name": "StackExchange"
} |
Q:
возврат значения
Суть вопроса в простом: существует ли function которая возвратит значение переменной если она существует.
в противоположном случае возвратит что-то подобное false/null итд.
isset()
empty()
все это не годится, т.к.
1) isset() если переменная не создана возвращает ошибку.
2) empty() возвращает true или false, а мне надо переменную.
мне нужно что-то подобное:
<?php
function returnValue($perem)
{
return empty($perem) ? null : $perem;
}
?>
но этот пример function мне не годится. ошибку возвращяет так как не сушествует переменной!
<b>Notice</b>: Undefined property: stdClass::$ref in <b>/storage/ssd2/169/12967169/public_html/groups/index.php</b> on line <b>40</b><br />
<br />
<b>Notice</b>: Undefined property: stdClass::$ref_source in <b>/storage/ssd2/169/12967169/public_html/groups/index.php</b> on line <b>41</b><br />
<br />
<b>Notice</b>: Undefined property: stdClass::$geo in <b>/storage/ssd2/169/12967169/public_html/groups/index.php</b> on line <b>44</b><br />
<br />
<b>Notice</b>: Undefined property: stdClass::$payload in <b>/storage/ssd2/169/12967169/public_html/groups/index.php</b> on line <b>45</b><br />
<br />
<b>Notice</b>: Undefined property: stdClass::$keyboard in <b>/storage/ssd2/169/12967169/public_html/groups/index.php</b> on line <b>46</b><br />
<br />
<b>Notice</b>: Undefined property: stdClass::$reply_message in <b>/storage/ssd2/169/12967169/public_html/groups/index.php</b> on line <b>48</b><br />
<br />
<b>Notice</b>: Undefined property: stdClass::$action in <b>/storage/ssd2/169/12967169/public_html/groups/index.php</b> on line <b>49</b><br />
<br />
<b>Notice</b>: Undefined property: stdClass::$carousel in <b>/storage/ssd2/169/12967169/public_html/groups/index.php</b> on line <b>58</b><br />
часть кода с переменными:
$_message = $vkAnswer->object->message;
$id = returnValue($_message->id); #идентификатор сообщения.
$date = returnValue($_message->date); #время отправки в Unixtime.
$peer_id = returnValue($_message->peer_id); #идентификатор назначения.
$from_id = returnValue($_message->from_id); #идентификатор отправителя.
$text = returnValue($_message->text); #текст сообщения.
$random_id = returnValue($_message->random_id); #идентификатор, используемый при отправке сообщения.
$ref = returnValue($_message->ref); #произвольный параметр для работы с <источниками переходов>.
$ref_source = returnValue($_message->ref_source); #произвольный параметр для работы с <источниками переходов>.
$attachments = returnValue($_message->attachments); #медиавложения сообщения (фотографии, ссылки и т.п.).
$important = returnValue($_message->important); #true, если сообщение помечено как важное.
$geo = returnValue($_message->geo); #информация о местоположении.
$payload = returnValue($_message->payload); #сервисное поле для сообщений ботам (полезная нагрузка).
$keyboard = returnValue($_message->keyboard); #<объект клавиатуры> для ботов.
$fwd_messages = returnValue($_message->fwd_messages); #массив пересланных сообщений (если есть).
$reply_message = returnValue($_message->reply_message); #сообщение, в ответ на которое отправлено текущее.
$action = returnValue($_message->action); #информация о сервисном действии с чатом.
unset($_message);
A:
$var = 'test';
function returnValue($perem)
{
return !empty($perem) ? $perem : null;
}
returnValue($var ?? null);
returnValue($_message ?? null);
Если не существует переменной $message то вы будете получать ошибку ещё на передаче параметра в функцию для этого следует сделать проверку при вставке аргумента, по сути вам тогда и функция не нужна, достаточно будет написать так:
$id = $_message->id ?? null;
| {
"pile_set_name": "StackExchange"
} |
Q:
Removing last word from FOREACH loop
I'm building a basic function, which builds out Mysql WHERE clauses based on how many are in the array.
$array = array('id' => '3', 'name' => 'roger');
$sql = "SELECT * FROM table WHERE ";
foreach ($array as $k => $v) {
$sql .= $k . ' = ' . $v . ' AND ';
}
which will output
SELECT * FROM table WHERE id = 3 AND name = roger AND
However obviously I don't want that last AND, how do I go about removing it from the string?
Thanks
A:
You could do
$sql = substr($sql, 0, -5);
But perhaps the more elegant solution is
$array = array('id' => '3', 'name' => 'roger');
$clauses = array();
foreach ($array as $k => $v)
$clauses[] = $k . ' = ' . $v;
$sql = "SELECT * FROM table WHERE " . implode(' AND ', $clauses);
| {
"pile_set_name": "StackExchange"
} |
Q:
Автоматическое обновление SQLite
Создал приложение для тестирования. Вопросы тестов хранятся в SQLite. Когда добавляю новый вопрос, то нужно удалить и заново установить приложение, чтобы появились новые вопросы.
Что нужно сделать, чтобы при обновлении приложения новые вопросы добавились автоматически?
A:
Если в вашем приложении данные (вопросы) не берутся с сервера, а находятся в самом приложении, то используйте метод onUpgrade, чтобы автоматически обновлять содержимое БД при загрузке новой версии вашего приложения. В самом методе пропишите логику, где старая таблица с вопросами будет удаляться и на ее место будет загружаться новая таблица, либо будут просто загружаться новые вопросы, если структура таблицы не изменилась.
Если используете сервер, то там все строится на взаимодействии вашего клиента и API сервера. Можно обновлять данные в БД через отдельные запросы к серверу (новые данные просто добавляются в таблицу, а если меняется ее структура, то используем все тот же onUpgrade).
| {
"pile_set_name": "StackExchange"
} |
Q:
What are usability, accessibility, screen-reader or any other development, functionality, cross browser issue with iframe?
What are the usability, accessibility, screen-reader, or any other development, functionality, or cross browser issues with <iframe>?
Is there any alternative for <iframe>?
And are there any JavaScript/jQuery or server-side techniques which can decrease the usability, accessibility, or screen-reader issues with <iframe>?
Why has the W3C not included <iframe> in XHTML Strict, while HTML 5 supports <iframe>?
update:
I found some good thoughts here also : http://uxexchange.com/questions/1817/iframe-accessibility-and-usability-issues
A:
Accessibility:
It's harder to scroll you iframe , your mouse must be int the range of the iframe. It difficult with people with movement desabilities
Browsers for blind people may not include the content from you iframe and those people will not reach to it.
Usability:
It's not cool when you have several
scroll bars on the main window and on
the iframe. It's difficult for
scrolling
Other issues:
Mobile browsers probably won't render you iframe. Even if it render it, it will look bad and ugly.
Search engines will have hard time indexing your pages in the iframe. Probably they will skip it or won't take indexed properly
Loading an iframe will take longer time than a page with the same content and no frame
A:
Why W3C not included Iframe in XHTML Strict
Because at the time it was seen as a bastard child of the widely-reviled <frame> tag. In principle <iframe> has many of the same properties as <frame>, but in practice it seems to have encouraged more tasteful use, generally avoiding the worst of the navigational and usability problems that frameset interfaces suffered.
While HTML 5 is supports Iframe ?
(a). Because, unlike the <frame>, <iframe> has since turned out to be essential for mixed documents such as those including adverts, and many types of web application. There are still problems, as mentioned in other answers, but generally the <iframe> is seen as a necessary feature that is here to stay. This isn't true of <frame>, which is a “non-conforming feature” in HTML5 (the nearest HTML5 gets to any kind of ‘strict’).
(b). because the authors of HTML5 don't so much care about encouraging good practice anyway; it's about documenting what user-agents must do. They have thrown every obsolete feature of HTML4 into the standard, along with a lot of other traditional but dodgy browser behaviour including every last quirk of broken tag soup parsing. [aside: I am greatly amused to see the latest argument being discussed on their list being how the <isindex> element should be handled — an element that literally nobody has used since HTML 2.0's form elements made it obsolete in 1995.]
Given the staggering size and complexity of HTML5, it's not really surprising that they didn't want the extra effort of declaring a more limited ‘strict mode’ profile. As work comes to an end, though, I would love to see an XHTML5 Strict or similar effort to trim back some of this mess. As it stands, Hixie and chums have taken a snapshot of every nasty hack a browser has to put in for compatibility today, and made it a standard requirement for all browsers in the foreseeable future, effectively condoning the bad practice.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to see the left pager in the following jqGrid directive
I am working for the jqGrid for the first time at all.I wanted to use it in my application with all its native features, like editing, deleting,a dding, sorting and all others.
I came across this project, which seems to be a basic implementation of jqGrid. It was a good starting point. However, I am having trouble displaying the Add, Delete, Search buttons in Left pager.
I have tried setting the pager to true, setting it to an div-id.
Tried setting nav grid options.
Tried binding the .navGrid function to the pager element in directive.
But the left pager won't show up at all. I have a related issue here.
below is the entire code I have apart from the above directive.
<!Doctype html>
<html ng-app="poc">
<head>
<link rel="stylesheet" href="jquery-ui.css" />
<link rel="stylesheet" href="ui.jqgrid.min.css" />
<!--<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css">-->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="jquery.jqgrid.min.js"></script>
<script type="text/javascript" src="angular-jqgrid.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="ctrl">
<jq-grid dataset="myData" options="myGridOptions"></jq-grid>
<div id="pager"></div>
</body>
</html>
angular.module("poc", ['angular-jqgrid']);
angular.module("poc").controller('ctrl', function ($scope) {
$scope.myData = [{ "OrderID": "10248", "CustomerID": "WILMK", "OrderDate": "1996-07-04 00:00:00", "Freight": "32.3800", "ShipName": "Vins et alcools Chevalier" }, { "OrderID": "10249", "CustomerID": "TRADH", "OrderDate": "1996-07-05 00:00:00", "Freight": "11.6100", "ShipName": null }, { "OrderID": "10250", "CustomerID": "HANAR", "OrderDate": "1996-07-08 00:00:00", "Freight": "65.8300", "ShipName": "Hanari Carnes" }, { "OrderID": "10251", "CustomerID": "VICTE", "OrderDate": "1996-07-08 00:00:00", "Freight": "41.3400", "ShipName": "Victuailles en stock" }, { "OrderID": "10252", "CustomerID": "SUPRD", "OrderDate": "1996-07-09 00:00:00", "Freight": "51.3000", "ShipName": null }, { "OrderID": "10253", "CustomerID": "HANAR", "OrderDate": "1996-07-10 00:00:00", "Freight": "58.1700", "ShipName": "Hanari Carnes" }, { "OrderID": "10254", "CustomerID": "CHOPS", "OrderDate": "1996-07-11 00:00:00", "Freight": "22.9800", "ShipName": "Chop-suey Chinese" }, { "OrderID": "10255", "CustomerID": "RICSU", "OrderDate": "1996-07-12 00:00:00", "Freight": "148.3300", "ShipName": "Richter Supermarkt" }, { "OrderID": "10256", "CustomerID": "WELLI", "OrderDate": "1996-07-15 00:00:00", "Freight": "13.9700", "ShipName": "Wellington Importadora" }, { "OrderID": "10257", "CustomerID": "HILAA", "OrderDate": "1996-07-16 00:00:00", "Freight": "81.9100", "ShipName": null }, { "OrderID": "10258", "CustomerID": "ERNSH", "OrderDate": "1996-07-17 00:00:00", "Freight": "140.5100", "ShipName": "Ernst Handel" }, { "OrderID": "10259", "CustomerID": "CENTC", "OrderDate": "1996-07-18 00:00:00", "Freight": "3.2500", "ShipName": "Centro comercial Moctezuma" }, { "OrderID": "10260", "CustomerID": "OLDWO", "OrderDate": "1996-07-19 00:00:00", "Freight": "55.0900", "ShipName": null }, { "OrderID": "10261", "CustomerID": "QUEDE", "OrderDate": "1996-07-19 00:00:00", "Freight": "3.0500", "ShipName": null }, { "OrderID": "10262", "CustomerID": "RATTC", "OrderDate": "1996-07-22 00:00:00", "Freight": "48.2900", "ShipName": "Rattlesnake Canyon Grocery" }, { "OrderID": "10263", "CustomerID": "ERNSH", "OrderDate": "1996-07-23 00:00:00", "Freight": "146.0600", "ShipName": "Ernst Handel" }, { "OrderID": "10264", "CustomerID": "FOLKO", "OrderDate": "1996-07-24 00:00:00", "Freight": "3.6700", "ShipName": null }, { "OrderID": "10265", "CustomerID": "BLONP", "OrderDate": "1996-07-25 00:00:00", "Freight": "55.2800", "ShipName": null }, { "OrderID": "10266", "CustomerID": "WARTH", "OrderDate": "1996-07-26 00:00:00", "Freight": "25.7300", "ShipName": "Wartian Herkku" }, { "OrderID": "10267", "CustomerID": "FRANK", "OrderDate": "1996-07-29 00:00:00", "Freight": "208.5800", "ShipName": "Frankenversand" }];
$scope.myGridOptions = {
colNames: ["OrderID", "Customer ID", "Order Date", "Freight", "Ship Name",],
colModel:[
{ label: 'OrderID', name: 'OrderID', key: true, width: 75 },
{ label: 'Customer ID', name: 'CustomerID', width: 50 },
{ label: 'Order Date', name: 'OrderDate', width: 150 },
{ label: 'Freight', name: 'Freight', width: 150 },
{ label:'Ship Name', name: 'ShipName', width: 150 }
],
cmTemplate: { autoResizable: true, editable: true },
hoverrows: true,
rowNum: 20,
autoResizing: { compact: true },
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
sortable: true,
pager: true,
pgbuttons : true,
pagerRightWidth: 150,
sortname: "OrderID",
sortorder: "desc",
formEditing: {
width: 310,
closeOnEscape: true,
closeAfterEdit: true,
savekey: [true, 13]
},
formViewing: {
labelswidth: "80%"
},
navOptions: {
view: true,
},
singleSelectClickMode: "selectonly", // optional setting
ondblClickRow: function (rowid) {
$(this).jqGrid("editGridRow", rowid);
},
caption: "Angular Implementation of jqGrid",
width: 1280,
height: 450,
};
});
This is simply all I have for now. My console shows no error, and I think I pretty much have all needed libraries in place. The grid displays fine except for the blank left pager.
Am I missing something in configuration object. How can I make the Add Delete button to appear.
Any help is appreciated.
A:
I don't know angular-jqgrid, but it's code is simple and you can insert it in your code directly. The code from my old answer, does mostly the same. I modified it using your colModel and inserted just some additional properties and options, which can be interesting for you.
The demo used 3 lines
$grid.jqGrid(newValue)
.jqGrid("navGrid")
.jqGrid("filterToolbar");
which call navGrid and filterToolbar. You can easy extend the code to call more options.
I insert the code, which I used in the demo below:
var initDatepicker = function (elem) {
var self = this;
$(elem).datepicker({
minDate: new Date(1995, 1 - 1, 1),
defaultDate: new Date(1996, 6, 15),
onSelect: function () {
setTimeout(function () {
self.triggerToolbar();
}, 0);
},
dateFormat: "dd-M-yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
};
var myApp = angular.module("myApp", []);
myApp.directive("ngJqGrid", function ($compile) {
return {
restrict: "E",
scope: {
config: "=",
data: "="
},
link: function (scope, element, attrs) {
var $grid;
scope.$watch("config", function (newValue) {
element.children().empty();
$grid = angular.element("<table></table>");
element.append($compile($grid)(scope));
element.append($grid);
angular.extend(newValue, {
loadComplete: function () {
$compile(this)(scope);
},
autoencode: true,
iconSet: "fontAwesome"
});
$grid.jqGrid(newValue)
.jqGrid("navGrid")
.jqGrid("filterToolbar");
});
scope.$watch("data", function (newValue, oldValue) {
var p = $grid.jqGrid("getGridParam");
p.data = newValue;
$grid.jqGrid("destroyFilterToolbar");
$grid.trigger("reloadGrid");
$grid.jqGrid("filterToolbar");
});
}
};
});
myApp.controller("MyController", function ($scope) {
$scope.config = {
colModel:[
{ label: 'OrderID', name: 'OrderID', key: true, width: 75, sorttype: "integer" },
{ label: 'Customer ID', name: 'CustomerID', width: 90, stype: "select",
searchoptions: {
clearSearch: true,
sopt: ["eq", "ne"],
generateValue: true,
noFilterText: "Any"
}},
{ label: 'Order Date', name: 'OrderDate', width: 125,
autoResizing: { minColWidth: 90 },
align: "center", sorttype: "date",
formatter: "date", formatoptions: { newformat: "d-M-Y" },
editoptions: { dataInit: initDatepicker },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDatepicker } },
{ label: 'Freight', name: 'Freight', template: "number", width: 70,
autoResizing: { minColWidth: 65 },},
{ label: 'Ship Name', name: 'ShipName', width: 180,
createColumnIndex: true,
searchoptions: {
dataInit: function (elem, options) {
$(elem).autocomplete({
source: $(this).jqGrid("getUniqueValueFromColumnIndex", "ShipName"),
delay: 0,
minLength: 0
});
},
sopt: [ "cn", "eq", "bw", "ew", "bn", "nc", "en" ],
clearSearch: true
}}
],
cmTemplate: { autoResizable: true, editable: true },
hoverrows: true,
rowNum: 20,
pagerRightWidth: 105,
autoResizing: { compact: true },
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
sortable: true,
pager: true,
sortname: "OrderID",
sortorder: "desc",
formEditing: {
width: 310,
closeOnEscape: true,
closeAfterEdit: true,
savekey: [true, 13]
},
formViewing: {
labelswidth: "80%"
},
navOptions: {
view: true,
},
singleSelectClickMode: "selectonly", // optional setting
ondblClickRow: function (rowid) {
$(this).jqGrid("editGridRow", rowid);
},
caption: "Angular Implementation of jqGrid"//,
//width: 1280,
//height: 450
};
$scope.data = [
{ "OrderID": "10248", "CustomerID": "WILMK", "OrderDate": "1996-07-04 00:00:00", "Freight": "32.3800", "ShipName": "Vins et alcools Chevalier" },
{ "OrderID": "10249", "CustomerID": "TRADH", "OrderDate": "1996-07-05 00:00:00", "Freight": "11.6100", "ShipName": null },
{ "OrderID": "10250", "CustomerID": "HANAR", "OrderDate": "1996-07-08 00:00:00", "Freight": "65.8300", "ShipName": "Hanari Carnes" },
{ "OrderID": "10251", "CustomerID": "VICTE", "OrderDate": "1996-07-08 00:00:00", "Freight": "41.3400", "ShipName": "Victuailles en stock" },
{ "OrderID": "10252", "CustomerID": "SUPRD", "OrderDate": "1996-07-09 00:00:00", "Freight": "51.3000", "ShipName": null },
{ "OrderID": "10253", "CustomerID": "HANAR", "OrderDate": "1996-07-10 00:00:00", "Freight": "58.1700", "ShipName": "Hanari Carnes" },
{ "OrderID": "10254", "CustomerID": "CHOPS", "OrderDate": "1996-07-11 00:00:00", "Freight": "22.9800", "ShipName": "Chop-suey Chinese" },
{ "OrderID": "10255", "CustomerID": "RICSU", "OrderDate": "1996-07-12 00:00:00", "Freight": "148.3300", "ShipName": "Richter Supermarkt" },
{ "OrderID": "10256", "CustomerID": "WELLI", "OrderDate": "1996-07-15 00:00:00", "Freight": "13.9700", "ShipName": "Wellington Importadora" },
{ "OrderID": "10257", "CustomerID": "HILAA", "OrderDate": "1996-07-16 00:00:00", "Freight": "81.9100", "ShipName": null },
{ "OrderID": "10258", "CustomerID": "ERNSH", "OrderDate": "1996-07-17 00:00:00", "Freight": "140.5100", "ShipName": "Ernst Handel" },
{ "OrderID": "10259", "CustomerID": "CENTC", "OrderDate": "1996-07-18 00:00:00", "Freight": "3.2500", "ShipName": "Centro comercial Moctezuma" },
{ "OrderID": "10260", "CustomerID": "OLDWO", "OrderDate": "1996-07-19 00:00:00", "Freight": "55.0900", "ShipName": null },
{ "OrderID": "10261", "CustomerID": "QUEDE", "OrderDate": "1996-07-19 00:00:00", "Freight": "3.0500", "ShipName": null },
{ "OrderID": "10262", "CustomerID": "RATTC", "OrderDate": "1996-07-22 00:00:00", "Freight": "48.2900", "ShipName": "Rattlesnake Canyon Grocery" },
{ "OrderID": "10263", "CustomerID": "ERNSH", "OrderDate": "1996-07-23 00:00:00", "Freight": "146.0600", "ShipName": "Ernst Handel" },
{ "OrderID": "10264", "CustomerID": "FOLKO", "OrderDate": "1996-07-24 00:00:00", "Freight": "3.6700", "ShipName": null },
{ "OrderID": "10265", "CustomerID": "BLONP", "OrderDate": "1996-07-25 00:00:00", "Freight": "55.2800", "ShipName": null },
{ "OrderID": "10266", "CustomerID": "WARTH", "OrderDate": "1996-07-26 00:00:00", "Freight": "25.7300", "ShipName": "Wartian Herkku" },
{ "OrderID": "10267", "CustomerID": "FRANK", "OrderDate": "1996-07-29 00:00:00", "Freight": "208.5800", "ShipName": "Frankenversand" }
];
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting EXC_BAD_ACCESS while Applying filter to CIImage [Core Image]
I am Working on Imagebase Application. I want to Apply some filter on Images. For that I have used [Core Image].
I have stored some FilterName in array and to show filter effect as preview I am using UICollection view. When user tap on Preview image then Filter will be apply on Main Imageview. But when I tap on preview cell , then filter applied successfully on Main Imageview. but after that when I am dragging collection view cell to apply next preview I am getting BAD_ACCESS Error on Filter Method.
-(UIImage *) applyFilter: (UIImage*) picture withFilterName:(NSString*)Filtername
Here is my Code to apply Filter :-
Initial setup with Filter array and RegisterCollectionview cell:-
-(void)setUpDefaultUI{
[self HideControlsAndSetupUI];
arrFilter = @[ @"Original",
@"CILinearToSRGBToneCurve",
@"CIPhotoEffectChrome",
@"CIPhotoEffectFade",
@"CIPhotoEffectInstant",
@"CIPhotoEffectMono",
@"CIPhotoEffectNoir",
@"CIPhotoEffectProcess",
@"CIPhotoEffectTonal",
@"CIPhotoEffectTransfer",
@"CISRGBToneCurveToLinear",
@"CIVignette",
// @"CIVignetteEffect",
@"CISepiaTone",
];
[self.vwCollection registerClass:[ActivityCollectionViewCell class] forCellWithReuseIdentifier:@"ActivityCollectionViewCell"];
[self.vwCollection registerNib:[UINib nibWithNibName:@"ActivityCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ActivityCollectionViewCell"];
_imgEdit.image=_stillImage; // To apply filter on this Image
_OriginalImage=_stillImage; // Original image if user declined to use filter
}
CollectionView Datasource:-
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"filterAvailable");
ActivityCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"ActivityCollectionViewCell" forIndexPath:indexPath];
if (cell == nil) {
NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"ActivityCollectionViewCell" owner:self options:nil];
cell = [xib objectAtIndex:0];
[cell.imgVw setContentMode:UIViewContentModeScaleAspectFill];
}
if (indexPath.item==0) {
cell.imgVw.image = _OriginalImage; //Original Image on 0 index
}else{
UIImage *img=[self applyFilter:_stillImage withFilterName:[arrFilter objectAtIndex:indexPath.row]]; // Apply filter on this method
cell.imgVw.image=img;
}
return cell;
}
Collectionview Delegate :-
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
ActivityCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ActivityCollectionViewCell" forIndexPath:indexPath];
if (cell == nil) {
NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"ActivityCollectionViewCell" owner:self options:nil];
cell = [xib objectAtIndex:0];
}
if (indexPath.item==0) {
_imgEdit.image=_OriginalImage; // Set original image in main Imageview
}else{
UIImage *img=[self applyFilter:_stillImage withFilterName:[arrFilter objectAtIndex:indexPath.row]];
_imgEdit.image = img; // Apply filter on Main Imageview
}
}
Filter Apply from This Method :-
-(UIImage *) applyFilter: (UIImage*) picture withFilterName:(NSString*)Filtername
{
UIImageOrientation originalOrientation = picture.imageOrientation;
CGFloat originalScale = picture.scale;
CIImage *beginImage = [CIImage imageWithCGImage:picture.CGImage];
CIContext *context = [CIContext contextWithOptions:nil];
CIFilter *filter = [CIFilter filterWithName:Filtername keysAndValues: kCIInputImageKey, beginImage, nil, [NSNumber numberWithFloat:0.7], nil];
CIImage *outputImage = [filter outputImage];
CGImageRef cgimg =
[context createCGImage:outputImage fromRect:[outputImage extent]];
UIImage *newImg = [UIImage imageWithCGImage:cgimg scale:originalScale orientation:originalOrientation];
//CGImageRelease(CGImageRef) method.
CGImageRelease(cgimg);
return newImg;
}
Image of Error:-
- BAD_ACCESS
A:
Finally , I got the problem. Actually the problem is , I am applying filter on Still image in Both the method.
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
and
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
So, Final solution is use different image in Both the methods .
Here is the code :-
//Initial Setup
-(void)setUpDefaultUI{
[self HideControlsAndSetupUI];
arrFilter = @[ @"Original",
@"CILinearToSRGBToneCurve",
@"CIPhotoEffectChrome",
@"CIPhotoEffectFade",
@"CIPhotoEffectInstant",
@"CIPhotoEffectMono",
@"CIPhotoEffectNoir",
@"CIPhotoEffectProcess",
@"CIPhotoEffectTonal",
@"CIPhotoEffectTransfer",
@"CISRGBToneCurveToLinear",
@"CIVignette",
// @"CIVignetteEffect",
@"CISepiaTone",
];
[self.vwCollection registerClass:[ActivityCollectionViewCell class] forCellWithReuseIdentifier:@"ActivityCollectionViewCell"];
[self.vwCollection registerNib:[UINib nibWithNibName:@"ActivityCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ActivityCollectionViewCell"];
_imgEdit.image=_stillImage;
_OriginalImage=_stillImage;
temp=_OriginalImage;
}
//Datasource method To display image in collection view with filter
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"filterAvailable");
ActivityCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"ActivityCollectionViewCell" forIndexPath:indexPath];
if (cell == nil) {
NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"ActivityCollectionViewCell" owner:self options:nil];
cell = [xib objectAtIndex:0];
//[cell.imgVw setContentMode:UIViewContentModeScaleAspectFill];
cell.imgVw.clipsToBounds = YES;
cell.imgVw.layer.cornerRadius = 5;
}
if (indexPath.item==0) {
cell.imgVw.image = _OriginalImage; //Set original image of 1st index
}else{
UIImage *img=[self applyFilter:temp withFilterName:[arrFilter objectAtIndex:indexPath.row]]; // Set temp image in place of stilimage
cell.imgVw.image=img;
}
return cell;
}
//Apply filter on Main Imageview .
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
if (_EnumPhotos==defaultPhotos) {
if (indexPath.item==0) {
_imgEdit.image=_OriginalImage; //If user click on 1st index then original filter applied on main image
}else{
UIImage *img=[self applyFilter:_stillImage withFilterName:[arrFilter objectAtIndex:indexPath.row]]; // Use still image here .
_imgEdit.image = img; // Apply image on main image view
}
}
}
//Apply filter Method
-(UIImage *) applyFilter: (UIImage*) picture withFilterName:(NSString*)Filtername
{
UIImageOrientation originalOrientation = picture.imageOrientation;
CGFloat originalScale = picture.scale;
CIImage *beginImage = [CIImage imageWithCGImage:picture.CGImage];
CIContext *context = [CIContext contextWithOptions:nil];
CIFilter *filter = [CIFilter filterWithName:Filtername keysAndValues: kCIInputImageKey, beginImage, nil, [NSNumber numberWithFloat:0.7], nil];
CIImage *outputImage = [filter outputImage];
CGImageRef cgimg =
[context createCGImage:outputImage fromRect:[outputImage extent]];
UIImage *newImg = [UIImage imageWithCGImage:cgimg scale:originalScale orientation:originalOrientation];
//CGImageRelease(CGImageRef) method.
CGImageRelease(cgimg);
return newImg;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Foxx/ArangoDB: Can you create a response that adhere to JSON API specification?
I am currently writing some micro services with Foxx to be consumed by Ember.js. Ember data plays very nicely with JSON API (http://jsonapi.org) responses. So I tried to serialize the Foxx responses with the json-api-serializer (https://www.npmjs.com/package/json-api-serializer) - but with no luck. I only found the forClient method, but this only allows me to operate on the JSON representation of single objects, not the whole response. So my question: Is it possible to implement JSON API with Foxx/ArangoDB?
A:
You can return arbitrary responses from Foxx routes, so it's entirely possible to generate JSON responses that conform to JSON API.
However there's no built-in way to do this automatically.
I don't see anything in json-api-serializer that shouldn't work in Foxx, so I'm not sure what problems you are encountering. You should be able to simply return the output object with res.json(outputFromSerializer) and set the content type with res.set('content-type', 'application/vnd.api+json').
If everything else fails you can just write your own helper functions to generate the boilerplate and metadata JSON API expects.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: vectorizing a function call which uses an array of objects
I have an array of objects. I also have a function that requires information from 2 of the objects at a time. I would like to vectorize the call to the function so that it calculates all calls at once, rather than using a loop to go through the necessary pair of objects.
I have gotten this to work if I instead create an array with the necessary data. However this partially defeats the purpose of using objects.
Here is the code. It currently works using the array method and only one line needs to be commented/uncommented in the function to switch to the "object" mode that does not work, but I dearly wish would.
The error I get is: TypeError: only integer arrays with one element can be converted to an index
import numpy as np
import time as time
class ExampleObject():
def __init__(self, r):
self.r = r
def ExampleFunction(x):
""" WHAT I REALLY WANT """
# answer = exampleList[x].r - exampleList[indexArray].r
"""WHAT I AM STUCK WITH """
answer = coords[x] - exampleList[indexArray].r
return answer
indexArray = 5 #arbitrary choice of array index
sizeArray = 1000
exampleList = []
for i in range(sizeArray):
r = np.random.rand()
exampleList.append( ExampleObject( r ) )
index_list = np.arange(0,sizeArray,1)
index_list = np.delete(index_list,indexArray)
coords = np.array([h.r for h in exampleList])
answerArray = ExampleFunction(index_list)
The issue is that when I pass the function an array of integers, it doesn't return an array of answers (the vectorization I want) when I use the array (actually, list) of objects. It does work if I use an array (with no objects, just data in each element). But as I have said, this defeats in my mind, the purpose of storing information on objects to begin with. Do I really need to ALSO store the same information in arrays?
A:
I can't comment, sorry for misusing the answer section...
If the data type of a numpy array is python object, the memory of the numpy array is not contiguous. Vectorization of the operation may not improve the performance much if any. Perhaps you might want to try numpy structured array instead.
assume the object has attributes a & b and they are double precision floating point number, then...
import numpy as np
numberOfObjects = 6
myStructuredArray = np.zeros(
(numberOfObjects,),
[("a", "f8"), ("b", "f8")],
)
you can initialize individual attributes for say object 0 like this
myStructuredArray["a"][0] = 1.0
or you can initialize individual attributes for all objects like this
myStructuredArray["a"] = [1,2,3,4,5,6]
print(myStructuredArray)
[(1., 0.) (2., 0.) (3., 0.) (4., 0.) (5., 0.) (6., 0.)]
A:
numpy.ufunc when given an object dtype array, iterate through the array, and try to apply a cooresponding method to each element.
For example np.abs tries to apply the __abs__ method. Lets add such a method to your class:
In [31]: class ExampleObject():
...:
...: def __init__(self, r):
...: self.r = r
...: def __abs__(self):
...: return self.r
...:
Now create your arrays:
In [32]: indexArray = 5 #arbitrary choice of array index
...: sizeArray = 10
...:
...: exampleList = []
...: for i in range(sizeArray):
...: r = np.random.rand()
...: exampleList.append( ExampleObject( r ) )
...:
...: index_list = np.arange(0,sizeArray,1)
...: index_list = np.delete(index_list,indexArray)
...:
...: coords = np.array([h.r for h in exampleList])
and make an object dtype array from the list:
In [33]: exampleArr = np.array(exampleList)
In [34]: exampleArr
Out[34]:
array([<__main__.ExampleObject object at 0x7fbb541eb9b0>,
<__main__.ExampleObject object at 0x7fbb541eba90>,
<__main__.ExampleObject object at 0x7fbb541eb3c8>,
<__main__.ExampleObject object at 0x7fbb541eb978>,
<__main__.ExampleObject object at 0x7fbb541eb208>,
<__main__.ExampleObject object at 0x7fbb541eb128>,
<__main__.ExampleObject object at 0x7fbb541eb198>,
<__main__.ExampleObject object at 0x7fbb541eb358>,
<__main__.ExampleObject object at 0x7fbb541eb4e0>,
<__main__.ExampleObject object at 0x7fbb541eb048>], dtype=object)
Now we can get an array of the r values by calling the np.abs function:
In [35]: np.abs(exampleArr)
Out[35]:
array([0.28411876298913485, 0.5807617042932764, 0.30566195995294954,
0.39564156171554554, 0.28951905026871105, 0.5500945908978057,
0.40908712567465855, 0.6469497088949425, 0.7480045751535003,
0.710425181488751], dtype=object)
It also works with indexed elements of the array:
In [36]: np.abs(exampleArr[:3])
Out[36]:
array([0.28411876298913485, 0.5807617042932764, 0.30566195995294954],
dtype=object)
This is convenient, but I can't promise speed. In other tests I found that iteration over object dtypes is faster than iteration (in Python) over numeric array elements, but slower than list iteration.
In [37]: timeit np.abs(exampleArr)
3.61 µs ± 131 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [38]: timeit [h.r for h in exampleList]
985 ns ± 31.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [39]: timeit np.array([h.r for h in exampleList])
3.55 µs ± 88.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
| {
"pile_set_name": "StackExchange"
} |
Q:
What does !! mean in objective-c syntax?
I found some code similar to the following:
BOOL hasValue_:1;
- (BOOL) hasValue {
return !!hasValue_;
}
- (void) setHasValue:(BOOL) value {
hasValue_ = !!value;
}
I'm wondering why the double exclamation points are necessary? Are we not already passing BOOL to the method and returning BOOL? Is BOOL really a typedef for an int?
Thanks!
EDIT
Thanks for all of the responses thus far. I understand that using !! with other data types effectively performs some typecasting to a boolean result. However, in the example above, I'm strictly working with BOOL already.
EDIT
If I'm working with a BOOL already, why is it necessary to normalize it to a 0 for false and 1 for true? Doesn't a BOOL guarantee that it is false for 0 and true for everything else?
A:
I'm wondering why the double exclamation points are necessary?
BOOL is a signed char, or a char posing as a boolean type via typedef. It will happily represent any integer in the range [SCHAR_MIN...SCHAR_MAX]. The double exclamation point applies a boolean NOT operation twice, which effectively converts the original value to an int of 0 or 1, narrowing the value to the range of boolean.
But there's a twist: BOOL hasValue_:1; declares a single-bit bitfield representation. It can represent two values. return !!hasValue_; is not needed. However, it is needed to correctly narrow when going from signed char (BOOL) to one bit.
Are we not already passing BOOL to the method and returning BOOL?
Nope. It's a signed char. !!value reduces input values to YES or NO.
If I'm working with a BOOL already, why is it necessary to normalize it to a 0 for false and 1 for true?
Doesn't a BOOL guarantee that it is false for 0 and true for everything else?
BOOL is a signed char. A typedef of signed char does not make this guarantee.
C99 (which has been available for you to use for many years when targeting osx or ios) has a more useful boolean type representation (bool). Unfortunately, BOOL remains in regular use in objc for historical reasons. Personally, I use BOOL only when necessary (e.g. overriding).
A:
I'm not 100% certain about objective C, but in other languages, it's two boolean operators next to each other. It's typically used to ensure that falsy or trusy statements are converted to proper booleans (e.g. true or false). Since objective C is derived from C, there's a good chance that this is also what it's used for.
A:
Looking at this question, BOOL is a typedef for signed char. This means that it could have values aside from 0 or 1 (on all modern systems I'm familiar with, it can have values from -128 to 127). It shouldn't, but I wouldn't like to count on a BOOL always having values 0 or 1.
Therefore, it's desirable to have a way of normalizing it to 0 or 1. In C and the derived languages I'm familiar with, ! is the not operator, which takes a value and returns either 1 if the value is treated as false (in C, that would be numeric 0 or 0.0 or the null pointer constant for a pointer type), and 0 otherwise. !! is just ! applied twice, which yields 0 for an initially false value and 1 for an initially true value.
| {
"pile_set_name": "StackExchange"
} |
Q:
Blackberry 10 Cascades onclick
How to call a screen while clicking a button in Blackberry 10 cascades? I have tried this code but it's not working,
Button {
text: "Sign-in"
onClicked: main.qml
}
Can any one send me some sample codes, for on-click function?
Thanks
A:
To show a new Page you'll need to define a NavigationPane and push the Page onto that. Example:
import bb.cascades 1.0
NavigationPane {
id: navigationPane
Page {
Button {
text: "Sign-in"
onClicked: {
var page = secondPageDefinition.createObject();
navigationPane.push(page);
}
attachedObjects: [
ComponentDefinition {
id: secondPageDefinition
source: "DetailsPage.qml"
}
]
}
}
}
The nice thing about this is that NavigationPane takes care of the back button automatically for you.
When you create a new BlackBerry Cascades project in Momentics choose the NavigationPane template for something very similar to this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Oozie jobs struck in running state
I installed oozie 4.0.1 on a hadoop 2.2 cluster. After that, I tried to run a oozie job(java action). Everything seems to be fine :
When I run job.properties,it gives the job id as usually.
When i checked oozie console job is in running state.
It runs the java code.
However, oozie suddenly stops and shows the following error.
ACTION[0000001-140526105244150-oozie-labu-W@javaMainAction] Exception in check(). Message[java.net.ConnectException: Call From labuser-VirtualBox/127.0.1.1 to localhost:10020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused]
java.io.IOException: java.net.ConnectException: Call From labuser-VirtualBox/127.0.1.1 to localhost:10020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
at org.apache.hadoop.mapred.ClientServiceDelegate.invoke(ClientServiceDelegate.java:331)
at org.apache.hadoop.mapred.ClientServiceDelegate.getJobStatus(ClientServiceDelegate.java:416)
at org.apache.hadoop.mapred.YARNRunner.getJobStatus(YARNRunner.java:522)
at org.apache.hadoop.mapreduce.Cluster.getJob(Cluster.java:183)
at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:580)
at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:578)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491)
at org.apache.hadoop.mapred.JobClient.getJobUsingCluster(JobClient.java:578)
at org.apache.hadoop.mapred.JobClient.getJob(JobClient.java:596)
at org.apache.oozie.action.hadoop.JavaActionExecutor.getRunningJob(JavaActionExecutor.java:992)
at org.apache.oozie.action.hadoop.JavaActionExecutor.check(JavaActionExecutor.java:1005)
at org.apache.oozie.command.wf.ActionCheckXCommand.execute(ActionCheckXCommand.java:177)
at org.apache.oozie.command.wf.ActionCheckXCommand.execute(ActionCheckXCommand.java:56)
at org.apache.oozie.command.XCommand.call(XCommand.java:280)
at org.apache.oozie.service.CallableQueueService$CallableWrapper.run(CallableQueueService.java:175)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Call From labuser-VirtualBox/127.0.1.1 to localhost:10020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:783)
at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:730)
at org.apache.hadoop.ipc.Client.call(Client.java:1351)
at org.apache.hadoop.ipc.Client.call(Client.java:1300)
at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:206)
at com.sun.proxy.$Proxy31.getJobReport(Unknown Source)
at org.apache.hadoop.mapreduce.v2.api.impl.pb.client.MRClientProtocolPBClientImpl.getJobReport(MRClientProtocolPBClientImpl.java:133)
at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.mapred.ClientServiceDelegate.invoke(ClientServiceDelegate.java:317)
... 19 more
Caused by: java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:739)
at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:529)
at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:493)
at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:547)
at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:642)
at org.apache.hadoop.ipc.Client$Connection.access$2600(Client.java:314)
at org.apache.hadoop.ipc.Client.getConnection(Client.java:1399)
at org.apache.hadoop.ipc.Client.call(Client.java:1318)
... 27 more
2014-05-26 11:02:15,305 WARN ActionCheckXCommand:542 - USER[labuser] GROUP[-] TOKEN[] APP[WorkflowJavaMainAction] JOB[0000001-140526105244150-oozie-labu-W] ACTION[0000001-140526105244150-oozie-labu-W@javaMainAction] Exception while executing check(). Error Code [ JA006], Message[ JA006: Call From labuser-VirtualBox/127.0.1.1 to localhost:10020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused]
org.apache.oozie.action.ActionExecutorException: JA006: Call From labuser-VirtualBox/127.0.1.1 to localhost:10020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
at org.apache.oozie.action.ActionExecutor.convertExceptionHelper(ActionExecutor.java:412)
at org.apache.oozie.action.ActionExecutor.convertException(ActionExecutor.java:392)
at org.apache.oozie.action.hadoop.JavaActionExecutor.check(JavaActionExecutor.java:1095)
at org.apache.oozie.command.wf.ActionCheckXCommand.execute(ActionCheckXCommand.java:177)
at org.apache.oozie.command.wf.ActionCheckXCommand.execute(ActionCheckXCommand.java:56)
at org.apache.oozie.command.XCommand.call(XCommand.java:280)
at org.apache.oozie.service.CallableQueueService$CallableWrapper.run(CallableQueueService.java:175)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Call From labuser-VirtualBox/127.0.1.1 to localhost:10020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:783)
at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:730)
at org.apache.hadoop.ipc.Client.call(Client.java:1351)
at org.apache.hadoop.ipc.Client.call(Client.java:1300)
at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:206)
at com.sun.proxy.$Proxy31.getJobReport(Unknown Source)
at org.apache.hadoop.mapreduce.v2.api.impl.pb.client.MRClientProtocolPBClientImpl.getJobReport(MRClientProtocolPBClientImpl.java:133)
at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.mapred.ClientServiceDelegate.invoke(ClientServiceDelegate.java:317)
at org.apache.hadoop.mapred.ClientServiceDelegate.getJobStatus(ClientServiceDelegate.java:416)
at org.apache.hadoop.mapred.YARNRunner.getJobStatus(YARNRunner.java:522)
at org.apache.hadoop.mapreduce.Cluster.getJob(Cluster.java:183)
at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:580)
at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:578)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491)
at org.apache.hadoop.mapred.JobClient.getJobUsingCluster(JobClient.java:578)
at org.apache.hadoop.mapred.JobClient.getJob(JobClient.java:596)
at org.apache.oozie.action.hadoop.JavaActionExecutor.getRunningJob(JavaActionExecutor.java:992)
at org.apache.oozie.action.hadoop.JavaActionExecutor.check(JavaActionExecutor.java:1005)
... 7 more
Caused by: java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:739)
at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:529)
at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:493)
at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:547)
at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:642)
at org.apache.hadoop.ipc.Client$Connection.access$2600(Client.java:314)
at org.apache.hadoop.ipc.Client.getConnection(Client.java:1399)
at org.apache.hadoop.ipc.Client.call(Client.java:1318)
... 27 more
2014-05-26 11:02:15,307 INFO ActionCheckXCommand:539 - USER[labuser] GROUP[-] TOKEN[] APP[WorkflowJavaMainAction] JOB[0000001-140526105244150-oozie-labu-W] ACTION[0000001-140526105244150-oozie-labu-W@javaMainAction] Next Retry, Attempt Number [1] in [60,000] milliseconds
What is the problem ?
A:
If you are working in hadoop-2.2.0 you must start job historyserver to avoid the above mentioned error.
By default historyserver was located in hadoop/sbin. while starting hadoop some times jobhistory server will not run so must start jobhistory server manually using below command.
hadoop/sbin/mr-jobhistory-daemon.sh start historyserver
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues with youtube video on mobile browser
I have an embed tag containing youtube video.
However this does not play on mobile browsers as it says flash required.
I am using HTML and not HTML 5 since my app should support IE 8 too.
I browsed through some awesome JQuery solutions but got only HTML5 based Jquery solutions
Can someone suggest me good solution to have my youtube video play in IE8+ , Chrome , FF+ and mobile browsers too.
A:
This embed code youtube provides by default will work for HTML5 browsers (mobile phones) as well as old browsers that need flash:
http://jsfiddle.net/austinpray/G5GhH/1
<iframe width="560" height="315" src="http://www.youtube.com/embed/VIDEO_ID" frameborder="0" allowfullscreen></iframe>
As best I can tell by looking at the iframe's code, this code sniffs the capabilities of what your browser can play and displays what works best. If you are on browser that has flash capabilities it uses flash and if flash isn't available it defaults to HTML 5. I tested this and it works on iPhones and Android phones. Here is the Youtube support document.
| {
"pile_set_name": "StackExchange"
} |
Q:
Count the number of correct answers in database
I am trying to count the correct answers in the database. I have the following lines of code:
$getresult = $quizAns->getAnswersByUser($_POST['user_id']);
if($getresult){
$count = count($getresult);
for ($x = 1; $x <= $count; $x++) {
$match = $quiz->matchAnswer($getresult[$x]->question_id, $getresult[$x]->ans_id);
}
}
$counts = count($match);
In the $getresult I am getting numbers of answers submitted by a user which should have to be 4 always like this:
Array
(
[0] => stdClass Object
(
[id] => 220
[user_id] => 84
[question_id] => 43
[answer_id] => 31
)
[1] => stdClass Object
(
[id] => 219
[user_id] => 84
[question_id] => 48
[answer_id] => 53
)
[2] => stdClass Object
(
[id] => 218
[user_id] => 84
[question_id] => 49
[answer_id] => 56
)
[3] => stdClass Object
(
[id] => 217
[user_id] => 84
[question_id] => 50
[answer_id] => 62
)
)
I want to loop through every index and count the number of matched answer. But, if I try to debug $counts I am getting 1 only. I expect to have 4 or 3 but not one only. Follwing code is for the function match answer:
public function matchAnswer($question_id, $ans_id){
$args = array(
'where' => array(
'id' => $question_id,
'ans_id' => $ans_id
)
);
return $this->select($args);
}
And here is the function for getAnswersByUser:
public function getAnswersByUser($id, $is_die = false){
$args = array(
'where' => array(
'user_id' => $id
)
);
return $this->select($args);
}
A:
Replace this with
$getresult = $quizAns->getAnswersByUser($_POST['user_id']);
if($getresult){
$count = count($getresult);
for ($x = 1; $x <= $count; $x++) {
$match = $quiz->matchAnswer($getresult[$x]->question_id,$getresult[$x]->ans_id);
}
}
$counts = count($match);
with
$getresult = $quizAns->getAnswersByUser($_POST['user_id']);
$counts = 0;
if($getresult){
$count = count($getresult);
for ($x = 0; $x < $count; $x++) {
$match = $quiz->matchAnswer($getresult[$x]->question_id, $getresult[$x]->ans_id);
if($match){
$counts += 1;
}
}
}
$counts = count($match);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Booting Problem - Ubuntu GNOME 16.04.01 LTS
So, I mounted Kali Linux Light iso image on my usb stick and ran it Live. Eveything was fine. When I finished, I shut down the Kali and unplugged my usb. Then I turned back on my PC and my screen started flashing before login screen.
I'm getting this message:
/dev/sda1: recovering journal
/dev/sda1: clean 221608/30269440 files, 4431756/121048320 blocks
[ OK ] Starting Anonymizing overlay network for TCP.
[ OK ] Created slice User Slice for gdm.
Starting User Manager for UID 121...
[ OK ] Started Session c1 of user gdm.
[ OK ] Started User Manager for UID 121.
Stopping User Manager for UID 121...
_
I'm not sure if this is connected somehow.
I tried this (but it didn't help):
Checked BIOS settings
Reinstalled GRUB using my installation USB (I ran a live version with it, here's the report - http://paste2.org/78CUHf9H )
Scanned for issues in recovery mode
I can hit CTRL+ALT+F1 while my screen is flashing, but every 4 seconds my monitor flashes again with this error message ^^ so I need to hit those buttons again to access the terminal again, it's really annoying.
A:
I would normally refer you to my Q&A on NVIDIA issues, but that involves using TTYs, which won't work for you, at least right away.
Boot into Recovery Mode, drop to a root shell, and follow the steps below:
Run mount -o rw,remount / to mount the drive in Read-Write mode.
Run sudo apt-get purge nvidia-* to purge the NVIDIA driver.
You may also need to purge xserver-xorg and reinstall it, which will require you to enable networking in Recovery.
Reboot. You may have to add the nouveau.modeset=0 flag in GRUB to boot properly (Check my Q&A for specifics).
You should be past the screen flicker and be at your desktop.
Now reinstall the NVIDIA drivers the proper way:
sudo apt-get install nvidia-367 (or 340, 352, 364, 370, whichever works).
Reboot again.
You should be up and running: good as before. I don't see how Kali could have done this, but if you messed around with your filesystem, then it's definitely possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
DexNav Shiny Chaining Questions
I'm familiar with the general rules for shiny chaining using the DexNav in Pokemon Omega Ruby and Alpha Sapphire.
Compiled from various sites:
Leaving the area will break your chain.
Whenever a player captures or feints a hidden Pokemon of any species, the chain increases.
Encountering anything but a hidden wild Pokemon (whether trainer or regular wild Pokemon) will break your chain.
Failing to capture or defeat the wild Pokemon for any reason will break the chain.
Once it appears, failing to encounter a hidden wild Pokemon in the wild for any reason (walking too fast, walking too far away, or taking too long and letting it run away) will break the chain. Bringing up the menu once the Pokemon has appeared will not stop the timer on the Pokemon running. From my own experience, NPCs walking around in the grass will also scare away hidden Pokemon. Stay away from those buggers.
The DexNav does not have to be used to keep a chain going, and receiving a "The Pokemon couldn't be found..." message while using the search feature does not break the chain.
Every 5 successive encounters increases the level of hidden Pokemon by 1. Every hundred encounters, this level bonus resets to 0.
Even though the items I'm curious about aren't explicitly stated above, I don't want to assume that they're true or false implicitly.
My concerns:
If a shiny Pokemon is encountered, and fainted, does it break the chain? (for instance, I encounter a shiny that I already have, and I want to keep chaining for a different one)
Confirm that it does not have to be the same Pokemon encountered every time in order maintain the chain, as long as it's a hidden Pokemon encountered.
Capturing a shiny Pokemon also breaks the chain, right? Otherwise you could just keep chaining in the area until you have all available Pokemon. Which I'm totally fine with if that's the case lol, but I'm assuming not.
When the bonus that affects the hidden, wild Pokemon's level and potential is reset, does this break the chain? (I'm assuming not)
A:
I'll answer every question following your order:
Fainting or catching a shiny Pokemon doesn't break the chain, but it will reset the chance to find another shiny Pokemon to the default value.
No, you can encounter different hidden Pokemon while chaining without breaking it. As Bulbapedia states:
A chain builds every time the player captures or defeats a hidden Pokémon of any species.
As said above, catching a shiny Pokemon will reset the chance, but it doesn't break the chain.
No, reaching a chain of 100 doesn't break the chain, it will only reset the Pokemon level bonus. According to a previous version of the DexNav page:
The chance of encountering a Shiny Pokémon increases, estimated to reach 0.5% per encounter after 40 chained encounters, and remain at that rate as long as the chain continues. There is thus a 50% chance of encountering a Shiny Pokémon in the first (roughly) 130 chained encounters.
(This means that you need a chain of 100+ to get a decent chance of a shiny encounter.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Need a way to shorten and make code more effective
I want to perform a bootstrap simulation 1000 times and compute percentile confidence intervals 1000 times for different samplesizes n = 10,20,...,100. I've solved this problem and I'm just asking, instead of doing this huge computations 10 times, covering 300 lines of code, is there a way to shorten this? Like, running this function over and over again 10 times? I tried a for-loop but it did not work. Here is the code that does work:
B = 1000 # number of replicates
kHat = Parameters[1] # approx = 2.06786
gammaHat = Parameters[2] # approx = 0.51144
TheoreticalMean = kHat/gammaHat
TheoreticalVariance = kHat/gammaHat^2
PercCoverage = vector("numeric", 10L)
n = 10 # sample size
getCI = function(B, k, gamma, n) {
getM = function(orgData, idx) {
bsM = mean(orgData[idx])
bsS2M = (((n-1) / n) * var(orgData[idx])) / n
c(bsM, bsS2M)
}
F = rgamma(n, kHat, gammaHat) # simulated data: original sample
M = mean(F) # M from original sample
S2M = (((n-1)/n)*var(F))/n # S^2(M) from original sample
# bootstrap
boots = t(replicate(B, getM(F, sample(seq(along=F), replace=TRUE))))
Mstar = boots[,1] # M* for each replicate
S2Mstar = boots[,2] # S^2*(M) for each replicate
biasM = mean(Mstar)-M # bias of estimator M
# indices for sorted vector of estimates
idx = trunc((B+1)*c(0.05/2,1-0.05/2))
ciPerc = sort(Mstar)[idx] # percentile CI
c(perc=ciPerc)
}
# 1000 bootstraps
Nrep <- 1000 # number of bootstraps
CIs <- t(replicate(Nrep, getCI(B, kHat, gammaHat, n)))
# coverage probabilities
PercCoverage[1] = sum((CIs[,"perc1"]<TheoreticalMean) & (CIs[,"perc2"]>TheoreticalMean)) / Nrep
However, here I need to script this for n=10, n=20 and so on to n=100, and each time I need to change PercCoverage[1] to PercCoverage[2]...PercCoverage[10] in order to store these values in an array for later plotting.
I tried setting n=c(10,20,30,40,50,60,70,80,90,100) and then placing all of the above in a for loop but the function getCI needed numerical value.
EDIT: For loop attempt:
n = c(10,20,30,40,50,60,70,80,90,100)
B = 1000 # number of replicates
kHat = Parameters[1] # approx = 2.06786
gammaHat = Parameters[2] # approx = 0.51144
TheoreticalMean = kHat/gammaHat
TheoreticalVariance = kHat/gammaHat^2
PercCoverage = vector("numeric", 10L)
for (i in length(n)){
getCI = function(B, k, gamma, n[i]) {
getM = function(orgData, idx) {
bsM = mean(orgData[idx])
bsS2M = (((n[i]-1) / n[i]) * var(orgData[idx])) / n[i]
c(bsM, bsS2M)
}
F = rgamma(n[i], kHat, gammaHat) # simulated data: original sample
M = mean(F) # M from original sample
S2M = (((n[i]-1)/n[i])*var(F))/n[i] # S^2(M) from original sample
# bootstrap
boots = t(replicate(B, getM(F, sample(seq(along=F), replace=TRUE))))
Mstar = boots[,1] # M* for each replicate
S2Mstar = boots[,2] # S^2*(M) for each replicate
biasM = mean(Mstar)-M # bias of estimator M
# indices for sorted vector of estimates
idx = trunc((B+1)*c(0.05/2,1-0.05/2))
ciPerc = sort(Mstar)[idx] # percentile CI
c(perc=ciPerc)
}
# 1000 bootstraps
Nrep <- 1000 # number of bootstraps
CIs <- t(replicate(Nrep, getCI(B, kHat, gammaHat, n[i])))
# coverage probabilities
PercCoverage[i] = sum((CIs[,"perc1"]<TheoreticalMean) & (CIs[,"perc2"]>TheoreticalMean)) / Nrep
}
A:
Consider defining multiple functions: a master one boostrap_proc, gCI, and getM. Then pass in your sequences of sample sizes in lapply for list return or sapply for numeric vector each calling the master function and returning a series of probabilities (last line of function). Be sure to remove the hard coded n = 10.
Define Functions
B = 1000 # number of replicates
kHat = Parameters[1] # approx = 2.06786
gammaHat = Parameters[2] # approx = 0.51144
TheoreticalMean = kHat/gammaHat
TheoreticalVariance = kHat/gammaHat^2
bootstrap_proc <- function(n) {
Nrep <- 1000 # 1000 bootstraps
CIs <- t(replicate(Nrep, getCI(B, kHat, gammaHat, n)))
# coverage probabilities
sum((CIs[,"perc1"]<TheoreticalMean) & (CIs[,"perc2"]>TheoreticalMean)) / Nrep
}
getCI <- function(B, k, gamma, n) {
F <- rgamma(n, kHat, gammaHat) # simulated data: original sample
M <- mean(F) # M from original sample
S2M <- (((n-1)/n)*var(F))/n # S^2(M) from original sample
# bootstrap
boots <- t(replicate(B, getM(F, sample(seq(along=F), replace=TRUE),n)))
Mstar <- boots[,1] # M* for each replicate
S2Mstar <- boots[,2] # S^2*(M) for each replicate
biasM <- mean(Mstar)-M # bias of estimator M
# indices for sorted vector of estimates
idx <- trunc((B+1)*c(0.05/2,1-0.05/2))
ciPerc <- sort(Mstar)[idx] # percentile CI
c(perc=ciPerc)
}
getM <- function(orgData, idx, n) {
bsM <- mean(orgData[idx])
bsS2M <- (((n-1) / n) * var(orgData[idx])) / n
c(bsM, bsS2M)
}
Call Function
sample_sizes <- c(10,20,30,40,50,60,70,80,90,100)
# LIST
PercCoverage <- lapply(sample_sizes, bootstrap_proc)
# VECTOR
PercCoverage <- sapply(sample_sizes, bootstrap_proc)
# VECTOR
PercCoverage <- vapply(sample_sizes, bootstrap_proc, numeric(1))
| {
"pile_set_name": "StackExchange"
} |
Q:
Maximum imbalance in a graph?
Let $G$ be a connected graph $G = (V,E)$ with nodes $V = 1 \dots n$ and edges $E$. Let $w_i$ denote the (integer) weight of graph $G$, with $\sum_i w_i = m$ the total weight in the graph. The average weight per node then is $\bar w = m/n$. Let $e_i = w_i - \bar w$ denote the deviation of node $i$ from the mean. We call $|e_i|$ the imbalance of node $i$.
Suppose that the weight between any two adjacent nodes can differ by at most $1$, i.e.,
$$ w_i - w_j \le 1\; \forall (i,j) \in E.$$
Question: What is the largest possible imbalance the network can have, in terms of $n$ and $m$? To be more precise, picture the vector $\vec{e} = (e_1, \dots, e_n)$. I'd be equally content with results concerning $||\vec{e}||_1$ or $||\vec{e}||_2$.
For $||\vec{e}||_\infty$, a simple bound in terms of the graph diameter can be found: Since all $e_i$ must sum to zero, if there is a large positive $e_i$, there must somewhere be a negative $e_j$. Hence their difference $|e_i - e_j|$ is at least $|e_i|$, but this difference can be at most the shortest distance between nodes $i$ and $j$, which in turn can be at most the graph diameter.
I'm interested in stronger bounds, preferably for the $1$- or $2$-norm. I suppose it should involve some spectral graph theory to reflect the connectivity of the graph. I tried expressing it as a max-flow problem, to no avail.
EDIT: More explanation.
I'm interested in the $1$- or $2$-norm as they more accurately reflect the total imbalance. A trivial relation would be obtained from $||\vec{e}||_1 \leq n|||\vec{e}||_\infty$, and $||\vec{e}||_2 \leq \sqrt{n}||\vec{e}||_\infty$. I expect, however, that due to the connectedness of the graph and my constraint in the difference of loads between adjacent nodes, that the $1$- and $2$-norms should be much smaller.
Example: Hypercube of Dimension d, with $n = 2^d$. It has diameter $d = \log_2(n)$. The maximum imbalance is then at most $d$. This suggest as an upper bound for the $1$-norm $nd = n\log_2(n)$. So far, I have been unable to construct a situation where this is actually obtained, the best I can do is something along the lines of $||\vec{e}||_1 = n/2$, where I embed a cycle into the Hypercube and have the nodes have imbalances $0$, $1$, $0$, $-1$ etc. So, here the bound is off by a factor of $\log(n)$, which I consider already too much, as I'm looking for (asymptotically) tight bounds.
A:
Since $|e_i|$ is bounded by the diameter $d$, the $\ell_1$ norm is going to be trivially bounded by $nd$, likewise for the $\ell_2$ norm, except by $\sqrt{n}d$ (in fact the $\ell_p$ norm is bounded by $n^{1/p}d$).
The $\ell_1$ case turns out to be surprisingly easy to analyze.
For a path, it's easy to see that $\|\vec e\|_1$ is $O(n^2)$, so you can't do any better than $O(nd)$.
For a complete $k$-ary tree, you can divide it in half at the root, setting $w_{\text{root}} = 0$, ascending one side and descending the other until the leaves have $|e_i| = |w_i| = \log_k n$, producing $O(n\log_k n) = O(nd)$ again.
For a clique it doesn't really matter how you distribute the weights, since they'll all be within $1$ of each other, and that will yield $O(n) = O(nd)$ again.
When you realize that what we're talking about here is a function $e : \mathbb{Z} \to [-d/2,d/2] \subset \mathbb{R}$, and then we're taking its $\ell_1$ norm, as long as you can arbitrarily distribute weights $e_i \in [-d/2,d/2]$ evenly across the range, the bound will be $O(nd)$.
The only way to change this is to play games with the mass. For instance, if you have several giant cliques at points that are necessarily balanced, like a giant clique with two paths of equal length jutting out of it, then you can count on a bound of only (for example) $O(d^2)$.
This may be true for expanders to some degree as well, but I'm not sure. I could imagine a case where you set $w_1 = 0$ in a regular graph and then let the values increase subsequently from every hop. It seems likely that the mean could possibly have the most mass, but I don't know if it would be enough to affect the bound.
I think that you could reason similarly about $\ell_2$.
EDIT:
In the comments we figured out a (loose) $\ell_2$ bound of $O(|E|/\lambda_2(L))$ using the constraints of the problem and some basic spectral graph theory.
A:
For connected graphs, the imbalance is upper bounded by the diameter of the graph. In order to bound the imbalance $|w_i - 1/n\sum_k w_k|$, we can rewrite each $w_k$ as $w_k - v_1 + v_1 - v_2 + v_2 - ... - v_k + v_k - w_i + w_i$ where $w_k, v_1,...,v_k, w_i$ is the shortest path from $w_i$ to $w_k$. Define $w_{ki} = w_k - v_1 + v_1 - v_2 + v_2 - ... - v_k + v_k - w_i$. We can write
$$|w_i - 1/n\sum_k w_k| = |w_i - 1/n\sum_k (w_{ki} + w_i)| = |\sum_{k\neq i} \frac{w_{ki}}{n}|$$
Each $w_{ki}$ is upper bounded by the length of the shortest path from $i$ to $k$ by your assumption that $w_i - w_j \leq 1$ for each $i,j\in E$. Therefore, we get the trivial bound:
$$|w_i - 1/n\sum_k w_k| \leq \frac{(n-1)}{n} D$$
This might not actually be too far from optimal. I'm thinking of a complete $k$-ary tree where the nodes on each level have weight one higher than the weight of the previous level. A large fraction of the graph has the highest weight, $D+1$. So, the average should be skewed towards the top. As $k$ and $n$ get larger, I expect $m$ to get closer and closer to $D+1$ which means the imbalance should get closer and closer to $D$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I install MATLAB R2012a?
I have downloaded MATLAB R2012a for Unix platform and i want to install it on my ubuntu 11.10.
To install i try this command:
/<matlab_installation_file_directory>/install
and it says:
install: missing file operand
According to it's manual i must give it an input file, So i create an input file like this to install in 'Stand Alone' mode:
destinationFolder=usr/local/R2012a
fileInstallationKey=xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
agreeToLicense=yes
outputFile=/tmp/mathworks_usr.log
mode=interactive
activationPropertiesFile=home/.../lic_standalone.dat
Acctually i'm not sure in "activationPropertiesFile" field what file is required, so i supposed it requires license file. I saved this file as txt format in the same directory which installation files are.
Then i tried this command:
install -inputFile my_input_file.txt
and it gets this error:
install: invalid option -- 'i'
I know there is some helps in other websites and also some questions here about this topic, but i can't figure out what's the problem, Please help me, i'm a real noob on linux .
Thank you guys
UPDATE:
in properties of the install file i checked the item "Allow executing file as Program", now it's like this:
after that i can run install file by clicking on it or by typing ./install in terminal. but in both ways i get this:
Preparing installation files ...
Installing ...
eval: 1: /tmp/mathworks_xxxx/sys/java/jre/glnx86/jre/bin/java: Permission denied
Finished
in third line xxxx is a random number every time like 6370 or 5310 ... .
why i have not permission? what should i do?
UPDATE:
using Mahesh help i tried these commands:
sudo chmod +x ./install
sudo ./install -v
the result is:
Preparing installation files ...
-> DVD = /home/mehdi/qBT_dir/Matlab_Unix_2012a/ml2012au
-> ARCH = glnx86
-> DISPLAY = :0.0
-> TESTONLY = 0
-> JRE_LOC = /tmp/mathworks_6114/sys/java/jre/glnx86/jre
-> LD_LIBRARY_PATH = /tmp/mathworks_6114/bin/glnx86
Command to run:
/tmp/mathworks_6114/sys/java/jre/glnx86/jre/bin/java -splash:"/home/mehdi/qBT_dir/Matlab_Unix_2012a/ml2012au/java/splash.png" -Djava.ext.dirs=/tmp/mathworks_6114/sys/java/jre/glnx86/jre/lib/ext:/tmp/mathworks_6114/java/jar:/tmp/mathworks_6114/java/jarext:/tmp/mathworks_6114/java/jarext/axis2/:/tmp/mathworks_6114/java/jarext/guice/:/tmp/mathworks_6114/java/jarext/webservices/ com/mathworks/professionalinstaller/Launcher -root "/home/mehdi/qBT_dir/Matlab_Unix_2012a/ml2012au" -tmpdir "/tmp/mathworks_6114"
Installing ...
eval: 1: /tmp/mathworks_6114/sys/java/jre/glnx86/jre/bin/java: Permission denied
Finished
UPDATE:
Last thing to do is go into /matlab-install-files/sys/java/jre/glnx86/jre/bin/java and :
sudo chmod +x ./java
and then go back to installation files directory and run install by:
./install
or
sudo ./install
and it will work :-)
Thank you all specially "Mahesh" and "John"
A:
Something's wrong here. I've installed Matlab R2012a, and the install file does not require any input file.
This should work.
Command line way.
Open Terminal
cd into Matlab directory ( which has the install file and is shown in your screenshot)
sudo chmod +x ./install
sudo ./install
This will open a window, from where you will be able to proceed yourself.
GUI way:
type alt+F2. this opens the run dialog
type gksudo nautilus and hit enter
open the Matlab directory (as shown in your screenshot)
check if install file has execute permissions (as in your screenshot)
Double click install. You will get a window asking you wether to display or run.
Click on Run
you should be able to find your way from here. this opens a window with necessary instructions.
as you see, The Command line way is easier and safer.. ;)
This is guaranteed to work.
And just so you know, when you executed install, as described in your question, /usr/bin/install must have got executed. It is probably the one that complained of a missing file operand.
A:
For the error:
eval: 1: /tmp/mathworks_11425/sys/java/jre/glnxa64/jre/bin/java: Permission denied
You have to give permissions for the java to run (credits to http://kittipatkampa.wordpress.com/2012/02/12/matlab-on-ubuntu-from-install-make-launching-icon-to-uninstall/ )
After proceeding the steps by Mahesh, go to the folder
cd sys/java/jre/glnxa64/jre/bin/ (the folder that appears in your error message)
and then
chmod +x java
Ready to go. Go back to where your install file is and type
sudo sh install
The setup will (hopefully) launch.
| {
"pile_set_name": "StackExchange"
} |
Q:
Chart (or picture) does't appear in Crystal Report
I have been using visual studio 2013 along with crystal report service pack 9.
I also have created a window form to make a report with chart. The data works fine, but the chart or even picture doesn't appear in the report (only text data).
can anyone tell me where my problem is ?
Thanks in advance
A:
I think you are trying to change different crystal report file , please make sure that you edit and run the same file
| {
"pile_set_name": "StackExchange"
} |
Q:
programming tests/questions
Does anybody know a good reference I can use to prepare for interview questions/tests about c++ programming? From basic questions about OO programming to advanced ones.
Thank you,
A:
Check out C++ -FAQ lite by Marshall Cline. It covers almost everything that might be asked in a C++ technical interview
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete file on mongoDb gridFs results in "0", even if it is there
is there anything obvious I'm doing wrong with this code?
$result = $this->_grid->remove(
$someQueryWithOneResult, array('safe' => true, 'justOne' => true)
);
if ($result['n'] === 0) {
throw new FileNotFoundException("no file with xuuid '" . $xuuid . "'", 404);
} else if ($result['n'] === 1) {
return true;
}
Sometimes the exception is thrown (meaning the result was 0). I'm quite sure the file exists and it is deleted afterwards. I run this in a batch job against a mongoDb cluster with 2 shards and 2 replicasets.
I suspect a bug inside mongoDb either PHP driver (maybe 'safe' => true doens't work), or maybe some problem with the shard.
Any ideas? Google couldn't really help :-(
Regards
Marko
A:
You are likely running into either https://jira.mongodb.org/browse/SERVER-4532 or a variant of it https://jira.mongodb.org/browse/SERVER-7958.
These are fixed in current development version 2.3 (which will become 2.4 production release) and the fixes have been back-ported to 2.2 and will be in 2.2.3 release later this winter.
| {
"pile_set_name": "StackExchange"
} |
Q:
string.find not returning nil when searching for "."
There isn't very much explaining to do with this question, so if I type this into the Lua Interpreter (modified from here):
print(tostring(string.find("Hello Lua user", "banana")))
The returned output is nil, as expected. But, if I try the same thing with "." instead of "banana", like this:
print(tostring(string.find("Hello Lua user", ".")))
I get 1, why is this? And is there any way I can detect whether there are dots in a string? (In case it's relevant, I need to know so I can detect whether a directory is a file or a folder (Yes, I know you can have dots in folders/no dots in files on Linux))
A:
find uses Lua's pattern matching unless you tell it not to. . is a character class meaning "any character". If you want to find an actual period, you need to either:
Escape the period: %..
Tell find to not using pattern matching.
This is all in the manual, which is probably where you should start with these kinds of questions.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I limit the table width to the containing element (or screen)?
I need to show tabular data using a table, but it will be within a fluid layout; I want to have a it fill the entire available width but not to expand horizontally beyond maximum screen-width, such that the body does not get a horizontal scrollbar. Instead the too wide td elements shall get the scrollbar.
In the example there is DATA in the table, the table has border:1px solid black and the output shall be for easy parsing when piped from curl as well (hence the white-space:pre); The div is just the normal CSS layout helper, if possible let's get rid of that, too!
The important part is, that it shall be no fixed pixel width layout type, and the table shall be smaller than the available width in case the data does not need that much room. So to sum it up, a plain table which just does not get wider than the screen. Ideally the table would only stretch the parental element until the max-width of that enclosing element is reached and then do not get wider.
In Chrome, with something I consider to be an evil hack, I got to keep the table at the maximum width available and to display the scrollbars on the td if needed. However this does not work for FF, nor is that solution something which can be considered a correct one.
Following example of that can be found at https://hydra.geht.net/table-quirx.html for a while:
.nw { white-space:nowrap }
.quirx div { width:100%; max-width:100%; white-space:pre }
.quirx td { max-width:90px; border:1px solid black }
.quirx td+td { max-width:500px; overflow:auto }
table.quirx { width:100%; max-width:100%; border:1px solid black; border-collapse:collapse }
td { align:left; max-width:100% }
<head>
<title>Obey max-width for table</title>
</head>
<body>
<table summary="" class="quirx"><tr><td colspan="3">
Just some info
</td></tr><tr><td>KEY</td><td><div>DATA (which might contain long lines PRE formatted) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX </div>
</td></tr></table>
</body>
Note that the "colspan=3" is no error here, in my app sometimes a third column may show up, this cannot be known at the time the table header is output. (Some style things are redundant, too.)
The trick above is, that the td's max-width together are smaller than the usual screen (590px) and the table then is stretched to the given width, which is 100%. As the tds do not stretch beyond the screen, the inner div's overflow property can work as expected. However in FF it does not work this way, neither with width nor with max-width (which is probably due to their inline-status). In Chrome a width:100% or similar does not work on the td nor the tr elements. Note that with max-width one gets a more pleasant table layout than with width (I do not understand that difference).
Besides the bug that this only works in Chrome, another bug is, that the table uses the full screen-width even if that is not needed if there is only small data to display.
Some notes about that all:
I think this here is a very basic thing and I am puzzled why it seems so hard to express with CSS
A goal is to keep it free of any JavaScript, so only CSS with hacks
The user can resize the window, for example from 800px to 1920px or even wider, and so the table's width shall automatically follow (without JavaScript)
It shall display good on text based browsers like Lynx and w3m, too
Output shall not be too cluttered for easy parsing when piped from curl
It shall display more or less properly on the major 4 (IE, FF, Chrome, Safari)
It shall not break on others (it can have render bugs, but content must not be hidden)
I really have no idea how to archive that. Perhaps it's a FAQ, but I was unable to spot a solution myself.
A:
I'm including some markup below that tests the HTML/CSS to achieve what I believe you want.
There is a fixed-width cell style .fixedcell and fluid width cell style .fluidcell. I've set a fixed width (75px for this example) simply to illustrate things better.
The fluid width ones have width:auto so they fill the width of the remaining table space; they also importantly have white-space:nowrap so the text doesn't expand the cell height-wise (white-space:pre works too); and finally they have overflow:hidden so the text doesn't overflow the width and make things ugly, alternatively you could set overflow:scroll for it to have a scrollbar in those cells when/if necessary.
The table is set to be 100% width so it will expand to fit the screen/etc as needed. And the important thing regarding the table's style is the table-layout:fixed, this makes the table adhere to the layout of the page rather than auto-sizing itself based on its own content (table-layout:auto).
I also added some borders to help illustrate the boundaries of the table and cells.
<html>
<head>
<title>Table with auto-width sizing and overflow hiding.</title>
<style type="text/css">
table {width:100%; border:solid 1px red; table-layout:fixed;}
table td {border:solid 1px green;}
.fixedcell {width:75px;}
.fluidcell {width:auto; overflow:hidden; white-space:nowrap;}
</style>
</head>
<body>
Table with one fluid column:
<table>
<tr>
<td class="fixedcell">row 1</td>
<td class="fluidcell">a whole bunch of content could go here and it still needs to fit nice into the cell without mucking things up</td>
<td class="fixedcell">fixie</td>
<td class="fixedcell">another</td>
</tr>
</table>
Table with two fluid columns:
<table>
<tr>
<td class="fixedcell">row 1</td>
<td class="fluidcell">a whole bunch of content could go here and it still needs to fit nice into the cell without mucking things up</td>
<td class="fluidcell">blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah</td>
<td class="fixedcell">fixie</td>
<td class="fixedcell">another</td>
</tr>
</table>
</body>
</html>
I tested it in several modern browsers and seemed to work correctly in each.
PS. Although tables are a no-no for page layout in general, tables are correct and encouraged for tabular data layout.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between "any" and "a/an"?
I have a sentence
There isn’t ------ egg on the table.
Should the gap have any or an? What's the difference?
A:
I'm sorry Stockfish decided to pull his inspiring answer.
You may or may not expect many assorted eggs on the table. You may have been told that the table is where the egg was placed. Saying "There is not an egg" would be fine. If you had expected to find more than one egg then saying an egg would be a good way to emphasize your surprise. As would saying "There is not a single egg on that table".
If you were told that the table was covered in cooked/fried/scrambled etc. eggs then finding a clean table you could say "There isn't any egg on this table." Looking for a related food stain on your shirt you might say "There isn't any egg on my shirt".
"Egg" may be found as the singular in the shell or in the plural as the processed meal. As such it is not the best word to explore the a versus an question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Info for replacing a shift cable housing
I have a Raleigh MT 200 - 1994. I lost the segment of the housing for the cable of the rear derailleur (Shimano STX) that goes to the shifter, see red in the image 1.
I would likely purchase a replacement online. I want to know what should I look for in the spec, to make sure that I am buying the right thing.
What I found in the segment that goes to the derailleur (which is similar to the segment that goes to the front shifter):
Legend in the housing: Shimano SIS SP, image 4.
Outer diameter: 5mm, measured with caliper.
Two different metallic ferrules in the ends, images 2-4. The grooved ferrule goes to the shifter. These look very much like types A and B in https://www.bikeman.com/bicycle-repair-tech-info/bikeman-tech-info/1641-cables-a-housing
Length: about 200mm.
So, I have several specific questions:
Is there anything else I should look for?
Will an SP40 work (like http://www.ebay.com/itm/Shimano-XTR-XT-SLX-Shifter-Cable-Housing-SIS-SP40-/301329907340)?
Or an SP41?
Is it mandatory that the two ferrules are different, of types A and B respectively? (I do not know the difference among them).
What does "sealed" mean (like in http://www.ebay.com/itm/SHIMANO-180mm-SIS-SP-Sealed-Cable-Housing-New-w-black-ferrules/222309191697)
A:
I would suggest replacing the inner as well as all the outers. If the inner is frayed at all, you will not be able to rethread it. The benefits of a new cable are much better shifting, to the point cables are considered a consumable by many riders - just like tires and brake pads.
Shifter cables are very generic and cheap - as low as $5 online for a set.
You will also need a cable cutter. Dedicated bicycles ones make the job fast and tidy. You can use heavy duty wire cutters, but needs more care and is less successful get tidy and fray free cuts. If you don't have access to a decent cutter, you could buy one for about $25. If you plan this to be a once only, the LBS will install a new cable cheaper than buying the tool.
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel-Mix + BrowserSync Not Loading at localhost:3000
I'm trying to set up BrowserSync to work with my Laravel project. However, when I run npm run watch, localhost:3000 doesn't load. I'm not getting any compilation errors in the terminal. Interestingly enough, the UI dashboard on localhost:3001 works perfectly fine.
If I run php artisan serve, localhost:8000 loads up fine, but of course, it's not connected with BrowserSync.
My webpack.mix.js file looks like this:
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
mix.browserSync({proxy:'localhost:3000'});
I'm using the following versions:
Laravel-Mix: 4.0.7
browser-sync: 2.26.7
webpack-dev-server: 3.8.0
browser-sync-webpack-plugin: 2.0.1
Any thoughts?
A:
install this 2 plugins
"browser-sync": "^2.26.5"
"browser-sync-webpack-plugin": "^2.0.1",
mix.browserSync('http://localhost:8000/');
| {
"pile_set_name": "StackExchange"
} |
Q:
How to run Matlab code on an Android device?
I would like to run Matlab code on an Android device. There is the JAVA Builder in Matlab, which can create Java classes from the M-Files. But it requires a MatlabRunTime to be installed on the target machine. I use Matlab on Windows, so the JAVA Builder creates a MatlabRunTime as *.
Is there a way to run M-Files on an Android Smartphone?
A:
It's not possible to use any of the deployment products (including MATLAB Compiler and MATLAB Builder for Java) to run MATLAB code on Android. The deployed components you get from any of those products depend on the MATLAB Compiler Runtime, which has a much larger footprint than an Android device could handle.
You could consider either
Writing an app that connects, as @Oli suggested, to MATLAB code (or deployed MATLAB code) running somewhere on a server
Using MATLAB Coder, which can convert a subset of the MATLAB language into C code that could be integrated into your app.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Delete duplicate rows with lowest number
I can't find appropriate way to delete duplicate keys in sql table with lowest number. If there is a duplicate rows with the same Number, I need to delete one of them.
For example
Key Number Description
11111 5 Desc1
11111 4 Desc2
22222 2 Desc1
22222 2 Desc2
33333 3 Desc1
33333 5 Desc2
Here I need to be deleted the second row with Number 4 which is smaller then Number 5, one of the third or fourth row, and fifth row which have smaller Number 3 then the last row 5.
A:
Query to remove duplicate in SQL-Server:
;with c as
(
select *, row_number() over(partition by [Key] order by Number desc) as n
from YouTable
)
delete from c
where n > 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Need advice on moving a cable with a steel beam and stairs in the way
I live in a tri-level home. I am on the bottom floor and trying to run a cable from the wall up into the ceiling of the lower floor to put lights into this room. The way that it is currently done is not okay. Looking at my picture, the cable comes up and then it runs horizontally into the open space in the steel I-beam. It then hits a junction box (guessing the cable was too short) and then further down it runs up into the ceiling basically on the face of the stud. The drywall on the wall was notched to allow clearance for the cable. I know that is no okay, which is why I am trying to move it.
The beam runs the whole length of the wall, so I cannot just go further down to go up into the ceiling. And it is my understanding that I cannot drill a hole through the top flange of the beam.
So I think my only option (and not even sure if it is an option) is to go through the wood that is to the left and above the beam. Instead of the cable that is circled in red going through that stud, I need it to go up and come out above the wall where I have the purple circle. Not sure what is okay to drill through since there is so much going on here.
In short, how do I get a cable from red circle to purple circle without compromising the structure of the floor above or the stairs?
Edit to add picture where existing cable goes into ceiling on the surface of the studs.
A:
I'd be looking at a larger re-run to address the illegal junction box. You might be able to avoid this hurdle altogether. Aside from that, I'd do this:
Open up a little more drywall so you can get your drill and a drill bit in each of those openings.
Drill from below at about a 10 degree angle to the right, and to a depth of about 3" into the triple beam above. Roughly center the hole in the wall depth and keep it centered on that plane.
Drill from right to left through the triple beam, 2 inches up, intersecting the earlier hole. Angle slightly downward to ease the bend where the bores intersect.
I'd use a 3/4" or 7/8" bit. That should be forgiving enough yet not be absurdly large in terms of framing damage. It's important that you align the holes carefully. Then pull a light wire or string through as a fish line. Feed the cable gently though the bend to avoid sharp kinks.
| {
"pile_set_name": "StackExchange"
} |
Q:
function takes iterabls and return a list
def group_when(iterable,p):
x = iter(iterable)
z = []
d = []
try:
while True:
y = next(x)
if p(y) == False:
z.append(y)
elif p(y) == True:
z.append(y)
d.append(z)
z = []
except StopIteration:
pass
return
The group_when generator takes one iterable and one predicate as parameters: it produces lists that each end in a value from the iterable where the predicate is True. If the iterable ends on a value for which the predicate returns False, yield a final list containing all the values from the one after the previous end to the last value produced by the iterable
for example:
for i in group_when('combustibles', lambda x : x in 'aeiou'):
print(i,end='')
prints the 5 lists ['c', 'o']['m', 'b', 'u']['s', 't', 'i']['b', 'l', 'e']['s'].
my function is getting so close to the correct answer. when the input is
('combustibles', lambda x : x in 'aeiou')
my function returns
[['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']]
but the correct output should be:
[['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
Therefore, I am only missing the last letter 's'.
can anyone tell me how to fix it? many thanks
I posted the error I got below just to help you to understand my function:
26 *Error: Failed [v for v in group_when('combustibles', lambda x : x in 'aeiou')] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
evaluated: [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
27 *Error: Failed [v for v in group_when(hide('combustibles'), lambda x : x in 'aeiou')] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
evaluated: [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
A:
So going with your original form, this is how I would fix your issue.
def group_when(iterable,p):
x = iter(iterable)
z = []
d = []
for y in x:
z.append(y)
if p(y):
d.append(z)
z = []
if z:
d.append(z)
return d #added the d here, think OP dropped it by accident
| {
"pile_set_name": "StackExchange"
} |
Q:
Redirect on successful login
I am using the following snippet to control redirects after successful logins....
add_action( 'wp_login', 'redirect_on_login' ); // hook failed login
function redirect_on_login() {
$referrer = $_SERVER['HTTP_REFERER'];
$homepage = get_option('siteurl');
if (strstr($referrer, 'incorrect')) {
wp_redirect( $homepage );
}
elseif (strstr($referrer, 'empty')) {
wp_redirect( $homepage );
}
else
{
wp_redirect( $referrer );
}
}
What i want it to do is this...
If $referrer is www.mydomain.com/?login=incorrect then redirect to the homepage
If $referrer is www.mydomain.com/?login=empty then redirect to the homepage
Anything else then redirect to $referrer
I'm sure there is something wrong with my logic as whatever $referrer is it just redirects me to the same. Am i missing something obvious?
UPDATE
As requested, here is a bit more of an explanation...
Somebody goes to my custom WordPress login page at www.mydomain.com
They try to log in with an incorrect password or username
The following function runs...
add_action( 'wp_login_failed', 'pu_login_failed' ); // hook failed login
function pu_login_failed( $user ) {
// check what page the login attempt is coming from
$referrer = $_SERVER['HTTP_REFERER'];
$loginpage = 'http://www.mydomain.com/login';
// check that were not on the default login page
if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') && $user!=null ) {
// make sure we don't already have a failed login attempt
if ( !strstr($referrer, '?login=failed' )) {
// Redirect to the login page and append a querystring of login failed
wp_redirect( $loginpage . '/?login=incorrect');
} else {
wp_redirect( $referrer );
}
exit;
}
}
This is how the ?login=incorrect gets added, I am probably going about it the wrong way though
A:
According to the Codex page for wp_redirect(), you should follow your wp_redirect() calls with exit.
add_action( 'wp_login', 'redirect_on_login' ); // hook failed login
function redirect_on_login() {
$referrer = $_SERVER['HTTP_REFERER'];
$homepage = get_option('siteurl');
if (strstr($referrer, 'incorrect')) {
wp_redirect( $homepage );
exit;
} elseif (strstr($referrer, 'empty')) {
wp_redirect( $homepage );
exit;
} else {
wp_redirect( $referrer );
exit;
}
}
If that doesn't work, try commenting out your wp_redirect() calls and then echo( $referrer ); to see if $referrer is set correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fix "expected token ',', got 'invalid'" eroor in flask
I want to throw every error which is done by the user while filling up the form.
I have tried putting a comma here and there but nothing seems to be working
ERROR
Traceback (most recent call last):
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/bhuvan/Documents/seriously_portfolio/app.py", line 14, in index
return render_template("index.html", form=form)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/templating.py", line 140, in render_template
ctx.app,
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/flask/templating.py", line 120, in _render
rv = template.render(context)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "/home/bhuvan/Documents/seriously_portfolio/templates/form.html", line 39, in template
<div class="invalid-feedback">
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/environment.py", line 1005, in render
return concat(self.root_render_func(self.new_context(vars)))
File "/home/bhuvan/Documents/seriously_portfolio/templates/index.html", line 3, in top-level template code
{% extends 'layout.html' %}
File "/home/bhuvan/Documents/seriously_portfolio/templates/layout.html", line 21, in top-level template code
{% block content %}
File "/home/bhuvan/Documents/seriously_portfolio/templates/index.html", line 115, in block "content"
{% include 'form.html' %}
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "/home/bhuvan/Documents/seriously_portfolio/templates/form.html", line 39, in template
<div class="invalid-feedback">
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/environment.py", line 497, in _parse
return Parser(self, source, name, encode_filename(filename)).parse()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 901, in parse
result = nodes.Template(self.subparse(), lineno=1)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 883, in subparse
rv = self.parse_statement()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 130, in parse_statement
return getattr(self, 'parse_' + self.stream.current.value)()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 213, in parse_if
'name:endif'))
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 165, in parse_statements
result = self.subparse(end_tokens)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 875, in subparse
add_data(self.parse_tuple(with_condexpr=True))
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 620, in parse_tuple
args.append(parse())
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 432, in parse_expression
return self.parse_condexpr()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 437, in parse_condexpr
expr1 = self.parse_or()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 450, in parse_or
left = self.parse_and()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 459, in parse_and
left = self.parse_not()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 470, in parse_not
return self.parse_compare()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 474, in parse_compare
expr = self.parse_math1()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 496, in parse_math1
left = self.parse_concat()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 507, in parse_concat
args = [self.parse_math2()]
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 517, in parse_math2
left = self.parse_pow()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 528, in parse_pow
left = self.parse_unary()
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 547, in parse_unary
node = self.parse_postfix(node)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 676, in parse_postfix
node = self.parse_call(node)
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/parser.py", line 767, in parse_call
self.stream.expect('comma')
File "/home/bhuvan/Documents/seriously_portfolio/env/lib/python3.6/site-packages/jinja2/lexer.py", line 384, in expect
self.name, self.filename)
jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'invalid'
'''
form.html
<form method="POST" action="">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.name.label() }}
{% if form.name.errors %}
{{ form.name(class="form-control is-invalid") }}
<div class="invalid-feedback">
{% for error in form.name.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.name(class="form-control") }}
<!-- <small class="form-text text-muted">
Enter Characters between 5-20.
</small> -->
{% endif %}
</div>
<div class="form-group">
{{ form.email.label() }}
{% if form.email.errors %}
{{ form.email(class="form-control is-invalid") }}
<div class="invalid-feedback">
{% for error in form.email.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.email(class="form-control") }}
{% endif %}
</div>
<div class="form-group">
{{ form.message.label() }}
<!-- {{ form.message(class="form-control", rows="4", cols="50", placeholder="Enter your message...") }} -->
{% if form.message.errors %}
{{ form.message(class="form-control is-invalid) }}
<div class="invalid-feedback">
{% for error in form.message.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.message(class="form-control") }}
<!-- <small class="form-text text-muted">
Optional. Max Characters 300 only.
</small> -->
{% endif %}
</div>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info")}}
</div>
</form>
Edit: I'm just writing random things to get the post submitted. Please ignore this thing. Nope it still wont submit help goddamnit.
A:
You are missing a closing ":
{{ form.message(class="form-control is-invalid) }}
| {
"pile_set_name": "StackExchange"
} |
Q:
Prevent programmers from acquiring lock on class instance
Is it possible to write a class such that other programmers cannot acquire a lock on an instance of the class?
Lock-abuse, if there's a term like that, can be a serious killer. unfortunately, programmers torn between the disastrous forces of delivering thread-safe code and limited knowledge of concurrency, can wreak havoc by adopting the approach of locking instances even when they're invoking operations which really don't require the instance's resources to be blocked
A:
The only way to do this is to ensure that the classes instances are not visible. For example, you could declare is as a private nested class, and make sure that the enclosing class does not leak reference instances.
Basically, if something can get hold of a reference to an instance, there is nothing to stop it from locking it.
Normally, it is sufficient to ensure that the reference to the lock object doesn't leak ... and not worry about the class visibility.
FOLLOW UP - in response to the OP's comments.
You cannot stop someone else's code from taking a lock an instance of one of your classes. But you can design your class so that this won't interfere with your classes internal synchronization. Simply arrange that your class uses a private object (even an Object instance) for synchronizing.
In the more general sense, you cannot stop application programmers from using your classes in ways that you don't like. Other examples I've heard of (here) include trying force people to override methods or provide particular constructors. Even declaring your class fields private won't stop a determined (or desperate) programmer from using reflection to get at them.
But the flip-side is that those things you are trying to prevent might actually not be stupid after all. For example, there could actually be a sound reason for an application to use your class as a lock object, notwithstanding your objection that it reduces concurrency. (And it in general it does, It is just that this may not be relevant in the particular case.)
My general feeling is that is a good idea to document the way your class is designed to be used, and design the API to encourage this. But it is unwise to try to force the issue. Ultimately it is the responsibility of the people who code against your classes to use them sensibly ... not yours.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I set size.pr in OpenLDAP?
I think one of my LDAP clients is hitting a pagination limit in OpenLDAP. The specific error the client sees is the following Java thing:
REASON: Caught exception running LDAP sync.
[LDAP: error code 2 - paged results cookie is invalid];
nested exception is javax.naming.CommunicationException:
[LDAP: error code 2 - paged results cookie is invalid];
remaining name 'dc=example,dc=com'
Googling for that error brought up a discussion of LDAP pagination and relevant limits. This document on OpenLDAP limits mentions olcSizeLimit and size.pr.
I was able to change my olcSizeLimit from 500 to -1 using this ldif:
dn: cn=config
changetype: modify
replace: olcSizeLimit
olcSizeLimit: -1
Unfortunately my client is still seeing its pagination issue.
size.pr is a slapd.conf setting, while my OpenLDAP uses slapd.d instead. After grepping around in the LDAP schema, I've found olcDbClientPr which is described as 'PagedResults handling'. Also, here's how it's described in the OpenLDAP source code:
{ "client-pr", "accept-unsolicited|disable|<size>", 2, 2, 0,
ARG_MAGIC|LDAP_BACK_CFG_CLIENT_PR,
meta_back_cf_gen, "( OLcfgDbAt:3.111 "
"NAME 'olcDbClientPr' "
"DESC 'PagedResults handling' "
"SYNTAX OMsDirectoryString "
"SINGLE-VALUE )",
NULL, NULL },
On the assumption that olcDbClientPr is the same thing as size.pr, how do I set it?
I've tried this:
dn: cn=config
changetype: modify
replace: olcDbClientPr
olcDbClientPr: -1
It throws this error:
modifying entry "cn=config"
ldap_modify: Object class violation (65)
additional info: attribute 'olcDbClientPr' not allowed
In case it's relevant, here are the contents of my cn=config directory:
# ls /etc/openldap/slapd.d/cn=config/
cn=module{0}.ldif olcDatabase={0}config.ldif olcDatabase={1}hdb.ldif
cn=schema olcDatabase={-1}frontend.ldif olcDatabase={1}monitor.ldif
cn=schema.ldif olcDatabase={1}hdb
A:
size.pr is a, per database (and dn/group scopable), olcLimits option. You might also be interested in the global olcSizeLimit option.
From slapd-config(5):
olcSizeLimit: size[.{soft|hard|unchecked}]= [...]
Specify the maximum number of entries to return from a search operation. The default size limit is 500. Use unlimited to specify no limits. The second format allows a fine grain setting of the size limits. Extra args can be added in the same value or as additional values. See olcLimits for an explanation of the different flags.
olcDbClientPr is not the same as size.pr.
| {
"pile_set_name": "StackExchange"
} |
Q:
Needing a nudge with a Commutative Algebra Question
I have a commutative ring with identity $R$, and an $R$-module $M$. Next I have an $R$-submodule $N$ of $M$. Finally, I have a multiplicatively closed subset $S$ of $R$.
I am asked to show that $S^{-1}(M/N)$ is isomorphic to $(S^{-1}M)/(S^{-1}N)$.
I guessed at the following mapping:
Define $\phi:S^{-1}(M/N)\to (S^{-1}M)/(S^{-1}N)$ by $\phi(\frac{m+N}{s}) = \frac{m}{s} + S^{-1}N$.
I'm stuck trying to show that my map is well defined. Let's assume that $\frac{m_1+N}{s_1} = \frac{m_2+N}{s_2}$. Then I want to show that $\frac{m_2}{s_2} + S^{-1}N = \frac{m_2}{s_2} + S^{-1}N$
By the definition of the equivalence of elements of $S^{-1}(M/N)$, there is an $s\in S$ such that
$s[s_2(m_1 + N) - s_1(m_2 + N)] = N$ (since $N$ is the $0$ element of $M/N$).
Now I get from this that
$s[\{(s_2m_1) + N\} - \{(s_1m_2) + N\}] = N$
and thus
$s[(s_2m_1 - s_1m_2) + N] = N$
Then
$s(s_2m_1 - s_1m_2) + N = N$
which implies
$s(s_2m_1 - s_1m_2) \in N$
or
$ss_2m_1 - ss_1m_2 \in N$
which is the definition of
$ss_2m_1 + N = ss_1m_2 + N$.
Now somehow from here I need to get to the conclusion that $\frac{m_1}{s_1} + S^{-1}N = \frac{m_2}{s_2} + S^{-1}N$. That is, $\frac{m_1}{s_1} - \frac{m_2}{s_2} \in S^{-1}N$.
I've been stuck for a while now, any advice? or have I gone wrong somewhere?
A:
Remember that
$$\frac{m_1}{s_1}-\frac{m_2}{s_2} = \frac{s_2m_1-s_1m_2}{s_1s_2} = \frac{s(s_2m_1-s_1m_2)}{ss_1s_2}.$$
And you know something about $s(s_2m_1-s_1m_2)$, right?
| {
"pile_set_name": "StackExchange"
} |
Q:
Matlab - add string index and numerical column to matrix
I have a 4*3 matrix, and I would like to add column names, e.g.[1,2,3] and index name, e.g. ['A','B','C','D'] on it. How can I do this?
I'm thinking to transfer this matrix into data frame. but i saw matlab seems don't have this feature. Should i download any add-in or other functions?
thanks.
A:
You can use matlab's table data structure as in
T = table( rand(4,3) );
and modify the metadata properties with
T.Properties.VariableNames = {'c1' 'c2' 'c3'}; % columns
T.Properties.RowNames = {'A' 'B' 'C' 'D'}; % rows
Column names can't be pure numbers though, because you need to access them as in
T.c1 % get the column c1
T{'A',:} % get the row A
(T.1 can't exist)
This is matlab's option to get something close to a dataframe.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert triplets to matrix in R
I have triplets and want to convert them to the matrix.
This is my code:
data = data.frame(row = c(1,2,3), column = c(2,3,1), value = c(0.1, 0.2, 0.5));
m <- matrix(0, nrow = max(data$row), ncol = max(data$column));
m[ data$row, data$col ] = data$value;
The output is
[,1] [,2] [,3]
[1,] 0.1 0.1 0.1
[2,] 0.2 0.2 0.2
[3,] 0.5 0.5 0.5
Desire output is
[,1] [,2] [,3]
[1,] 0 0.1 0
[2,] 0 0 0.2
[3,] 0.5 0 0
How can I do that without loop?
A:
Try
m[cbind(data[,1], data[,2])] <- data$value
Or
m[as.matrix(data[1:2])] <- data$value
m
# [,1] [,2] [,3]
#[1,] 0.0 0.1 0.0
#[2,] 0.0 0.0 0.2
#[3,] 0.5 0.0 0.0
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I find a basis for the following subspace?
I'm unsure how to do the following problem: Find a basis of the following subspace of $R^4$. W = all vectors of the form $(a,b,c,d)$ where $a+b-c+d=0$. Any help would be great, many thanks :)
A:
It's one equation in four-dimensional space, so the subspace in question has three dimensions. Three linearly independent vectors satisfying the relation would do it. For instance:
$$
(1,0,1,0),(0,1,1,0),(0,0,1,1)
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Drawbacks to an idling fixed threadpool
I'm currently in the process of doing various performance improvements in a software. As it is using SWT for it's GUI, I have come across a problem where under certain circumstances a lot of UI elements are created in the Display Thread.
Since the person before me, didn't really take care to do any calculations outside of the Display Thread, the whole software can be unresponsive for several seconds on startup.
I've now isolated the code that needs to be performed in the Display Thread, and I'm now calculating everything else in Runnables that I submit to a fixed Threadpool.
I'm using the pool like this:
public abstract class AbstractChartComposite {
private static ExecutorService pool = Executors.newFixedThreadPool(8);
private List<String> currentlyProcessingChartItems = new ArrayList<>();
protected void doCalculate(constraints){
for (IMERuntimeConstraint c : constraints) {
if(!currentlyProcessingChartItems.contains(c.getId())){
currentlyProcessingChartItems.add(c.getId());
pool.submit(new Runnable(){
@Override
public void run() {
try{
createChartItem(c);
currentlyProcessingChartItems.remove(c.getId());
}catch(Throwable e){
e.printStackTrace();
}
}
});
}
}
}
}
I'm now wondering, if I have any drawbacks to leaving the Threadpool running at idle, once all the UI elements have been created. I cannot really shut it down for garbage collection, because it will be needed again on user Input when a new element needs to be created.
So are there any major drawbacks on leaving a threadpool with no submitted Runnables running?
A:
No, there are no drawbacks.
The threads won't be actually running, they'll be parked until a new task is submitted. So it does not affect CPU. Also you say that you will use this pool again, so in your case there's no point of shutting it down and recreating again.
As to the memory - yes, idle threads will consume some amount of memory, but that's not an issue as well, until you have hundreds (thousands?) of threads.
Also, a piece of advice. Do not do premature optimizations. That's the root of all evil. Analyze a problem once you have real performance issues, using special utilities for that and detecting bottlenecks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Google couldn't fetch my sitemap.xml file
I've got a small flask site for my old wow guild and I have been unsuccessful in getting google to read my sitemap.xml file. I was able to successful verify my site using googles Search Console and it seems to crawl it just fine but when I go to submit my sitemap, it lists the status as "Couldn't fetch". When I click on that for more info all it says is "Sitemap could not be read" (not helpful)
I originally used a sitemap generator website (forgot which one) to create the file and then added it to my route file like this:
@main.route('/sitemap.xml')
def static_from_root():
return send_from_directory(app.static_folder, request.path[1:])
If I navigated to www.mysite.us/sitemap.xml it would display the expected results but google was unable to fetch it.
I then changed things around and started using flask-sitemap to generate it like this:
@ext.register_generator
def index():
yield 'main.index', {}
This also works fine when I navigate directly to the file but google again does not like this.
I'm at a loss. There doesn't seem to but any way to get help from google on this and so far my interweb searches aren't turning up anything helpful.
For reference, here is the current sitemap link: www.renewedhope.us/sitemap.xml
A:
I finally got it figured out. This seems to go against what google was advising but I submitted the sitemap as http://renewedhope.us/sitemap.xml and that finally worked.
From their documentation:
Use consistent, fully-qualified URLs. Google will crawl your URLs
exactly as listed. For instance, if your site is at
https://www.example.com/, don't specify a URL as https://example.com/
(missing www) or ./mypage.html (a relative URL).
I think that only applies to the sitemap document itself.
When submitting the sitemap to google, I tried...
http://www.renewedhope.us/sitemap.xml
https://www.renewedhope.us/sitemap.xml
https://renewedhope.us/sitemap.xml
The only format that they were able to fetch the sitemap from was:
http://renewedhope.us/sitemap.xml
Hope this information might help someone else facing the same issue :)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fill a multi select input from a hidden input and vice versa?
So I have an address book tool that I setup using this http://www.phpkobo.com/address_book.php. I also setup Select2 which is a jquery plugin that manages multiple select inputs https://select2.github.io/examples.html.
So this address book tool does not allow you to setup a multi select input so i had to engineer my way around this by creating a multi select input that then copied your selected input into a hidden input. Using the below script I managed to get the selected items copied over automatically over to a hidden input i had.
function loopSelected()
{
var txtSelectedValuesObj = document.getElementById('hidden_input');
var selectedArray = new Array();
var selObj = document.getElementById('selected_items');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
So this script works just fine however, the problem is that when I got to edit an entry my multi select input is empty since all the data was saved on the hidden input. Im trying to figure out how can I fill the multi select input with the data that's already in the hidden input and vice versa?
Any help would be appreciated.
Here is an example of what I got working:
https://jsfiddle.net/akhyp/1956/
A:
Got some help via this thread Jquery script - Fill select with input text and vice versa
Here is the final product working as desired: http://jsfiddle.net/akhyp/1966/
$("#txt").bind('keyup' , function(e){
var ar = $(this).val().split(",");
$("#sel option").each(function(){
if(ar.indexOf($(this).val()) != -1)
$(this).attr("selected","selected");
});
});
$('#sel').change(function(){
$('#txt').val($('#sel').val());
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Determine size of files in zip?
To keep total size of my app down, I would like to distribute some very large databases as ZIP files, then unpack them as needed. Is there an easy way to determine the size of a file in a ZIP so I know in advance if there is space on the device to even try to unzip one of them?
The ZIP file would contain only one file. Yes, I could measure the size in advance and hardcode it, but that's error prone, as I update the databases on a regular basis.
Best regards,
Anders
A:
There are a few 3rd party Objective-C libraries for working with ZIP files. These would allow you to interrogate the contents of a zip file without needing to unzip them first.
Check out ZipKit or Objective-Zip.
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting from RGB to Lαβ Color spaces and converting it back to RGB using OpenCV
I am currently trying to convert colors between RGB (red, green, blue) color space and Lαβ color space, Based on the details in the this paper.
My difficulties are in reversing the conversion process. When the result is not as same as initial RGB Mat. I think I missing something in type castings between Mats but I can't tell what is it!
here is my code:
<!-- language: lang-cc -->
Mat DetectTrackFace::RGB2LAlphBeta(Mat &src)
{
Mat dest;
Mat L_AlphBeta(src.rows, src.cols, CV_32FC3);
//cvtColor(src,dest,CV_BGR2XYZ);
float X,Y,Z,L,M,S,_L,Alph,Beta;
int R,G,B;
for(int i = 0; i < src.rows; i++)
{
for(int j = 0; j < src.cols; j++)
{
B = src.at<Vec3b>(i, j)[0];
G = src.at<Vec3b>(i, j)[1];
R = src.at<Vec3b>(i, j)[2];
X = ( 0.4124 * R ) + ( 0.3576 * G ) + ( 0.1805 * B);
Y = ( 0.2126 * R ) + ( 0.7152 * G ) + ( 0.0722 * B);
Z = ( 0.0193 * R ) + ( 0.1192 * G ) + ( 0.9505 * B);
L = (0.3897 * X) + (0.6890 * Y) + (-0.0787 * Z);
M = (-0.2298 * X) + (1.1834* Y) + (0.0464 * Z);
S = (0.0000 * X) + (0.0000 * Y) + (1.0000 * Z);
//for handling log
if(L == 0.0000) L=1.0000;
if(M == 0.0000) M = 1.0000;
if( S == 0.0000) S = 1.0000;
//LMS to Lab
_L = (1.0 / sqrt(3.0)) *((1.0000 * log10(L)) + (1.0000 * log10(M)) + (1.0000 * log10(S)));
Alph =(1.0 / sqrt(6.0)) * ((1.0000 * log10(L)) + (1.0000 * log10(M)) + (-2.0000 * log10(S)));
Beta = (1.0 / sqrt(2.0)) * ((1.0000 * log10(L)) + (-1.0000 * log10(M)) + (-0.0000 * log10(S)));
L_AlphBeta.at<Vec3f>(i, j)[0] = _L;
L_AlphBeta.at<Vec3f>(i, j)[1] = Alph;
L_AlphBeta.at<Vec3f>(i, j)[2] = Beta;
}
}
return L_AlphBeta;
}
Mat DetectTrackFace::LAlphBeta2RGB(Mat &src)
{
Mat XYZ(src.rows, src.cols, src.type());
Mat BGR(src.rows, src.cols, CV_8UC3);
float X,Y,Z,L,M,S,_L,Alph,Beta, B,G,R;
for(int i = 0; i < src.rows; i++)
{
for(int j = 0; j < src.cols; j++)
{
_L = src.at<Vec3f>(i, j)[0]*1.7321;
Alph = src.at<Vec3f>(i, j)[1]*2.4495;
Beta = src.at<Vec3f>(i, j)[2]*1.4142;
/*Inv_Transform_logLMS2lab =
0.33333 0.16667 0.50000
0.33333 0.16667 -0.50000
0.33333 -0.33333 0.00000*/
L = (0.33333*_L) + (0.16667 * Alph) + (0.50000 * Beta);
M = (0.33333 * _L) + (0.16667 * Alph) + (-0.50000 * Beta);
S = (0.33333 * _L) + (-0.33333 * Alph) + (0.00000* Beta);
L = pow(10 , L);
if(L == 1) L=0;
M = pow(10 , M);
if(M == 1) M=0;
S = pow(10 , S);
if(S == 1) S=0;
/*Inv_Transform_XYZ2LMS
1.91024 -1.11218 0.20194
0.37094 0.62905 0.00001
0.00000 0.00000 1.00000*/
X = (1.91024 *L ) + (-1.11218 * M ) +(0.20194 * S);
Y = (0.37094 * L ) + (0.62905 * M ) +(0.00001 * S);
Z = (0.00000 * L) + (0.00000 * M ) +(1.00000 * S);
/*Inv_Transform_RGB2XYZ
3.240625 -1.537208 -0.498629
-0.968931 1.875756 0.041518
0.055710 -0.204021 1.056996*/
R = ( 3.240625 * X) + ( -1.537208 * Y) + ( -0.498629 * Z);
G = ( -0.968931 * X) + ( 1.875756 * Y) + ( 0.041518 * Z);
B = ( 0.055710 * X) + ( -0.204021 * Y) + ( 1.056996 * Z);
if(R>255) R = 255;
if(G>255) G = 255;
if(B>255) B = 255;
if(R<0) R = 0;
if(G<0) G = 0;
if(B<0) B = 0;
if(R > 255 || G > 255 || B > 255 || R < 0 || G < 0 || B<0)
cout<<"R = "<<R<<" G = "<<G <<" B = "<<B<<endl;
BGR.at<Vec3b>(i, j)[0] = (uchar)B;
BGR.at<Vec3b>(i, j)[1] = (uchar)G;
BGR.at<Vec3b>(i, j)[2] = (uchar)R;
}
}
//normalize(BGR,BGR, 255, 0, NORM_MINMAX, CV_8UC3 );
return BGR;
}
A:
You have float to uchar truncation errors in the function LAlphBeta2RGB here:
BGR.at<Vec3b>(i, j)[0] = (uchar)B;
BGR.at<Vec3b>(i, j)[1] = (uchar)G;
BGR.at<Vec3b>(i, j)[2] = (uchar)R;
You can solve this using:
BGR(i, j)[0] = uchar(cvRound(B));
BGR(i, j)[1] = uchar(cvRound(G));
BGR(i, j)[2] = uchar(cvRound(R));
However, you shouldn't take care of conversion problems explicitly. You can use saturate_cast to handle this for you. You can declare R,G,B variables as uchar:
uchar B, G, R;
and perform the conversion as:
R = saturate_cast<uchar>((3.240625 * X) + (-1.537208 * Y) + (-0.498629 * Z));
G = saturate_cast<uchar>((-0.968931 * X) + (1.875756 * Y) + (0.041518 * Z));
B = saturate_cast<uchar>((0.055710 * X) + (-0.204021 * Y) + (1.056996 * Z));
and then assign as:
BGR(i, j)[0] = B;
BGR(i, j)[1] = G;
BGR(i, j)[2] = R;
Or avoid using R,G,B entirely using:
BGR(i, j)[2] = saturate_cast<uchar>((3.240625 * X) + (-1.537208 * Y) + (-0.498629 * Z));
BGR(i, j)[1] = saturate_cast<uchar>((-0.968931 * X) + (1.875756 * Y) + (0.041518 * Z));
BGR(i, j)[0] = saturate_cast<uchar>((0.055710 * X) + (-0.204021 * Y) + (1.056996 * Z));
Here the full code. I took the liberty to use Mat_ instead of Mat as functions arguments, to avoid using at<type>() to access pixel values. In fact, you are already assuming that inputs of your functions are CV_8UC3 and CV_32FC3, respectively.
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
Mat RGB2LAlphBeta(Mat3b &src)
{
Mat3f L_AlphBeta(src.rows, src.cols);
//cvtColor(src,dest,CV_BGR2XYZ);
float X, Y, Z, L, M, S, _L, Alph, Beta;
int R, G, B;
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{
B = src(i, j)[0];
G = src(i, j)[1];
R = src(i, j)[2];
X = (0.4124 * R) + (0.3576 * G) + (0.1805 * B);
Y = (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
Z = (0.0193 * R) + (0.1192 * G) + (0.9505 * B);
L = (0.3897 * X) + (0.6890 * Y) + (-0.0787 * Z);
M = (-0.2298 * X) + (1.1834* Y) + (0.0464 * Z);
S = (0.0000 * X) + (0.0000 * Y) + (1.0000 * Z);
//for handling log
if (L == 0.0000) L = 1.0000;
if (M == 0.0000) M = 1.0000;
if (S == 0.0000) S = 1.0000;
//LMS to Lab
_L = (1.0 / sqrt(3.0)) *((1.0000 * log10(L)) + (1.0000 * log10(M)) + (1.0000 * log10(S)));
Alph = (1.0 / sqrt(6.0)) * ((1.0000 * log10(L)) + (1.0000 * log10(M)) + (-2.0000 * log10(S)));
Beta = (1.0 / sqrt(2.0)) * ((1.0000 * log10(L)) + (-1.0000 * log10(M)) + (-0.0000 * log10(S)));
L_AlphBeta(i, j)[0] = _L;
L_AlphBeta(i, j)[1] = Alph;
L_AlphBeta(i, j)[2] = Beta;
}
}
return L_AlphBeta;
}
Mat LAlphBeta2RGB(Mat3f &src)
{
Mat3f XYZ(src.rows, src.cols);
Mat3b BGR(src.rows, src.cols);
float X, Y, Z, L, M, S, _L, Alph, Beta;
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{
_L = src(i, j)[0] * 1.7321;
Alph = src(i, j)[1] * 2.4495;
Beta = src(i, j)[2] * 1.4142;
/*Inv_Transform_logLMS2lab =
0.33333 0.16667 0.50000
0.33333 0.16667 -0.50000
0.33333 -0.33333 0.00000*/
L = (0.33333*_L) + (0.16667 * Alph) + (0.50000 * Beta);
M = (0.33333 * _L) + (0.16667 * Alph) + (-0.50000 * Beta);
S = (0.33333 * _L) + (-0.33333 * Alph) + (0.00000* Beta);
L = pow(10, L);
if (L == 1) L = 0;
M = pow(10, M);
if (M == 1) M = 0;
S = pow(10, S);
if (S == 1) S = 0;
/*Inv_Transform_XYZ2LMS
1.91024 -1.11218 0.20194
0.37094 0.62905 0.00001
0.00000 0.00000 1.00000*/
X = (1.91024 *L) + (-1.11218 * M) + (0.20194 * S);
Y = (0.37094 * L) + (0.62905 * M) + (0.00001 * S);
Z = (0.00000 * L) + (0.00000 * M) + (1.00000 * S);
/*Inv_Transform_RGB2XYZ
3.240625 -1.537208 -0.498629
-0.968931 1.875756 0.041518
0.055710 -0.204021 1.056996*/
BGR(i, j)[2] = saturate_cast<uchar>((3.240625 * X) + (-1.537208 * Y) + (-0.498629 * Z));
BGR(i, j)[1] = saturate_cast<uchar>((-0.968931 * X) + (1.875756 * Y) + (0.041518 * Z));
BGR(i, j)[0] = saturate_cast<uchar>((0.055710 * X) + (-0.204021 * Y) + (1.056996 * Z));
}
}
//normalize(BGR,BGR, 255, 0, NORM_MINMAX, CV_8UC3 );
return BGR;
}
int main()
{
Mat3b img = imread("path_to_image");
Mat3f labb = RGB2LAlphBeta(img);
Mat3b rgb = LAlphBeta2RGB(labb);
Mat3b diff;
absdiff(img, rgb, diff);
// Check if all pixels are equals
cout << ((sum(diff) == Scalar(0, 0, 0, 0)) ? "Equals" : "Different");
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Can we use multiple when then condition in a single rule in Drools.?
I am writing a .drl file to implement Drools rules. As per business requirements I need to check 3 conditions for a single rule. So my question is, is it possible to have multiple when in the same rule.
I did search for many hours, but I didn't get any useful info. Can someone please guide me how to write multiple when in the single rule in drools.
Ie is it possible to do like this?
rule "Test rule 1"
when
condition1
then
<execute code>
when
condition2
then
<execute code>
end
A:
No, 80% sure you can not. You caught me with a opened .drl and did a try, says 'mismatched input', but fails on the inmediate token after the second then. Hence the 80% (to say some number). Cheerfully the compiler passed all along the second when without fail.
Try and post.
| {
"pile_set_name": "StackExchange"
} |
Q:
If PhD programmes prepare the candidate for research, why do teaching positions require it?
Example, example.
From the first example:
The Department of Biological and Agricultural Engineering invites applications for a full-time Assistant Professor of Teaching (Lecturer with Potential for Security of Employment (LPSOE)), comparable to a tenure-track assistant professor appointment. Professor of Teaching faculty are Academic Senate faculty members whose expertise and responsibilities center on undergraduate education and scholarly analysis/improvement of teaching methods. The successful applicant will be responsible for teaching both lower and upper division undergraduate Agricultural Sensing and Data Science lecture and laboratory courses (up to six courses per year) ... Qualified applicants must have a PhD in Engineering or a BS in Engineering with a PhD in a scientific field, preferably with postgraduate experience.
(Emphasis mine)
If this is a full-time teaching position, why are they looking for PhD degrees and postgraduate experience? How are these primarily-research degrees relevant to teaching?
A:
In order to teach new ideas in any field, you have to (1) understand how research is conducted, and (2) be current on the state of research in the field. By allowing you to do original research, doctoral programs prepare you for both, even if you do not continue research activity.
A:
There is not a good reason. Some poor reasons are:
Tradition
Prestige
Student expectations
Regulation/accreditation
Narrowing the job applicant pool in the face of oversupply
They ought to require training in teaching the discipline instead of training in doing the discipline. The reality is that in the near future, both will be expected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - Use values from 1D array as column indices for 2D array
Little tricky to explain it with few words (and google it), so:
I have this 2D np array:
import numpy as np
x = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15,16,17]])
and this 1D np array:
y = np.array([0,2,1,0,2,0])
what I would like to do is to return the column values from x using y as a (column) index, so it will return something like this:
[0, 5, 7, 9, 14, 15]
in ugly-code it would be solved like this:
for row,col in zip(x,y):
print(row[col])
and in a not-so-ugly code:
[row[col] for row,col in zip(x,y)]
Is there another way solve this? I would like something like:
x[y]
or a numpy specific function.
A:
You can use advanced indexing:
x[np.arange(6), y]
# array([ 0, 5, 7, 9, 14, 15])
| {
"pile_set_name": "StackExchange"
} |
Q:
Robocopy in c# not copying data
My robocopy is not working..I have the code below and I am not getting any error.Could you please help?
try
{
System.Diagnostics.Process p = new Process();
p.StartInfo.Arguments = string.Format("/C ROBOCOPY {0} {1}",
sourceTextBox.Text , destinationTextBox.Text, "CopyFilesForm.exe");
p.StartInfo.FileName = "CMD.EXE";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
p.Start();
p.WaitForExit();
if (p.HasExited)
{
MessageBox.Show("Copy Successful");
}
}
catch
{
MessageBox.Show("Error. Please try closing the application and try again.");
throw;
}
A:
I would bet you have a space in your destination path. Try encapsulate both source and destination path with quotes:
p.StartInfo.Arguments = string.Format("/C ROBOCOPY \"{0}\" \"{1}\"",
sourceTextBox.Text , destinationTextBox.Text, "CopyFilesForm.exe");
Also, just to clarity, the "CopyFilesForm.exe" argument is never used, but i Think it's just a debugging leftover?
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I ask windbg for the fullpath of the dump file it has open
When you open a dump with windbg it outputs something like:
Loading Dump File [\serverX\dumpfiles\myapp.dmp]
User Mini Dump File with Full Memory: Only application data is available
...
How do I ask windbg for that info at any time in the future?
For example I ran
.cls
.wtitle foo
now that full path is gone.
Is there other file specific info I can get (Not crash related)
date time stamp for example?
A:
There is no simple way to get the info back except opening the dump again (try .restart). But there are commands to mimic similar behavior. I'll go through those line by line.
Microsoft (R) Windows Debugger Version 10.0.15003.1001 X86
Copyright (c) Microsoft Corporation. All rights reserved.
That information is part of the version command.
Loading Dump File [D:...\demo.dmp]
This is also shown in version and you can use || if you want less output.
User Mini Dump File with Full Memory: Only application data is available
This information is not directly accessible. The || command tells you that it's a user mode dump. To get the exact flags which were used to create the dump, use
.shell -ci ".dumpdebug" findstr "MiniDump"
************* Symbol Path validation summary **************
Response Time (ms) Location
Deferred SRV*f:\debug\symbols*https://msdl.microsoft.com/download/symbols
Symbol search path is: SRVf:\debug\symbolshttps://msdl.microsoft.com/download/symbols
You can see the symbol path info with .sympath.
Executable search path is:
Use .exepath for this.
Windows 7 Version 7601 (Service Pack 1) MP (2 procs) Free x86 compatible
Product: WinNt, suite: SingleUserTS Personal
6.1.7601.18015 (win7sp1_gdr.121129-1432)
Machine Name:
Debug session time: Tue Jun 10 17:41:42.000 2014 (UTC + 1:00)
System Uptime: 0 days 0:27:20.402
Process Uptime: 0 days 0:00:27.000
You can get that by vertarget.
This dump file has an exception of interest stored in it.
The stored exception information can be accessed via .ecxr.
(e40.a44): Access violation - code c0000005 (first/second chance not available)
I always use .exr -1, but the output is not close to that.
eax=00000000 ebx=0039f4a4 ecx=00000000 edx=00193d1c esi=022924f8 edi=0039f3ec
eip=0024008d esp=0039f3d8 ebp=0039f3f8 iopl=0 nv up ei pl nz na po nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010202
0024008d 8b01 mov eax,dword ptr [ecx] ds:002b:00000000=????????
These are the registers, accessible with r, usually of thread 0, so ~0s;r should do the trick.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling popToRootViewControllerAnimated from a modal
I have a modal that I am calling presentModalViewController to display from a custom menubar. This menubar is overlaying a viewcontroller that is pushed from a tableView cell.
Now... that all being said, I need to find some way to jump the user back to the root of the tableView from the modal screen. Is this possible? I've been fighting with this for the past couple of hours with no results.
A:
If you're starting from a tablview, drilling down to a detail view via a navigation controller, and then presenting a modal view controller on top of that detail view, you'd have two steps to get back to your list/tableview: First you'd dismiss your modal view controller, then you'd pop your detail view off your navigation stack.
That should put you back where you started (at the tablview), if I'm reading this correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I search for one array whose contents match another?
I have an ArrayList of int arrays that is returning false when I ask if it contains the specified coordinates. It does contain the coordinates I request so it should return TRUE.
Here's my code.
//debug code
for (int i = 0; i < Locations.size(); i++)
{
int[] TestLoc = Locations.get(i);
System.out.print(TestLoc[0] + " " + TestLoc[1] + " " + TestLoc[2] + " == " + Location[0] + " " + Location[1] + " " + Location[2] + "? - ");
if (Location == TestLoc)
{
System.out.println("TRUE");
}
else
{
System.out.println("FALSE");
}
}
//real code
if (Locations.contains(Location))
{
Locations.remove(Location);
}
else
{
System.out.println("FAIL");
}
And output, requesting the coordinates 57, 64, 105 when the list contains 4 coordinates.
56 64 105 == 57 64 105? - FALSE
56 64 106 == 57 64 105? - FALSE
56 64 107 == 57 64 105? - FALSE
57 64 105 == 57 64 105? - FALSE
What gives???
A:
Java's arrays equals are identity equality. You need to create an actual Coordinate class.
Put another way:
int[] c1 = new int[] { 1, 2 };
int[] c2 = new int[] { 1, 2 };
System.out.println(c1.equals(c2)); // prints false
A:
The best would be to get a data class, for instance Coordinate to store your data and override the equals method. Another option, if you just store phone numbers, could be to use strings to reprensent well formatted phone numbers, and the use the equals method of the String class.
A:
Arrays in Java are objects.
When you use the == operator, you are comparing whether Location is the same array as Testloc, which it isn't. What you really want is to compare the values in each array to see if they are equal.
Rather than writing your own, you can use the Arrays.equals() static method to compare the two for equality.
| {
"pile_set_name": "StackExchange"
} |
Q:
wxPython Tables to display data on full frame
I can't find anything in the docs. All the code I find is messy and all over the place;
all I want to do, is have a table take up the whole frame, and have 6 columns;
ID
Name
Author
Type
Tags
More Info
The "More Info" column should have a button, which will call a function with the ID column as param. How would I do this? I want to be able to "fill" this table using an array, with each row
A:
Have you thought about using a ListCtrl instead? I think that might work better. I especially like the ObjectListView widget, which is a nice object oriented wrapper of the ListCtrl.
Note that neither the grid nor the ListCtrl really support buttons in their cells, although the grid might work better by using a custom renderer. On the other hand, there's a new widget called the UltimateListCtrl that supports putting ANY widget anywhere in it, so that's an option.
| {
"pile_set_name": "StackExchange"
} |
Q:
Running 2 installations of Wordpress in Docker
I'm trying to run 2 separate installations of Wordpress in Docker, but I'm having conflicts with the databases.
Here's what I've tried so far:
I runned the below code and got the logs also below.
Open putty > nano docker-compose.yml > pasted the below code > docker-compose up -d
version: '3.1'
services:
wordpress_multi_1:
image: wordpress
restart: always
ports:
- 11:80 ##change_this
environment:
WORDPRESS_DB_HOST: db_multi_1
WORDPRESS_DB_USER: exampleuser_multi_1
WORDPRESS_DB_PASSWORD: examplepass_multi_1
WORDPRESS_DB_NAME: exampledb_multi_1
volumes:
- /srv/dev-disk-by-label-1TB/Config/wordpress_multi_1:/var/www/html ##change_this
db_multi_1:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: exampledb_multi_1
MYSQL_USER: exampleuser_multi_1
MYSQL_PASSWORD: examplepass_multi_1
MYSQL_RANDOM_ROOT_PASSWORD: '1' #I didn´t changed this
volumes:
- /srv/dev-disk-by-label-1TB/Config/wordpress_multi_3/db1:/var/lib/mysql
# Other Instalation
wordpress_multi_2: #2nd_instance
image: wordpress
restart: always
ports:
- 12:80 ##change_this
environment:
WORDPRESS_DB_HOST: db_multi_2 #point to 2nd db instance
WORDPRESS_DB_USER: exampleuser_multi_2
WORDPRESS_DB_PASSWORD: examplepass_multi_2
WORDPRESS_DB_NAME: exampledb_multi_2
volumes:
- /srv/dev-disk-by-label-1TB/Config/wordpress_multi_2:/var/www/html ##change_this
db_multi_2: #2nd_instance
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: exampledb_multi_2
MYSQL_USER: exampleuser_multi_2
MYSQL_PASSWORD: examplepass_multi_2
MYSQL_RANDOM_ROOT_PASSWORD: '1' #I didn´t changed this
volumes:
- /srv/dev-disk-by-label-1TB/Config/wordpress_multi_2/db2:/var/lib/mysql
volumes: ##remove these line if you bind the volume to host machine
wordpress_multi_1:
db_multi_1:
wordpress_multi_2:
db_multi_2:
I can´t access the first container in MY-IP:11 ,
when I access 2nd container MY-IP:12 I get this error message Error establishing a database connection
I have this in the container logs:
In the Logs of root wordpress multi _1_1 I have this
[25-Jul-2020 15:53:03 UTC] PHP Warning: mysqli::__construct(): (HY000/2002): Connection refused in Standard input code on line 22
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
MySQL Connection Error: (2002) Connection refused
WARNING: unable to establish a database connection to 'db_multi_1'
continuing anyways (which might have unexpected results)
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.27.0.3. Set the 'ServerName' directive globally to suppress this message
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.27.0.3. Set the 'ServerName' directive globally to suppress this message
[Sat Jul 25 15:53:30.918212 2020] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.38 (Debian) PHP/7.4.8 configured -- resuming normal operations
[Sat Jul 25 15:53:30.918429 2020] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'
In the Logs of root_db_multi_1_1 I have this
2020-07-25 15:53:59+00:00 [Note] [Entrypoint]: Creating user exampleuser,
2020-07-25 15:53:59+00:00 [Note] [Entrypoint]: Giving user exampleuser access to schema exampledb,
,
2020-07-25 15:53:59+00:00 [Note] [Entrypoint]: Stopping temporary server,
2020-07-25T15:53:59.954860Z 0 [Note] Giving 0 client threads a chance to die gracefully,
2020-07-25T15:53:59.954994Z 0 [Note] Shutting down slave threads,
2020-07-25T15:53:59.955028Z 0 [Note] Forcefully disconnecting 0 remaining clients,
2020-07-25T15:53:59.955057Z 0 [Note] Event Scheduler: Purging the queue. 0 events,
2020-07-25T15:53:59.955668Z 0 [Note] Binlog end,
2020-07-25T15:53:59.957922Z 0 [Note] Shutting down plugin 'ngram',
2020-07-25T15:53:59.957982Z 0 [Note] Shutting down plugin 'partition',
2020-07-25T15:53:59.958006Z 0 [Note] Shutting down plugin 'BLACKHOLE',
2020-07-25T15:53:59.958027Z 0 [Note] Shutting down plugin 'ARCHIVE',
2020-07-25T15:53:59.958045Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA',
2020-07-25T15:53:59.958138Z 0 [Note] Shutting down plugin 'MRG_MYISAM',
2020-07-25T15:53:59.958162Z 0 [Note] Shutting down plugin 'MyISAM',
2020-07-25T15:53:59.958196Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL',
2020-07-25T15:53:59.958218Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES',
2020-07-25T15:53:59.958240Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES',
2020-07-25T15:53:59.958257Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS',
2020-07-25T15:53:59.958274Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN',
2020-07-25T15:53:59.958291Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS',
2020-07-25T15:53:59.958308Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS',
2020-07-25T15:53:59.958325Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES',
2020-07-25T15:53:59.958378Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS',
2020-07-25T15:53:59.958400Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES',
2020-07-25T15:53:59.958421Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE',
2020-07-25T15:53:59.958439Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE',
2020-07-25T15:53:59.958458Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG',
2020-07-25T15:53:59.958477Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED',
2020-07-25T15:53:59.958496Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED',
2020-07-25T15:53:59.958515Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD',
2020-07-25T15:53:59.958535Z 0 [Note] Shutting down plugin 'INNODB_METRICS',
2020-07-25T15:53:59.958555Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO',
2020-07-25T15:53:59.958575Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS',
2020-07-25T15:53:59.958595Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU',
2020-07-25T15:53:59.958614Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE',
2020-07-25T15:53:59.958633Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET',
2020-07-25T15:53:59.958652Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX',
2020-07-25T15:53:59.958672Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET',
2020-07-25T15:53:59.958696Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM',
2020-07-25T15:53:59.958715Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET',
2020-07-25T15:53:59.958732Z 0 [Note] Shutting down plugin 'INNODB_CMP',
2020-07-25T15:53:59.958755Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS',
2020-07-25T15:53:59.958773Z 0 [Note] Shutting down plugin 'INNODB_LOCKS',
2020-07-25T15:53:59.958792Z 0 [Note] Shutting down plugin 'INNODB_TRX',
2020-07-25T15:53:59.958813Z 0 [Note] Shutting down plugin 'InnoDB',
2020-07-25T15:53:59.959041Z 0 [Note] InnoDB: FTS optimize thread exiting.,
2020-07-25T15:53:59.959779Z 0 [Note] InnoDB: Starting shutdown...,
2020-07-25T15:54:00.060456Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool,
2020-07-25T15:54:00.062402Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 200725 15:54:00,
2020-07-25T15:54:02.601970Z 0 [Note] InnoDB: Shutdown completed; log sequence number 12578970,
2020-07-25T15:54:02.606084Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1",
2020-07-25T15:54:02.606173Z 0 [Note] Shutting down plugin 'MEMORY',
2020-07-25T15:54:02.606192Z 0 [Note] Shutting down plugin 'CSV',
2020-07-25T15:54:02.606207Z 0 [Note] Shutting down plugin 'sha256_password',
2020-07-25T15:54:02.606218Z 0 [Note] Shutting down plugin 'mysql_native_password',
2020-07-25T15:54:02.606496Z 0 [Note] Shutting down plugin 'binlog',
2020-07-25T15:54:02.610743Z 0 [Note] mysqld: Shutdown complete,
,
2020-07-25 15:54:02+00:00 [Note] [Entrypoint]: Temporary server stopped,
,
2020-07-25 15:54:02+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.,
,
2020-07-25T15:54:03.386358Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).,
2020-07-25T15:54:03.392303Z 0 [Note] mysqld (mysqld 5.7.31) starting as process 1 ...,
2020-07-25T15:54:03.404842Z 0 [Note] InnoDB: PUNCH HOLE support available,
2020-07-25T15:54:03.404912Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins,
2020-07-25T15:54:03.404931Z 0 [Note] InnoDB: Uses event mutexes,
2020-07-25T15:54:03.404949Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier,
2020-07-25T15:54:03.404967Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11,
2020-07-25T15:54:03.404984Z 0 [Note] InnoDB: Using Linux native AIO,
2020-07-25T15:54:03.405903Z 0 [Note] InnoDB: Number of pools: 1,
2020-07-25T15:54:03.406261Z 0 [Note] InnoDB: Using CPU crc32 instructions,
2020-07-25T15:54:03.412184Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M,
2020-07-25T15:54:03.450230Z 0 [Note] InnoDB: Completed initialization of buffer pool,
2020-07-25T15:54:03.458769Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().,
2020-07-25T15:54:03.477366Z 0 [Note] InnoDB: Highest supported file format is Barracuda.,
2020-07-25T15:54:03.572954Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables,
2020-07-25T15:54:03.573169Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...,
2020-07-25T15:54:04.136273Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.,
2020-07-25T15:54:04.140875Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.,
2020-07-25T15:54:04.140953Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.,
2020-07-25T15:54:04.142674Z 0 [Note] InnoDB: Waiting for purge to start,
2020-07-25T15:54:04.194101Z 0 [Note] InnoDB: 5.7.31 started; log sequence number 12578970,
2020-07-25T15:54:04.196142Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool,
2020-07-25T15:54:04.198000Z 0 [Note] Plugin 'FEDERATED' is disabled.,
2020-07-25T15:54:04.214845Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200725 15:54:04,
2020-07-25T15:54:04.223928Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.,
2020-07-25T15:54:04.223996Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.,
2020-07-25T15:54:04.225843Z 0 [Warning] CA certificate ca.pem is self signed.,
2020-07-25T15:54:04.225943Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.,
2020-07-25T15:54:04.227467Z 0 [Note] Server hostname (bind-address): '*'; port: 3306,
2020-07-25T15:54:04.227657Z 0 [Note] IPv6 is available.,
2020-07-25T15:54:04.227691Z 0 [Note] - '::' resolves to '::';,
2020-07-25T15:54:04.227764Z 0 [Note] Server socket created on IP: '::'.,
2020-07-25T15:54:04.259808Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.,
2020-07-25T15:54:04.296032Z 0 [Note] Event Scheduler: Loaded 0 events,
2020-07-25T15:54:04.298053Z 0 [Note] mysqld: ready for connections.,
Version: '5.7.31' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL),
In the Logs of root wordpress multi_2_1 I have this:
[25-Jul-2020 15:53:03 UTC] PHP Warning: mysqli::__construct(): (HY000/2002): Connection refused in Standard input code on line 22,
,
MySQL Connection Error: (2002) Connection refused,
[25-Jul-2020 15:53:06 UTC] PHP Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES) in Standard input code on line 22,
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
MySQL Connection Error: (1045) Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
,
WARNING: unable to establish a database connection to 'db_multi_2',
continuing anyways (which might have unexpected results),
,
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.27.0.5. Set the 'ServerName' directive globally to suppress this message,
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.27.0.5. Set the 'ServerName' directive globally to suppress this message,
[Sat Jul 25 15:53:30.922486 2020] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.38 (Debian) PHP/7.4.8 configured -- resuming normal operations,
[Sat Jul 25 15:53:30.922705 2020] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND',
192.168.1.21 - - [25/Jul/2020:15:53:48 +0000] "GET / HTTP/1.1" 500 2952 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
192.168.1.21 - - [25/Jul/2020:15:53:49 +0000] "GET /favicon.ico HTTP/1.1" 500 2952 "http://192.168.1.198:12/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
192.168.1.21 - - [25/Jul/2020:16:01:07 +0000] "GET / HTTP/1.1" 500 2952 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
192.168.1.21 - - [25/Jul/2020:16:01:08 +0000] "GET /favicon.ico HTTP/1.1" 500 2952 "http://192.168.1.198:12/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
In the Logs of root_db_multi_2_1 I have this
2020-07-25 15:53:02+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.31-1debian10 started.,
2020-07-25 15:53:02+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql',
2020-07-25 15:53:02+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.31-1debian10 started.,
2020-07-25T15:53:03.349210Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).,
2020-07-25T15:53:03.355966Z 0 [Note] mysqld (mysqld 5.7.31) starting as process 1 ...,
2020-07-25T15:53:03.369477Z 0 [Note] InnoDB: PUNCH HOLE support available,
2020-07-25T15:53:03.369554Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins,
2020-07-25T15:53:03.369574Z 0 [Note] InnoDB: Uses event mutexes,
2020-07-25T15:53:03.369600Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier,
2020-07-25T15:53:03.369618Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11,
2020-07-25T15:53:03.369636Z 0 [Note] InnoDB: Using Linux native AIO,
2020-07-25T15:53:03.370895Z 0 [Note] InnoDB: Number of pools: 1,
2020-07-25T15:53:03.371337Z 0 [Note] InnoDB: Using CPU crc32 instructions,
2020-07-25T15:53:03.379153Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M,
2020-07-25T15:53:03.423703Z 0 [Note] InnoDB: Completed initialization of buffer pool,
2020-07-25T15:53:03.432259Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().,
2020-07-25T15:53:03.449044Z 0 [Note] InnoDB: Highest supported file format is Barracuda.,
2020-07-25T15:53:03.749813Z 0 [Note] InnoDB: Log scan progressed past the checkpoint lsn 12578846,
2020-07-25T15:53:03.750534Z 0 [Note] InnoDB: Doing recovery: scanned up to log sequence number 12578855,
2020-07-25T15:53:03.750614Z 0 [Note] InnoDB: Database was not shutdown normally!,
2020-07-25T15:53:03.750659Z 0 [Note] InnoDB: Starting crash recovery.,
2020-07-25T15:53:03.952127Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1",
2020-07-25T15:53:03.952210Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables,
2020-07-25T15:53:03.952808Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...,
2020-07-25T15:53:05.161161Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.,
2020-07-25T15:53:05.168757Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.,
2020-07-25T15:53:05.168874Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.,
2020-07-25T15:53:05.172052Z 0 [Note] InnoDB: 5.7.31 started; log sequence number 12578855,
2020-07-25T15:53:05.173264Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool,
2020-07-25T15:53:05.174026Z 0 [Note] Plugin 'FEDERATED' is disabled.,
2020-07-25T15:53:05.187982Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200725 15:53:05,
2020-07-25T15:53:05.195363Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.,
2020-07-25T15:53:05.195433Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.,
2020-07-25T15:53:05.197818Z 0 [Warning] CA certificate ca.pem is self signed.,
2020-07-25T15:53:05.197923Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.,
2020-07-25T15:53:05.199723Z 0 [Note] Server hostname (bind-address): '*'; port: 3306,
2020-07-25T15:53:05.199889Z 0 [Note] IPv6 is available.,
2020-07-25T15:53:05.199923Z 0 [Note] - '::' resolves to '::';,
2020-07-25T15:53:05.199996Z 0 [Note] Server socket created on IP: '::'.,
2020-07-25T15:53:05.232986Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.,
2020-07-25T15:53:05.269606Z 0 [Note] Event Scheduler: Loaded 0 events,
2020-07-25T15:53:05.271134Z 0 [Note] mysqld: ready for connections.,
Version: '5.7.31' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL),
2020-07-25T15:53:06.493594Z 2 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:09.499889Z 3 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:12.505293Z 4 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:15.510159Z 5 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:18.515748Z 6 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:21.522246Z 7 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:24.528657Z 8 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:27.534936Z 9 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:30.538996Z 10 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:49.230001Z 11 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T15:53:49.697588Z 12 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T16:01:07.993591Z 13 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
2020-07-25T16:01:08.232897Z 14 [Note] Access denied for user 'exampleuser'@'172.27.0.5' (using password: YES),
Can someone tell me what I am doing wrong? Or fix the code/stack I tried to run? I'm not an experienced user.
I had other installations of Wordpress in the past that I deleted and I am thinking that may be causing the conflicts... I don't know... I tried some diferences in the stack files that I searched the internet, renamed the containers, but I keep getting the same errors, and I am out of ideas.
Any solution will be appreciated. Thanks.
I'm running Open Media Vault > Docker > Portainer.
A:
You are binding multiple volumes under same root of wordpress_multi_2.This is not a good way to mount volumes. Split them to separate folders (example for /wp and /db). And do not bind ports under 1024, as they are reserved, common convention for plaintext HTTP ports is like 8080 on development machines.
wordpress_multi_1:
...
ports:
- 8080:80
...
volumes:
- /srv/dev-disk-by-label-1TB/Config/wordpress_multi_1/wp:/var/www/html
db_multi_1:
...
volumes:
- /srv/dev-disk-by-label-1TB/Config/wordpress_multi_1/db:/var/lib/mysql
wordpress_multi_2: #2nd_instance
...
ports:
- 8081:80
...
volumes:
- /srv/dev-disk-by-label-1TB/Config/wordpress_multi_2/wp:/var/www/html
db_multi_2: #2nd_instance
...
volumes:
- /srv/dev-disk-by-label-1TB/Config/wordpress_multi_2/db:/var/lib/mysql
| {
"pile_set_name": "StackExchange"
} |
Q:
Aggregating timeseries from sensors
I have about 500 sensors which emit a value about once a minute each. It can be assumed that the value for a sensor remains constant until the next value is emitted, thus creating a time series. The sensors are not synchronized in terms of when they emit data (so the observation timestamps vary), but it's all collected centrally and stored per sensor (to allow filtering by subset of sensors).
How can I produce an aggregate time series that gives the sum of the data from the sensors? n
(need to create a time series over 1 day's set of observations - so will need to take into account 24x60x500 observations per day). The calculations also need to be fast, preferrably run in in < 1s.
Example - raw input:
q)n:10
q)tbl:([]time:n?.z.t;sensor:n?3;val:n?100.0)
q)select from tbl
time sensor val
----------------------------
01:43:58.525 0 33.32978
04:35:12.181 0 78.75249
04:35:31.388 0 1.898088
02:31:11.594 1 16.63539
07:16:40.320 1 52.34027
00:49:55.557 2 45.47007
01:18:57.918 2 42.46532
02:37:14.070 2 91.98683
03:48:43.055 2 41.855
06:34:32.414 2 9.840246
The output I'm looking for should show the same timestamps, and the sum across sensors. If a sensor doesn't have a record defined at a matching timestamp, then it's previous value should be used (the records only imply times when the output from the sensor changes).
Expected output, sorted by time
time aggregatedvalue
----------------------------
00:49:55.557 45.47007 / 0 (sensor 0) + 0 (sensor 1) + 45.47007 (sensor 2)
01:18:57.918 42.46532 / 0 (sensor 0) + 0 (sensor 1) + 42.46532 (new value on sensor 2)
01:43:58.525 75.7951 / 33.32978 + 0 + 42.46532
02:31:11.594 92.43049 / 33.32978 + 16.63539 + 42.46532
02:37:14.070 141.952 / 33.32978 + 16.63539 + 91.98683
03:48:43.055 91.82017 / 33.32978 + 16.63539 + 41.855
04:35:12.181 137.24288 / 78.75249 + 16.63539 + 41.855
04:35:31.388 60.388478 / 1.898088 + 16.63539 + 41.855
06:34:32.414 28.373724 / 1.898088 + 16.63539 + 9.840246
07:16:40.320 64.078604 / 1.898088 + 52.34027 + 9.840246
A:
I'm assuming the records are coming in in time order, therefore tbl will be sorted by time. If this is not the case, sort the table by time first.
d is a dictionary of last price by sensor at each time. The solution below is probably not the most elegent and I can imagine a more performant method is available that would not require the each.
q)d:(`long$())!`float$()
q)f:{d[x]::y;sum d}
q)update agg:f'[sensor;val] from tbl
time sensor val agg
-------------------------------------
00:34:28.887 2 53.47096 53.47096
01:05:42.696 2 40.66642 40.66642
01:26:21.548 1 41.1597 81.82612
01:53:10.321 1 51.70911 92.37553
03:42:39.320 1 17.80839 58.47481
05:15:26.418 2 51.59796 69.40635
05:47:49.777 0 30.17723 99.58358
11:32:19.305 0 39.27524 108.6816
11:37:56.091 0 71.11716 140.5235
12:09:18.458 1 78.5033 201.2184
Your data set of 720k records will be relatively small, so any aggregations should be well under a second. If you storing many days of data you may want to consider some of the techniques (splaying, partitioning etc) outlined here .
| {
"pile_set_name": "StackExchange"
} |
Q:
transient domain instance jpa&spring
My domain objects are roughly like:
@Entity
public class Customer{
@Id
private String id;
private String name;
@OneToMany(cascade=CascadeType.ALL)
private List<Account> accountList;
}
@Entity
public class Account{
@Id
private String id;
private String name;
@OneToMany
private List<Service> serviceList;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(nullable=false)
private Customer customer;
}
@Entity
public class Service{
@Id
private String id;
private String name;
@ManyToOne
@JoinColumn(nullable=false)
private Account account;
}
I have a transactional Spring service. I want to return an Account instance to fronthand but I don't want to send Customer and Service List informations because of bandwith issues.
When I do:
account.setServiceList(null);
It gives no error but after a while it deletes all my service list.
When I do:
account.setCustomer(null);
It says customer_id of account cannot be null.
I just want to return a transient instance without a validation. How can I handle this.
A:
The solution to your problem is to make the entity detached, by calling entityManager.detach(accountInstance) (or entityManager.clear() if you use JPA 1.0 to detach all entities) and only THAN change anything to it. If you use Hibernate's sessions, use the Session.evict() method.
The other solution is to use a DTO, something that has only the fields that you need.
PS: I think you have an bug, in which the bidirectional relationships are missing on one side the mapped property. E.g in Customer you should have something like
@OneToMany(cascade=CascadeType.ALL, mappedBy="customer")
private List<Account> accountList;
The same with the other relationship.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.Net 5 js, css bundling
I am currently using the gulp-bundle-assets module in a task to bundle css and js in my project. Each time I run it the module generates new filename making sure the browser will pick the latest bundle. However I need to change my file references manually in my html whenever the filename changes. The gulp-bundle-asset suggests a way to programmatically update the views by reading a json file.
What would be the proper way to handle the bundling with dynamic filenames in Visual Studio?
How are the relative paths for static content treated such as images,fonts?
Thanks!
A:
I'm the author of gulp-bundle-assets. I actually created an example of this awhile back using ASP.NET 5 (now named ASP.NET Core v1) seen here: https://github.com/dowjones/gulp-bundle-assets-example-aspnet-5. You'll want to rely on the bundle.result.json file.
The key pieces are as follows:
// read bundle.result.json
public async Task<dynamic> GetBundleResult()
{
string fileName = Path.Combine(_appEnvironment.ApplicationBasePath, "bundle.result.json");
string jsonText = File.ReadAllText(fileName);
return await Task.FromResult(JObject.Parse(jsonText));
}
And in your view:
@inject ExampleMVC6Application.Services.BundlerService Bundler
@{
dynamic Bundles = await Bundler.GetBundleResult();
}
<!DOCTYPE html>
<html>
<head>
@Html.Raw((object)Bundles.vendor.styles)
@Html.Raw((object)Bundles.main.styles)
</head>
...
| {
"pile_set_name": "StackExchange"
} |
Q:
SSIS Excel Destination Editor closes unexpectedly
I'm fairly new to SSIS, but what I'm trying to do should be simple:
I have a Data Flow task that has an OLE DB Source feeding into an Excel Destination. The issue though, is I can't configure the Excel Destination correctly. I'm able to connect my Excel connection manager, but when I hit the "New..." button next to the "Name of the Excel sheet" dropdown, the Excel Destination Editor window just closes instead of opening a different dialog. In the image below, I highlighted the button that's closing the window.
In general, I'm following this guide How to use SSIS to Export to Excel (current step is just above the second to last image in the article).
A:
I think the issue lies with the Excel connection instead. Once I changed the output file to .xls instead of .xlsx and changed the connection to Excel 97-2003, I was able to create a new Excel Sheet for the file.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# - Globally intercept and modify DNS resolution responses
There's a similar question ( Can I temporarily override DNS resolution within a .NET application? ) but I just can't figure it out with the meager response there.
Background info
I have a server set up in my home network, an old computer. Our router has the right ports forwarded, the server runs server software for things like http, svn, games, etc. I've got a domain name registered that always points to our external IP address. For all intents and purposes, I've got a typical webserver set up. My friends can game on my server by connecting via the domain name, I can push and pull svn projects, etc.
The only problem is that I also need to use my server when I'm connected to my home network (the same network as the server). Using the domain name results in Windows resolving it to our own IP address, and my router is too retarded to realize it just needs to forward it back into our network to the server as per the usual. I've done some looking around, configuring, telnetting and DNS overriding, but I have it on good authority that our ISP apparently crippled the DNS override feature of their routers to prevent this exact scenario. Apparently they don't like internal loopbacks.
I now basically have to keep 2 configs for each of my server's services: one config that specifies the domain name for when I'm abroad, and a second that specifies the server's internal IP for when I'm at home. It's frustrating because it just isn't always possible.
I want to instantiate a global DNS resolution request/response listener that will do the following: if the requested domain name matches a given string, override the IP in the response with one of my choice.
I've looked things up like easyhook, dllimport, msdn pages, etc, but I still can't figure out where to actually start, which classes I need to get access to, and so on. I basically have no pre-existing code for this particular problem.
I have Visual Studio, years of relatively simple programming experience and a good understanding of unfamiliar code and everything else, just no idea how to start or what to look for.
Many thanks for anything that can get me going.
A:
I ended up solving this with (as a few have suggested) the hosts file after all.
I first used ManagedWifi to set a network connection monitor. It detects changes to my connection status and reports the network name.
Then I wrote a console app that stays open (using Hidden Start allows me to hide the window) and safely modifies the hosts file, then flushes the DNS cache. This seems to work in pretty much realtime. :)
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the proper way to insulate box sill joists in the basement?
The floor joists of the first floor are sitting directly in breaks in the concrete/cinderblock walls, and there's large gaps all around the edges. I've done some looking around and it appears that these are a large source of air loss, so I need to insulate them. Can I just spray some expanding foam in that area, or is it better to get some rigid foam, cut it, and then just use foam to seal the edges where it meets the joists/wall? What about a vapor barrier?
A:
The Family Handyman recommends using rigid foam, caulk, and spray foam to insulate the rim joist, in this article Insulate Basement Rim Joists.
Not sure if this is exactly what you're looking to do, but the idea should work in your situation I think.
Summary of steps:
Cut rigid foam to fit between joists.
Insert foam into gaps (against rim joist).
Caulk around the edge of the foam.
Fill any gaps in the rigid foam where pipes or vents pass through, with spray foam.
| {
"pile_set_name": "StackExchange"
} |
Q:
percona toolkit Replication filters error
I put the percona toolkit onto my DB hosts so I could try and deal with a problem with mysql going silently out of sync. That is replication seems fine on all nodes. Slave IO running / Slave SQL running and 0 seconds behind master.
I have 4 dbs setup in master/master on the first two, and two slaves, I'm using MariaDB-server-10.0.21 for the MySQL database on each node.
Yet the content of the wiki I run on them seems to go out of sync even with those positive indicators. For instance, you'll create a page, save it, get the thumbs up from the wiki. Then reload the page and the content will be gone! Then you point the wiki config to look at each db one at a time, reload the page. Until you find the db that saved the changes you made.
Then dump that db, stop the slaves on each host one at time and then import that version of the database. It's a real pain!
So I installed the percona toolkit after reading an article on how to solve this problem.
And when I run the pt-table-checksum command I get this error, saying Replication filters are set on these hosts:
[root@db1:~] #pt-table-checksum --replicate=test.checksum --databases=sean --ignore-tables=semaphore localhost
10-17T00:31:11 Replication filters are set on these hosts:
db3
binlog_do_db = jfwiki,jokefire,bacula,mysql
db2
binlog_do_db = jfwiki,jokefire,bacula,mysql
db4
binlog_do_db = jfwiki,jokefire,bacula,mysql
Please read the --check-replication-filters documentation to learn how to solve this problem. at /bin/pt-table-checksum line 9644.
But that EC2 host it claims that it's having trouble contacting equates to my 4th database host. I found out by ssh'ing in as my user to that DNS address. And I have no trouble at all logging into that host on the command line using mysql:
Can someone please explain what does this error mean, and how can I fix the issue? Is there any general advice you can give for mysql replication falling silently out of sync?
Thanks
A:
Some of the pt tools need to create their own database and have it replicated. Your binlog_do_db prevents the extra db from being replicated, hence preventing that tool from working.
While you have the binlog_do removed, see what db it being built. Then add it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Request to Verify - How Databases and Java store and handle timezones?
My apologies for the extremely basic question, I think I know the answer but would like to verify:
When refering to time zones and how they are usually stored in a database and in a java.util.Date:
When saving a date field in a database, it is timezone agnostic (e.g. always saves in UTC)
When using a Java Date object the date it is also timezone agnostic
Time zone is depeneded only when formatting and parsing dates (DB and Java)
If using Java - it will use the JVM user.timezone to format / parse dates
If using Java on Windows - Java will take this from the Regional settings automatically
The database timezone (and it's machine's timezone) is irrelevant to the Java JDBC client
The timezone of the Database Server is relevant only for direct SQL parsing and formating
My questions are:
Are all of the above assumptions correct? some are? all incorect?
Is there a reference / official source that verifies this more "officially"?
A:
The assumption are mostly correct for Java. They are not necessarily correct for databases, as there are variations.
Java handles time zones with Calendar objects. The java.util.Date object always contains the UTC value.
Databases generally store and return dates and timestamps (with hour, minutes, etc.) as they are written, regardless of the internal format used by storage. If you store 2010-12-25, you will retrieve the same value regardless of the time zone of the clients or server.
Some databases have the TIMESTAMP WITH TIMEZONE data type which stores both the timestamp and the time zone separately.
Dates and timestamps are converted between Java and Database, usually in a manner that the subclasses of java.util.Date that are used are interpreted in the JDBC client's time zone.
| {
"pile_set_name": "StackExchange"
} |
Q:
rdf representation of entity references in text
Consider a sentence like:
John Smith travelled to Washington.
A name tagger would identify, on a good day, 'John Smith' as a person, and 'Washington' as a place. However, without other evidence, it can't tell which of all the possible 'John Smith's in the world, or even which of the various 'Washington's, it's got.
Eventually, some resolution process might decide, based on other evidence. Until that point, however, what is a good practice for representing these references in RDF? Assign them made-up unique identifiers in some namespace? Make blank tuples (e.g. 'Some person named John Smith was referenced in Document d'.)? Some other alternative? A book I have gives an example involving anonymous weather stations, but I am not quite following how their example fits in with everything else about RDF being described.
A:
Assign them unique identifiers in your own namespace. If you later discover that this "Washington" is the same as http://dbpedia.org/resource/Washington,_D.C., or whatever, you can add an owl:sameAs to assert that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Last-child doesn't seem to be working
This is the code I have:
HTML:
<div id="nav">
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
</ul>
</div>
CSS:
#nav ul li a {
width:162px;
background:url('http://i.imgur.com/DmeCv.png') -164px 0px;
#nav ul li:first-child a {
width:164px;
background:url('http://i.imgur.com/DmeCv.png');
}
#nav ul li:last-child a {
background:url('http://i.imgur.com/DmeCv.png') -326px 0px;
}
So far, so good. This works, and displays the image properly.
#nav ul li a:hover {
background:url('http://i.imgur.com/DmeCv.png') -164px -50px;
}
#nav ul li:first-child a:hover {
background:url('http://i.imgur.com/DmeCv.png') 0px -50px;
#nav ul li:last-child a:hover {
background:url('http://i.imgur.com/DmeCv.png') -326px -50px;
}
This doesn't work, however. It displays the mid section hover image, rather than the last-child hover image.
Here is an example:
http://result.dabblet.com/gist/2973127/8bf204a16e7caca43ad129cad141fa4810bf18ce
A:
In your CSS example, you are missing your closing curly brace } in first-child a:hover.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django project file - Cannot spot the mistake: "Invalid block tag: 'static'
I have the following error
Invalid block tag on line 4: 'static'. Did you forget to register or load this tag?
It is being generated by this code (see below) but I cannot (even after having looked through the various similar questions and answers) spot the error.
<html>
<head>
<link rel="stylesheet" href="{% static 'wgb/styles.css' %}"/>
</head>
<body>
<div class="login">
<h1>Login</h1>
<form method="post">
<input type="text" name="u" placeholder="Username" required="required" />
<input type="password" name="p" placeholder="Password" required="required" />
<button type="submit" class="btn btn-primary btn-block btn-large">Let me in.</button>
</form>
</div>
</body>
</html>
The error is obviously in this line:
<link rel="stylesheet" href="{% static 'wgb/styles.css' %}"/>
but I have checked for spaces, order, and spelling/syntax but none of those seem to be the problem.
More specifically, the error notes:
Error during template rendering and it is pointing to: <link rel="stylesheet" href="{% static 'worldguestbook/styles.css' %}"/>
A:
You need to load the static template tag before you can use it. You usually do it in the top of your template file:
{% load static %}
<html>
<head>
....
Source: Django docs: Managing static files (e.g. images, JavaScript, CSS)
| {
"pile_set_name": "StackExchange"
} |
Q:
How could django model get one field?
I know how to get a line,but I don't know how to get one field.
for exmple,there is a table,have id,title,content fields.
ModelsExample.objects.filter(id = showid)# get one line.
how to get title field only?
A:
You can use values or values_list for that matter. Depending on how you would like to use tour context:
Use of values() example:
r = ModelsExample.objects.filter(id=showid).values('title')
This would return something like: [{'title': 'My title'}] so you could access it with r[0]['title'].
Use of values_list() example:
r = ModelsExample.objects.filter(id=showid).values_list('title')
This would return something like: [('My title',)] so you could access it as r[0][0].
Use of values_list(flat=True) example:
r = ModelsExample.objects.filter(id=showid).values_list('title', flat=True)
This would return something like: ['My title'] so you could access it as r[0].
And of course you can always access each field of the model as:
r = ModelsExample.objects.get(id=showid)
r.title
| {
"pile_set_name": "StackExchange"
} |
Q:
Why aren't there any 400V ultracapacitors?
I thought that ulracaps could be better than electrolytic ones for filtering after a bridge rectifier in a compact switching power supply due to their higher energy density. But, for some reason, I can't find any high-voltage supercapacitors on ebay or amazon. I could, of course, put a bunch of low-voltage ultracapacitors in series but that would defeat the whole purpose of a power supply being compact. Is there any reason why there are no high-voltage supercapacitors? There already are 5.5V ultracapacitors, which are basically two 2.75V caps in series, so why they can't go higher? Did I miss something? Are they hard to manufacture?
A:
A high-voltage super-capacitor/ultra-capacitor would be a contradiction in existing technologies. They achieve their high capacitive values by having a super thin dielectric of special materials, hence the low voltage limit.
To build a 400 volt capacitor means having a thicker 'solid' dielectric with more common materials, which 'fattens' up the size a lot.
There are large 450 volt electrolytic capacitors to 20,000 uF or more. To have a super-capacitor with the same voltage rating would be duplicating the large can-type electrolytics.
Super-capacitor/ultra-capacitors have been around a couple of decades now, mostly changing in materials to cut down on self-leakage. Graphene is the latest trend. The laws of physics and chemistry limit the size of such capacitors, or we would already have them to buy.
Engineers would love to have giant super-capacitors for cars, etc, so there is an on-going effort to reach that goal.
This is a snippet from Wikipedia:
A supercapacitor (SC) (also electric double-layer capacitor (EDLC),
also called supercap, ultracapacitor or Goldcap) is a high-capacity
capacitor with capacitance values much higher than other capacitors
(but lower voltage limits) that bridge the gap between electrolytic
capacitors and rechargeable batteries. They typically store 10 to 100
times more energy per unit volume or mass than electrolytic
capacitors, can accept and deliver charge much faster than batteries,
and tolerate many more charge and discharge cycles than rechargeable
batteries.
Supercapacitors are used in applications requiring many rapid
charge/discharge cycles rather than long term compact energy storage:
within cars, buses, trains, cranes and elevators, where they are used
for regenerative braking, short-term energy storage or burst-mode
power delivery. Smaller units are used as memory backup for static
random-access memory (SRAM).
Unlike ordinary capacitors, supercapacitors do not use the
conventional solid dielectric, but rather, they use electrostatic
double-layer capacitance and electrochemical pseudocapacitance, both
of which contribute to the total capacitance of the capacitor, with a
few differences:
Electrostatic double-layer capacitors use carbon electrodes or
derivatives with much higher electrostatic double-layer capacitance
than electrochemical pseudocapacitance, achieving separation of charge
in a Helmholtz double layer at the interface between the surface of a
conductive electrode and an electrolyte. The separation of charge is
of the order of a few ångströms (0.3–0.8 nm), much smaller than in a
conventional capacitor.
Electrochemical pseudocapacitors use metal
oxide or conducting polymer electrodes with a high amount of
electrochemical pseudocapacitance additional to the double-layer
capacitance. Pseudocapacitance is achieved by Faradaic electron
charge-transfer with redox reactions, intercalation or
electrosorption. Hybrid capacitors, such as the lithium-ion capacitor,
use electrodes with differing characteristics: one exhibiting mostly
electrostatic capacitance and the other mostly electrochemical
capacitance.
A:
Supercapacitors are created by placing many, many layers of conductive plates and dielectric together in a package. In order to obtain a very high capacitance in a small amount of space, each plate must be spaced very close to one another (the dielectric must be extremely thin). The thickness of the dielectric is what limits the voltage levels in most cases. 400 volts can punch through thin dielectric very easily, rendering the capacitor useless. The low voltage is required to ensure the dielectric does not break down during use.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add a marker to a Raphael 'paper' in javascript?
I need a marker that behaves much like adding a marker to a map. On double click cause a marker to be displayed at the point that was clicked, and returns the x/y pixel coordinates of the point that was clicked.
I have Raphael paper:
var R = Raphael("paper", 500, 500);
with paths (R.path("M 92.3456 ... 37.0934 Z")) on it that defines shapes. And I have to be albe to add markers on this paper with shapes.
I am not a javascript programmer so I don't really even know where to start. So any help here is much appreciated!
A:
Ok, I've made this simple fiddle to help you with your problem.
http://jsfiddle.net/mN5du/1/
I just add a Raphael doubleclick event to the circle (you can do the same with your paths). When this event is fired up, stores the mouse coordinates in two variables. Then I just use those two variables to draw a new circle. If you want to draw a path instead of a circle, you just need to use the variables within the path coordinates.
I hope this works for you! If you have any questions just tell me! bye!
Edit: Look at the commentary Below, is a good contribution to the answer!
Edit2: The line console.log(x,y) Its there to print the mouse values in the browser console, it's not necessary for the code to work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can disconnected knob-and-tube wiring be left in place?
The house I recently bought (over 100 years old) has had almost all of its wiring replaced with a new elctrical board. However, in two cases the new wiring has been connected to existing knob-and-tube wiring in a junction box, with the ground wire not connected. So the knob-and-tube wiring is still in place, fed by new wires coming from the panel. Can I just disconnect the knob-and-tube wiring, leave it where it is, and bypass it with new wiring? If I can leave the disconnnected knob-and-tube wiring, do I have to label it somehow?
A:
Yes, you can leave the knob-and-tube wiring in place. Labeling is neither required nor common, but if things are confusing enough that you think it's warranted, it can't hurt. It's also a good idea to rip out whatever wiring is accessible (e.g., in an unfinished basement).
If you have an electrician do the disconnection work, you should ask the electrician to sign a form certifying that all knob-and-tube wiring has been removed. Such a form is sometimes required before blowing in insulation, or when selling the house.
A:
The typical process of disconnecting an unused wire while leaving it in the wall is to join the hot(s) and neutral at each end so that it's obvious that it's unused and any attempt to reconnect it would trip a breaker. And I hope that no crazy electrician would ever want to reconnect an old knob and tube line. I would take the extra step to completely remove it from anywhere that it's easily accessible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Index not getting created in Elasticsearch
This is my code which Im using to index some data. But,when I search for the index,in elasticsearch it is not getting created there.
var createIndex = function(refId,docFeed){
esClient.create({
index:"indexName",
type:"typeName",
id:refId,
body:docFeed
},
function(error,response){
emptyFunction();
});
}
Can anybody help me on this?
A:
Index names are limited by the file system. They may only be lower
case, and my not start with an underscore. While we(elasticsearch)
don't prevent index names starting with a ., we(elasticsearch) reserve
those for internal use. Clearly, . and .. cannot be used.
source
Change your code to
var createIndex = function(refId, docFeed) {
esClient.create({
index: "indexname",
type: "typename",
id: refId,
body: docFeed
},
function(error, response) {
emptyFunction();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
is KEY_ID automatically generated for sqlite database tables in Android? and is it called "KEY_ID"?
I have an sqlite database with one table in an android app. When it was created with the statement shown below there are two collumns, KEY_CHECKBOX_STATUS and KEY_CHECKBOX_LABEL. "ID" is the primary key that was created.
If I do not explicitly create a primary key at creation time like in the following statement, does it automatically get created? and is the name, "KEY_ID"?
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"CREATE_TABLE IF NOT EXISTS " + MYDATABASE_TABLE + " (" + "ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CHECKBOX_STATUS + " BIT, " + KEY_CHECKBOX_LABEL + " TEXT NOT NULL);";
A:
Sqlite will create a "rowid" and it is unique. You can access this using "rowid" or "oid" or "_rowid_". For example SELECT rowid as id ...
You can read more here http://www.sqlite.org/autoinc.html. Note that rowid is case insensitive.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does my shark not get damaged when colliding with other sharks?
I also get errors on my output such as:
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_AnimateHorizontally()
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_AnimateHorizontally_2()
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_EnterFrameHandler_2()[
Scene 1 - Main Menu
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
import flash.system.fscommand
import flash.events.MouseEvent
stop();
//Button Scripts
Play_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene);
function fl_ClickToGoToScene(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}
Instructions_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_10);
function fl_ClickToGoToAndStopAtFrame_10(event:MouseEvent):void
{
gotoAndStop(6);
}
function quit (event:MouseEvent):void
{
fscommand ("quit");
}
Quit_Button.addEventListener(MouseEvent.MOUSE_DOWN,quit);
Scene 2 - Game
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
import flash.system.fscommand;
import flash.events.TimerEvent;
import flash.utils.Timer;
stop();
//Variables
var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var sharkSpeed:Number = 10;
var score1:Number = 0;
var maxHP:int = 100;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;
//Health Script
function updateHealthBar():void
{
percentHP = currentHP / maxHP;
healthBar.barColor.scaleX = percentHP;
}
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_2);
function fl_ClickToGoToScene_2(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
Instructions_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextScene_2);
function fl_ClickToGoToNextScene_2(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(6, "Main Menu");
}
//Keyboard Movement
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
function keyDownHandler(KeyEvent:KeyboardEvent):void
{
if (KeyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.DOWN)
{
downPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.UP)
{
upPressed = true;
}
}
function keyUpHandler(keyEvent:KeyboardEvent):void
{
if (keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = false;
}
else if (keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = false;
}
else if (keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = false;
}
else if (keyEvent.keyCode == Keyboard.UP)
{
upPressed = false;
}
}
function gameLoop(loopEvent:Event):void
{
if (rightPressed)
{
shark.x += sharkSpeed;
}
else if (leftPressed)
{
shark.x -= sharkSpeed;
}
else if (downPressed)
{
shark.y += sharkSpeed;
}
else if (upPressed)
{
shark.y -= sharkSpeed;
}
}
//AI Movement
addEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);
function fl_AnimateHorizontally(event:Event)
{
enemy1.x += 2;
enemy2.x += 2;
enemy3.x += 2;
enemy4.x += 2;
enemy5.x += 2;
enemy6.x += 2;
megaladon.x += 2;
}
addEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally_2);
function fl_AnimateHorizontally_2(event:Event)
{
fishes.x += 1.5;
}
//Colission
function hitsTheObject(e:Event)
{
if (shark.hitTestObject(enemy1))
{
trace("player collided with enemy");
currentHP -= 50;
if (currentHP <= 0)
{
currentHP = 0;
trace("You died!");
MovieClip(this.root).gotoAndPlay(1, "Game Over");
}
updateHealthBar();
}
}
//Score Script
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler_2);
function fl_EnterFrameHandler_2(event:Event):void
{
gameScore.text = String(score1);
score1 += 1;
trace("gameScore.text is : " + gameScore.text);
trace("score1 is : " + score1);
}
//Timer Script
var myTimer:Timer = new Timer(1000,50);
myTimer.addEventListener(TimerEvent.TIMER, onTimer);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);
myTimer.start();
function onTimer(e: TimerEvent):void
{
myText_txt.text = String(myTimer.repeatCount - myTimer.currentCount);
}
function onComplete(e: TimerEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "You Survived");
}
Scene 3 - You Survived
stop();
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_4);
function fl_ClickToGoToScene_4(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
PlayAgain_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_12);
function fl_ClickToGoToScene_12(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}Scene 4 - Game Over
stop();
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_9);
function fl_ClickToGoToScene_9(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
PlayAgain_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_11);
function fl_ClickToGoToScene_11(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}
A:
As identified in the comments, you need to remove the eventListener which you can achieve with:
removeEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);.
I would suggest implementing the following line whenever you bind to a frame event such as Event.ENTER_FRAME
this.addEventListener(Event.REMOVED_FROM_STAGE, function(){
try{
removeEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);
}catch(error){
//error handling optional in this case.
}
});
This will get called ONCE only right before the object is destroyed/removed from the stage i.e. when you call MovieClip(this.root).gotoAndPlay(1, "Game");
Note: You can just put all of your 'global' events into the try area - you don't need this call every time you add an event.
Additionally, you don't need this whatsoever for movieclips as all of your events will get cleaned up automatically once they are removed from the stage via the garbage collector.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to control parallel execution in Oracle DB
I'm trying to execute a script that I developed for data transformation in Oracle.
I have a table with a very large amount of data and I want to split that data into another table based on a condition and then delete the affected rows from the original table.
My approach was to use create table as select for the second table, then the same to the first table with the condition inverted. Finally I truncated the original table and moved back the data to the original from the temporary table. Like so:
create table data_reject as
select a, b, c
from table_original
where a in (select criteria from aux_table)
/
then
create table data_aux as
select a, b, c
from table_original
where a NOT in (select criteria from aux_table)
/
finally I would do
truncate table data_original
/
and
insert into table_original (a, b, c)
select a, b, c
from table_aux
/
My problem is I placed a parallel hint on all the select and create table commands, and it appears that one statement is issued, and the next one starts executing without waiting for the first statement to end execution.
This leads to the original table losing all its data before the script has time to populate the other two tables.
This script was executed with the command
alter session enable parallel dml
How can I prevent one command from starting before the previous one ends execution?
This is what the script looks like:
-- create temp table
create table id_loc_rejected_temp parallel 32 nologging as
with
id_hier as
(select hierarchy7_key as id from id_hierarchy),
loc_hier as
(select hierarchy6_key as loc from loc_hierarchy)
select /* + PARALLEL (a, 32) */
id_key,
loc_key
from sls a
where a.id_key not in (select key from merch_hier)
union all
select /* + PARALLEL (a, 32) */
id_key,
loc_key
from sls a
where a.loc_key not in (select store from loc_hier)
union all
select /* + PARALLEL (a, 32) */
id_key,
loc_key
from id_loc_rejected_previous a
/
insert into debug_msg values(sysdate, 'First filter. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
--add more filters
insert /* + APPEND PARALLEL (id_loc_rejected_temp, 32) */
into id_loc_rejected_temp(id_key,
loc_key)
with
store_repl as
(select /* + PARALLEL (t, 32) */ id_key as id, loc_key as store from srep t)
select /* + PARALLEL (a, 32) */
id_key,
loc_key
from sls a
where (a.id_key, a.loc_key) not in (select id, store from store_repl)
union all
select /* + PARALLEL (a, 32) */
id_key,
loc_key
from inv a
where (a.id_key, a.loc_key) not in (select id, store from store_repl)
/
insert into debug_msg values(sysdate, 'Second filter. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
-- remove duplicates
create table id_loc_rejected parallel 32 nologging as
select /* + PARALLEL (a, 32) */ distinct id_key, loc_key from id_loc_rejected_temp a
/
insert into debug_msg values(sysdate, 'Transformed temp table into final table. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
drop table id_loc_rejected_temp
/
insert into debug_msg values(sysdate, 'Dropped id loc rejected temp table')
/
-- Create rejected data tables
create table sls_rejected parallel 32 nologging as
select /* + PARALLEL (a, 32) */
id_key,
id_level,
loc_key,
loc_level,
date1,
ticket,
units
from sls a
where (a.id_key, a.loc_key) in (select id_key, loc_key from id_loc_rejected)
/
insert into debug_msg values(sysdate, 'Sales rejected created. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
-- inventory reject table
create table inv_rejected parallel 32 nologging as
select /* + PARALLEL (a, 32) */
id_key,
id_level,
loc_key,
loc_level,
date1,
ticket,
units
from inv a
where (a.id_key, a.loc_key) in (select id_key, loc_key from id_loc_rejected)
/
insert into debug_msg values(sysdate, 'Inventory rejected created. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
-- stockouts reject table
create table oos_rejected parallel 32 nologging as
select /* + PARALLEL (a, 32) */
id_key,
id_level,
loc_key,
loc_level,
date1,
ticket,
flag
from oos a
where (a.id_key, a.loc_key) in (select id_key, loc_key from id_loc_rejected)
/
insert into debug_msg values(sysdate, 'Stockout rejected created. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
-- store replenishment reject table
create table stg_ro_st_re_rejected parallel 32 nologging as
select /* + PARALLEL (a, 32) */
id_key,
loc_key,
review
from srep a
where (a.id_key, a.loc_key) in (select id_key, loc_key from id_loc_rejected)
/
insert into debug_msg values(sysdate, 'Store replenishment parameters rejected created. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
-- now, create temp tables to hold the rest of the data (what we want to keep)
-- sales temp table
create table sls_tmp parallel 32 nologging as
select /* + PARALLEL (a, 32) */
id_key,
id_level,
loc_key,
loc_level,
date1,
ticket,
ticket
from sls a
where (a.id_key, a.loc_key) not in (select id_key, loc_key from id_loc_rejected)
/
insert into debug_msg values(sysdate, 'Sales temp created. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
-- Store replenishmment temp table
create table stg_ro_store_repl_tmp parallel 32 nologging as
select /* + PARALLEL (a, 32) */
id_key,
loc_key,
review
from srep a
where (a.id_key, a.loc_key) not in (select id_key, loc_key from id_loc_rejected)
/
insert into debug_msg values(sysdate, 'Store replenishment temp created. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
-- truncate original tables and reinsert
-- Final Sales
truncate table sls
/
insert /* + APPEND PARALLEL (sls, 32) */
into sls(id_key,
id_level,
loc_key,
loc_level,
date1,
ticket,
ticket)
(
select /* + PARALLEL (a, 32) */
id_key,
id_level,
loc_key,
loc_level,
date1,
ticket,
ticket
from sls_tmp a
)
/
insert into debug_msg values(sysdate, 'Sales reinserted. Inserted ' || SQL%ROWCOUNT || ' rows')
/
commit
/
drop table sls_tmp
/
A:
The problem was with the select statements in the script. Some of them had blank lines for organization inside and these lines made sqlplus think it had to execute two commands instead of one.
This made the very long commands fail completely, while the next commands had basically nothing to do or failed too.
The other problem was the SQL%ROWCOUNT inside the insert, it made it look like only some of the inserts were being performed while others lagged behind.
Finally, I broke the script apart, executing one step at a time and everything worked fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML Canvas fails to drawImage
Given the following two objects:
function newDoodle() {
var Doodle = {
/* Variables for creating the canvases */
cnvWdth: 800,
cnvHght: 250,
bgCanvas: false,
fgCanvas: false,
bgContext: false,
fgContext: false,
bodyElement: false,
/* Variables for future objects */
background: false,
init: function(bodyElement) {
/* Set up the two canvas elements */
this.bodyElement = bodyElement;
this.bgCanvas = this.createCanvas('background');
this.fgCanvas = this.createCanvas('foreground');
this.bgContext = this.getContext(this.bgCanvas);
this.fgContext = this.getContext(this.fgCanvas);
/* Set up the background canvas */
this.bgImage = newBackground();
this.bgImage.init(this.bgContext);
},
createCanvas: function(id) {
var canvas = $('<canvas />').appendTo(this.bodyElement);
canvas.attr('width', this.cnvWdth);
canvas.attr('height', this.cnvHght);
return canvas[0];
},
getContext: function(canvas) {
var context = canvas.getContext('2d');
return context;
}
}
return Doodle;
}
function newBackground() {
var Background = {
/* Background Image source variables */
srcXPos: 0,
srcYPos: 0,
srcWdth: 800,
srcHght: 250,
bgImage: new Image(),
bgImageSrc: 'doodle_background.png',
context: false,
init: function(ctx) {
this.context = ctx;
this.bgImage.addEventListener('load', this.drawBackground(), false);
this.bgImage.src = this.bgImageSrc;
},
drawBackground: function() {
this.context.drawImage(this.bgImage, 0, 0);
}
}
return Background;
}
I store newDoodle()'s returned object into a variable and call its init function. Ultimately it will call newBackground()'s object's drawBackground() function. I've verified that both the image and contexts are valid, and even with "use strict", nothing is reported in the console, yet nothing is getting drawn to the canvas. What am I missing?
A:
This line is the culprit:
this.bgImage.addEventListener('load', this.drawBackground(), false);
See how you're calling this.drawBackground right here, and not passing it as an event handler?
What you probably want is this:
var that = this;
this.bgImage.addEventListener('load',
function () { that.drawBackground(); }, false);
Note that you cannot shorten to
this.bgImage.addEventListener('load',
this.drawBackground, false); // will not work!
since drawBackground needs the context – the this context, not the canvas context. Well, that too. Anyway, I digress :)
| {
"pile_set_name": "StackExchange"
} |
Q:
perl split function returns infinite array
I think there's a bug here. I have a string consisting of numbers separated by ':'. when I use split(), the number of list items is not a number, it returns "1289,2235,2300,2336". What's wrong here?
#!/opt/local/bin/perl
$data="10:2284:2345:2381:9:2235:2300:2336:8:2212:2273:2320:7:2194:2262:2295:6:2165:2232:2269:5:2118:2167:2205:4:2086:2142:2161:3:2039:2106:2138:2:2034:2088:2127:1:2028:2079:2109:01:1999:2046:2080:02:1972:2016:2052:03:1960:1987:2019:04:1915:1945:1971:05:1870:1888:1911:06:1798:1828:1855:07:1764:1789:1809:08:1692:1728:1753:09:1665:1688:1706:010:1636:1657:1679:011:1575:1607:1641:012:1549:1582:1620:013:1485:1539:1582:014:1395:1485:1540:015:1382:1456:1504:016:1368:1422:1465:017:1301:1360:1405:018:1267:1252:1283:019:1213:1252:1283:020::1159:1180:021::1112:1143:022::1087:1094::";
@l = split(':',$data);
print scalar @l ;
A:
Your code works fine for me - I get 128 printed when I run it.
I think the thing that will be tripping you up is that you don't print a line feed. E.g. \n or use say.
So your number is:1289,2235,2300,2336 which implies this bit of the code is printing 128 and elsewhere in your code is printing 9,2235,2300,2336.
If you can extract more of your code, and produce an MCVE - minimal complete verifiable example - the fine folk of StackOverflow can help you further. I suspect when you do this, your problem will disappear - whilst there are bugs in perl, it's quite a mature language and so the bugs really don't show up unless you're doing something particularly obscure.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: How do I prevent long variable names in scope
I have stuff like:
self.megacity.resourceloader.sound.mcintro.play()
Is there any elegant way to prevent such long stuff like this?
Some sort of structural change, perhaps?
Thanks.
A:
x = self.megacity.resourceloader.sound.mcintro
x.play()
| {
"pile_set_name": "StackExchange"
} |
Q:
Python 3 and Tkinter. Too many global variables
I started programming a simple GUI application in Python, using Tkinter library.
Everything works fine but, to dynamically change any widget (for example a button from "login" to "logout", etc), I have to get the variable containing the widget object itself in the function from outside.
I can do this in two ways:
passing the widget as a argument;
using global variables.
A simplified example:
1) Passing as argument:
def changeLabel(b):
b.config(text='Logout')
btn1 = Button(f0,text="Login",width=15)
btn1.grid(row=1,column=2,rowspan=1,padx=10,ipadx=10)
changeLabel(btn1)
2) Or using a global variable:
def changeLabel():
global btn1
btn1.config(text='Logout')
btn1 = Button(f0,text="Login",width=15)
btn1.grid(row=1,column=2,rowspan=1,padx=10,ipadx=10)
changeLabel(btn1)
Now, I know that global variables should be avoided but passing every widget as argument through many functions, even in a simple application, it's a mess.
So, what's the best way to manipulate the Tkinter widgets at runtime? Can you suggest me the right way?
Thank you
A:
The best way to manipulate tkinter widgets at runtime is to store those widgets as attributes of a class.
For example:
class Example(...):
def create_widgets(self):
...
self.btn1 = Button(...)
...
def changeLabel(self):
self.bt1.config(...)
For more information see Best way to structure a tkinter application
| {
"pile_set_name": "StackExchange"
} |
Q:
How to split list to lists by condition?
I want split a list into multiple lists, based on a condition. If the difference in the series grows more than 4, then it is trigger to split the list till that item from last split item.
For example:
in = [1,2,3,9,10,11,100,200]
out = [ [1,2,3 ], [ 9,10,11 ], [100], [200] ]
by condition
If (next - prev) > 4
A:
def splitlist(L):
if not L: return []
answer = [[L[0]]]
for i in L[1:]:
if i - answer[-1][-1] < 4:
answer[-1].append(i)
else:
answer.append([i])
return answer
Output:
In [112]: splitlist([1,2,3,9,10,11,100,200])
Out[112]: [[1, 2, 3], [9, 10, 11], [100], [200]]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to tint icons of MediaStyle notification actions?
In my application I have a media notification (using the MediaStyle) and I need to have action icons with different tints. An example of what I want to achieve is the Spotify notification running on Android N:
Spotify notification example
The Previous action icon doesn't have the same color than the other actions. I know I can tint all of them with NotificationCompat.Builder.setColor() method, but how can each action icon have a different color/tint?
A:
Finally found the solution. Starting from Lollipop, Android only use the alpha from drawables and apply its own color on them. The Spotify app use a black color, and with some alpha they can have a grey icon. So by tweaking the alpha of the used drawables, it's possible to have different tints on action icons.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find Path During Runtime To Delete File
The code basically allows the user to input the name of the file that they would like to delete which is held in the variable 'catName' and then the following code is executed to try and find the path of the file and delete it. However, it doesn't seem to work, as it won't delete the file this way. Is does however delete the file if I input the whole path.
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
A:
If you're deleting files in the same directory that the program is executing in, you don't need specify a path, but if it's not in the same directory that your program is running in and you're expecting the program to know what directory your file is in, that's not going to happen.
Regarding your code above: the following examples all do the same thing. Let's assume your path is /home/kim/files and that's where you executed the program.
// deletes /home/kim/files/somefile.txt
boolean result = new File("somefile.txt").delete();
// deletes /home/kim/files/somefile.txt
File f = new File("somefile.txt");
boolean result = new File(f.getCanonicalPath()).delete();
// deletes /home/kim/files/somefile.txt
String execPath = System.getProperty("user.dir");
File f = new File(execPath+"/somefile.txt");
f.delete();
In other words, you'll need to specify the path where the deletable files are located. If they are located in different and changing locations, then you'll have to implement a search of your filesystem for the file, which could take a long time if it's a big filesystem. Here's an article on how to implement that.
| {
"pile_set_name": "StackExchange"
} |
Q:
mod_rewrite is ignoring rules in subdirectories
Wanted rewrite behaviour (internal rewrite!)
http://<subdomain>.domain.tld/<path> -> /<subdomain>/<path>
http://www.domain.tld/path/file.php -> /www/path/file.php
http://project.domain-tld/index.php -> /project/index.php
Folder structure:
/ root
.htaccess
/www www.domain.tld
index.php
/www
file.php
/foo
/bar
file.php
/project project.domain.tld
index.php
someRandomFiles
/somesubdomain somesubdomain.domain.tld
index.php
someRandomFiles
/anothersubdomain anothersubdomain.domain.tld
index.php
someRandomFiles
Full .htaccess
# Unicode
AddDefaultCharset utf-8
# Activate mod_rewrite
RewriteEngine on
RewriteBase /
# Subdomains
# Extract (required) subdomain (%1), and first path element (%3), discard port number if present (%2)
RewriteCond %{HTTP_HOST}<>%{REQUEST_URI} ^([^.]+)\.janbuschtoens\.de(:80)?<>/([^/]*) [NC]
# Rewrite only when subdomain not equal to first path element (prevents mod_rewrite recursion)
RewriteCond %1<>%3 !^(.*)<>\1$ [NC]
# Rewrite to /subdomain/path
RewriteRule ^(.*) /%1/$1 [L]
My .htaccess seems to work. You can live test it here:
http://test.janbuschtoens.de/
rewrites to /test/
http://www.janbuschtoens.de/
rewrites to /www/
But there is some strange behaviour in subdirectories. mod_rewrite seems to ignore the rule if the first directory in the requested path has the same name as the subdomain itself. For example:
http://www.domain.tld/foo/bar/file.php -> /www/foo/bar/file.php - Fine!
http://www.domain.tld/ -> /www/ - Fine!
http://www.domain.tld/www/ -> /www/ - Should be: /www/www/
http://www.domain.tld/www/www/ -> /www/www/ - Should be: /www/www/www/
For another live test:
http://test.janbuschtoens.de/ rewrites to /test/
http://test.janbuschtoens.de/test/ rewrites to /test/
It seems like the rule gets ignored.
A:
This is the only good rule that I was able come up with, otherwise after initial rewriting (which is very easy) it goes into the loop (and that is the problem). For example: www.domain.com/www/123.png gets properly redirected into /www/www/123.png, but then goes to the next loop, where it get's redirected to /www/www/www/123.png and then again and again.
This rule ONLY gets invoked if FINAL filename DOES EXIST.
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -d
RewriteRule ^(.*)$ /%1/$1 [QSA,L]
For example: if you request www.domain.com/www/123.png, and file/folder WEBSITEROOT/www/www/123.png exist, then it will be rewritten, otherwise nothing.
The same here: if you request meow.domain.com/ .. but have no WEBSITEROOT/meow/ folder on your drive, it gets nowhere.
Please note, this still will not help much if you have subfolder with the same name as subdomain. For example: if you request www.domain.com it should be rewritten to WEBSITEROOT/www/ ... but if you also have WEBSITEROOT/www/www/ then (because of loop) it will be rewritten to WEBSITEROOT/www/www/ instead.
Unfortunately I have not found the way how to bypass it. If you wish -- you can try combining your rules with mine.
| {
"pile_set_name": "StackExchange"
} |
Q:
segmentation fault on getline in Ubuntu
I'm having the famous segmentation fault. I've tracked it down to a single line in the code (getline). Here's someone with a similar issue, also on Ubuntu:
http://www.daniweb.com/software-development/cpp/threads/329191
Note that getline returns -1 after the segmentation fault, but it couldn't have been really the end of the stream (in my case).
When the stream is smaller, everything goes ok. As we can deduce from the output, the segmentation fault is on line 98.
1 /*
2 * File: RequestDispatcher.cpp
3 * Author: albert
4 *
5 * Created on July 8, 2011, 7:15 PM
6 */
7
8 #include "iostream"
9 #include "fstream"
10 #include "stdlib.h"
11 #include "stdio.h"
12 #include "cstring"
13 #include "algorithm"
14
15 #include "RequestDispatcher.h"
16 #include "Functions.h"
17
18 #define PROXIES 1
19
20 RequestDispatcher::RequestDispatcher()
21 {
22 }
23
24 RequestDispatcher::RequestDispatcher(const RequestDispatcher& orig)
25 {
26 }
27
28 RequestDispatcher::~RequestDispatcher()
29 {
30 }
31
32 int RequestDispatcher::addRequest(string host, string request, IResponseReceiver* response_receiver)
33 {
34 RequestInfo info;
35 info.request_index = request_info.size();
36 info.host = host;
37 info.request = request;
38 info.response_receiver = response_receiver;
39 request_info.push_back(info);
40 return info.request_index;
41 }
42
43 void RequestDispatcher::run()
44 {
45 if (request_info.size()==0)
46 {
47 return;
48 }
49 FILE* pipe[PROXIES];
50 int per_proxy = (request_info.size() + PROXIES - 1) / PROXIES;
51 int count_pipes = (request_info.size() + per_proxy - 1) / per_proxy;
52 for (int pipe_index=0; pipe_index<count_pipes; ++pipe_index)
53 {
54 int from = pipe_index * per_proxy;
55 int to = min(from + per_proxy, int(request_info.size()));
56 cout << "FROM: "<< from << "; TO: " << to;
57 const char* cmd = generateCmd(from, to);
58 pipe[pipe_index] = popen(cmd, "r");
59 if (!pipe[pipe_index])
60 {
61 cerr << "Error executing command in RequestDispatcher::run()";
62 }
63 }
64 string result[PROXIES];
65 bool finished[PROXIES];
66 for (int pipe_index=0; pipe_index<count_pipes; pipe_index++)
67 {
68 finished[pipe_index] = false;
69 }
70 int count_finished = 0;
71 char* buffer;
72 size_t buffer_length=1024;
73 buffer = (char *) malloc (buffer_length + 1);
74 while (count_finished < count_pipes)
75 {
76 cout << "D\n";
77 fflush(stdout);
78 for(int pipe_index=0; pipe_index<count_pipes; ++pipe_index)
79 {
80 cout << "E\n";
81 fflush(stdout);
82 if (finished[pipe_index])
83 {
84 continue;
85 }
86 cout << "Getline" << buffer_length << "\n";
87 ssize_t bytes_read = getline(&buffer, &buffer_length, pipe[pipe_index]);
88 cout << "Getline Done ("<<bytes_read<< "," << buffer_length << ")\n";
89 fflush(stdout);
90 while (bytes_read>0)
91 {
92 for (int i=0; i<bytes_read; i++)
93 {
94 result[pipe_index] += buffer[i];
95 }
96 cout << "P\n";
97 fflush(stdout);
98 bytes_read = getline(&buffer, &buffer_length, pipe[pipe_index]);
99 cout << "Bytes read ("<<bytes_read<<","<< buffer_length << ")\n";
100 fflush(stdout);
101
102 }
103 if (bytes_read == -1) // then finished this pipe
104 {
105 string* r = &result[pipe_index];
106 //cout << *r;
107 finished[pipe_index] = true;
108 ++count_finished;
109 cout << "HI\n";
110 fflush(stdout);
111 // delete trailing '\0' from result
112 pclose(pipe[pipe_index]);
113 result[pipe_index] = result[pipe_index].substr(0, result[pipe_index].length()-1);
114 int pos = r->find("RESPONSE_DATA");
115 int valuepos, endvaluepos;
116 int request_index, length;
117 string headers;
118 int headerslength;
119 string body;
120 int bodypos, bodylength;
121 while (pos!=r->npos)
122 {
123 valuepos = r->find("REQUEST_INDEX=", pos) + 14;
124 endvaluepos = r->find("\n", valuepos);
125 request_index = pipe_index * per_proxy + atoi(r->substr(valuepos, endvaluepos-valuepos).c_str());
126
127 cout << "REQUEST_INDEX " << request_index;
128
129 valuepos = r->find("LENGTH=", pos) + 7;
130 endvaluepos = r->find("\n", valuepos);
131 length = atoi(r->substr(valuepos, endvaluepos-valuepos).c_str());
132
133 pos = r->find("START", pos)+5;
134 bodypos = r->find("\r\n\r\n", pos)+4;
135 headerslength = bodypos-pos-4;
136 bodylength = length-headerslength-4;
137 headers = r->substr(pos, headerslength);
138 body = r->substr(bodypos, bodylength);
139 request_info[request_index].response_receiver->notifyResponse(headers, body, request_index);
140
141 pos=r->find("RESPONSE_DATA", pos+length);
142 }
143 }
144 }
145 }
146 cout << "\n?\n";
147 fflush(stdout);
148 free(buffer);
149 request_info.clear();
150 }
151
152 const char* RequestDispatcher::generateCmd(int first_request, int to_request)
153 {
154 string r("/home/albert/apachebench-standalone-read-only/ab -a");
155 for (int i=first_request; i<to_request; i++)
156 {
157 r.append(" '");
158 r.append(request_info.at(i).request);
159 r.append("'");
160 }
161 ofstream out("/home/albert/apachebench-standalone-read-only/debug");
162 if(! out)
163 {
164 cerr<<"Cannot open output file\n";
165 return "";
166 }
167 out << r.c_str();
168 out.close();
169 return "/home/albert/apachebench-standalone-read-only/debug";
170 /*int size = strlen("/home/albert/apachebench-standalone-read-only/ab -a");
171 for (int i=first_request; i<to_request; i++)
172 {
173 size += 2+strlen(request_info.at(i).request)+1;
174 cout << "len: " << strlen(request_info.at(i).request) << "\n";
175 cout << "total: " << size << "\n";
176 }
177 size += 1;
178 char* cmd = new char[size];
179 strcpy(cmd, "/home/albert/apachebench-standalone-read-only/ab -a");
180 for (int i=first_request; i<to_request; i++)
181 {
182 cout << "LEN: " << strlen(cmd) << "\n";
183 cout << "NEXT: " << strlen(request_info.at(i).request) << "\n";
184 fflush(stdout);
185 strcat(cmd, " '");
186 strcat(cmd, request_info.at(i).request);
187 strcat(cmd, "'");
188 }
189 cout << "LEN: " << strlen(cmd) << "\n";
190 fflush(stdout);
191 return cmd;*/
192 }
When I run /home/albert/apachebench-standalone-read-only/debug from the command line everything works perfectly fine. It returns binary data.
The end of the output is:
P
Bytes read (272,6828)
P
Bytes read (42,6828)
P
Bytes read (464,6828)
P
Bytes read (195,6828)
P
Bytes read (355,6828)
P
Bytes read (69,6828)
P
Bytes read (111,6828)
P
Segmentation fault
Bytes read (368,6828)
P
Bytes read (-1,6828)
HI
REQUEST_INDEX 46REQUEST_INDEX 48REQUEST_INDEX 44REQUEST_INDEX 0REQUEST_INDEX 45
?
Mind the "?" for exiting the loop. After this, the program is finished.
By the way, I always thought the program would terminate on a segmentation fault (edit: I did not do anything to catch it).
In reply to some answers: There seem to be different versions of getline and I seem to be using the one documented here:
http://www.kernel.org/doc/man-pages/online/pages/man3/getline.3.html
A:
So after some thought the issue I believe is that your buffer is being written to as you're reading it. In some cases the buffer is not done being written to and you remove some of the data from it (which could mean that you may read an empty buffer because the write isn't done). This is because you are using popen and simply piping data from another process. What I would recommend is that for one you use the C++ standard for getline (although both are somewhat unsafe) and that you have some leeway for reading data from the pipe. Retry logic might be what you need as I can't think of a clean way to solve this. If anyone knows please post it, I'm posting this because this is what I believe to be the likely culprit of the problem.
Also if you're coding in C++ I highly recommend that you use the C++ libraries so that you're not constantly mixing or casting between types (such as string to char * and such, it just saves you some hassle) and that you use the safer versions of methods so you avoid errors such as buffer overflows.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to shorten code for geoJSON file
I'm building a Florida county map using geoJSON. I downloaded 67 county files and combined them in Cartodb. The current file is huge: 4MB with thousands of lines of code, especially in the coordinates. Here's what it looks like. The map works, but it's slow to load on the browser. I've seen other JSON files that are smaller and easier on the browser. Is there a way to shorten the code so they still show the counties on my map? Maybe removing a majority of the coordinates?
A:
you can use TopoJSON which is a topology encoding extension to GeoJSON.
"Rather than representing geometries discretely, geometries in TopoJSON files are stitched together from shared line segments called arcs."
read more: https://github.com/mbostock/topojson/wiki
repo:
https://github.com/mbostock/topojson
| {
"pile_set_name": "StackExchange"
} |
Q:
Parallel workers with guarantee of processing
I have some tasks stored in a table of SQL-Server. Every task can be long-running. I want to process them on parallel workers. For example run more workers when load is high, and stop them, when no need. And when one worker is unavailable or failed his job, the processing task should return in queue.
What is the best way to organize queue and multiply workers with guarantee of processing? Tasks storage can be changed.
A:
I decided to use MS SQL table as a queue, store all requests in this queue, run multiply workers with Quartz.NET. Every worker receive one request. Every request is processing only by one worker.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble with createBufferStrategy in Java
I'm fairly new at java, however I suspect my problem is caused by the same reasons as this post
Since this makes me think I am trying to render before my component is added to a container, I just need help figuring out where this is happening. I commented the lines where the IllegalStateException is being thrown.
public void run() {
init();
long lastTime = System.nanoTime();
final double amountOfTicks = 60D;
double ns = 1000000000/amountOfTicks;
double delta = 0;
long now = System.nanoTime();
while(running)
{
delta += (now - lastTime)/ns;
lastTime = now;
if(delta >= 1)
{
tick();
delta--;
}
render(); //ISSUE HERE AND
}
stop();
}
public void tick() {
player.tick();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3); //ISSUE HERE, TOO
return;
}
Graphics g = bs.getDrawGraphics();
//RENDER HERE
//g.fillRect(0, 0, 1200, 600);
player.render(g);
//END RENDER
g.dispose();
bs.show();
}
public static void main(String[] args)
{
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
Gui go = new Gui();
game.start();
//Program seems to continue running after ESC
}
Error Message
Exception in thread "Thread-0" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers(Unknown Source)
at java.awt.Component$FlipBufferStrategy.<init>(Unknown Source)
at java.awt.Component$FlipSubRegionBufferStrategy.<init>(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at msa.devillegame.main.Game.render(Game.java:81)
at msa.devillegame.main.Game.run(Game.java:68)
at java.lang.Thread.run(Unknown Source)
A:
i set up custom rendering like this
public class FrameTest { //not a subclass from frame
public static void main(String[] args) {
//FIXME look at SwingUtilities invokeLater
new FrameTest().createAndShow(); //because it's just a starter
}
private JFrame frame;
private BufferStrategy bufferStrategy;
private Rectangle screenBounds;
private GraphicsDevice myScreen;
private boolean isRunning = false;
private void createAndShow() {
try {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
myScreen = env.getDefaultScreenDevice(); //maybe select a certain device
GraphicsConfiguration gConf = myScreen.getDefaultConfiguration(); //maybe setup a different configuration
screenBounds = gConf.getBounds();
frame = new JFrame(gConf);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setUndecorated(true);
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
goExit();
}
});
frame.setVisible(true);
myScreen.setFullScreenWindow(frame);
bufferStrategy = null;
BufferCapabilities bcaps = gConf.getBufferCapabilities();
int amountBuffer = 0;
if (bcaps.isMultiBufferAvailable() ){
amountBuffer = 3;
}else {
amountBuffer = 2;
}
frame.createBufferStrategy(amountBuffer, bcaps);
bufferStrategy = frame.getBufferStrategy();
isRunning = true;
startRendering(); //starts a render loop
startUniverse(); //starts the physic calculations
System.out.println("created a buffer with "+amountBuffer+" pages");
} catch (HeadlessException e) {
} catch (AWTException e) {
}
}
//this is an example caluclation
private double xpos = 0;
private double ypos = 0;
private double xCenter = 0;
private double yCenter = 0;
private double radius = 100;
private double dAngle = 0;
private double angle = (2d * Math.PI / 360d);
private void startUniverse() {
Runnable r = new Runnable() {
@Override
public void run() {
while(isRunning){
//this is the example calculation
xCenter = screenBounds.getCenterX();
yCenter = screenBounds.getCenterY();
dAngle = dAngle + angle;
xpos = xCenter + radius*(Math.sin(dAngle) );
ypos = yCenter + radius*(Math.cos(dAngle) );
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r); //create and...
t.setDaemon(true);
t.start(); //...start the thread
}
//this method starts the rendering thread
//look at the full screen tutorial
private void startRendering() {
Runnable r = new Runnable() {
@Override
public void run() {
while(isRunning){ //an endless loop
Graphics g = null;
try {
g = bufferStrategy.getDrawGraphics();
render(g); //render the graphics
} finally {
if (g != null){
g.dispose(); //IMPORTANT - dispose the graphics - MemeoryLeak
}
}
bufferStrategy.show(); //bring it to the front
//i strongly recommend to let the render thread sleep a little
//this reduces cpu power - without it it uses
//one of my cpus for 100% (having 8 cpus this means 12.5%)
//but when it sleeps 10ms my cpu is down to 1% !!!
//try {
// Thread.sleep(10);
//} catch (InterruptedException e) {
//}
}
}
};
Thread t = new Thread(r);
t.setDaemon(true);
t.start();
}
//the render method draws the calculated stuff
protected void render(Graphics g) {
//fist, fill with white
g.setColor(Color.WHITE);
int x = 0;
int y = 0;
int width = screenBounds.width;
int height = screenBounds.width;
g.fillRect(x, y, width, height);
//xpos and ypos was calulated in the other thread
g.setColor(Color.BLACK);
int x_a = (int)xpos;
int y_a = (int)ypos;
int x_b = (int)xCenter;
int y_b = (int)yCenter;
g.drawLine(x_a, y_a, x_b, y_b);
}
//simple method to quit
protected void goExit() {
isRunning = false;
frame.setVisible(false);
frame.dispose();
myScreen.setFullScreenWindow(null);
}
}
take this tutorial as a help sheet...
| {
"pile_set_name": "StackExchange"
} |
Q:
Joomla backend disable eerror reporting in my component
I am developing a joomla component for backend. For now for debugging i just put die() to place where i need to stop and display debug info all the way to figure out what happens. I did not use XDEBUG because there many query's and i need to check many results at once.
But i have a problem. When i get error in my SQL query because some error in script or my mistake instead just put it at bottom at all other info Joomla back from, for example page:
/administrator/index.php?option=com_xyz&view=build to /administrator/ trowing away all debug info, so i just cant figure out where error happens or which SQL query cause this trouble.
So i have similar error on top main admin page inside red block:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 3
All i want it did not catch errors and allow me to see it with other my script output.
So how disable joomla reporting in my component, temporary.
A:
First i use:
restore_exception_handler();
and then
try {
$dict_data = $db->loadObject();
}
catch (Exception $e){
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
die();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Solid solution to flexibly resize UIView based on subviews
Imagine you have four or so views, all width 100, different heights. You have a wrapper view W which holds them all.
A |
B | W
C |
D |
the heights of the small views can change. At that time you want them all to move, float, appropriately, and resize W.
Now, I was just about to write a few lines of code to do this.
So .. (1) you'd have W find all the subviews and list them in order from top to bottom. Then (2) each time there is a change, you'd (3) reposition each of ABCD. the position of each one is the sum of the heights of the items above it, and (4) resize W to the sum of all heights.
Now that's all fine but -- idiots reinvent the wheel!
Am I missing something obvious in iOS? is there already a package everyone uses to do this all the time? Or something built in? What's the situation?
(Note that of course frustratingly, for our Android friends this is built in! And of course any web-html system does this automatically.)
What's the right engineering solution for iOS views here? For the record this is iOS7+ only, no old-fashioned stuffs need be covered, if it makes a difference. Cheers
A:
(1) you'd have W find all the subviews and list them in order from top
to bottom. Then (2) each time there is a change, you'd (3) reposition
each of ABCD. the position of each one is the sum of the heights of
the items above it, and (4) resize W to the sum of all heights.
You can use constraints in Interface Builder for that whole process, no code required. Do this:
set the width of subview A to 100
constrain B, C, and D to match A's width
add vertical spacing constraints between A and B, B and C, and C and D to maintain their relative position
add a vertical spacing constraint between W (the superview, shown in gray) and A
add a vertical spacing constraint between W and D
add leading and trailing space constraints between W and view A
You'll end up with something that looks like this:
The constraints editor in Xcode isn't completely intuitive, but it is easy to use once you understand what you can and can't do with constraints in IB and when you need to use code to set up the constraints.
| {
"pile_set_name": "StackExchange"
} |
Q:
Char* memory in data model gets reclaimed?
I have the following code to read a credit card number from a text field and store it in a datamodel. The card number is correct when it is stored but later when I try to read from it it has become gibberish. Now I am guessing this is because the memory is reclaimed and it no longer makes sense.
Code to set the card number from the label:
[cardInfo setCardNumber: [textField.text cStringUsingEncoding:[NSString defaultCStringEncoding]]];
Code in the data model:
- (void) setCardNumber:(char *)number{
cardNumber = number;
//Value of cardNumber here is correct
}
Everything looks correct until I use the property to retrieve the value at a later time.
A:
From the docs for -[NSString cStringUsingEncoding:]:
The returned C string is guaranteed to be valid only until either the
receiver is freed, or until the current autorelease pool is emptied,
whichever occurs first. You should copy the C string or use
getCString:maxLength:encoding: if it needs to store the C string
beyond this time.
Also, you should never use +[NSString defaultCStringEncoding]. It's completely unreliable and can't generally represent arbitrary strings. From the docs:
in general this encoding should be used rarely, if at all
| {
"pile_set_name": "StackExchange"
} |
Q:
Присоединение файлов в почте в Perl
Здравствуйте.
Подскажите, пожалуйста, как присоединять в Perl файлы , например, графические, к электронным письмам.
Спасибо.
A:
Используя MIME::Lite:
use MIME::Lite;
use Net::SMTP;
### Выбрать отправителя получателя и почтовика
my $from_address = '[email protected]';
my $to_address = '[email protected]';
my $mail_host = 'smtp.yandex.ru';
### Выбрать тело и заголовок сообщения
my $subject = 'Пример письма с вложением';
my $message_body = "Тело письма с вложением";
### Выбрать имена файлов
my $my_file_gif = 'my_file.gif';
my $your_file_gif = 'your_file.gif';
### Создать контейнер
$msg = MIME::Lite->new (
From => $from_address,
To => $to_address,
Subject => $subject,
Type =>'multipart/mixed'
) or die "Ошибка создания контейнера: $!\n";
### Добавить текст
$msg->attach (
Type => 'TEXT',
Data => $message_body
) or die "Ошибка добавления текста: $!\n";
### Добавить рисунок
$msg->attach (
Type => 'image/gif',
Path => $my_file_gif,
Filename => $your_file_gif,
Disposition => 'attachment'
) or die "Ошибка добавления $file_gif: $!\n";
### Послать сообщение
MIME::Lite->send('smtp', $mail_host, Timeout=>60);
$msg->send;
| {
"pile_set_name": "StackExchange"
} |
Q:
Separating the iPhone sleep from all other applicationWillResignActive scenarios
My app supports pin code for my users and I was asked to show the pin code every time the app returns from multitasking or the device returns from sleep.
In order to make sure the first thing the user sees is the pin code screen and not the real data for a sec before seeing the pin code, I am watching the applicationDidEnterBackground and applicationWillResignActive methods.
The problem is that applicationWillResignActive is called on many occasions like when the user is double tapping on the home button, gets an SMS or push notification, on tries to purchase an in app purchase request.
Is there a way for me to separate all of those cases and simply recognize the auto sleep of the device or the case when the user taps on the sleep button?
Thanks
Roi
A:
There isn't a direct way to differentiate all the reasons why your app enters the background mode. You can, however, call CFAbsoluteTimeGetCurrent() in applicationWillResignActive:, save the time stamp, and check if enough time has passed in applicationDidBecomeActive: to warrant showing PIN code entry. For example, if less than 10 seconds has passed, you can skip showing PIN code entry. This does make your app less secure, but then it will nag users a bit less too.
While this solution may look far from being ideal, in fact, it doesn't matter why your app resigned its active state. Whatever the reason, it may become active after a very long time, and it may as well never become active again if iOS decides to terminate it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can monit filesystem check handle NTFS disk?
I am getting "unable to read filesystem '/dev/sdb1' state" from monit and don't understand why. fdisk -l shows /dev/sbd1: /dev/sdb1 2048 283113471 283111424 135G 7 HPFS/NTFS/exFAT
It is not mounted but exists under /dev/sdb1
The monit config looks like this
group filesystem
if space usage > 80 % then alert
if inode usage > 80 % then alert
Can anybody give me a hint why monit alerts?
Best regards
Thomas
A:
Sorry your configuration is incomplete, it is lacking the check and mount point. For example:
check filesystem NTFS_Disk with path /mnt/ntfs_disk
Make sure you are monitoring a mount point and not a device (like /dev/sdb1)
| {
"pile_set_name": "StackExchange"
} |
Q:
Should we have country name tags? If so, how should we use them?
I have been sifting through the tags looking for ones that seem problematic and one problem that I am finding are tags that are about the work or the scene of the work, but not actually about the question. One example of this is country tags, such as mexico or japan. In the mexico case, both uses of the tag are categorizing the work and not the question. In the case of japan, one usage relates to Japanese and Manga, but not Japan at all, and the other is about the exploration of Japanese culture in the United States. I personally find the usages categorizing the works as opposed to the question problematic, but I have two questions for meta:
Should we have country name tags?
If so, how should we use country tags if we keep them?
A:
My answer is "it doesn't matter at this point, in the context of larger issue of whether we have nation/country/culture/language based tags in the first place".
A bigger, strategic question is, Do we want to have a concept of tags that allow broad categorization of questions based on geographic/linguistic/national groupings.
If someone is interested in and specializes in "Russian literature" (however you define that, it's a legit specialization), will we as a community/site provide a way for that specialist to be able to easily find most "russian" - however you define that - questions, without having to subscribe to 50-100-500 individual tags for "russian" authors, which is what that person would have to do as of now (or simply be forced to scan 100% of site questions, which may be too much given the site size).
Please note that specifics of such tags (should they be based on geography? language? country? both?) is irrelevant to that large philosophical and strategic question of whether such tags as a concept have a place on the site. Yes, those specifics and differences change the exact set of questions for such tags by, say, 5% (Do Russian language works published in Israel count? Are USSR and Russian pre-USSR works same tag?). We can hash out and work through that 5% later, at our leisure, after we figure out whether we want to solve the first 95% of the problem first.
Please note that the above is 100% distinct from "country as a subject of work" discussion, which I will cover in a separate answer saying "no".
A:
Tags for "country as a subject of work" is probably an idea we should REJECT.
They don't help a specialist with finding interesting questions to answer.
In the realm of literature, there are experts on, say, French literature.
There are, however, unlikely to be experts on "literature about France" (in any language by any authors).
They don't much help anyone to decide what the question is about, in the context of literature analysis.
If we do not want to have country-specific tags at all (see my other answer), they violate that approach. If we do want such tags, they would conflict with tags based on geography/country/language/culture; and confuse people (What's up with france vs. french-literature?)
| {
"pile_set_name": "StackExchange"
} |
Q:
specify callback on jquery bounce?
Data.BouncePrompt.effect("bounce", {times:3, mode:"hide"}, 300);
I want to let it continue displaying after the 3 bounces for like 2 seconds then hide it. Is that possible?
A:
Sure thing:
Data.BouncePrompt.effect("bounce", {times:3}, 300, function () {
var $el = $(this);
setTimeout(function () {
$el.hide();
}, 2000);
});
Example: http://jsfiddle.net/6agah/
| {
"pile_set_name": "StackExchange"
} |
Q:
Alias Domain to Zend Directory
I have a ZF website at domainA.com and I'd like to alias domainB.com to something like: domainA.com/photos/album so that album would be the root of domainB.
How might this be accomplished?
A:
The first step here is to rewrite the URL to the correct route using mod_rewrite. Something like the following at the top of your exisitng .htaccess root should work:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} =domainB.com [NC]
RewriteCond %{REQUEST_URI} !^/photos/album
RewriteRule .* /photos/album/$0 [L]
This will redirect to /photos/album/ if no path is specified after domainB.com. If I remember correctly, Zend Framework isn't picky about whether your controllers/actions are terminated by a slash or not, so this should be fine. If it needs to be /photos/album for some reason, I have a solution for that as well, but it's overkill if it's not needed.
Later, your ruleset translates the URL to index.php, and Zend Framework does its routing. However, the default way Zend Framework does routing is to use REQUEST_URI, which happens to not be what we want in this case (It will be whatever was passed after domainB.com, instead of what we rewrote the request to). We actually need to use REDIRECT_URL, which is set by our new RewriteRule.
The controller request documentation describes this scenario (kind of), and explains that you can use Zend_Controller_Request_Apache404 as a drop-in request object to obtain the correct route information:
$request = new Zend_Controller_Request_Apache404();
$front->setRequest($request);
I'm fairly certain that you could also just get the current request object, and call
$request->setRequestUri($_SERVER['REDIRECT_URL']);
on it. Just condition this operation on the host, and hopefully it should all work out correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get Item from POJO in listview onClick()?
I have a POJO, which describes some model (Item?) and some custom Adapter.
I am setting my adapter for ListView and then, in onItemClick() I want to get value of one of variables which I had added Into the Item.
How I can reach this?
In my code I am doing something like:
private List<SomeItem> items = new ArrayList();
items.add(new SomeItem(firstValueString, secondValueBitmap, thirdValueString));
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(
...
@Override
public void onItemClick(){
//How to reach for example firstValueString value of currently clicked item??
}
)
A:
Use android.widget.AdapterView.OnItemClickListener:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
+ id);
SomeItem item = items.get(position); // specific item
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Frequency Counting on a Raspberry PI
I am trying to count a square wave on a Raspberry PI.
I tried a variety of approaches:
http://abyz.co.uk/rpi/pigpio/examples.html (Freq counter 1 and 2)
http://www.dnacoil.com/tools/measuring-light-intensity-with-the-tsl-235-and-a-raspberry-pi/#comment-2850
Both approaches seem to top out around a frequency of 300 which is not useful for direct light conditions .(Ok for low light.)
Data sheet of sensor: TSL235
Is there a better method for getting a square wave, 50% duty cycle on the PI
A:
The Pi is not really the best tool for the job. You have an entire operating system vying for processing time, with many processes running at the same time as yours. The only way you would be able to do it reliably would be to directly interface with the hardware and use timers and such to do the job.
Certainly trying to do anything where reading rapidly from a GPIO is going to only work at low speeds, simply because your program isn't running all the time - it's sharing time with everything else the Pi is doing.
You would be better off using a dedicated microcontroller as an interface to the Pi which takes the square wave, calculates the frequency, then reports it over a serial protocol, such as the UART or SPI connections.
| {
"pile_set_name": "StackExchange"
} |
Q:
as3 why is my public var changing?
I have a var called "currentMystery" I have reduced the issue down to these two functions
I believe. Anyway, the first time through it works and traces a var from an Array... but the second time through something is changing it to [Event type="soundComplete" bubbles=false cancelable=false eventPhase=2]
What in the code is changing this or what am I doing wrong?
Thanks so much!
Any ideas on how to keep it as the same var as it assigned here:
currentMystery = "" + Mystries[4] + "";
...
public static var Mystries:Array = new Array("null","Joyful","Luminous","Sorrowful","Glorious");
public function checkDecade(e:Event = null)
{
if (decadeCount < 6)
{
Announce = true;
currentMystery = "" + Mystries[4] + "";
prayDecade(currentMystery);
}
}
public function prayDecade(currentMystery:String)
{
//// MY ISSUE IS WITH currentMystery. First time through
//// it works but the second through it is changing to
//// something like [Event type="soundComplete" bubbles=false etc...
trace("Pray Decade called: " +currentMystery);
if (Announce)
{
/// Sets PAUSE before Announc || Add features later to all prayers
setTimeout(function()
{
MainDoc.cPrayer.text = currentMystery;
trace("Called Announce"+decadeCount);
trace("Called Announce: Mystery: " + currentMystery+" Current Decade: " +decadeCount);
theAnnounce = new Sound();
theAnnounce.load(new URLRequest("audio/Rosary/Announce/"+currentMystery+"/"+decadeCount+".mp3"));
Praying = theAnnounce.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
Announce = false;
}, 2000);
}
else
{
if (prayerCount==0)
{
trace("Our Father " + decadeCount);
//trace(love);
Begin = true;
/// Sets PAUSE before Our Father || Add features later to all prayers
setTimeout(function()
{
Begin = true;
ourFather();
}, 2000);
}
if (prayerCount >0 && prayerCount<11)
{
trace("Hail Mary " + prayerCount);
Begin = true;
hailMary();
}
if (prayerCount==11)
{
trace("Glory Be... " + prayerCount);
Begin = true;
gloryBe();
}
if (prayerCount==12)
{
trace("Oh My Jesus... " + prayerCount);
Begin = true;
ohMyJesus();
}
function ourFather(e:Event = null)
{
if (Begin)
{
Praying = OFB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, ourFather );
}
else
{
Praying = OFE.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
prayerCount++;
}
Begin = false;
}
function hailMary(e:Event = null)
{
if (Begin)
{
Praying = HMB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, hailMary );
}
else
{
Praying = HME.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
prayerCount++;
}
Begin = false;
}
function gloryBe(e:Event = null)
{
if (Begin)
{
Praying = GBB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, gloryBe );
}
else
{
Praying = GBE.play();
Praying.addEventListener(Event.SOUND_COMPLETE, checkDecade );
prayerCount++;
}
Begin = false;
}
function ohMyJesus(e:Event = null)
{
Praying = OMJ.play();
Praying.addEventListener(Event.SOUND_COMPLETE, checkDecade );
prayerCount = 0;
decadeCount++;
}
}//End if Else
}
A:
You're using the prayDecade method as a handler for the sound complete event as well as calling it directly in your code. When it is invoked as an event handler, the parameter it receives is an event object which is being cast to a string and overwriting your public variable within the local (prayDecade function) scope.
I think if you update the function as follows you'll get the results you expect (assuming currentMystery is a public variable in the class scope:
public function prayDecade(e:Event)
{
trace("Pray Decade called: " + currentMystery);
// ....
}
And when you invoke the method directly, don't pass the variable:
// Assuming currentDecade is in scope in the prayDecade method
prayDecade(/*currentMystery*/);
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.