title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Postgresql query did not terminate, after restart the service postgresql doesn't start | <p>At my work I was running a complex query. I cancelled it and went home yesterday. This morning in the back the query was impossible to be terminated, also with the 'terminate backend' functionality. A colleague of mine restarted the host machine where postgres is installed. After the machine restart, the postgres database sever would not start up. </p>
<p>In my log files I see the error:</p>
<blockquote>
<p>'pg_ctl: this data directory appears to be running a pre-existing postmaster'</p>
</blockquote>
<p>I am not sure how to handle this problem. I could try to fix it or try to extrapolate the data from the save files. What is the most logical step to take and do you know how to fix this? </p>
<p>Earlier it gave this error message : </p>
<blockquote>
<p>2016-01-28 15:52:33 GMT FATAL: lock file "postmaster.pid" already exists<br>
2016-01-28 15:52:33 GMT HINT: Is another postmaster (PID 2100) running in data directory "C:/PostgreSQL/9.1/data"?</p>
</blockquote>
<p>UPDATE... I located the file postmaster.pid and deleted it. Now I am restarting the computer and hoping it will start.</p>
<p>UPDATE... It works now. I rebooted the computer and postgres just instantly started. Happy as a child but at the same time not fully satisfied because of the following forum: <a href="https://superuser.com/questions/553045/fatal-lock-file-postmaster-pid-already-exists">https://superuser.com/questions/553045/fatal-lock-file-postmaster-pid-already-exists</a> . Here it is stated to NEVER delete the postmaster.pid because of possible data corruption. So because of that I will backup all databases I have in postgres now.</p>
<p>So if anyone can share some more light on my ICT adventure of today I would be very satisfied. That is why I will not state that this question is answered, since I have no idea what went wrong and perhaps will run into it again someday. </p> | 1 |
Adding security headers to request in CXF | <p>I created a client based on a wsdl file.</p>
<p>I am using the following code to call a Web Service:</p>
<pre><code> PrivateService ser = new PrivateService();
PrivatePortType port = ser.getPrivateSOAPPort();
BindingProvider bindingProvider = (BindingProvider) port;
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://192.168.4.48/PrivateSimulator/PrivateWebService.svc");
bindingProvider.getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY, true);
bindingProvider.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, "CreateParty");
CreatePartyRequest createReq = new CreatePartyRequest();
createReq.setParam("123456");
createReq.setCallback("http://192.168.5.106:9999/Service");
try {
CreatePartyResponse resp = port.createParty(createReq);
PartyInfo ci = resp.getPartyInfo();
System.out.println(ci.getPartyId());
} catch (WSException e) {
e.printStackTrace();
}
</code></pre>
<p>On the createParty call I accept "Object reference not set to an instance of an object" exception message.</p>
<p>This is probably because the web service was written with C#, and, most likely, it expects oasis headers, in which it store username and password values.</p>
<p>The enevelope which I could create by now is:</p>
<pre><code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<CreatePartyRequest xmlns="http://teleParty.QQQ.com/CCGW">
<param>10000903</param>
<callback>http://192.168.5.106:9999/Service</callback>
</CreatePartyRequest>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>And the required enevelope is as follows:</p>
<pre><code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<o:UsernameToken u:Id="uuid-2aae5c05-19af-43e6-8814-7d7e7a306d4d-3">
<o:Username>QQQ</o:Username>
<o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">QQQPass</o:Password>
</o:UsernameToken>
</o:Security>
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CreatePartyRequest xmlns="http://teleParty.QQQ.com/CCGW">
<param>10000903</param>
<callback>http://192.168.5.106:9999/Service</callback>
</CreatePartyRequest>
</s:Body>
</s:Envelope>
</code></pre>
<p>How can I add those headers and properties to the request?</p> | 1 |
AngularJS : function triggers twice on ng-change while selecting any option from dropdown | <p>Actually I am new to angularjs and I am facing problem which confuses me alot.
I have written angularjs controller, it populates data in dropdown menu and selection of each option it should show particular location on map. To trigger event I have used ng-change.</p>
<p>My HTML view looks like,</p>
<pre><code><select name="DeviceList" ng-model="deviceList" ng-change="filterMarkers()">
<option value="0" selected="selected">All</option>
<option ng-repeat="device in data" value="{{device.id}}">{{device.name}}</option>
</select>
</code></pre>
<p>JSON object looks like,</p>
<pre><code>[{
"id": 1,
"name": "MacVend1001",
"latitude": "12.9383145",
"longitude": "77.57274628",
"status": "ON",
"failureMessage": null,
"healthIndex": [{
"Parameter": "Voltage",
"value": "29",
"y-axis": [244, 124, 226, 372, 180, 290, 135, 350, 175, 145],
"x-axis": ["2016-01-01 13:49:32", "2016-01-02 13:48:43", "2016-01-03 13:48:43", "2016-01-04 13:48:43", "2016-01-05 13:49:32", "2016-01-06 13:48:43", "2016-01-07 13:48:43", "2016-01-08 13:48:43", "2016-01-09 13:48:43", "2016-01-10 13:48:43"],
"chart-type": "Trend"
}, {
"Parameter": "Internal Temprature",
"value": "30",
"y-axis": [44, 24, 26, 72, 80, 90, 35, 50, 75, 45],
"x-axis": ["2016-01-01 13:49:32", "2016-01-02 13:48:43", "2016-01-03 13:48:43", "2016-01-04 13:48:43", "2016-01-05 13:49:32", "2016-01-06 13:48:43", "2016-01-07 13:48:43", "2016-01-08 13:48:43", "2016-01-09 13:48:43", "2016-01-10 13:48:43"],
"chart-type": "Trend"
}, {
"Parameter": "External Temprature",
"value": "45",
"y-axis": [144, 224, 126, 372, 180, 2940, 1355, 250, 175, 345],
"x-axis": ["2016-01-01 13:49:32", "2016-01-02 13:48:43", "2016-01-03 13:48:43", "2016-01-04 13:48:43", "2016-01-05 13:49:32", "2016-01-06 13:48:43", "2016-01-07 13:48:43", "2016-01-08 13:48:43", "2016-01-09 13:48:43", "2016-01-10 13:48:43"],
"chart-type": "Trend"
}]
</code></pre>
<p>}]</p>
<p>and finally Controller is here,</p>
<pre><code>angular.module('mapsApp', [])
.controller('NewMapCtrl', function ($scope,$http) {
$scope.data=[];
$http({method:'GET',url: 'https://korbsbvm130.apac.bosch.com:8244/intelrfc/1.0/devicelist'}).success(function(API_RESPONSE){
$scope.data=API_RESPONSE;
$scope.devicelist=0;
});
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.0000, -98.0000),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city,
Name:info.name
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div><div class="infoWindowContent">' + info.city + '</div><div class="infoWindowContent">' + info.name + '</div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.Name +'<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
for (i = 0; i < $scope.data.length; i++) {
createMarker($scope.data[i]);
}
$scope.openInfoWindow = function (e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
$scope.clearMarkers = function() {
for (var i = 0; i < $scope.markers.length; i++) {
$scope.markers[i].setMap(null);
}
$scope.markers.length = 0;
}
$scope.filterMarkers = function() {
//1.select filtered cities
var devicesData;
var deviceName = $scope.deviceList;
if(deviceName == '0') {
devicesData = $scope.data;
}
else {
devicesData = $scope.data.filter(function(c){
alert("C.id="+c.id)
if(c.id == deviceName)
return c;
});
}
//2.update markers on map
$scope.clearMarkers();
for (i = 0; i < devicesData.length; i++) {
createMarker(devicesData[i]);
}
}
});
</code></pre>
<p>Now the problem is whenever I click on any option from populated dropdown it calls filtermarkers() function twice, but usually it should not. Kindly share your idea to how to get rid of it.</p>
<p>It also shows me two empty options in populated dropdown list.</p>
<p><a href="https://i.stack.imgur.com/WxQXj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxQXj.png" alt="empty options "></a></p> | 1 |
python.failure.Failure OpenSSL.SSL.Error in Scrapy (version 1.0.4) | <p>I'm working on a data scraping project and my code uses <strong>Scrapy</strong> (version <strong>1.0.4</strong>) and <strong>Selenium</strong> (version <strong>2.47.1</strong>).</p>
<pre><code>from scrapy import Spider
from scrapy.selector import Selector
from scrapy.http import Request
from scrapy.spiders import CrawlSpider
from selenium import webdriver
class TradesySpider(CrawlSpider):
name = 'tradesy'
start_urls = ['My Start url',]
def __init__(self):
self.driver = webdriver.Firefox()
def parse(self, response):
self.driver.get(response.url)
while True:
tradesy_urls = Selector(response).xpath('//div[@id="right-panel"]"]')
data_urls = tradesy_urls.xpath('div[@class="item streamline"]/a/@href').extract()
for link in data_urls:
url = 'My base url'+link
yield Request(url=url,callback=self.parse_data)
time.sleep(10)
try:
data_path = self.driver.find_element_by_xpath('//*[@id="page-next"]')
except:
break
data_path.click()
time.sleep(10)
def parse_data(self,response):
'Scrapy Operations...'
</code></pre>
<p>When I execute my code, I'm getting expected output for some urls but for others I'm getting the following error.</p>
<pre><code>2016-01-19 15:45:17 [scrapy] DEBUG: Retrying <GET MY_URL> (failed 1 times): [<twisted.python.failure.Failure OpenSSL.SSL.Error: [('SSL routines', 'SSL3_READ_BYTES', 'ssl handshake failure')]>]
</code></pre>
<p>Please provide a solution for this query.</p> | 1 |
Error When trying to add a image on android studio (java) | <p>My script is post to show a image each time I run it on android studios but I keep on getting an error each time I try to run the script it's post to show funny picture of trumps face. I am not really sure why I keep on getting an error each time i run the script because it works when I put in a image of a smiley face. </p>
<p>Here's the script:</p>
<pre><code>package com.udacity.gamedev.logging;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class LoggingDemo extends ApplicationAdapter {
// TODO: Give your ApplicationListener a log TAG]
public static final String TAG = LoggingDemo.class.getName();
SpriteBatch batch;
Texture img;
@Override
public void create() {
batch = new SpriteBatch();
img = new Texture("Trump.jpg");
// TODO: Use Gdx.app to find what ApplicationType we're running
// TODO: Use Gdx.app to log the result
Gdx.app.log(TAG, "We're running on" +
Gdx.app.getType()
);
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
}
// TODO: Run the Desktop app and find your log message
// TODO: Run the Android app and find your log message
}
</code></pre>
<p>Here's the error:
<a href="http://i.stack.imgur.com/UO5tk.jpg" rel="nofollow">enter image description here</a></p> | 1 |
How to exclude .class files from file search in Eclipse? | <p>I want eclipse to ignore all .class files when I search for a keyword in files. I don't want a particular directory to be excluded, instead I want to exclude all files of type .class</p> | 1 |
Show emails in queue | <p>I use free account <code>mandrillapp</code>. Now I've exceeded the limit (more than 25 mail in hour).</p>
<p>Can I see all email which now is in backlog of <code>mandrillapp</code>?</p> | 1 |
UVM ports: put,get,export, analysis | <p>I am trying to master in UVM, and completely lost in UVM ports. Please help better understand the ports.</p>
<p>So as I understood there are 3 main types of ports</p>
<ol>
<li>Put-> get : producer put data and consumer gets the data. This is blocking statement.</li>
<li>Put-> Export->Imp</li>
<li>Analysis->Subscriber : producer transmit the data and other subscribers gets it. This is non-blocking statement.</li>
</ol>
<p>Also there are TLM_FIFOs which allows to buffer the transaction for later usage. It has 2 types: <code>uvm_tlm_fifo</code> and <code>uvm_tlm_analysis_fifo</code>.</p>
<p>And my questions are:</p>
<ol>
<li>Is my understanding right?</li>
<li>What is the difference between get and export?</li>
<li>What is the difference between <code>uvm_tlm_fifo</code> and <code>uvm_tlm_analysis_fifo</code>?</li>
</ol>
<p>Thanks<br>
Hayk</p> | 1 |
Parse JSON { "key" : "value" } JQuery | <p>I'm makeing autocomplete fetaure.</p>
<p>This is mine ajax - json - response, representing <code>"id":"name"</code> pairs: </p>
<pre><code>// consloe:
Object {"14":"Mike","15":"John","23":"Drew","45":"Steve","52":"Andrew"}
</code></pre>
<p>which i get from: </p>
<pre><code>while($row=$result->fetch_array()){
$output[$row['user_id']] = $row['user'];
}
echo json_encode($output);
</code></pre>
<p>Im trying to make this <code><div data-user="id">name</div></code> for each of pair. But I can't handle it.. :/</p>
<pre><code>var results = JSON.parse(data);
$(results).each(function(key, value) {
$('#results').append('<div class="item">'+ value + '</div>');
})
</code></pre>
<p>Code above worked fine while I had only <code>name</code>s in json response (<code>$output[] = $row['user'];</code>). </p>
<p>But I need <code>user_id</code> to assign it into input value of chosen option. </p>
<p>This is what I've wright now:</p>
<pre><code>console.log(results);
$(results).each(function(key, value) {
console.log(key);
console.log(value);
})
// console:
// Object {"14":"Mike","15":"John","23":"Drew","45":"Steve","52":"Andrew"}
// 0
// {"14":"Mike","15":"John","23":"Drew","45":"Steve","52":"Andrew"}
</code></pre>
<p>I'm totally confused</p> | 1 |
Validate only if the field is entered in Laravel 5.2 | <pre><code>public function rules() {
return [
'num_of_devices' => 'integer'
];
}
</code></pre>
<p>I want to validate an integer field if and only if the field is entered. But above rule validates it for integer even if the field is empty. I used <code>somtimes</code>, but no result. But when I <code>var_dump($num_of_devices)</code> it is string.I am using Laravel 5.2. I think It was working fine in 5.1. </p> | 1 |
How do I use wdio.conf.js? | <p>I'm trying to use <code>webdriverio</code> with the <code>jasmine</code> test framework. I can run my test by typing <code>jasmine</code> at the command line. However, when I do <code>wdio wdio.conf.js</code> it opens a bunch of extra browsers which don't do anything. I'm just wondering what the point of the wdio.conf.js file is when I can just run jasmine at the commandline. Ultimately it's the same thing, right? However, I can't get the wdio.conf.js file to work in the same manner so it's useless to me. Perhaps I'm not managing the browser clients correctly but I don't see any guidelines on how this is commonly done. I read the documentation but it's pretty vague beyond auto-generating the wdio.conf file so that 'everything just works'. Am I supposed to use grunt or gulp to run my tests or are those tools separate from the wdio.conf idea?</p>
<p>I'm Just trying to get my head around all these different tools. All I need to do is make multiple automated tests to test a website. Thanks for your help.</p> | 1 |
how do i add vendor javascript to ember-cli 2.2 | <p>This might be a silly question stemming from unfamiliarity. I'm rewriting a project that was previously using Ember 1.7 in Ember 2.3, using Ember-cli v2.2</p>
<p>Now, in the old project, there were a couple of libraries being included manually on the index.html file, put in the scripts directory and then compiled. For example, let's say the JS asset I want to include is offline.js. </p>
<p>I understand that Ember-cli uses Bower and can be used to install bower components, like Bootstrap or moment.js and such. What about custom JS? I've put the file in offline.js, included it in index.html but that doesn't do anything. </p>
<p>I don't think I understand how to add/import vendor assets at all; how do add, say offline.js to the project and have it available throughout the application?</p> | 1 |
SourceTree how to reset on a already pushed commit | <p>How can I reset a project to a commit which is already pushend onto the remote Server?</p>
<p>If I do a usual reset, source tree wont push it onto the server because the server has a "newer" version?</p>
<p>How can I solve this problem?
Is it even possible to overrite a branch?</p> | 1 |
iOS network requests in a serial queue | <p>In my View Controller's I make network calls using a class called Client. Client is basically a wrapper around Alamofire (AFNetworking) network calls, so I have save (POST), get (GET), and delete (DELETE) methods. </p>
<p>Each view controller has an instance variable client, and user's can Create, Edit, and Delete objects like so:</p>
<pre><code>client.save(object) { error in
print(error)
}
client.delete(object)
</code></pre>
<p>I want to ensure that for a given client, the same object isn't being simultaneously deleted/modified. There may be multiple instances of Client dealing with the same user-editable objects. </p>
<p>My idea is to create a serial queue that all instances of a client will use to enqueue requests, however I'm running into issues with the closure's of each function. I want the requests to be done asynchronously (to avoid blocking main thread) and Alamofire uses closures, but I want the Client to treat the requests as synchronous so that they are performed in the order received and wait for all closures to complete before proceeding to the next request to avoid any conflicts.</p>
<p>My Client save method looks like this:</p>
<pre><code>dispatch_async(self.serialQueue) {
self.httpClient.post("url", object) { error in
// handle errors, maybe make another request, etc
}
}
</code></pre>
<p>How would I go about ensuring each request (and its closures) complete before the client executes the next request. I need to be able to support chained requests as well (so in a closure I'd make another request).</p> | 1 |
Parse error: syntax error, unexpected 'curl_setopt' (T_STRING) | <p>I wached a youtube video and came across these codes.</p>
<p>my php file index.php</p>
<pre><code><?php
//initialize session
$ch = curl_init();
//set the URL
$url = "http://localhost:81/data.php"
//set options
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execution
$json=curl_exec($ch);
//close
curl_close($ch);
//decode the json
$json=json_decode($json, true);
//loop through the results
for($i=0;$i<['Metadata']['TotalResults'];$i++){
echo "JSON : <b>First Name = </b>". $json['Result'][$i]["FirstName"]." , <b>Last Name = </b>".$json['Result'][$i]["LastName"];
}
?>
</code></pre>
<p>my json file data.php</p>
<pre><code><?php
//metadata which will contain how many resukts we have
$meta_array['TotalResults'] = 1;
$metadata = '{"Metadata" : ';
$metadata .= json_encode($meta_array). ',';
//the data
$array["FirstName"] = 'Gary';
$array["LastName"] = 'George';
$data[] = $array;
//json encode the array
$json_encoded = utf8_encode(json_encode($data));
echo $metadata . ' "Result" : '.$json_encoded. '}' ;
exit();
?>
</code></pre>
<p>I am continuously getting the above mentioned error.</p>
<p>I am new to jason and curl.
please help me to solve my problem.</p>
<p>thanks in advance :)</p> | 1 |
How to hide a Snackbar and show a new one right after that? | <p>I show a Snackbar indefinitely. If the Bluetooth gets turned off, I want to hide it and show a new one to tell the users that they have to turn on the bluetooth. I dismiss the previous Snackbar before showing the new one, but still only the old Snackbar stays visible.</p>
<pre><code>activeSnackbar.dismiss();
Snackbar.make(parent, "Bluetooth is off", Snackbar.LENGTH_INDEFINITE)
.setAction("Turn on", new View.OnClickListener() {
@Override
public void onClick(View v) {
BluetoothUtil.enableBluetooth(main);
}
}).show()
</code></pre>
<p>How can I make the old Snackbar disappear before showing the new one?</p> | 1 |
Jersey on Spring Boot - ApplicationPath | <p>Is there a more programmatic way, equivalent to the below config:</p>
<pre><code>@ApplicationPath("api")
public class MyResourceConfig extends ResourceConfig {
</code></pre>
<p>, of setting the application path for Jersey app? I wanted to make it configurable and maybe make use something like:</p>
<pre><code>property("jersey.config.<application.path>", api);
</code></pre>
<p>with addtitinal:</p>
<pre><code>@ConfigurationProperties(prefix = "jersey")
public class MyResourceConfig extends ResourceConfig {
@Setter @Getter protected String api;
</code></pre> | 1 |
MVC6 EF7 Viewcomponent ajax refresh issues | <p>In reference to <a href="https://stackoverflow.com/questions/32618759/viewcomponent-alternative-for-ajax-refresh">Viewcomponent alternative for ajax refresh</a>. I can't get the ajax to refresh in MVC6. The JavaScript container finds the Div value but the data is not updating. Any ideas would be appreciated!</p>
<p>ViewComponent - Default.cshtml:</p>
<pre><code>@model IEnumerable<My.Models.Queue>
@foreach (var item in Model)
{
@item.Queue
}
</code></pre>
<p>Index.cshtml:</p>
<pre><code><div id="Queue" class="blink">@Component.Invoke("Queue")</div>
</code></pre>
<p>javascript:</p>
<pre><code>var container = document.getElementById("Queue");
var refreshComponent = function () {
$.get("Shared/Components/Queue", function (data) { container[data]; });};
$(function () { window.setInterval(refreshComponent, 1000); });
</code></pre> | 1 |
How to use NVIDIA K80? | <p>The machine has 4 NVIDIA K80s setuped and the outputs of <code>nvidia-smi</code> are the information of the 4 cards. Their GPU IDs are <code>0,1,2,3</code>. Each K80 have two types of GPU memory: <code>FB</code> and <code>BAR1</code>, both have 12 Gb. But the CUDA programs always use the <code>FB</code> memory, with the <code>BAR1</code> memory left be free. When the CUDA programs allocate more than 12 Gb GPU memory in each card, an error of <code>Out of memory</code> will be occurred, but the <code>BAR1</code> memory still be not used. </p>
<p>How could I use the <code>BAR1</code> memory correctly in this setting?</p>
<p><strong>UPDATED</strong>
The partial output of <code>nvidia-smi</code> is</p>
<pre><code> Compute Mode:
< Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >
> Peer access from Tesla K80 (GPU0) -> Tesla K80 (GPU1) : Yes
> Peer access from Tesla K80 (GPU0) -> Tesla K80 (GPU2) : No
> Peer access from Tesla K80 (GPU0) -> Tesla K80 (GPU3) : No
> Peer access from Tesla K80 (GPU1) -> Tesla K80 (GPU0) : Yes
> Peer access from Tesla K80 (GPU1) -> Tesla K80 (GPU2) : No
> Peer access from Tesla K80 (GPU1) -> Tesla K80 (GPU3) : No
> Peer access from Tesla K80 (GPU2) -> Tesla K80 (GPU0) : No
> Peer access from Tesla K80 (GPU2) -> Tesla K80 (GPU1) : No
> Peer access from Tesla K80 (GPU2) -> Tesla K80 (GPU3) : Yes
> Peer access from Tesla K80 (GPU3) -> Tesla K80 (GPU0) : No
> Peer access from Tesla K80 (GPU3) -> Tesla K80 (GPU1) : No
> Peer access from Tesla K80 (GPU3) -> Tesla K80 (GPU2) : Yes
</code></pre> | 1 |
Issue with materialize-css and Webpack, module with an equal name when case is ignored, JQuery | <p>I have a basic single page React/Redux app that i am bundling using Webpack, all is working fine except the following error when i try to load the materialise-css js files. I have tried loading from the NPM module and the compiles source and the errors are the same.</p>
<pre><code>WARNING in ./~/jQuery/dist/jquery.js
There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.
WARNING in ./~/jquery/dist/jquery.js
There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.
</code></pre>
<p>I am loading everything at the top of my entry file as follows:</p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import App from './components/app'
import reducers from './reducers'
require('../materialize/css/materialize.css');
require('../materialize/js/materialize.js');
require("../style/main.scss");
</code></pre>
<p>and JQuery is loaded from an NPM module as follows:</p>
<pre><code>new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
</code></pre>
<p>Now everything still works, it loads all the fonts, js files, and everything works/looks correct in the application, but a warning is there for a reason so i would really like to make it go away!</p>
<p>Let me know if you need any more information.</p>
<p>You can view the full source code here <a href="https://github.com/gazzer82/freeCodeCamp_Recipes" rel="nofollow">https://github.com/gazzer82/freeCodeCamp_Recipes</a></p>
<p>Thanks</p> | 1 |
How to remove special char in golang when reading file? | <p>I have a file like this:
<a href="http://i.stack.imgur.com/KY4Ai.png" rel="nofollow">Each line represents a Website</a></p>
<pre><code>1 www.google.com$
2 www.apple.com$
3 www.facebook.com$
</code></pre>
<p>I read it in golang like this:</p>
<pre><code>type ListConf struct {
File string
Datas map[string]struct{}
}
func loadListConf(conf *ListConf, path string) {
file, err := os.Open(path + "/" + conf.File)
if err != nil {
fmt.Println("Load conf " + conf.File + " error: " + err.Error())
return
}
defer file.Close()
conf.Datas = make(map[string]struct{})
buf := bufio.NewReader(file)
end := false
for !end {
line, err := buf.ReadString('\n')
if err != nil {
if err != io.EOF {
fmt.Println("Load conf " + conf.File + " error: " + err.Error())
return
} else {
end = true
}
}
item := strings.Trim(line, "\n")
if item == "" {
continue
}
conf.Datas[item] = struct{}{}
}
}
</code></pre>
<p>But when I search key such like "www.google.com" in the map, it shows that there is not a "www.google.com" in the map.</p>
<pre><code>website := "www.google.com"
if _, ok := conf.Datas[website]; ok {
fmt.Printf("%s is in the map.", website)
} else {
fmt.Printf("%s is not in the map.", website)
}
</code></pre>
<p>It print "www.google.com is not in the map".
I found that a ^M in the end of each key in the map, my question is how can I remove the ^M character?</p>
<pre><code>www.google.com^M
www.apple.com^M
www.facebook.com^M
</code></pre> | 1 |
shareReplay in RxJS 5 | <p>According to the RxJS 5 <a href="https://github.com/ReactiveX/RxJS/blob/master/MIGRATION.md#operators-renamed-or-removed" rel="noreferrer">MIGRATION.md</a> it looks like <code>shareReplay()</code> been removed. </p>
<ol>
<li>Why?</li>
<li>Does <code>.publishReplay(1).refCount()</code> faithfully replicate the behaviour? Basically I need to replay the single most recent data set to any new subscribers.</li>
</ol> | 1 |
Why doesn't a generic NSDictionary warn me about incorrectly-typed key inserts/assignments? | <p>Why don't the following <code>NSDictionary</code>/<code>NSMutableDictionary</code> calls produce an error or warning?</p>
<p>I expect an error here because the rhs <code>NSDictionary</code> literal doesn't match the generic types of the <code>NSDictionary</code> lhs local variable.</p>
<pre><code>NSDictionary<NSString *, NSNumber *> *foo = @{ @(42) : @"foo" };
</code></pre>
<p>I expect an error here because the key type doesn't match the <code>NSMutableDictionary</code>'s key generic type:</p>
<pre><code>NSMutableDictionary<NSString *, NSNumber *> *foo = [NSMutableDictionary new];
// neither of these calls produces an error. :(
foo[@(42)] = @(42);
[foo setObject:@(42) forKey:@(42)];
</code></pre>
<p>I see an error when I try to assign an improperly-typed value, so I know generics errors are working somewhat:</p>
<pre><code>NSMutableDictionary<NSString *, NSNumber *> *foo = [NSMutableDictionary new];
foo[@"foo"] = @"bar";
</code></pre>
<p>Causes the following warning:</p>
<pre><code>Foo.m:81:16: Incompatible pointer types sending 'NSString *' to parameter of type 'NSNumber * _Nullable'
</code></pre>
<p>Why don't literal assignment or improperly-typed keys cause warnings/errors?</p>
<p><a href="http://www.openradar.me/25060179" rel="nofollow">I filed this as a radar.</a></p> | 1 |
How do I convert strings to enums in SystemVerilog? | <p>I have command-line plusargs that I want to map to enumerated values.</p>
<pre><code> vsim foo +MY_PLUSARG=BAR
</code></pre>
<p>How do I get the string <code>"BAR"</code> to become the enum <code>BAR</code>?</p> | 1 |
Android Gradle compiling commons-io creates duplicate in library tree | <p>I'm trying to build and maintain an old application for work but I can't get past the build phase. In my <code>app/build.gradle</code> file I have </p>
<pre><code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.apache.commons:commons-io:1.3.2'
//some more libraries compiled as well
}
</code></pre>
<p>but get the following error when trying to execute:</p>
<blockquote>
<p>Error:Execution failed for task ':myApp'.
com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class</p>
</blockquote>
<p>This is almost certainly because when I compile that jar, at the top of my External Libraries tree, this is generated:</p>
<p><a href="https://i.stack.imgur.com/1Q2SI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1Q2SI.png" alt="enter image description here"></a></p>
<p>Why is this happening, and how can I get it to stop so I can complete the build?</p> | 1 |
Using SQL as Session Cache in Azure | <p>I am currently looking for the best way to use session caching in an Azure Webservice. Because multiple Instances are used, standard asp.net Session state does not work.</p>
<p>I found some documents that this can be solved by using an external session state provider which allows using a shared cache (Redis cache) or SQL as an external provider.</p>
<p>But while I found a lot of documentations how to configure the Redis cache, I did not find a single example how to configure an Azure-SQL-Database for caching.</p>
<p>If this is still supported in Azure: Can you provide an example?</p> | 1 |
Embedding Liferay site as iframe is not working on external site | <p>I have got a Liferay page which has Portlet. I tried to embed this page as an iframe in external site which is not in Liferay but it is giving the error in console as: </p>
<blockquote>
<p>Refused to display '<a href="https://example.com" rel="noreferrer">https://example.com</a>' in a frame because it set
'X-Frame-Options' to 'SAMEORIGIN'</p>
</blockquote>
<p>I am using html iframe tag like below to embed it:</p>
<pre><code><iframe allowfullscreen="" frameborder="0" height="400" src="https://example.com" style="border:0" width="500"></iframe>
</code></pre>
<p>Following this thread I tried putting "&output=embed" at end of the URL but it didn't work: <a href="https://stackoverflow.com/questions/20498831/refused-to-display-in-a-frame-because-it-set-x-frame-options-to-sameorigin">Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'</a> </p>
<p>I am not sure whether I need to change setting or any code on Liferay side to make it work. Any idea what is causing this and how can I fix this? </p> | 1 |
UI design for Microsoft Access - what is possible? | <p>I'm a graphic designer/web-UI designer by trade but have some (albeit limited) knowledge of Access. I haven't used it for a few years now but have been asked by a company to redesign the front end of their split database that was built using Access 2010. They had a programmer design the whole database, and it works well, but they do not like the actual appearance of the front-end so they have asked me to update it with some 'modern design' so-to-speak (i.e. stylise the buttons, fieds etc.)</p>
<p>I'm just wondering, what options do I have with this? Is there any way to use CSS as such to stylise the front-end? Or is there any built-in design tools that are useful? I plan to produce concepts using Photoshop to show them but it's knowing the limitations of what can be done with Access in terms of the front-end design. Any help would be appreciated!</p> | 1 |
Dynamically set install dir in WiX from environment variable | <p>I'm new to MSI development (with WiX or otherwise) and I'm trying to read the value of an environment variable and use it as the installation directory. My msi is gui-less too and giving the user to override the path is not permitted.</p>
<p>I can successfully read the var with:</p>
<pre><code><SetProperty
Id="TARGETINSTALLDIR"
Value="[%MY_ENV_VAR]\My\Install\Path"
After="LaunchConditions"
Sequence="first" />
</code></pre>
<p>I can see in the msi logs the correct path retrieved. </p>
<p>I have tried the following to set the returned path:</p>
<pre><code><Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="APPLICATIONROOTDIRECTORY" Name="[TARGETINSTALLDIR]"/>
</Directory>
</code></pre>
<p>Also,</p>
<pre><code><Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="APPLICATIONROOTDIRECTORY" Name="TARGETINSTALLDIR"/>
</Directory>
</code></pre>
<p>Failing that, I also tried to read the directory path within the ROOT Directory as shown below</p>
<pre><code><Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ROOT" Name="[%MY_ENV_VAR]">
<Directory Id="My" Name="My">
<Directory Id="Install" Name="Install">
<Directory Id="APPLICATIONROOTDIRECTORY" Name="Path"/>
</Directory>
</Directory>
</Directory>
</Directory>
</code></pre>
<p>Is there some syntax I'm missing or am I fundamentally misunderstanding how this should be done?</p> | 1 |
connecting angularJS to plotly | <p>So I want to use angularJS to get data from a server and plot the data using Plotly. I am running a server in the background. The HTML I am using is shown below. I think it is pretty straight forward. </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Testign Plotly</title>
<script type="text/javascript" src='plotly.min.js'></script>
<script type="text/javascript" src='jquery.min.js'></script>
<script type="text/javascript" src='angular.min.js'></script>
<script type="text/javascript" src='plotApp.js'></script>
</head>
<body ng-app='myApp'>
<div id="graph" style="width:600px;height:250px;"></div>
<script type="text/javascript" ng-controller='plotXY'>
// var data = [{
// x:[1,2,3,4],
// y:[5,3,6,12],
// }];
Plotly.plot( $('#graph')[0], {{data}} , {margin: {t:0}});
</script>
<hr><div ng-controller='plotXY'>{{data}}</div>
</body>
</html>
</code></pre>
<p>I have the angularJS script <code>plotApp.js</code> as shown below, also very simple ...</p>
<pre><code>var app = angular.module('myApp', []);
app.controller('plotXY', function($scope, $http){
$scope.data = {};
$scope.refresh = function(){
$http.get('http://localhost:8080/data').success(function(data){
$scope.data = {};
for(k in data){$scope.data[k] = data[k].map(Number);}
$scope.data = [$scope.data];
});
};
$scope.refresh();
});
</code></pre>
<p>Now, The compiled HTML for this (saved from the browser) is shown below ...</p>
<pre><code><!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252"><style type="text/css">@charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>
<title>Testign Plotly</title>
<script type="text/javascript" src="Testign%20Plotly_files/plotly.js"></script><style></style>
<script type="text/javascript" src="Testign%20Plotly_files/jquery.js"></script>
<script type="text/javascript" src="Testign%20Plotly_files/angular.js"></script>
<script type="text/javascript" src="Testign%20Plotly_files/plotApp.js"></script>
</head>
<body class="ng-scope" ng-app="myApp">
<div id="graph" style="width:600px;height:250px;"></div>
<script class="ng-scope" type="text/javascript" ng-controller="plotXY">
// var data = [{
// x:[1,2,3,4],
// y:[5,3,6,12],
// }];
Plotly.plot( $('#graph')[0], {{data}} , {margin: {t:0}});
</script>
<hr><div class="ng-scope ng-binding" ng-controller="plotXY">[{"y":[1.26642e-14,2.8044e-14,6.1484e-14,1.33457e-13],"x":[-10,-9,-8,-7]}]</div>
</body></html>
</code></pre>
<p>As you can tell, the portion within the <code>div</code> gets updates with the right data. However, that within the script doesn't! </p>
<p>Just so you know, If I use the <code>data</code> variable (the one that is commented out), I am able to see the plot. So Plotly is working.</p>
<p>I want the client to pull data from the server and have plotly display it. I can do it if I create the entire page from the server and send it over. However, I think that this way is much better. However, for some reason, I dont seem to be able to connect the data source in Plotly, to that in angularJS. I would really appreciate some help ...</p> | 1 |
Android using animation to make an object fall towards the ground using gravity | <p>I am new to Android development and I am trying to create an image at the top of the screen and make it fall to the bottom. I have been looking around and cannot get a straight answer or pointer in the correct direction. A lot of the examples I am finding are out of date and many of the methods don't work any more. </p>
<p>I have an image in my drawable folder that I would like to create after 10 seconds and have it fall towards the ground like it has gravity.</p>
<p>I have seen a lot about ObjectAnimator, canvas, velocity, animation. I am not sure where to start.</p> | 1 |
React how to remove listners correctly in componentWillUnmount, why do I need the bind in the constructor? | <p>I'm a bit confused, what is the difference between this sintax:</p>
<pre><code> constructor(props) {
super(props);
this.state = {
openPane: false
}
this.togglePaneHelper = this.togglePaneHelper.bind(this);
}
componentDidMount() {
document.body.addEventListener('click', this.togglePaneHelper);
}
componentWillUnmount() {
document.body.removeEventListener('click', this.togglePaneHelper);
}
</code></pre>
<p>and this one:</p>
<pre><code> constructor(props) {
super(props);
this.state = {
openPane: false
}
}
componentDidMount() {
document.body.addEventListener('click', this.togglePaneHelper.bind(this));
}
componentWillUnmount() {
document.body.removeEventListener('click', this.togglePaneHelper);
}
</code></pre>
<p>My concern is that the second syntax isn't removing correctly the listner and it cause this warning:</p>
<pre><code>Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
</code></pre> | 1 |
Python Machine Learning/Data Science Project Structure | <p>I'm looking for information on how should a Python Machine Learning project be organized. For Python usual projects there is <a href="http://cookiecutter.readthedocs.org/en/latest/" rel="nofollow">Cookiecutter</a> and for R <a href="http://projecttemplate.net/getting_started.html" rel="nofollow">ProjectTemplate</a>. </p>
<p>This is my current folder structure, but I'm mixing Jupyter Notebooks with actual Python code and it does not seems very clear.</p>
<pre><code>.
├── cache
├── data
├── my_module
├── logs
├── notebooks
├── scripts
├── snippets
└── tools
</code></pre>
<p>I work in the scripts folder and currently adding all the functions in files under my_module, but that leads to errors loading data(relative/absolute paths) and other problems.</p>
<p>I could not find proper <em>best practices</em> or good examples on this topic besides this <a href="https://github.com/rafacarrascosa/samr" rel="nofollow">kaggle competition solution</a> and some Notebooks that have all the functions condensed at the start of such Notebook.</p> | 1 |
UnicodeDecodeError after upgrading to django-rest-framework 3 | <p>Under django-rest-framework 2, the following works fine:</p>
<pre><code>from rest_framework import rest_response, generics
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
class SomeView(generics.GenericAPIView):
renderer_classes = JSONRenderer, BrowsableAPIRenderer
def get(self, request, *args, **kwargs):
...
# Build a response dict with non-ascii in it
...
return rest_response.Response(some_dict_with_non_ascii_in_it_somewhere)
</code></pre>
<p>I didn't have to explicitly encode any non-ascii...</p>
<p>However, after upgrading to DRF 3, the same code now throws the following error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
return self.application(environ, start_response)
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/whitenoise/base.py", line 119, in __call__
return self.application(environ, start_response)
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
response = self.get_response(request)
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/django/core/handlers/base.py", line 261, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/django_extensions/management/technical_response.py", line 5, in null_technical_500_response
six.reraise(exc_type, exc_value, tb)
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/django/core/handlers/base.py", line 164, in get_response
response = response.render()
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/django/template/response.py", line 158, in render
self.content = self.rendered_content
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/rest_framework/response.py", line 71, in rendered_content
ret = renderer.render(self.data, media_type, context)
File "/Users/troy/.virtualenvs/publisher/lib/python2.7/site-packages/rest_framework/renderers.py", line 104, in render
separators=separators
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 210, in encode
return ''.join(chunks)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 671: ordinal not in range(128)
</code></pre>
<p>I'm guessing DRF 3 now has some new config value, somewhere, that was default under DRF 2. I've tried setting the REST_FRAMEWORK <code>UNICODE_JSON</code> setting to <code>True</code>, but I still get the same error...</p>
<p>Is there a setting that can make that piece behave as DRF 2 did? or does DRF 3 need me to hunt down the non-ascii character in my dictionary and manually encode it?</p> | 1 |
jasig cas too many redirects issue | <p>I'm trying to secure a spring-boot web application using spring security and spring-security-cas (SSO with Jasig CAS).</p>
<p>I'm facing a too many redirects error when trying to access a protected resources. The project is available <a href="https://github.com/ikane/microservices-demo-security-cas.git" rel="nofollow">here</a></p>
<p>Do you see any error in my configuration?</p>
<p>Thanks in advance</p>
<p><a href="http://i.stack.imgur.com/1ZNgE.png" rel="nofollow">redirect loop error screenshot</a></p> | 1 |
How to get current time in datetime format in XML file of odoo? | <p>My code is as follows....</p>
<p>My Model is ...</p>
<pre><code>class Today_Status(models.Model):
_name = 'today.status'
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
starttime = fields.Many2one(comodel_name='book.meeting')
</code></pre>
<p>My XML file is as follows...</p>
<pre><code><record model="ir.actions.act_window" id="dashboard-menu">
<field name="name">DashBoard</field>
<field name="res_model">today.status</field>
<field name="view_type">form</field>
<field name="view_mode">tree,form</field>
<field name="domain">[("start_time", ">=", "current_time")]</field>
<field name="view_id" ref="dash-view"/>
</record>
</code></pre>
<p>I want to get current time in XML or i want to use the variable current_time specified in model in the XML file. How is it possible?</p> | 1 |
oauth2client.client.ApplicationDefaultCredentialsError: 'type', 'authorized_user' or 'service_account' values should be set | <p>I'm trying to access the BigQuery API from my Python script. At the moment I'm experimenting only trying to get <a href="https://cloud.google.com/bigquery/bigquery-api-quickstart#completecode" rel="nofollow">this sample</a> to run.</p>
<p>I've created credentials, set the environment variable and ran the script, only to get this error:</p>
<pre><code>oauth2client.client.ApplicationDefaultCredentialsError: An error was encountered while reading json file: /PATH/TO/MY/google_api_credentials.json (pointed to by GOOGLE_APPLICATION_CREDENTIALS environment variable): 'type' field should be defined (and have one of the 'authorized_user' or 'service_account' values)
</code></pre>
<p>Well, it isn't set in the JSON file:</p>
<pre><code>{"installed":{"client_id":"blahblah.apps.googleusercontent.com","project_id":"blahblah","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"blahblah","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
</code></pre>
<p>Since I downloaded the JSON from the Google console, it should just work? I do not know what 'type' I would need to define.</p> | 1 |
Web API 2 Ninject "error occurred when trying to create a controller" | <p>I'm getting this error when loading my controller.</p>
<pre><code>An error occurred when trying to create a controller of type 'MembersController'. Make sure that the controller has a parameterless public constructor.
</code></pre>
<p>I have added </p>
<pre><code>System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);
</code></pre>
<p>to the <code>NinjectWebCommon</code> class after registering the bindings.</p>
<p>And I have registered the relevant services. see <strong><em>EDIT</em></strong> </p>
<p><s></p>
<pre><code> private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IMembersService, MembersService>();
kernel.Bind<MemberContext, MemberContext>();
}
</code></pre>
<p></s>
Here are the ninject packages I have added - </p>
<pre><code> <package id="Ninject" version="3.2.0.0" targetFramework="net451" />
<package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net451" />
<package id="Ninject.Web.Common" version="3.2.0.0" targetFramework="net451" />
<package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net451" />
<package id="Ninject.Web.WebApi" version="3.2.4.0" targetFramework="net451" />
<package id="Ninject.WebApi.DependencyResolver" version="0.1.4758.24814" targetFramework="net451" />
</code></pre>
<p>What am I missing? </p>
<p><strong><em>EDIT</em></strong> </p>
<p>Thanks to my conversation with Jerrod Horton (below) I realized I doing the binding incorrectly. </p>
<p>Should have been </p>
<pre><code>private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IMembersService>().To<MembersService>();
kernel.Bind<MemberContext>().To<MemberContext>();
}
</code></pre> | 1 |
In Spark Json to Csv converting? | <p>I have a Json object like bellow</p>
<pre><code>{"Event":"xyz","Name":"test","Prog":0,"AId":"367","CId":"11522"}
</code></pre>
<p>using bellow spark script,I have converted into csv</p>
<pre><code> val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val df = sqlContext.load("org.apache.spark.sql.json", Map("path" -> "test1.json"))
df.save("com.databricks.spark.csv", SaveMode.ErrorIfExists, Map("path" -> "datascv", "header" -> "true"))
</code></pre>
<p>I am able to convert into CSV file,My Output is</p>
<pre><code>AId,CId,Event,Name,Prog
367,11522,xyz,test,0
</code></pre>
<p>but here header of csv is in ascending order,but I want to maintain my csv file header in customized format like bellow i.e same as my json order.</p>
<pre><code>Event,Name,Prog,AId,CIdEvent,Name,Prog,AId,CId
</code></pre>
<p>Please help me with this.</p>
<p>Thanks in advance.</p> | 1 |
Explanation of the @ variables inside Rails models | <p>I've worked through a few Rails applications which are using @ attribute variables (which are already attr_accessible) in the models. I was having a tough time getting information on this but from what I gather <code>name</code> and <code>@name</code> are the same thing in a model but im probably incorrect on this. </p>
<p>How do these @ variables work and why would one ever use the @ symbol variables?</p> | 1 |
Braintree - What to post for paymentMethodNonce | <p>I am just getting started with Braintree and using it's API in PHP.</p>
<p>I have come across one thing, the "paymentMethodNouce" which is posted from the HTML file.</p>
<p>My question, is what does this need to include? I.e. do we post the send the credit card, billing information through here? And in what content does the form need to be in? I.e. Should it be like this:</p>
<pre><code> <form>
<input type="text" name="payment['creditcard']" value="124214124" />
<input type="text" name"payment['billingaddress']" value="12312313"/>
</form>
</code></pre>
<p>If this is not correct, what actually get's passed through to the <code>paymentMethodNonce</code> and how is the credit card details handled?</p> | 1 |
java.sql.Timestamp to Joda Instant and vice versa | <p>Is this possible? I found a few solution for converting to and from localDateTime like can be seen <a href="http://www.roytuts.com/conversion-of-joda-date-time-to-sql-timestamp-and-vice-versa/" rel="nofollow noreferrer">here</a></p>
<p>But I can't find a solution for Joda Instant...</p> | 1 |
Location Reload Jasmine | <p>I got a problem with mocking the location reload functionality within Jasmine. I tried several methods (<a href="https://stackoverflow.com/questions/23344058/location-reload-in-jasmine">method 1</a> , <a href="https://stackoverflow.com/questions/27306194/mock-window-location-reload-in-jasmine-testing">method 2</a>) to mock any location reload events but with no luck. </p>
<p>My situation is the following thing. I have a rather simple function:</p>
<pre><code>function TestCall(xhr) {
if (xhr === 401) {
location.reload();
}
}
</code></pre>
<p>I tried creating the following Jasmine tests:</p>
<pre><code>it("FakeCall", function (){
spyOn(TestCall, 'reload').and.callFake(function(){});
TestCall(401);
expect(TestCall).toHaveBeenCalled(); // this should check if reload functionality have been called
});
</code></pre>
<p>I want to mock the location reload function but I have no clue why this does not work. Can anyone guide/tell me what I do wrong?</p>
<p>Total code:</p>
<pre><code>describe("multiple scripts", function () {
describe("2# FakeCall", function() {
function TestCall(xhr) {
if (xhr === 401) {
location.reload();
}
}
it("2.1 # Reload", function (){
spyOn(location, 'reload');
TestCall(401);
expect(location.reload).toHaveBeenCalled();
});
});
});
</code></pre> | 1 |
Send email to confirm registration with FOSUserBundle | <p>I use FOSUserBundle to perform login/registration on my application.</p>
<p>I want a new user to confirm his email by sending him a confirmation email.</p>
<p>After reading the official documentation and different tutorials i have the same error : </p>
<blockquote>
<p>The check email page appear after i register a user but i don't receive the email.</p>
</blockquote>
<p>This is my configurations </p>
<pre><code>#config/config.yml
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
fos_user:
db_driver: orm
firewall_name: main
user_class: VK\UserBundle\Entity\User
registration:
confirmation:
enabled: true
from_email:
address: [email protected]
sender_name: Demo registration
service:
mailer: fos_user.mailer.twig_swift
</code></pre>
<p>And this is my parameters</p>
<pre><code>config/parameters.yml
parameters:
mailer_transport: smtp
mailer_host: smtp.gmail.com
mailer_encryption: ssl
mailer_user: [email protected]
mailer_password: my_password
</code></pre>
<p>Please can some one help me solve this issue ? thank's</p> | 1 |
Vim - how to join lines using matching pattern | <p>I have a txt file that contains contact info for businesses. Currently, each line contains a different piece of data for the business. I'm attempting to construct a pipe-delimited file with all the info for each business on a single line. The catch is that there are a different number of lines for each business. So the file looks like this:</p>
<pre class="lang-none prettyprint-override"><code>Awesome Company Inc|
Joe Smith, Owner|
Jack Smith, Manager|
Phone: (555)456-2349|
Fax: (555)456-9304|
Website: www.awesomecompanyinc.com [HYPERLINK: http://www.awesomecompanyinc.com]|
* Really Cool Company|
* Line of business: Awesomesauce|
Killer Products LLC|
Jack Black, Prop|
Phone: (555)234-4321|
Fax: (555)912-1234|
1234 Killer Street, 1st Floor|
Houston, TX 77081|
* Apparel for the classy assassin|
* Fearful Sunglasses|
* Member of the National Guild of Killers since 2001|
* Line of business: Fuhgettaboutit|
</code></pre>
<p>etc.</p>
<p>So I can use <code>:g/<pattern>/j</code> to join lines within a pattern but I'm having trouble working out what the pattern should be. In the example above, lines 1-9 need to joined, and then lines 10-19.</p>
<p>The key is the lines that begin with 2 spaces and an asterisk:</p>
<pre class="lang-none prettyprint-override"><code> * Line of business
</code></pre>
<p>The pattern should basically say: "Starting with the first line beginning with a letter, join all lines until the first line after the last line beginning with <code>\ \ \*\</code>, then repeat until the end of the file."</p>
<p>How would I write this? Should I maybe do it in two steps - i.e., is there a way to first join all the lines starting with letters, then all the lines starting with <code>\ \ \*\</code>, then join each resulting pair?</p> | 1 |
Why does Rotativa always generate my login page? Why is it slow? | <p>I was using this Rotativa 1.6.4 code example to generate a PDF from a page in my .NET MVC 5 app.</p>
<pre><code>public ActionResult PrintIndex()
{
var a = new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
a.Cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k].Value);
a.FormsAuthenticationCookieName = System.Web.Security.FormsAuthentication.FormsCookieName;
a.CustomSwitches = "--load-error-handling ignore";
return a;
}
public ActionResult Index(string name)
{
ViewBag.Message = string.Format("Hello {0} to ASP.NET MVC!", name);
return View();
}
</code></pre>
<p>It was not printing the Index page, but instead was printing my login page.</p>
<p>Once I fixed the authentication issue, PDF generation was extremely slow even with <code>CustomSwitches</code>. (Several minutes)</p>
<p>The above code might actually work for you - it got around the authentication issue using the <code>Cookies</code> property, but it was way too slow for me.</p>
<p>How do I print a secure page as well as do it quickly?</p> | 1 |
ADFS + OpenID Connect email claim and external ADFS | <p>I'm having difficulties setting up ADFS with OpenID Connect on Windows Server 2016.</p>
<p>I've setup AD for testing and I can successfully authenticate, however the email claim is not in the id token.</p>
<p>Additionally I've setup an external ADFS in the Claims Provider trust. It is displayed as an option, however upon logging in I get the error:</p>
<pre><code> MSIS9642: The request cannot be completed because an id token is required but the server was unable to construct an id token for the current user.
</code></pre>
<p>Anybody have suggestions on how to fix this?</p> | 1 |
VS 2013 : Add Existing Project does not physically copy files. How do you do that? | <p>I have created a new Class Library where I add a lot of existing projects so that I can create one <code>.dll</code> which I reference to use these classes in multiple solutions.
I added all the projects using as <code>Add Existing Project</code> and created my Class Library Solution.
Now I see that the files have not actually been copied to the new Class Library location but as present as links. </p>
<p>How to I trigger a copy?</p> | 1 |
How to call an Erlang function in Elixir | <p>What is the format to call an Erlang function in Elixir?</p>
<p>Specifically, how can I call the function in <code>iex</code> and where can I find a list of modules and functions available from Erlang.</p> | 1 |
'ClaimsPrincipal' does not contain a definition for 'GetUserId' | <p>Some time ago, I created a project using the ASP.Net 5 web application template.
I recall the project built at the time.</p>
<p>Now when I try and build an old project I created I have the error</p>
<pre><code>Severity Code Description Project File Line Suppression State
Error CS1061 'ClaimsPrincipal' does not contain a definition for 'GetUserId'
and no extension method 'GetUserId' accepting a first argument of type 'ClaimsPrincipal' could be found
(are you missing a using directive or an assembly reference?) KGWebsite.DNX 4.5.1, KGWebsite.DNX Core 5.0
E:\EShared\Dev2016\KG.Website\KGWebsite\src\KGWebsite\Controllers\Web\ManageController.cs 291 Active
</code></pre>
<p>When I create a new project from scratch using he same template, the new project will build. I am having problems troubleshooting the difference between the two projects.</p>
<p>Both use DNX4.5.1 which shows in the solution explorer as having a reference to Microsoft.AspNet.Identity ( 3.0.0-rc1-final)</p>
<p>When I drill into the metadata for Microsoft.AspNet.Http in the working copy I have</p>
<pre><code>#region Assembly Microsoft.AspNet.Http.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Users\kirsten\.dnx\packages\Microsoft.AspNet.Http.Abstractions\1.0.0-rc1-final\lib\net451\Microsoft.AspNet.Http.Abstractions.dll
#endregion
</code></pre>
<p>In the non working copy I have </p>
<pre><code>#region Assembly Microsoft.AspNet.Mvc.ViewFeatures, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Users\kirsten\.dnx\packages\Microsoft.AspNet.Mvc.ViewFeatures\6.0.0-rc1-final\lib\net451\Microsoft.AspNet.Mvc.ViewFeatures.dll
#endregion
</code></pre>
<p>What steps should I be taking to correct the project that is not working?</p> | 1 |
"pause" for every host | <p>Before rolling updates I want to set downtime for every host in our monitoring tool. I created a custom module for this. There might be problems when setting downtime which can not be fixed on our end. In that case I want to give the user the choice to decide if the deployment should be aborted or continued without setting downtime.</p>
<p>So let's say I call my module like this:</p>
<pre><code>- downtime:
duration: 5m
comment: whatever
ignore_errors: true
register: downtime
</code></pre>
<p>So I'm ignoring the errors to be able to proceed. Otherwise hosts for which setting the downtime failed would not be processed any further.</p>
<p>In the next step I would like the user to manually confirm if he wants to proceed for every host that has no downtime set.</p>
<pre><code>- name: Request user confirmation to proceed in case downtime could not be set
pause:
prompt: 'Downtime could not be set for all hosts. Do you want to proceed? Press return to continue. Press Ctrl+c and then "a" to abort'
when: "{{ downtime | failed }}"
</code></pre>
<p>Unfortunately the <code>pause</code> module (actually it's an action plugin) would only pause for the first host that was processed. So if the first host failed, it will pause, if the first host passed and all other hosts failed it will simply continue with all hosts.</p>
<p>This seems to be the intended behavior. From the <a href="http://docs.ansible.com/ansible/pause_module.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p>The pause module integrates into async/parallelized playbooks without any special considerations (see also: Rolling Updates). When using pauses with the <code>serial</code> playbook parameter (as in rolling updates) you are only prompted once for the current group of hosts.</p>
</blockquote>
<p>So no matter how, even if I would use <code>serial: 1</code> (which would not be possible in this case) pause would only stop for the first host.</p>
<p>Right now I simply pause without a condition and let the user decide if he wants to continue or not, no matter if the downtime task failed or not. But since the fails should be very rare this is a manual step I'd like to avoid.</p>
<p>Can anyone see a solution how to either:</p>
<ul>
<li>pause for <em>every</em> host (that failed)</li>
<li>pause once, in case <em>any</em> host failed</li>
</ul> | 1 |
Testing href value from a link component while having dynamic props | <p>I am looking for a solution in order to still be able to use Link from react-router instead of a when testing href attribute value.
Indeed, I have some components which change of route according to the context. However, when I am testing the href attribute value, the only thing returned is null.
However, when I use an a, it returns me the expected value.</p>
<p>Here is an failing test:</p>
<pre><code>import React from 'react';
import {Link} from 'react-router';
import TestUtils from 'react-addons-test-utils';
import expect from 'must';
const LINK_LOCATION = '/my_route';
class TestComponent extends React.Component {
render() {
return (
<div>
<Link className='link' to={LINK_LOCATION}/>
<a className='a' href={LINK_LOCATION}/>
</div>
);
}
}
describe('Url things', () => {
it('should return me the same href value for both link and a node', () => {
const test_component = TestUtils.renderIntoDocument(<TestComponent/>);
const link = TestUtils.findRenderedDOMComponentWithClass(test_component, 'link');
const a = TestUtils.findRenderedDOMComponentWithClass(test_component, 'a');
expect(link.getAttribute('href')).to.eql(a.getAttribute('href'));
});
});
</code></pre>
<p>Output: AssertionError: null must be equivalent to "/my_route"</p>
<p><em>knowbody</em> from React-router answered to see how they test Link, but they do not have dynamic context which can change value of the href attribute.</p>
<p>So I have done something like that: </p>
<pre><code>class ComponentWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
set_props(props) {
this.setState({props});
}
render() {
if (this.state.props) {
return <Component {...this.state.props}/>;
}
return null;
}
}
</code></pre>
<p>But now, from my component helper: </p>
<pre><code>render_into_document() {
const full_component_props = {
location: this.location,
widget_categories: this.widget_categories
};
node = document.createElement('div');
this.component = render((
<Router history={createHistory('/')}>
<Route path='/' component={ComponentWrapper} />
</Router>
));
this.component.set_props(full_component_props);
return this;
}
</code></pre>
<p>I am not able to lay hand on <code>this.component</code> in order to changes props. How could I do that? </p> | 1 |
React Router (v3) redirect not redirecting to new location | <p>I have a router setup like this:</p>
<pre><code>import React from 'react';
import {IndexRoute, NotFoundRoute, Route, Redirect} from 'react-router';
import App from './components/app';
import Home from './components/Home';
import AuthorPage from './components/authors/AuthorPage';
import About from './components/about/About';
import NotFound from './components/NotFound';
const routes = (
<Route path="/" component={App} >
<IndexRoute component={Home} />
<Route path="about" component={About} />
<Route path="authors" component={AuthorPage} />
<Route path="*" component={NotFound} />
<Redirect from="/about-us" to="/about" />
</Route>
);
export default routes;
</code></pre>
<p>Everything but the redirecting works fine. Whenever I try to navigate to <code>/about-us</code>, I get a white page displaying <code>Cannot GET /about-us</code>.</p>
<p>Cannot seem to find anything about this in the docs. Does the "from" part of the route still have to exist for this to work, or should it just redirect me regardless?</p>
<p>EDIT:</p>
<p>I should also mention that I use the history package, as mentioned in the react-router upgrade guide: <code>https://github.com/rackt/react-router/blob/master/upgrade-guides/v1.0.0.md</code></p>
<p>Here is my main.js:</p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'react-router';
import routes from './routes';
import createBrowserHistory from 'history/lib/createBrowserHistory'
// Using history to avoid default behavior of weird urls like `?_k=umhx1s`
// See: https://github.com/rackt/react-router/blob/master/upgrade-guides/v1.0.0.md
let history = createBrowserHistory();
const root = document.getElementById('app');
ReactDOM.render(<Router history={history}>{routes}</Router>, root);
</code></pre> | 1 |
Always open camera in landscape mode in Android | <p>In my android app, after clicking on button I want camera to open in landscape mode. Even if I rotate my mobile into portrait mode, camera should always be in landscape mode or in portrait mode </p> | 1 |
React Native image as string not found | <p>This works just fine:</p>
<pre><code><Image source={require('./imgs/animage.jpg')}></Image>
</code></pre>
<p>This returns an error:</p>
<pre><code>var theimage = './imgs/animage.jpg';
<Image source={require(theimage)}></Image>
</code></pre>
<p>The error returned is:</p>
<p>"Requiring unknown module './imgs/animage.jpg'. If you are the module is there, try restarting the package"</p>
<p>Really no idea what the problem is.</p>
<p>This works:</p>
<pre><code>var theimage = require('./imgs/animage.jpg');
</code></pre>
<p>But this still does not:</p>
<pre><code>var theimage = 'animage';
var theimage = require('./imgs/' + theimage + '.jpg');
</code></pre>
<p>I can't see any way to produce images dynamically.</p> | 1 |
Use different paths for public and private resources Jersey + Spring boot | <p>I'm using Spring boot + Jersey + Spring security, I want to have public and private endpoints, I want an schema as follow:</p>
<ul>
<li><strong>/rest</strong> -- My root context </li>
<li><strong>/public</strong> -- I want to place my public endpoints in this context, It must be inside of the root context like <code>/rest/public/pings</code></li>
<li><strong>/private</strong> -- I want to place my private endpoints in this context, It must be inside of the root context like <code>/rest/private/accounts</code></li>
</ul>
<p>I have my configuration as follow:</p>
<p><strong>Jersey</strong> configuration:</p>
<pre><code>@Configuration
@ApplicationPath("/rest")
public class RestConfig extends ResourceConfig {
public RestConfig() {
register(SampleResource.class);
}
}
</code></pre>
<p><strong>Spring security</strong> configuration:</p>
<pre><code>@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
........
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/rest/public/**").permitAll();
http.antMatcher("/rest/**").authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic();
http.csrf().disable();
}
}
</code></pre>
<p>The question is how can I register two application paths inside of my /rest context, one for /public and the other one for /private ?</p>
<p>NOTE: I tried to create another ResourceConfig as follow:</p>
<pre><code>@Configuration
@ApplicationPath("/rest/public")
public class RestPublicConfig extends ResourceConfig{
public RestPublicConfig() {
register(PingResource.class);
}
}
</code></pre>
<p>But I'm getting the next error:</p>
<pre><code> No qualifying bean of type [org.glassfish.jersey.server.ResourceConfig] is defined: expected single matching bean but found 2: restConfig,restPublicConfig
</code></pre>
<p>Thanks for your help :)</p> | 1 |
VBa. Replace data from an array | <p>I Have an array like this Dim RG4() As String -- Name of the Array</p>
<pre><code>0 (XX-AA-2345)
1 (XX-DA-2454)
2 (XX-CD-9476)
3 (XX-AA-4711)
4 ...
</code></pre>
<p>And i want to replace the beggning of the whole array "XX-DA-" For something standard like for exaple "XX-AA-(numbers)" in all of them.</p>
<p>I´ve done some research and i couldnt find anything that could work here.</p> | 1 |
How can I create a new column and concatenate some values using php Excel? | <p>I want to read an excel file and add a new column to the left of the first column <strong><em>on each sheet</em></strong> using PHP. (The excel file can have as many as 10 sheets)</p>
<ol start="2">
<li>concatenate "AFS-" to the data in each row of the first column and store the new string in the new column to the left.</li>
</ol>
<p>Eg. sheet 1
<a href="https://i.stack.imgur.com/m1xYY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m1xYY.png" alt="enter image description here"></a></p> | 1 |
Extracting HTML Links with href | <p>I've used the below code:</p>
<pre class="lang-bsh prettyprint-override"><code>$URI = $webpage
$HTML = Invoke-WebRequest -Uri $URI
$price = ($HTML.ParsedHtml.getElementsByTagName("div") | Where {
$_.className -eq 'price'
}).innerText
</code></pre>
<p>to extract information from this HTML code:</p>
<pre class="lang-html prettyprint-override"><code><div class="price">
<span class="accessibility">Purchase price</span>
<small>$</small>3.50
</div>
</code></pre>
<p>but I can't seem to extract the URL from the following HTML code using <code>.ParsedHtml.getElementsByTagName()</code>.</p>
<pre class="lang-html prettyprint-override"><code></a>
<div class="detail">
<span role="presentation" aria-hidden="true" class="brand">Steves Fresh</span>
<span class="item" role="presentation" aria-hidden="true">
<a role="presentation" aria-hidden="true" class="product-url" href="http://testurlnodetailsshown.com.au">
Steves&nbsp;
2 pack
</a>
</code></pre> | 1 |
Force square corners on edges with graphviz | <p>I have the following <code>.dot</code> file.</p>
<pre><code>digraph
{
node [color=Limegreen,fontcolor=Limegreen,shape=oval]
ilocus [label="iLocus"]
gilocus [label="giLocus"]
pilocus [label="piLocus"]
nilocus [label="niLocus"]
silocus [label="siLocus"]
cilocus [label="ciLocus"]
filocus [label="fiLocus"]
iilocus [label="iiLocus"]
node [color=Blue,fontcolor=Blue,shape=diamond]
containgene [label="Contains gene(s)?"]
proteincoding [label="Protein coding?"]
multiplegenes [label="Multiple genes?"]
geneflank [label="Flanked by genes\non both sides?"]
ilocus -> containgene
containgene:e -> geneflank [xlabel="No"]
geneflank:e -> filocus [xlabel="No"]
geneflank:w -> iilocus [xlabel="Yes"]
containgene:w -> gilocus [xlabel="Yes"]
gilocus -> proteincoding
proteincoding:e -> nilocus [xlabel="No"]
proteincoding:w -> pilocus [xlabel="Yes"]
pilocus -> multiplegenes
multiplegenes:e -> silocus [xlabel="No"]
multiplegenes:w -> cilocus [xlabel="Yes"]
}
</code></pre>
<p>Rendering with graphviz I get the following.</p>
<p><a href="https://i.stack.imgur.com/Pghf9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Pghf9.png" alt="Graphviz take 1"></a></p>
<p>Is there any way I can force the edges to have square corners rather than rounded corners? The <code>splines=ortho</code> attribute from the documentation seems to be designed for this in principle, but in practice I just get straight lines when I add <code>graph [splines=ortho]</code> to my digraph.</p>
<p><a href="https://i.stack.imgur.com/eo4Fw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eo4Fw.png" alt="Graphviz take 2"></a></p>
<p>Any way I can get square corners on the edges with graphviz? Something like the following:</p>
<pre><code> ------ Multiple genes? -----
| |
| N Y |
| |
v V
siLocus ciLocus
</code></pre> | 1 |
Suricata IPS manual blocking/unblocking vs. snort and guardian | <p>Does anyone have experience with using Suricata as an IPS? Im on Debian and I'd like to be able to manually block and unblock specific ip addresses (iptables). I've not used Suricata as I am currently running Snort as an IDS and guardian as my IPS. I've done a bit of research into Suricata and, as far as I can tell, one can manually add rules to Suricata's rule file which will block a given ip address. When Suricata is running as a daemon, do the block rules get wiped when you restart the daemon like they do with guardian?
Thanks in advance for any tips.</p> | 1 |
Pass data to Mail Job/Queue - Lumen/Laravel | <p>I'm using <code>Lumen</code> and want to know how to pass <code>data</code> to my <code>job</code> class.
I have my <code>job</code> class like below;</p>
<pre><code><?php
namespace App\Jobs;
use App;
use Illuminate\Contracts\Mail\Mailer;
class TestEmailJob extends Job
{
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Mailer $mailer)
{
//
$data; // I want to pass this from my function
$mailer->queue('emails.emailtemplate', $data , function ($message) {
$message->from('[email protected]', 'Laravel');
$message->to('[email protected]')->cc('[email protected]');
});
}
}
</code></pre>
<p>I then have a function to push the job on the queue;</p>
<pre><code>public function emailTest () {
$data = ['user' => $user];
Queue::push(new TestEmailJob);
}
</code></pre>
<p>How can I pass <code>$data</code> and receive it and use it in the <code>job</code> class?</p> | 1 |
How to Deploy a jar onto Raspberry Pi 2 using Maven Plugin | <p>I have a simple java class using Pi4J that contains a main method. I want to build and deploy it to a Raspberry Pi. I'm using java 8 on a windows 10 and my IDE is NetBeans 8.1. If the project is set up to be a normal (non-Maven) Java Application and set up to deploy to the Raspberry Pi via the NetBeans build configurations as shown <a href="https://netbeans.org/kb/docs/java/javase-embedded.html" rel="nofollow">here</a>, the project will build normal and FTP over the jar and then run it with no issues.
I would like to do the same but using Maven. The problem is that the code that is being ran has C code native to the ARM's architecture of the Pi and the Maven plugin I'm using seems to run the jar on my local box first in which the C code will crash throwing the Exception</p>
<blockquote>
<p>SEVERE: Unable to load [libpi4j.so] using path: [/lib/libpi4j.so]
java.lang.IllegalArgumentException: The path has to be absolute, but found: \lib\libpi4j.so
at com.pi4j.util.NativeLibraryLoader.loadLibraryFromClasspath(NativeLibraryLoader.java:120)
at com.pi4j.util.NativeLibraryLoader.load(NativeLibraryLoader.java:92)
at com.pi4j.wiringpi.Gpio.(Gpio.java:174)
at com.pi4j.io.gpio.RaspiGpioProvider.(RaspiGpioProvider.java:51)
at com.pi4j.io.gpio.GpioFactory.getDefaultProvider(GpioFactory.java:106)
at com.pi4j.io.gpio.impl.GpioControllerImpl.(GpioControllerImpl.java:54)
at com.pi4j.io.gpio.GpioFactory.getInstance(GpioFactory.java:89)
at com.hadronix.pi4jsample2.ControlGpioExample.main(ControlGpioExample.java:24)</p>
<p>Exception in thread "main" java.lang.UnsatisfiedLinkError:
com.pi4j.wiringpi.Gpio.wiringPiSetup()I at
com.pi4j.wiringpi.Gpio.wiringPiSetup(Native Method) at
com.pi4j.io.gpio.RaspiGpioProvider.(RaspiGpioProvider.java:51)
at
com.pi4j.io.gpio.GpioFactory.getDefaultProvider(GpioFactory.java:106)
at
com.pi4j.io.gpio.impl.GpioControllerImpl.(GpioControllerImpl.java:54)
at com.pi4j.io.gpio.GpioFactory.getInstance(GpioFactory.java:89) at
com.hadronix.pi4jsample2.ControlGpioExample.main(ControlGpioExample.java:24)</p>
</blockquote>
<p>If i just do a clean build, it will build fine and create the jar. However, if i choose to run the build then thats where the crash happens. This is the Maven plugin I'm using to deploy the jar to the Pi.</p>
<pre><code><!-- OPTIONALLY DEPLOY THE FINAL JAR TO THE RASPBERRY PI -->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<!-- copy the compiled JAR file to the Raspberry Pi platform platform -->
<execution>
<id>ControlGpioExample.jar</id>
<phase>install</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<taskdef resource="net/sf/antcontrib/antcontrib.properties"
classpathref="maven.plugin.classpath" />
<if>
<equals arg1="${pi.transfer.dev}" arg2="true" />
<then>
<!-- ensure the target directory exists on the Raspberry Pi -->
<sshexec host="${pi.host.dev}" port="${pi.port.dev}" username="${pi.user.dev}"
password="${pi.password.dev}" trust="true" failonerror="false"
verbose="true" command="mkdir --parents ${pi.dirCopyTo.dev}" />
<!-- copy the JAR file to the Raspberry Pi -->
<scp
file="${project.build.directory}/${project.build.finalName}.jar"
todir="${pi.user.dev}:${pi.password.dev}@${pi.host.dev}:${pi.dirCopyTo.dev}"
port="${pi.port.dev}" trust="true" verbose="true" failonerror="true">
</scp>
</then>
</if>
</tasks>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-jsch</artifactId>
<version>${ant-jsch.version}</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>${jsch.version}</version>
</dependency>
<dependency>
<groupId>ant-contrib</groupId>
<artifactId>ant-contrib</artifactId>
<version>${ant-contrib.version}</version>
</dependency>
</dependencies>
</plugin>
</code></pre>
<p>I'm trying to figure out how to change this plugin to not execute the code first on my local machine. I just want it to assume the jar is built, ssh into the remote Pi and copy the jar over and then run it there. Also, if someone has a completely better way while using Maven then I'm open to suggestions. Any help would be great!</p>
<p>Here are links to what I'm using as references
<a href="http://artem.gratchev.com/2015/03/java-application-jar-raspberry-pi-maven-eclipse/" rel="nofollow">link</a> 1</p>
<p>Thanks in advance.</p> | 1 |
calculate position of a point on image in percentage | <p>I am calculating position of a point on a image with the formula below in pixel, where oW is original image width and oH is original image height.</p>
<pre><code>var x = oW * parseInt(document.getElementById('pageX').value - $tagImage.offset().left - 5) / $tagImage.width();
var y = oH * parseInt(document.getElementById('pageY').value - $tagImage.offset().top - 5) / $tagImage.height();
</code></pre>
<p>Now, I want to calculate same position in percentage so that the point remains responsive.
(Sorry, I am a bit weak in maths so need help) </p> | 1 |
Rails where not in array | <p>I have some posts that each has many tags.</p>
<p>I need to create a query that matches against the posts that are not having the exact tags as in an array.</p>
<p>Also it should return all the posts that are not having tags at all with that query.</p>
<p>Here is what I tried:</p>
<pre><code> query = posts.joins('LEFT JOIN post_tags ON post.id = post_tags.post_id')
no_tags = ['test', 'test1']
query = query.where('post_tags.name NOT IN (?) OR post_tags.name IS ?', no_tags, nil) if no_tags
</code></pre>
<p>This gives me all the posts that are having no tags at all which is correct, also it gives me the posts that haven't the tags specified, <strong>and no other tags</strong>, which is also correct.</p>
<p>The problem is that if a post has <strong>multiple</strong> tags, say <code>test, another</code>, it returns it in the query, which is not the behaviour I want.</p>
<p>I need to filter these posts out, if a post has a tag that is in the array, whether another tags are included or not.</p>
<p>Example:</p>
<pre><code>post1 has tag `test`
post2 has tag `another`
post3 has tags `test, another`
post4 has no tags
</code></pre>
<p>It should return:</p>
<pre><code>[post2, post4]
</code></pre>
<p>But now it returns:</p>
<pre><code>[post2, post3, post4]
</code></pre> | 1 |
Liferay : How can I land to custom url on signout | <p>I'm not sure if I can achieve this by simply configuration or I need to override LogoutAction for it. </p>
<p>I've configured multiple organisation and each organisation has there own site which I want to navigate to my custom url for different site instead of default url on logout from liferay.</p>
<p>[EDITED]
I want to navigate on different url for each site, not a common url.</p>
<p>Thanks </p> | 1 |
What is best practice to communicate between React components and services? | <p>Instead of using flux/redux architecture, how react components should communicate with services?</p>
<p><strong>For example:</strong>
There is a container having few representational (react) components:</p>
<ol>
<li>ChatBox - enables to read/write messages</li>
<li>AvatarBox with password changer - which enables to change user's password</li>
<li>News stream - lists news and apply filter to them</li>
</ol>
<p>Thinking of them as resources representation, I want each of them to access Microservice API by itself (getting or updating data). Is this correct?
It will provide clean responsibility managing models, but it gives performance doubts using http requests to load each component's content</p>
<p>This question also reffers to: <a href="https://stackoverflow.com/questions/35286730/how-to-execute-efficient-communication-for-multiple-microservices">How to execute efficient communication for multiple (micro)services?</a></p> | 1 |
Install php cURL on Windows Phpstorm | <p>How do you install the php curl extension on Windows for Phpstorm IDE? I would like to be able to run curl php functions on my local Windows 10 machine.</p>
<p><code>extension=php_curl.dll</code> is uncommented in php.ini</p>
<p>Thanks in advance!</p> | 1 |
CakePHP 3 - Parse Date with LocalStringFormat to correct SQL format and correct validation | <p>we have declared the following lines in the initialize function of our AppController to have globally the same format for displaying dates:</p>
<pre><code> // default time formats on load
Time::$defaultLocale = 'de-DE';
Time::setToStringFormat('dd.MM.YYYY');
</code></pre>
<p>This worked fine. The date is displayed correcly in the view. But we get an validation error if we want to save the entity with the the date field (The provided value is invalid). The validator is configured like so:</p>
<pre><code> $validator
->add('datefield', 'valid', ['rule' => 'date'])
->allowEmpty('datefield');
</code></pre>
<p>Here a debug of the entity with the date field:</p>
<p>Before patchEntity:</p>
<pre><code>'datefield' => '08.07.2014'
</code></pre>
<p>After patchEntity:</p>
<pre><code>'datefield' => object(Cake\I18n\Time) {
'time' => '2014-07-08T00:00:00+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
....
'[errors]' => [
'datefield' => [
'valid' => 'The provided value is invalid'
]
],
</code></pre>
<p>Is there a way to always parse the Date globally in the correct format for saving the entity and validation.</p> | 1 |
CUDA Installation for NVidia Quadro FX 3800 | <p>I'm having trouble installing CUDA 7.0 (to use with TensorFlow) on a workstation with the Nvidia Quadro FX 3800. I'm wondering if this is because the GPU is no longer supported.</p>
<p>Installation of the driver (340.96) seems to work fine:</p>
<pre><code>$ sh ./NVIDIA-Linux-x86_64-340.96.run
Installation of the NVIDIA Accelerated Graphics Driver for Linux-x86_64
(version: 340.96) is now complete. Please update your XF86Config or
xorg.conf file as appropriate; see the file
/usr/share/doc/NVIDIA_GLX-1.0/README.txt for details.
</code></pre>
<p>However, I think I may be having trouble with the following:</p>
<pre><code>$ ./cuda_7.0.28_linux.run --kernel-source-path=/usr/src/linux-headers-3.13.0-76-generic
The driver installation is unable to locate the kernel source. Please make sure
that the kernel source packages are installed and set up correctly. If you know
that the kernel source packages are installed and set up correctly, you may pass
the location of the kernel source with the '--kernel-source-path' flag.
...
Logfile is /tmp/cuda_install_1357.log
$ vi /tmp/cuda_install_1357.log
WARNING: The NVIDIA Quadro FX 3800 GPU installed in this system is
supported through the NVIDIA 340.xx legacy Linux graphics drivers.
Please visit http://www.nvidia.com/object/unix.html for more
information. The 346.46 NVIDIA Linux graphics driver will ignore
this GPU.
WARNING: You do not appear to have an NVIDIA GPU supported by the 346.46
NVIDIA Linux graphics driver installed in this system. For
further details, please see the appendix SUPPORTED NVIDIA GRAPHICS
CHIPS in the README available on the Linux driver download page at
www.nvidia.com.
...
ERROR: Unable to load the kernel module 'nvidia.ko'. This happens most
frequently when this kernel module was built against the wrong or
improperly configured kernel sources, with a version of gcc that
differs from the one used to build the target kernel, or if a driver
such as rivafb, nvidiafb, or nouveau is present and prevents the
NVIDIA kernel module from obtaining ownership of the NVIDIA graphics
device(s), or no NVIDIA GPU installed in this system is supported by
this NVIDIA Linux graphics driver release.
...
Please see the log entries 'Kernel module load error' and 'Kernel
messages' at the end of the file '/var/log/nvidia-installer.log' for
more information.
</code></pre>
<p>Is the installation failure due to CUDA dropping support for this graphics card?</p>
<p>I followed the link trail: <a href="https://developer.nvidia.com/cuda-gpus" rel="nofollow">https://developer.nvidia.com/cuda-gpus</a> > <a href="https://developer.nvidia.com/cuda-legacy-gpus" rel="nofollow">https://developer.nvidia.com/cuda-legacy-gpus</a> > <a href="http://www.nvidia.com/object/product_quadro_fx_3800_us.html" rel="nofollow">http://www.nvidia.com/object/product_quadro_fx_3800_us.html</a> and I would have thought the Quadro FX 3800 supported CUDA (at least at the beginning).</p> | 1 |
Statsmodels arima model returns error | <p>I have started to learn statsmodels package and can't implement basic forecasting with arima.</p>
<p>Error is </p>
<blockquote>
<p>ValueError: Given a pandas object and the index does not contain dates</p>
</blockquote>
<p>I am trying this as a version:</p>
<pre><code>df = make_df(filename_data)
y = []
x = []
# here I am preparing day by day sequence as that I have inconsistent data and I set 0 to NAN values
start_date = df[date_col].min()
end_date = df[date_col].max()
while start_date <= end_date:
x.append(start_date)
try:
y.append(
df[df[date_col] == start_date][rev_col].values[0])
except:
y.append(0)
start_date += datetime.timedelta(days=1)
y = np.array(y)
x = np.array(x)
y = pd.TimeSeries(y, index=x)
print(y)
arma_mod = sm.tsa.ARMA(y, order=(2,2))
arma_res = arma_mod.fit(trend='nc', disp=-1)
</code></pre>
<p>Before that I tried</p>
<pre><code>df = make_df(filename_data)
y = np.array(df[rev_col])
x = np.array(df[date_col])
y = pd.TimeSeries(y, index=x)
</code></pre>
<p>Why is it happening?</p>
<p>The date - revenue data looks OK:</p>
<pre><code>2014-08-04 59477
2014-08-05 29989
2014-08-06 29989
2014-08-07 116116
</code></pre> | 1 |
OneToOne entities won't persist with Doctrine in Symfony2 | <p>I have a OneToOne relation in Symfony between user and student, where user is the owner, when I try to persist changes are not made in neither of sides, this is my last configuration:</p>
<pre><code><?php
/**
* User
*
* @ORM\Table(name="user")
* @ORM\Entity(repositoryClass="BackendBundle\Repository\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="Student", mappedBy="user")
*/
private $student;
public function __construct() {
}
/**
* Set student
*
* @param \BackendBundle\Entity\Student $student
*
* @return User
*/
public function setStudent(\BackendBundle\Entity\Student $student)
{
$this->student = $student;
return $this;
}
/**
* Get student
*
* @return \BackendBundle\Entity\Student
*/
public function getStudent()
{
return $this->student;
}
}
</code></pre>
<p>The student:</p>
<pre><code><?php
/**
* Student
*
* @ORM\Table(name="Student")
* @ORM\Entity(repositoryClass="BackendBundle\Repository\StudentRepository")
*/
class Student
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="User", inversedBy="student")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
public function __construct() {
}
}
</code></pre>
<p>and in the controller:</p>
<pre><code> public function editAction(Request $request, User $user)
{
$student = new Student();
$user->setStudent($student);
$em = $this->getDoctrine()->getManager();
$em->persist($student);
$user->setStudent($student);
$em->persist($user);
$em->flush();
/.../
}
</code></pre>
<p>I can save both entities and changes without any exceptions, but I can't relate them, for example in view, when I do <code>{{ user.student }}</code> it gives me null, and <code>{{ student.user_id }}</code> also is null.</p> | 1 |
Out-file export to a network location powershell | <p>I am having an issue trying to output a file with PowerShell, I can export the file to the computer's local drives however when I want to export it to a network location it will not let me. </p>
<p>I receive the following error:</p>
<pre><code>Access to the path '\\fmadt-prod-web5\e$\ftproot\customer\temp\SiteLists\Classic\Hosted1.txt' is denied.
+ CategoryInfo : OpenError: (:) [Out-File], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
</code></pre>
<p>This is the code that I am using:</p>
<pre><code>$list2 | Format-Table -a -Property "WebAppName", "Version", "State"| Out-File '\\fmadt-prod-web5\e$\ftproot\customer\temp\SiteLists\Classic\Hosted1.txt' -force
</code></pre>
<p>Is it possible to export to a network location? The user I am using has admin access to that location as well. </p> | 1 |
Node + Passport, Error: Authentication strategies must have a name | <p>I'm trying to initialize a SAML strategy during the require line. Something like this:</p>
<pre><code>var myStrat = new require('passport-something').Strategy(
{ .... }
);
passport.use('something', myStrat);
</code></pre>
<p>but am getting the error:</p>
<pre><code>.../passport/lib/authenticator.js:54
if (!name) { throw new Error('Authentication strategies must have a name'); }
^
Error: Authentication strategies must have a name
at Authenticator.use ...
</code></pre>
<p>or <code>TypeError: Cannot read property 'name' of undefined at Authenticator.use</code> if a custom strategy name is not defined: <code>passport.use(myStrat);</code></p>
<p>.</p>
<p>I've had it like this (which works):</p>
<pre><code>var mySomething = require('passport-something');
var myStrat = new mySomething.Strategy(
{ .... }
);
passport.use(myStrat);
</code></pre>
<p>but I wish to change it because I need to call passport-saml's <code>Stragety.generateServiceProviderMetadata()</code> function later on.
Which (I think) mean I need a variable pointing to the new Strategy instance.
Not a big deal I know, just would like to have the code for this particular strategy look more in line with the rest if I can. Which all look like:</p>
<pre><code>var GoogleStrat = require( 'passport-google-oauth2' ).Strategy;
passport.use('google', new GoogleStrat(
....
));
</code></pre> | 1 |
simple drawing with pyqt on a QGraphicsview | <p>I'm looking for a simple way to draw a line on a widget within a main window of a QT application.
I designed with QtDesigner a main window with a QGraphicsview and a button. When pressing a button, a line should be drawn in the graphics view. Isn't there a simple way to do so. Is a QGraphicsview the right choice for drawing? I read dozents of articles now and really found no solution.
Here is my code in short:</p>
<pre><code>import sys
import mainwindowui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MainWindow(QMainWindow, mainwindowui.Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.connect(self.pushButton1, SIGNAL("clicked()"), self.pb1_pressed)
def pb1_pressed(self):
# here I want to draw a line on the QGraphicswidget:
# something simple like: graphview.line(x1,y1,x2,y2)
</code></pre>
<p>I saw a lot of very complicated looking solutions and I tried a lot, e.g. with overwriting paintevent using QPainter but got errors like "QPainter::begin: Paint device returned engine == 0, type: 1" and I don't know how if this is the right way.
Can someone please give me a really simple solution?
Thank you in advance.</p>
<p>Dieter </p> | 1 |
Android Locale Country name to Country code | <p>I have some country variable, "France" for example.
I want to get the country code, in this example, I want to get "FR" or "fr".</p>
<p>I tried :</p>
<pre><code> Locale locale = new Locale("", "FRANCE");
Log.e("test", locale.getCountry());
</code></pre>
<p>But it returns : </p>
<pre><code> FRANCE
</code></pre>
<p>What I'm missing ?</p>
<p>Thank you !</p> | 1 |
How can we detect a proxy/virtual mobile number? | <p>To filter scammers, we validate user accounts with a sms verification system.</p>
<p>As you can imagine, some people are using virtual numbers.</p>
<p>Some <a href="https://en.wikipedia.org/wiki/Mobile_Network_Code" rel="nofollow noreferrer">MCCMNC</a> can easily be banned as they are favored by scammers. But most scammer numbers have the MCCMNC of a "clean" telco.</p>
<p>How can we detect that?</p> | 1 |
"SSLError certificate verify failed" for every domain/url | <p>I broke the SSL setup of my machine. Every <code>request</code> call now ends in an <code>certificate verify failed</code>.</p>
<p>I am not sure what caused this, but I moved some module, that I had installed va <code>pip install -e .</code> and reinstalled it. After that I noticed that error.</p>
<p>I tried <code>sudo apt-get install libffi-dev</code> and <code>pip install requests[security] --user --upgrade</code> but it did not help.</p>
<p>Here the whole output:</p>
<pre><code>import requests; requests.get('https://www.google.com')
---------------------------------------------------------------------------
SSLError Traceback (most recent call last)
<ipython-input-1-b4a9dae5ffaa> in <module>()
1 import requests
----> 2 requests.get('https://www.google.com')
/home/my_computer/.local/lib/python2.7/site-packages/requests/api.pyc in get(url, params, **kwargs)
65
66 kwargs.setdefault('allow_redirects', True)
---> 67 return request('get', url, params=params, **kwargs)
68
69
/home/my_computer/.local/lib/python2.7/site-packages/requests/api.pyc in request(method, url, **kwargs)
51 # cases, and look like a memory leak in others.
52 with sessions.Session() as session:
---> 53 return session.request(method=method, url=url, **kwargs)
54
55
/home/my_computer/.local/lib/python2.7/site-packages/requests/sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
466 }
467 send_kwargs.update(settings)
--> 468 resp = self.send(prep, **send_kwargs)
469
470 return resp
/home/my_computer/.local/lib/python2.7/site-packages/requests/sessions.pyc in send(self, request, **kwargs)
574
575 # Send the request
--> 576 r = adapter.send(request, **kwargs)
577
578 # Total elapsed time of the request (approximately)
/home/my_computer/.local/lib/python2.7/site-packages/requests/adapters.pyc in send(self, request, stream, timeout, verify, cert, proxies)
445 except (_SSLError, _HTTPError) as e:
446 if isinstance(e, _SSLError):
--> 447 raise SSLError(e, request=request)
448 elif isinstance(e, ReadTimeoutError):
449 raise ReadTimeout(e, request=request)
SSLError: bad handshake: Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],)
</code></pre> | 1 |
How to swap out data via unload and load in C3.js | <p>I'm trying to swap out data sets in a C3.js graph.</p>
<p>The code I assumed would work based on the C3 docs looks like this:</p>
<pre><code>chart.unload();
chart.load({
columns: [
['data3', 100, 90, 80, 70, 60, 50]
]
});
</code></pre>
<p>But this doesn't work. You'll notice that the graph rendered on the following Plunkr renders improperly, so I'm clearly doing something wrong: <a href="https://jsfiddle.net/7rfm9om9/" rel="nofollow">https://jsfiddle.net/7rfm9om9/</a></p>
<p>What is the idiomatic way to replace data in a C3 chart?</p> | 1 |
Where to store user uploaded files in Django | <p>I'm building a Django app where users will upload a CSV file. Each row in the CSV file will then be added to the DB (after validating the data). The file can then be discarded.</p>
<p>From the Django documentation, I'm using this to save the file.</p>
<pre><code>def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
</code></pre>
<p>There's a lot of warnings on the Django site about handling user uploaded files so my question is, where should these files be saved? My guess is it doesn't matter, but I want to be sure.</p>
<p>At the moment I plan to create a variable called UPLOADS_URL in my settings file. All uploaded files will then be stored in there.</p> | 1 |
How does sorting work in the new mongodb PECL extension? | <p>I have just shifted from the old Mongo extension to the newest PHP driver (mongodb). I'm also using the PHP library provided for mongodb.</p>
<p>Previously, I could simply do <code>->sort()</code> on a cursor instance, but that doesn't seem to be the case any more since I get this error:</p>
<pre><code>Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Cursor::sort()
</code></pre>
<p>What is the alternative to sorting/limiting/skipping now?</p> | 1 |
Docker reserve a certain amount of memory for container | <p>I'm running <code>npm</code> inside a docker container and every so often it aborts because it cannot allocate enough memory. I see some flags like <code>--memory</code> (<a href="https://stackoverflow.com/questions/16084741/how-do-i-set-resources-allocated-to-a-container-using-docker">How do I set resources allocated to a container using docker?</a>) for the <code>docker run</code> command that seem to limit the maximum amount of memory that a container can consume, but haven't seen anything yet that would allow me to reserve an amount of memory for the container and abort immediately if it cannot be allocated.</p> | 1 |
How to validate CronSequenceGenerator cron expressions? | <p>How could I validate <code>cron</code> expressions that are prepared for use of <code>CronSequenceGenerator</code>?</p>
<p>I mean, I cannot wait until the cron executes automatically as I'm defining like monthly intervals.</p>
<p>Is the following correct? How can I be sure?</p>
<pre><code>monthly at midnight: `0 0 0 1 * *`
monthly at 1 am: `0 0 1 1 * *`
weekly, on sunday at midnight: `0 0 0 * * SUN`
</code></pre> | 1 |
Rank Selection in GA? | <p>I have implemented <code>Roulette wheel selection</code> in <code>GA</code>.<br></p>
<pre><code> TotalFitness=sum(Fitness);
ProbSelection=zeros(PopLength,1);
CumProb=zeros(PopLength,1);
for i=1:PopLength
ProbSelection(i)=Fitness(i)/TotalFitness;
if i==1
CumProb(i)=ProbSelection(i);
else
CumProb(i)=CumProb(i-1)+ProbSelection(i);
end
end
SelectInd=rand(PopLength,1);
for i=1:PopLength
flag=0;
for j=1:PopLength
if(CumProb(j)<SelectInd(i) && CumProb(j+1)>=SelectInd(i))
SelectedPop(i,1:IndLength)=CurrentPop(j+1,1:IndLength);
flag=1;
break;
end
end
if(flag==0)
SelectedPop(i,1:IndLength)=CurrentPop(1,1:IndLength);
end
end
</code></pre>
<p><strong>Now i was trying to implement <code>rank selection</code> in <code>GA</code>. I learned that:</strong></p>
<ul>
<li><p>Rank selection first ranks the population and then every chromosome receives fitness from this ranking. </p></li>
<li><p>The worst will have fitness 1, second worst 2 etc. and the best will have fitness N (number of chromosomes in population). <br></p></li>
</ul>
<p><strong>I saw these <a href="https://stackoverflow.com/questions/9462350/differences-between-roulette-wheel-selection-and-rank-based-selection">link1</a> and <a href="https://stackoverflow.com/questions/20290831/how-to-perform-rank-based-selection-in-a-genetic-algorithm">link2</a> and what i understood is that:</strong></p>
<ol>
<li><p>First i will sort the Fitness value of the Population.</p></li>
<li><p>Then if the Population number is 10 then i will give the probability of selection to the Population like 0.1,0.2,0.3,...,1.0 .</p></li>
<li>Then i will calculate cumulative Fitness like roulette wheel.</li>
<li>And the next steps is same as roulette wheel.</li>
</ol>
<p><strong>My Implementation:</strong></p>
<pre><code> NewFitness=sort(Fitness);
NewPop=round(rand(PopLength,IndLength));
for i=1:PopLength
for j=1:PopLength
if(NewFitness(i)==Fitness(j))
NewPop(i,1:IndLength)=CurrentPop(j,1:IndLength);
break;
end
end
end
CurrentPop=NewPop;
ProbSelection=zeros(PopLength,1);
CumProb=zeros(PopLength,1);
for i=1:PopLength
ProbSelection(i)=i/PopLength;
if i==1
CumProb(i)=ProbSelection(i);
else
CumProb(i)=CumProb(i-1)+ProbSelection(i);
end
end
SelectInd=rand(PopLength,1);
for i=1:PopLength
flag=0;
for j=1:PopLength
if(CumProb(j)<SelectInd(i) && CumProb(j+1)>=SelectInd(i))
SelectedPop(i,1:IndLength)=CurrentPop(j+1,1:IndLength);
flag=1;
break;
end
end
if(flag==0)
SelectedPop(i,1:IndLength)=CurrentPop(1,1:IndLength);
end
end
</code></pre>
<p><br><br>
<strong>Am i understanding the algo wrong?? If it is then can anyone give me any idea how to modify my roulette wheel to rank selection??</strong></p> | 1 |
GravityForms - List Field with DropDown on entries column | <p>I use GravityForms List field. I use multiple columns on this list fields.
My question is : for one column, can I get a drop-down with multiples choices ?</p>
<p>I can implement it in PHP but no idea for API to use. In fact I want just transform a textbox field in dropdown. Have you got an idea ?</p>
<p>You can see that I want here :
<a href="http://img11.hostingpics.net/pics/854196c20150309154121.jpg" rel="nofollow">http://img11.hostingpics.net/pics/854196c20150309154121.jpg</a></p> | 1 |
Kendo UI - MultiSelect replace dynamically created dataSource from external file | <p>How can I replace the Kendo UI MultiSelect dataSource values from external .js file...</p>
<p><strong>PS</strong>: Actual values are coming from <code>index.html</code> file like below:</p>
<p><strong>index.html</strong></p>
<pre><code><select multiple="multiple" class="city_fields initi-select-218" id="test">
</select>
var data = [
"New Jersey",
"San Francisco",
"Las Vegas",
"Chicago",
"Los Angeles",
"New York"
];
jQuery(".city_fields").kendoMultiSelect({
dataSource: data,
filter: "contains",
});
</code></pre>
<p>Above values I am trying to replace from init.js (external) file as below...</p>
<p><strong>init.js</strong></p>
<p><strong>Tried Option 1:</strong></p>
<pre><code>var newData = ["Delhi", "Bangalore"];
jQuery(".initi-select-218").kendoMultiSelect({
dataSource: newData,
filter: "contains",
placeholder: "Select",
});
</code></pre>
<p><strong>Tried Option 2:</strong></p>
<pre><code>var newData = ["Delhi", "Bangalore"];
$("#test").kendoMultiSelect({
dataSource: newData,
filter: "contains",
placeholder: "Select",
});
$("#test").setDataSource(new kendo.data.DataSource({ data: newData }));
</code></pre>
<p><strong>Tried Option 3:</strong></p>
<pre><code>var newData = ["Delhi", "Bangalore"];
var multiselect = $("#test").data("kendoMultiSelect");
multiselect.setDataSource(new kendo.data.DataSource({ data: newData }));
</code></pre>
<p>For Option 2 & 3, I am getting error as</p>
<p><code>Uncaught TypeError: $(...).setDataSource is not a function</code>...</p>
<p>But still, it is taking the values from <code>index.html</code> file</p> | 1 |
ERR_TOO_MANY_REDIRECTS when disable SSL in all pages on Prestashop | <p>I have disabled SSL in all pages at Prestashop and now there is this error (i do not enter https and it puts https):
<a href="https://i.stack.imgur.com/fOm7G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fOm7G.png" alt="enter image description here"></a></p>
<p>I tried deleting htaccess and regenerating it, but it didn't work.</p>
<p>This is the Prestashop configuration:
<a href="https://i.stack.imgur.com/yvNxJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yvNxJ.png" alt="enter image description here"></a></p>
<p>Which is the solution?</p>
<p>EDIT: My configuration of SSL at Prestashop configuration tab
<a href="https://i.stack.imgur.com/Sm6cL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sm6cL.png" alt="enter image description here"></a></p> | 1 |
Failed to start ElasticSearch - Could not find plugin class | <p>We have an existing java based custom plugin for ElasticSearch. We now upgraded to ElasticSearch 2.1.1 and added plugin-descriptor.properties files to point to our plugin class.</p>
<p>After that, we were able to install our custom plugin. But when we start ElasticSearch service, it is unable to find this custom plugin. We verified that the class file is present under the /usr/share/elasticsearch/plugins/ directory.</p>
<p>Following is the exception stack trace:</p>
<pre><code>[2016-01-20 13:13:48,527][ERROR][bootstrap] Exception
ElasticsearchException[Could not find plugin class [com.symc.edp.elasticsearch.plugin.CustomEDPPlugins]]; nested: ClassNotFoundException[com.symc.edp.elasticsearch.plugin.CustomEDPPlugins];
at org.elasticsearch.plugins.PluginsService.loadPluginClass(PluginsService.java:382)
at org.elasticsearch.plugins.PluginsService.loadBundles(PluginsService.java:348)
at org.elasticsearch.plugins.PluginsService.<init>(PluginsService.java:109)
at org.elasticsearch.node.Node.<init>(Node.java:146)
at org.elasticsearch.node.Node.<init>(Node.java:128)
at org.elasticsearch.node.NodeBuilder.build(NodeBuilder.java:145)
at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:178)
at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:285)
at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:35)
Caused by: java.lang.ClassNotFoundException: com.symc.edp.elasticsearch.plugin.CustomEDPPlugins
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.elasticsearch.plugins.PluginsService.loadPluginClass(PluginsService.java:380)
... 8 more
[2016-01-20 13:22:55,236][INFO ][node ] [localhost] version[2.1.1], pid[20680], build[40e2c53/2015-12-15T13:05:55Z]
[2016-01-20 13:22:55,237][INFO ][node ] [localhost] initializing ...
[2016-01-20 13:22:55,840][ERROR][bootstrap ] Exception
ElasticsearchException[Could not find plugin class [com.symc.edp.elasticsearch.plugin.CustomEDPPlugins.class]]; nested: ClassNotFoundException[com.symc.edp.elasticsearch.plugin.CustomEDPPlugins.class];
at org.elasticsearch.plugins.PluginsService.loadPluginClass(PluginsService.java:382)
at org.elasticsearch.plugins.PluginsService.loadBundles(PluginsService.java:348)
at org.elasticsearch.plugins.PluginsService.<init>(PluginsService.java:109)
at org.elasticsearch.node.Node.<init>(Node.java:146)
at org.elasticsearch.node.Node.<init>(Node.java:128)
at org.elasticsearch.node.NodeBuilder.build(NodeBuilder.java:145)
at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:178)
at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:285)
at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:35)
Caused by: java.lang.ClassNotFoundException: com.symc.edp.elasticsearch.plugin.CustomEDPPlugins.class
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.elasticsearch.plugins.PluginsService.loadPluginClass(PluginsService.java:380)
... 8 more
</code></pre>
<p>Following is the content of our plugin-descriptor.properties</p>
<pre><code>description=EDP Custom Plugins
version=${project.version}
name=edpCustomPlugins
jvm=true
site=false
classname=com.symc.edp.elasticsearch.plugin.CustomEDPPlugins
java.version=${java.specification.version}
elasticsearch.version=2.1.1
</code></pre> | 1 |
Securing Spring boot Rest services with CAS | <p>Friends,</p>
<p>Recently I have created one web-services application using spring-boot and now its having few unsecured entry points. (This is a pure rest based application having only rest entry points doesn't have any UI components).</p>
<p>Now I would like to add CAS client with this application for securing the rest entry points. </p>
<p>My CAS server is ready and its up and running. And I have configured CAS Rest protocol as well in my cas server to access TGT/ST through rest call and I'm in the planning of using only the rest call rather than using login pages.</p>
<p>So, when an user tries to access my rest application, I'm going to call CAS rest entry points internally (by using restTemplate) to validate user credentials and generating TGT and ST.</p>
<p>Available CAS entry points are (from jasig reference docs),</p>
<ol>
<li>POST /cas/v1/tickets HTTP/1.0
username=battags&password=password&additionalParam1=paramvalue</li>
<li>POST /cas/v1/tickets/{TGT id} HTTP/1.0
service={form encoded parameter for the service url}</li>
<li>DELETE /cas/v1/tickets/TGT-fdsjfsdfjkalfewrihfdhfaie HTTP/1.0</li>
</ol>
<p>I think, I'm little clear on this part. Please correct me if I'm wrong.</p>
<p>And now my query here is, <strong>what should I do to add a ST ticket validator in my spring boot application? Do I need to add any filters using spring-security? Or do I need to call any other rest api for validating the ST?</strong> Please guide me to proceed further.</p> | 1 |
How to save a standalone R environment object | <p>I am spending already hours trying to make this work and feel that I am missing something simple:</p>
<pre><code>my_env = new.env(hash = TRUE, parent = .GlobalEnv)
my_env[['echo']] <- function(x) {x}
my_env[['echo']](123)
[1] 123
my_env$echo(123)
[1] 123
save(my_env, file = "MyEnv.RData", envir = .GlobalEnv)
loaded_env <- load(file = "MyEnv.RData",envir = .GlobalEnv)
typeof(loaded_env)
[1] "character"
</code></pre>
<p>When I save entire workspace, functions are saved and then loaded back (after I close/open R Studio). But here, <code>save()</code> and/or <code>load()</code> do not work, and I have only a string in my environment after loading.</p>
<p>How could I save a separate environment object to a file, not a complete workspace? I then need all objects inside that environment (<code>my_env</code>) to be loaded into .GlobalEnv in another session. </p> | 1 |
How should I find the correct location data using userLocation in Mapbox for iOS SDK? (Swift) | <p>I'm trying to find the latitude and longitude of the user's location so that I can center the map on the user in viewdidload.</p>
<p>I've implemented what seems to be the right code but the values of userLat (latitude) and userLon (longitude) are way off.</p>
<p>N.B. Somebody else had the same problem as me but his answer was never resolved:
<a href="https://stackoverflow.com/questions/30914419/mapbox-ios8-swift-mapview-showuserslocation">Mapbox iOS8 Swift mapView.showUsersLocation</a></p>
<pre><code>import Mapbox
class ViewController: UIViewController, MGLMapViewDelegate, CLLocationManagerDelegate {
// let locationManager = CLLocationManager()
@IBOutlet weak var mapView: MGLMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Initalise map's center coordinate as vancouver
mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: 49.283382,
longitude: -123.117394),
zoomLevel: 15, animated: false)
view.addSubview(mapView)
// Set the delegate property of our map view to self after instantiating it.
mapView.delegate = self
// User location
mapView.showsUserLocation = true
let userLoc = mapView.userLocation!
userLoc.title = "Hello"
userLoc.subtitle = "I am here!"
let userLat = userLoc.coordinate.latitude
let userLon = userLoc.coordinate.longitude
print(userLat, userLon)
/*
self.locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}*/
}
func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
}
</code></pre>
<p>Resulting print:</p>
<pre><code>3.40282346638529e+38 3.40282346638529e+38
</code></pre>
<p>The strange thing is that the annotation works fine, and when I click my location I get the title and subtitle.</p> | 1 |
Clear or selectively remove Remote Desktop Connection history | <p>Microsoft RDC on Windows (to open type <strong>mstsc</strong> in Start -> Run ) saves the history of previous computers you have connected to in the "Computer" dropdown.</p>
<p><a href="https://i.stack.imgur.com/dBMBR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dBMBR.png" alt="enter image description here"></a></p>
<p>How can I clear them, or selfectively delete entries?</p> | 1 |
DjangoRestFramework how to get user in viewset | <p>Im trying to make a friends feed that lists all "Beat" objects that i am currently friends with. How can i access user inside of my viewset to return the correct objects?</p>
<p>MODELS:</p>
<pre><code>class Beat(models.Model):
created_at = models.DateTimeField( default=datetime.now)
title = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
likes = models.IntegerField(default=0)
artist = models.ForeignKey(UserProfile, null=True, blank=True)
audio = models.FileField(upload_to="media_files/audio/",null=True, blank=True)
beat_cover = models.ImageField(upload_to="media_files/img/",null=True, blank=True);
admin_name = models.CharField(max_length=255, blank=True, null=True)
class Meta:
ordering = ['-created_at']
def __unicode__(self):
return unicode(self.admin_name)
class UserProfile(models.Model):
user = models.OneToOneField(User, blank=True, null=True)
admin_name = models.CharField(default="beat",max_length=255,blank=True, null=True)
profile_pic = models.ImageField(upload_to="media_files/users/")
def __unicode__(self):
return unicode(self.admin_name)
</code></pre>
<p>SERIALIZERS:</p>
<pre><code>class AllBeatStreamSerializer(serializers.ModelSerializer):
class Meta:
model = Beat
fields = ('created_at', 'title', 'audio', 'artist' )
depth = 1
</code></pre>
<p>VIEWSET:</p>
<pre><code>class FriendsBeatStreamViewSet(viewsets.ModelViewSet):
user = self.request.user
my_battles = Battle.objects.filter(challenging_beat__artist=user)
obj = {}
my_beats = Beat.objects.filter(artist=user)
related_users = Relationship.objects.filter(from_user=user).values_list('to_user', flat=True).distinct()
stream = Beat.objects.filter(artist__in=related_users)
stream = list(my_beats) + list(stream) + list(my_battles)
queryset = stream
serializer_class = AllBeatStreamSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
</code></pre> | 1 |
Get Parent element from child element in appium | <p>I have a recycler view. All Rows have same ids. Each Row has checkbox and text and these elements also have same ids. But some rows does not have checkboxes.</p>
<p>So what i am trying to do is locate checkbox by id, then get its parent node and locate its child. </p>
<pre><code>MobileElement childElement= driver.findElement(By.id("checkbox-child"));
MobileElement parentElement= // need to know how to do it
parentElement.findElement(By.id("text-child")).getText();
</code></pre>
<p>So i wanted to know how can i get parent element from its child Element.</p>
<p><a href="https://i.stack.imgur.com/539pD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/539pD.png" alt="enter image description here"></a></p> | 1 |
Apache Spark: How do I convert a Spark DataFrame to a RDD with type RDD[(Type1,Type2, ...)]? | <p>For example, suppose I have the DataFrame:</p>
<pre><code>var myDF = sc.parallelize(Seq(("one",1),("two",2),("three",3))).toDF("a", "b")
</code></pre>
<p>I can convert it to a <code>RDD[(String, Int)]</code> with a map:</p>
<pre><code>var myRDD = myDF.map(r => (r(0).asInstanceOf[String], r(1).asInstanceOf[Int]))
</code></pre>
<p>Is there a better way to do this, maybe using the DF schema?</p> | 1 |
yet another "gnutls_handshake: A TLS packet with unexpected length was received." while lftp | <p>I tried setting the following:</p>
<p>set ftp:initial-prot ""
set ftp:ssl-force true
set ftp:ssl-protect-data true
set ftp:ssl-auth TLS</p>
<p>and am on RHEL4 trying to lftp to a 2010 Windows server but I am getting </p>
<p>Fatal error: gnutls_handshake: A TLS packet with unexpected length was received.</p>
<p>Can you please let me know what is that am missing now?</p> | 1 |
Performing a npm install via Docker on a windows host | <p>I'm trying to create a docker dev tools container for a devlopement environment on a windows host via docker toolbox but I have some trouble running the npm install command.
It worked fine on a linux host but on the windows host I got the following error :</p>
<pre><code>npm ERR! Linux 4.1.13-boot2docker
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v5.5.0
npm ERR! npm v3.3.12
npm ERR! path /var/www/site/.npm/gulp/3.9.0/package.tgz.e87c24357cd6065ee71ce44c6f23673b
npm ERR! code ETXTBSY
npm ERR! errno -26
npm ERR! syscall rename
npm ERR! ETXTBSY: text file is busy, rename '/var/www/site/.npm/gulp/3.9.0/package.tgz.e87c24357cd6065ee71ce44c6f23673b' -> '/var/www/site/.npm/gulp/3.9.0/package.tgz'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>
npm ERR! Linux 4.1.13-boot2docker
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v5.5.0
npm ERR! npm v3.3.12
npm ERR! path npm-debug.log.39d944b679d410e5293d6721cbc8287a
npm ERR! code ETXTBSY
npm ERR! errno -26
npm ERR! syscall rename
npm ERR! ETXTBSY: text file is busy, rename 'npm-debug.log.39d944b679d410e5293d6721cbc8287a' -> 'npm-debug.log'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>
npm ERR! Please include the following file with any support request:
npm ERR! /var/www/site/npm-debug.log
</code></pre>
<p>Here is my Dockerfile :</p>
<pre><code>FROM node:latest
RUN apt-get update
RUN apt-get install vim -y
RUN useradd -ms /bin/bash node
RUN echo "fs.inotify.max_user_watches=100000" > /etc/sysctl.conf
ADD . /var/www/site
RUN chown -R node:node /var/www/site
RUN chown -R node:node /usr/local/lib/node_modules
RUN chown -R node:node /usr/local/bin
USER node
ENV HOME /var/www/site
WORKDIR /var/www/site
RUN npm install -g bower
RUN npm install --global gulp -y
EXPOSE 80 8080 35729
</code></pre>
<p>In Docker quickstart terminal, I use the following commands :</p>
<p>Building the image (works fine)</p>
<pre><code>docker build -t dev_tools .
</code></pre>
<p>Building the container (works fine)</p>
<pre><code>docker run --name=dev_tools_container -t --rm -v "//c/Users/Public/site:/var/www/site" --net=host dev_tools
</code></pre>
<p>Trying to install npm dependencies (shoots the error):</p>
<pre><code>docker exec -it dev_tools_container npm install
</code></pre>
<p>Thank you for your time !</p> | 1 |
NLS_NUMERIC_CHARACTERS reset when accessed from weblogic datasource | <p>I have problem with certain code and the root cause turned out to be NLS_NUMERIC_CHARACTERS setting at session level.</p>
<p>when I run the query directly on database:</p>
<pre><code>SQL> select 'nls_database_parameters' , p.* from nls_database_parameters p where PARAMETER = 'NLS_NUMERIC_CHARACTERS'
2 union all
3 select 'nls_session_parameters', p.* from nls_session_parameters p where PARAMETER = 'NLS_NUMERIC_CHARACTERS'
4 union all
5 select 'nls_instance_parameters', p.* from nls_instance_parameters p where PARAMETER = 'NLS_NUMERIC_CHARACTERS';
'NLS_DATABASE_PARAMETERS' PARAMETER VALUE
------------------------- ------------------------ -----
nls_database_parameters NLS_NUMERIC_CHARACTERS .,
nls_session_parameters NLS_NUMERIC_CHARACTERS .,
nls_instance_parameters NLS_NUMERIC_CHARACTERS .,
</code></pre>
<p>But, when I run this same query from weblogic datasource</p>
<pre><code>select 'nls_database_parameters' , p.* from nls_database_parameters p where PARAMETER = 'NLS_NUMERIC_CHARACTERS'
union all
select 'nls_session_parameters', p.* from nls_session_parameters p where PARAMETER = 'NLS_NUMERIC_CHARACTERS'
union all
select 'nls_instance_parameters', p.* from nls_instance_parameters p where PARAMETER = 'NLS_NUMERIC_CHARACTERS';
-- 'NLS_DATABASE_PARAMETERS', PARAMETER, VALUE
1 nls_database_parameters NLS_NUMERIC_CHARACTERS .,
2 nls_session_parameters NLS_NUMERIC_CHARACTERS ,
3 nls_instance_parameters NLS_NUMERIC_CHARACTERS .,
</code></pre>
<p>The session value is wrong and is being reset by some trigger/script when accessed through weblogic datasource, I checked the weblogic startup scripts etc to see if we reset somewhere but no help.</p>
<p>Any pointers/ideas in this direction much appreciated if somebody faced similar issue.</p> | 1 |
What are the alternatives to eval in Ruby? | <p>I wrote the following recursive function in order to parse some settings and correctly populate some log file objects I have.</p>
<p>When I run this code against Code Climate it tells me that (of course) the use of <code>eval</code> is not encouraged. Is there a way I can rewrite this method so I do not need <code>eval</code> and also do not need a <code>case</code> statement? Nothing comes to mind.</p>
<pre><code>def parse(settings, logfile = nil)
settings.each do |key, value|
if value.is_a?(Hash)
logfile = Logmsg::LogFile.new
parse(value, logfile)
else
eval("logfile.#{key} = value")
end
end
end
</code></pre>
<p>Any ideas?</p>
<p>I am trying the <code>instance_variable_set</code> meta-programming method however I am still running into some issues with it. For some reason my tests are all failing now due to</p>
<pre><code>Argument Error: comparison of Fixnum with String failed
</code></pre>
<p>I am still trying to figure that out.</p> | 1 |
how to disable DEBUG in log4j? | <p>need your help, I have log4j.properties like this</p>
<pre><code># Root logger option
log4j.rootLogger=stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${catalina.home}/logs/Admin.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
</code></pre>
<p>and this is my Controller</p>
<pre><code>@SuppressWarnings("unused")
@RequestMapping(value="/addedc", method = RequestMethod.POST, consumes = "application/json", headers = "content-type=application/x-www-form-urlencoded")
public @ResponseBody Status_new addedc(@RequestBody installasimodel edc){
log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< START ADDEDC >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
log.debug("qqqqqqqqqqqqqq");
List<installasimodel>mapusr = null;
try{
insta.addistlsi(edc);
log.info(new Status_new(1, "Sukses!"));
return new Status_new(1, "Sukses!");
}catch(Exception mapi){
log.info(new Status_new(0, mapi.getMessage()));
log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< STOP ADDEDC >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
return new Status_new(0, mapi.getMessage());
}
}
</code></pre>
<p>I want to show "INFO" in the file .log, but why DEBUG also appear? thus fulfilling the page.This example logs generated</p>
<pre><code>....
....
2016-02-05 15:14:58 DEBUG FilterSecurityInterceptor:185 - Public object - authentication not attempted
2016-02-05 15:14:58 DEBUG FilterChainProxy:323 - /ins-server-insta/ins-list-all-insta-installasi reached end of additional filter chain; proceeding with original chain
2016-02-05 15:14:58 DEBUG DispatcherServlet:838 - DispatcherServlet with name 'mvc-dispatcher' processing GET request for [/admin-teknikal/ins-server-insta/ins-list-all-insta-installasi]
2016-02-05 15:14:58 DEBUG RequestMappingHandlerMapping:246 - Looking up handler method for path /ins-server-insta/ins-list-all-insta-installasi
2016-02-05 15:14:58 DEBUG RequestMappingHandlerMapping:251 - Returning handler method [public java.util.List<com.bni.edc.model.installasimodel> com.bni.edc.controller.instaController.getInsta()]
2016-02-05 15:14:58 DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'instaController'
2016-02-05 15:14:58 DEBUG DispatcherServlet:925 - Last-Modified value for [/admin-teknikal/ins-server-insta/ins-list-all-insta-installasi] is: -1
2016-02-05 15:14:58 INFO nanda:63 - <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< START ALL INSTALLASI LIST >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2016-02-05 15:14:58 DEBUG AbstractTransactionImpl:160 - begin
2016-02-05 15:14:58 DEBUG LogicalConnectionImpl:226 - Obtaining JDBC connection
2016-02-05 15:14:58 DEBUG DriverManagerDataSource:142 - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/bni]
2016-02-05 15:14:58 DEBUG LogicalConnectionImpl:232 - Obtained JDBC connection
2016-02-05 15:14:58 DEBUG JdbcTransaction:69 - initial autocommit status: true
2016-02-05 15:14:58 DEBUG JdbcTransaction:71 - disabling autocommit
2016-02-05 15:14:58 DEBUG SQL:109 - SELECT * FROM istlsi_edc_tkn_tebel WHERE sts!='1' ORDER BY id_istlsi_tkn DESC
2016-02-05 15:14:58 DEBUG Loader:951 - Result set row: 0
2016-02-05 15:14:58 DEBUG Loader:1485 - Result row: EntityKey[com.bni.edc.model.installasimodel#22344444]
2016-02-05 15:14:58 DEBUG Loader:951 - Result set row: 1
2016-02-05 15:14:58 DEBUG Loader:1485 - Result row: EntityKey[com.bni.edc.model.installasimodel#232323]
2016-02-05 15:14:58 DEBUG TwoPhaseLoad:160 - Resolving associations for [com.bni.edc.model.installasimodel#22344444]
2016-02-05 15:14:58 DEBUG TwoPhaseLoad:286 - Done materializing entity [com.bni.edc.model.installasimodel#22344444]
2016-02-05 15:14:58 DEBUG TwoPhaseLoad:160 - Resolving associations for [com.bni.edc.model.installasimodel#232323]
2016-02-05 15:14:58 DEBUG TwoPhaseLoad:286 - Done materializing entity [com.bni.edc.model.installasimodel#232323]
2016-02-05 15:14:58 DEBUG AbstractTransactionImpl:175 - committing
2016-02-05 15:14:58 DEBUG AbstractFlushingEventListener:149 - Processing flush-time cascades
2016-02-05 15:14:58 DEBUG AbstractFlushingEventListener:189 - Dirty checking collections
2016-02-05 15:14:58 DEBUG AbstractFlushingEventListener:123 - Flushed: 0 insertions, 0 updates, 0 deletions to 2 objects
2016-02-05 15:14:58 DEBUG AbstractFlushingEventListener:130 - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
2016-02-05 15:14:58 DEBUG EntityPrinter:114 - Listing entities:
2016-02-05 15:14:58 DEBUG EntityPrinter:121 - com.bni.edc.model.installasimodel{tngl_qrcode=null, tngl_sbm_istlsi=null, tngl_sbmit=2016-02-04, ttd_mrchn=null, kde_pos_sls=0, own=BN, mid=23232323, hp_penerima=null, id_istlsi_tkn=48, id_wlyh=1, tid=232323, id_spv=0, foto_istlsi=null, sc=1, ttd_istlsi=null, alamat_mrchn=asasa, jam=null, kde_pos=0, sn=null, ket_istlsi=sdsddsdsdsdsd, kde_pos_tkn=null, ntf_adm=0, ttd=null, ms=null, id_tkn=28, koor_lat=null, gprs_id=null, tngl_chck_adm=null, version=null, koor_long=null, sts=0, foto=null, phone=23232, nm_penerima=daa, sts_edc=0, id_usr_adm_sls=0, own_mrchn=null, nm_mrchn=dsds, id_usr_sls=0}
2016-02-05 15:14:58 DEBUG EntityPrinter:121 - com.bni.edc.model.installasimodel{tngl_qrcode=null, tngl_sbm_istlsi=null, tngl_sbmit=2016-02-04, ttd_mrchn=null, kde_pos_sls=0, own=BN, mid=20397878789, hp_penerima=null, id_istlsi_tkn=49, id_wlyh=3, tid=22344444, id_spv=0, foto_istlsi=null, sc=1, ttd_istlsi=null, alamat_mrchn=jl.soedirman kav.04, jam=null, kde_pos=0, sn=null, ket_istlsi=butuh cepat dan segera, kde_pos_tkn=null, ntf_adm=0, ttd=null, ms=null, id_tkn=27, koor_lat=null, gprs_id=null, tngl_chck_adm=null, version=null, koor_long=null, sts=0, foto=null, phone=09787879, nm_penerima=yuyun, sts_edc=0, id_usr_adm_sls=0, own_mrchn=null, nm_mrchn=laksana baru, id_usr_sls=0}
2016-02-05 15:14:58 DEBUG JdbcTransaction:113 - committed JDBC Connection
2016-02-05 15:14:58 DEBUG JdbcTransaction:126 - re-enabling autocommit
2016-02-05 15:14:58 DEBUG LogicalConnectionImpl:246 - Releasing JDBC connection
2016-02-05 15:14:58 DEBUG LogicalConnectionImpl:264 - Released JDBC connection
2016-02-05 15:14:58 INFO nanda:71 - <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< STOP ALL INSTALLASI LIST >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
....
</code></pre>
<p>how can I disable DEBUG ?</p> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.