title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
How can i use DataTable in the following case?
|
<p>The following html table is created from json data file.
Kindly tell me how can i use DataTable and i also need to refresh the table it means every few seconds the new data comes in the json file so the code should read the new json file and updates it in every few seconds.
The running table which i am trying to initiate with DataTable says no data availabe.
Thanks in advance </p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script src="js/myjs.js"></script>
<script
src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"
type="text/javascript"></script>
<link rel="stylesheet"
href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<title>qstat</title>
<style>
th,td,p,input {
font:14px Verdana;
}
table ,th, td
{
border: solid 1px#f345;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
color: #2f23d;
<div id="tables">
<div id="tabs">
<ul>
<li><a href="#running_jobs">Running Jobs</a></li>
<li><a href="#queued_jobs">Queued Jobs</a></li>
<li><a href="#hold">Hold Jobs</a></li>
</ul>
<div id="running_jobs">
<table class="data" id="running">
<thead>
<tr>
<th style="display: none">Color</th>
<th class="header_left">Job ID</th>
<th>Job Name</th>
<th>User</th>
<th>Time Use</th>
<th>Queue</th>
</tr>
</thead>
</table>
</div>
<div id="queued_jobs">
<table class="data" id="queued">
<thead>
<tr>
<th class="header_left">Job ID</th>
<th>Job Name</th>
<th>User</th>
<th>Time Use</th>
<th>Queue</th>
</tr>
</thead>
</table>
</div>
<div id="hold_jobs">
<table class="data" id="hold">
<thead>
<tr>
<th class="header_left">Job ID</th>
<th>Job Name</th>
<th>User</th>
<th>Time Use</th>
<th>Queue</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</body>
<script>
function CreateTable()
{
$.getJSON("jsonoutput.json",function(data){
var Running = new Object();
var Queue = new Object();
var Hold = new Object();
for(var i in data)
{
var job = {};
var ndi = data[i]
job.Job_ID = i;
job.Job_Name=ndi["Name"];
job.Job_User=ndi["User"];
job.Job_Time_Use=ndi["Time Use"];
job.Job_State= ndi["State"];
job.Job_Queue= ndi["Queue"];
var job_data = ' ';
job_data+= '<tr>';
job_data+='<td>' +job.Job_ID+'</td>';
job_data+='<td>'+job.Job_Name+'</td>';
job_data+='<td>'+job.Job_User+'</td>';
job_data+='<td>'+job.Job_Time_Use+'</td>';
job_data+='<td>'+job.Job_Queue+'</td>';
job_data+='</tr>';
if(job.Job_State=="R")
$('#running').append(job_data);
else if(job.Job_State=="Q")
$('#queued').append(job_data);
else
$('#hold').append(job_data);
}
});
}
</script>
<script>
CreateTable();
$('#running').DataTable();
</script>
</code></pre>
| 3 | 3,074 |
php variables correctly pass inside the jquery or javascript highchart
|
<p>click here for jsfiddle highchart link: <a href="http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-basic/" rel="nofollow">Column - Bar High Chart</a></p>
<p>this code is the actual code of the Column bar highchart, is there a way to make its graph base on php varible. </p>
<pre><code><html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type='text/javascript' src='js/jquery.min.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
</style>
<script type='text/javascript'>
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' mm';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tokyo',
data: [100, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}, {
name: 'New York',
data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]
}, {
name: 'London',
data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]
}, {
name: 'Berlin',
data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
}]
});
});
});
//]]>
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
</code></pre>
<p>Question
is this possible "
<code>[100, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]</code>"</p>
<p>to became</p>
<pre><code>[<?php $newval1.",".$newval2.",".$newval3.",".$newval4.",".$newval5.",".$newval6.",".$newval7.",".$newval8.",".$newval9.",".$newval10.",".$newval11.",".$newval12 ?>]
</code></pre>
<p>so that the value are from php variables, correct me.. thanks</p>
| 3 | 2,215 |
UItableView automaticDimension not working with UIStackView
|
<p>I want that my <code>UITableViewCell</code> calculates properly its height so its bottom matches the <code>UIStackView</code> bottom.</p>
<p>I have an understanding that for <code>UITableView.automaticDimension</code> to work you need to set all the vertical constraints of the <code>UITableViewCell</code> so it can calculate its height.</p>
<p>That's what I'm failing to do. I've made a test project in which I made sure of:</p>
<ul>
<li><code>tableView.rowHeight</code> property is set to <code>UITableView.automaticDimension</code>.</li>
<li>To not implement function <code>heightForRowAt</code>.</li>
<li><code>TableViewCell</code> <code>Row Height</code> is set to <code>Automatic</code> in the xib file.</li>
<li>All views are constrained vertically.</li>
<li>To play with <code>UIStackView</code> <code>distribution</code> property.</li>
<li>To set the <code>UIStackView</code> bottom constraint to the <code>superView</code> to <code>Less Than or Equal</code> (with this items are too tiny and with <code>Greater Than or Equal</code>, or <code>Equal</code>, item's height is equal to screen width since they have <code>aspect ratio</code> 1:1</li>
<li>To play with <code>Content Hugging Priority</code> and <code>Content Compression Resistance Priority</code>. In the test all views have default values, for hugging horizontal and vertical 250, and for compression horizontal and vertical 750.</li>
</ul>
<p>The code:</p>
<pre><code>import Foundation
import UIKit
class IBAutomaticDimensionTableViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet private weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableView.automaticDimension
tableView.register(
IBAutomaticDimensionTableViewCell.nib,
forCellReuseIdentifier: IBAutomaticDimensionTableViewCell.nibName
)
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
// view.layoutIfNeeded() Not working with or without it
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: IBAutomaticDimensionTableViewCell.nibName,
for: indexPath
) as! IBAutomaticDimensionTableViewCell
return cell
}
}
</code></pre>
<p>The cell's xib file:
<a href="https://i.stack.imgur.com/vyNt4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vyNt4.png" alt="The cell's xib file" /></a></p>
<p>Result with <code>Less Than or Equal</code> bottom constraint:</p>
<p><a href="https://i.stack.imgur.com/e7jQr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e7jQr.png" alt="Result with Less Than or Equal bottom constraint" /></a></p>
<p>Result with <code>Greater Than or Equal</code> or <code>Equal</code> bottom constraint:</p>
<p><a href="https://i.stack.imgur.com/b7Q1H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b7Q1H.png" alt="Result with Greater Than or Equal or Equal bottom constraint" /></a></p>
| 3 | 1,204 |
Unable to extract whole cookie with Python's requests module
|
<p>I want to make crawler for one website that requires login.
I have email and password (sorry but I can not share it)</p>
<p>This is the website:
<a href="https://www.eurekalert.org/" rel="nofollow noreferrer">https://www.eurekalert.org/</a>
When I click on login, it redirects me here:
<a href="https://signin.aaas.org/oxauth/login" rel="nofollow noreferrer">https://signin.aaas.org/oxauth/login</a></p>
<p>First I have done this:</p>
<pre><code>session = requests.session()
r = session.get('https://www.eurekalert.org/')
cookies = r.cookies.get_dict()
#cookies = cookies['PHPSESSID']
print("COOKIE eurekalert", cookies)
</code></pre>
<p>The only cookie that I could get is:</p>
<pre><code>{'PHPSESSID': 'vd2jp35ss5d0sm0i5em5k9hsca'}
</code></pre>
<p>But for logging in I need more cookie key-value pairs.</p>
<p>I have managed to log in, but for logging in I need to have cookie data, and I can not retrieve it:</p>
<pre><code>login_response = session.post('https://signin.aaas.org/oxauth/login', headers=login_headers, data=login_data)
headers = {
'authority': 'www.eurekalert.org',
'cache-control': 'max-age=0',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-fetch-site': 'cross-site',
'sec-fetch-mode': 'navigate',
'sec-fetch-user': '?1',
'sec-fetch-dest': 'document',
'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
'sec-ch-ua-mobile': '?0',
'referer': 'https://signin.aaas.org/',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'cookie': '_fbp=fb.1.1626615735334.1262364960; __gads=ID=d7a7a2d080319a5d:T=1626615735:S=ALNI_MYdVrKc4-uasMo3sVMCjzFABP0TeQ; __utmz=28029352.1626615736.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=28029352.223995016.1626615735.1626615735.1626615735.1; _ga=GA1.2.223995016.1626615735; adBlockEnabled=not%20blocked; _gid=GA1.2.109852943.1629792860; AMCVS_242B6472541199F70A4C98A6%40AdobeOrg=1; AMCV_242B6472541199F70A4C98A6%40AdobeOrg=-1124106680%7CMCIDTS%7C18864%7CMCMID%7C62442014968131466430435549466681355333%7CMCAAMLH-1630397660%7C6%7CMCAAMB-1630397660%7CRKhpRz8krg2tLO6pguXWp5olkAcUniQYPHaMWWgdJ3xzPWQmdj0y%7CMCOPTOUT-1629800060s%7CNONE%7CvVersion%7C5.2.0; s_cc=true; __atuvc=2%7C31%2C0%7C32%2C0%7C33%2C1%7C34; PHPSESSID=af75g985r6eccuisu8dvkkv41v; s_tp=1616; s_ppv=www.eurekalert.org%2C58%2C58%2C938',
}
response = session.get('https://www.eurekalert.org/reporter/home', headers=headers)
print(response)
soup = BeautifulSoup(response.content, 'html.parser')
</code></pre>
<p>The headers (full cookie data) are collected with <code>network->copy->copy curl->pasted here:</code>https://curl.trillworks.com/</p>
<p>But values that should go in the <code>cookie</code> should be retrieved dynamically. Im missing the value that should go in the <code>'cookie'</code>.
When I go in the cookie tab, all values are there, but I can not get it with my request.</p>
| 3 | 1,463 |
ContextMenuStrip does not appear when clicking on object within a UserControl
|
<p>I created a UserControl with a chart inside that are the same size.
In my main form I create these UserControls dynamically and I can delete or edit them using a ContextMenuStrip by right clicking.</p>
<p>The problem happens when I create dynamically and click on the UserControl above the chart (inside UserControl) the ContextMenuStrip does not appear, it appears only when I click on the <code>userform</code>.</p>
<p>I tested several alternatives to no avail. Someone would have an idea.</p>
<p>EDIT:</p>
<p><a href="https://i.stack.imgur.com/JrLA2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JrLA2.png" alt="Picture1" /></a></p>
<p>I have a UserControl (dynamically generated that is in blue), which is contained in my main form in green. The UserControl consists of just a chart and internal codes, it has the same size as the UserControl (I moved it to exemplify).</p>
<p>Right-clicking on the UserControl, I open a ContextMenuStrip (which belongs to the main form) that allows you to delete, edit and copy.</p>
<p>However the ContextMenuStrip only appears if I click on the UserControl (gray part), if I click on the chart (yellow part) it does not appear.</p>
<p>EDIT2:</p>
<p>I use this code in the main form</p>
<pre><code>Public Sub add_Control_Click(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Try
If e.Button = MouseButtons.Right Then
Dim cms = New ContextMenuStrip
Dim item1 = cms.Items.Add("Edit")
item1.Tag = 1
AddHandler item1.Click, AddressOf menuEdit
Dim item2 = cms.Items.Add("Delete")
item2.Tag = 2
AddHandler item2.Click, AddressOf menuEdit
Dim item3 = cms.Items.Add("Copy")
item2.Tag = 3
AddHandler item3.Click, AddressOf menuEdit
cms.Show(sender, e.Location)
tempControl = sender
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub menuEdit(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim item = CType(sender, ToolStripMenuItem)
Dim selection = CInt(item.Tag)
changedControls = True 'Set changed controls
SalvarToolStripMenuItem.Enabled = True 'Set definition enable
Select Case selection
Case 0
tempCopied = True
copiedControl = tempControl
Case 1
callEditControl(tempControl)
Case 3
If MsgBox("Do you want to remove the item.", vbOKCancel + vbQuestion, "Delete") = vbOK Then
Me.Controls.Remove(tempControl)
End If
End Select
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub`
</code></pre>
| 3 | 1,219 |
JavaScript add json to existing object
|
<p>I'm struggling with adding JSON to existing objects with Vue.js.
So I have a function that is calculating some variants and it's working well for now, but I would need to change them in order to give correct data to my Laravel backend.</p>
<p>So this is how my array looks like (this array is used to calculate variants)</p>
<pre><code>"attributes":[
{
"title":{
"text":"Size",
"value":"1"
},
"values":[
"Red",
"Green"
]
},
{
"title":{
"text":"Color",
"value":"2"
},
"values":[
"X",
"M"
]
}
]
</code></pre>
<p>And I'm calculating them like this:</p>
<pre><code>addVariant: function () {
const parts = this.form.attributes.map(attribute => attribute.values);
const combinations = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
this.form.variants = combinations;
},
</code></pre>
<p>And the output looks like:</p>
<pre><code>"variants":[
[
"Red",
"X"
],
[
"Red",
"M"
],
[
"Green",
"X"
],
[
"Green",
"M"
]
]
</code></pre>
<p>So this is calculated well, but this variants would need to look like this:</p>
<pre><code>"variants":[
{
"title": "Red/M",
"slug": "prooooo",
"options": [
{
"key": "Color",
"value": "Red"
},
{
"key": "Size",
"value": "M"
}
]
},
{
"title": "Red/X",
"slug": "prooooo",
"options": [
{
"key": "Color",
"value": "Red"
},
{
"key": "Size",
"value": "X"
}
]
}
</code></pre>
<p>As you see I have a title field that is calculated by options.values, but the real question is how to make that JSON look like the last given JSON.</p>
<p>Any ideas on how to do it?</p>
| 3 | 1,689 |
How to set fixed y-axis values in SAPUI5 VizFrame Column Chart using XMLView?
|
<p>I have created a VizFrame Column Chart in SAPUI5 using oData. Now I need to put fixed values in y-axis (Dimension axis) since I want to show the days of the week on the y-axis, and how many hours worked in which day using the x-axis. Since I use oData date values I got from SAP, I can only show those values, but I want to show all the days in that week.</p>
<ol>
<li>How can I set fixed scale for y-axis, and then fill those values with oData?</li>
<li>I want to show the time of work in the same days to be added, but I get only one value for a day, it does not add up with different data with the same date</li>
<li>I also cannot format the Time value as HH:mm:ss setting, when I try to format like that, it does not show the column data. The formatting works on sap.ui.Table, but not on the VizFrame.</li>
</ol>
<p>My code in XMLView is as follows:</p>
<pre><code>
<viz:VizFrame id="idVizFrame" width="100%" vizType='column' vizProperties="{title: {text: 'Weekly Timesheet Chart'}}">
<viz:dataset>
<viz.data:FlattenedDataset data="{/TasksSet}">
<viz.data:dimensions>
<viz.data:DimensionDefinition name="JobDate" value="{ path: 'JobDate', type: 'sap.ui.model.type.Date', formatOptions: {source: {pattern: 'yyyy-MM-dd'}, pattern: 'dd.MM.yyyy' } }" />
</viz.data:dimensions>
<viz.data:measures>
<viz.data:MeasureDefinition name="Duration"
value="{path: 'Duration', type: 'sap.ui.model.type.Time', formatOptions: {source:{pattern: 'HHmmss'},pattern: 'HH:mm:ss'}} "/>
</viz.data:measures>
</viz.data:FlattenedDataset>
</viz:dataset>
<viz:feeds>
<viz.feeds:FeedItem id='valueAxisFeed' uid="valueAxis" type="Measure" values="Duration"/>
<viz.feeds:FeedItem id='categoryAxisFeed' uid="categoryAxis" type="Dimension" values="JobDate"/>
</viz:feeds>
</viz:VizFrame>
</code></pre>
| 3 | 1,250 |
AJAX not working in django production mode?
|
<p>I've a django app deployed on heroku. In one of the section I asks for feedback and email of the person. If the email is valid email then I just reply Thank you. This is all being done using AJAX from getting values of form to returning thank you. It works fine in developement mode but not in prouction mode. </p>
<p>Here's my 'index.js'</p>
<pre><code>function valid(email)
{
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email);
}
$(document).on('submit','.Myform',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'',
data:{
message:$('#id_message').val(),
email:$('#id_email').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
success: function() {
let validate = valid($('#id_email').val());
if(validate){
$('.Myform').fadeOut();
$('.thank_you').fadeIn();
}
else{
$('.Myform').show();
alert('Please enter valid email address.');
}
}
});
});
</code></pre>
<p>I've only one view in my app. So transferring data of AJAX to that view.</p>
<p>Here's my <code>views.py</code></p>
<pre><code>def index(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
message = request.POST['message']
email = request.POST['email']
print(message)
print(email)
subject = "{} by {}".format(message,email)
recipients = ['xyz@mail.com']
sender = 'my@mail.com'
send_mail(subject, message, sender ,recipients,fail_silently=False)
return HttpResponse('')
else:
form = ThoughtForm()
return render(request,'my_webapp/index.html',{'form':form})
</code></pre>
<p>My <code>urls.py</code> file-</p>
<pre><code>urlpatterns = [
path('',views.index,name='index')
]
</code></pre>
<p>In developement mode- It all works well. </p>
<p><strong>In production mode as soon as I hit submit button it shows me the loading gif but then it dissappears with no thank you message, no wrong email alert nothing happens and form vanishes</strong> </p>
<p>The issue seems to be with the url. Can somebody help.</p>
<p>Here's the traceback error I'm getting in heroku logs-</p>
<pre><code>Internal Server Error: /
2019-10-07T18:30:33.977239+00:00 app[web.1]: Traceback (most recent call last):
2019-10-07T18:30:33.977241+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
2019-10-07T18:30:33.977243+00:00 app[web.1]: response = get_response(request)
2019-10-07T18:30:33.977246+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
2019-10-07T18:30:33.977248+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request)
2019-10-07T18:30:33.97725+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
2019-10-07T18:30:33.977253+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs)
2019-10-07T18:30:33.977255+00:00 app[web.1]: File "/app/my_webapp/views.py", line 27, in index
2019-10-07T18:30:33.977257+00:00 app[web.1]: send_mail(subject, thoughts, sender ,recipients,fail_silently=False)
2019-10-07T18:30:33.977259+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/__init__.py", line 60, in send_mail
2019-10-07T18:30:33.977261+00:00 app[web.1]: return mail.send()
2019-10-07T18:30:33.977263+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/message.py", line 291, in send
2019-10-07T18:30:33.977265+00:00 app[web.1]: return self.get_connection(fail_silently).send_messages([self])
2019-10-07T18:30:33.977267+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages
2019-10-07T18:30:33.977269+00:00 app[web.1]: new_conn_created = self.open()
2019-10-07T18:30:33.977271+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 70, in open
2019-10-07T18:30:33.977273+00:00 app[web.1]: self.connection.login(self.username, self.password)
2019-10-07T18:30:33.977275+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/smtplib.py", line 730, in login
2019-10-07T18:30:33.977277+00:00 app[web.1]: raise last_exception
2019-10-07T18:30:33.977279+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/smtplib.py", line 721, in login
2019-10-07T18:30:33.977281+00:00 app[web.1]: initial_response_ok=initial_response_ok)
2019-10-07T18:30:33.977283+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/smtplib.py", line 642, in auth
2019-10-07T18:30:33.977285+00:00 app[web.1]: raise SMTPAuthenticationError(code, resp)
2019-10-07T18:30:33.977446+00:00 app[web.1]: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials q2sm7667020qkc.68 - gsmtp')
2019-10-07T18:30:33.978833+00:00 app[web.1]: 10.51.220.16 - - [07/Oct/2019:18:30:33 +0000] "POST / HTTP/1.1" 500 13750 "https://application.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0"
2019-10-07T18:30:33.980844+00:00 heroku[router]: at=info method=POST path="/" host=application.herokuapp.com request_id=9bfdde45-dc5c-4fc6-bcee-4cdd3dd5aa72 fwd="103.212.146.48" dyno=web.1 connect=7ms service=191ms status=500 bytes=13976 protocol=https
</code></pre>
| 3 | 2,529 |
How to Render the categories in database on SQL server in _Layout.cshtml
|
<p>i am trying to show the categories in my database on <code>SQL</code> on the homepage of my <strong><code>MVC web</code></strong> , how to do that?
I have this in my <code>_Layout.cshtml</code>:</p>
<pre><code><div class="list-group">
<a href="#" class="list-group-item">Category 1</a>
<a href="#" class="list-group-item">Category 2</a>
<a href="#" class="list-group-item">Category 3</a>
</div>
</code></pre>
<p>this is my <code>Views/store/index.cshtml</code>:</p>
<pre><code>@model IEnumerable<MVCOnlineShop.Models.Category>
@{
ViewBag.Title = "Store";
}
<h3>Browse Categories</h3>
<p>
Select from @Model.Count()
Categories:
</p>
<ul>
@foreach (var Category in Model)
{
<li>
@Html.ActionLink(Category.CategoryName,
"Browse", new { Category = Category.CategoryName })
</li>
}
</ul>
</code></pre>
<p>this is my <code>StoreController</code>:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCOnlineShop.Models;
namespace MVCOnlineShop.Controllers
{
public class StoreController : Controller
{
OnlineStoreEntities storeDB = new OnlineStoreEntities();
//
// GET: /Store/
public ActionResult Index()
{
var Categories = storeDB.Categories.ToList();
return View(Categories);
}
//
// GET: /Store/Browse
public ActionResult Browse(string Category)
{
// Retrieve Category and its Associated Products from database
var CategoryModel = storeDB.Categories.Include("Products")
.Single(g => g.CategoryName == Category);
return View(CategoryModel);
}
//
// GET: /Store/Details
public ActionResult Details(int id)
{
var Product = storeDB.Products.Find(id);
return View(Product);
}
//
// GET: /Store/Browse?Category=Games
}
}
</code></pre>
<p>and this is my <code>Global.asax</code>:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace MVCOnlineShop
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
</code></pre>
| 3 | 1,363 |
How to make JavaScript output?
|
<p>I've been trying to make the following code to output a value based on the number allocated, to a span. I'm not sure why or how I'm going wrong.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myFunction() {
var league = 1
var shirt = 2
if (league == 1) {
if (shirt == 1) {
document.getElementById("shirt").innerHTML = "Score 70+ Goals = 7,500,000";
} else if (shirt == 2) {
document.getElementById("shirt").innerHTML = "Score 60+ Goals = 6,000,000";
} else if (shirt == 3) {
document.getElementById("shirt").innerHTML = "Score 55+ Goals = 5,500,000";
} else if (shirt == 4) {
document.getElementById("shirt").innerHTML = "Score 50+ Goals = 5,000,000";
} else if (shirt == 5) {
document.getElementById("shirt").innerHTML = "Score 45+ Goals = 4,500,000";
} else if (shirt == 6) {
document.getElementById("shirt").innerHTML = "Score 40+ Goals = 4,000,000";
} else if (shirt == 7) {
document.getElementById("shirt").innerHTML = "Score 35+ Goals = 3,000,000";
}
} else if (league == 2) {
if (shirt == 1) {
document.getElementById("shirt").innerHTML = "Score 70+ Goals = 7,000,000";
} else if (shirt == 2) {
document.getElementById("shirt").innerHTML = "Score 60+ Goals = 5,500,000";
} else if (shirt == 3) {
document.getElementById("shirt").innerHTML = "Score 55+ Goals = 5,000,000";
} else if (shirt == 4) {
document.getElementById("shirt").innerHTML = "Score 50+ Goals = 4,500,000";
} else if (shirt == 5) {
document.getElementById("shirt").innerHTML = "Score 45+ Goals = 4,000,000";
} else if (shirt == 6) {
document.getElementById("shirt").innerHTML = "Score 40+ Goals = 3,500,000";
} else if (shirt == 7) {
document.getElementById("shirt").innerHTML = "Score 35+ Goals = 2,500,000";
}
} else if (league == 3) {
if (shirt == 1) {
document.getElementById("shirt").innerHTML = "Score 70+ Goals = 6,500,000";
} else if (shirt == 2) {
document.getElementById("shirt").innerHTML = "Score 60+ Goals = 5,000,000";
} else if (shirt == 3) {
document.getElementById("shirt").innerHTML = "Score 55+ Goals = 4,500,000";
} else if (shirt == 4) {
document.getElementById("shirt").innerHTML = "Score 50+ Goals = 4,000,000";
} else if (shirt == 5) {
document.getElementById("shirt").innerHTML = "Score 45+ Goals = 3,500,000";
} else if (shirt == 6) {
document.getElementById("shirt").innerHTML = "Score 40+ Goals = 3,000,000";
} else if (shirt == 7) {
document.getElementById("shirt").innerHTML = "Score 35+ Goals = 2,000,000";
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="shirt">Placeholder text</span></code></pre>
</div>
</div>
</p>
| 3 | 1,129 |
Multibutton form doesn't map data back to textboxes .net core 1.1
|
<p>Ok, so now I'm trying to learn .net core mcv and I'm having a problem mapping data from MySQL back to my form. When I make the form as a single text box with a single button, and the other fields outside the form (but on the same page), the mapping works fine. If I include all the fields within the form, the data is obtained but not displayed on the page. I have even gone so far as to code one of the multiple submit buttons as an update of the data. I use the first text box to get the item from the database, which it does (but does not map to the text-boxes), then in the second text box (which should have the existing data, but is empty) I put the information to update in the database, click on the submit button for that text box, and the database is updated (but the text boxes in the view remain blank).</p>
<p>My model:</p>
<pre><code> using System;
namespace DbTest.Models
{
public class ProductInventory
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public int Field4 { get; set; }
}
}
</code></pre>
<p>my controller:</p>
<pre><code>using System;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using Microsoft.AspNetCore.Authorization;
using DbTest.Models;
namespace DbTest.Controllers
{
public class InventoryController : Controller
{
// [Authorize]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult ProcessForm(string button, ProductInventory p)
{
IActionResult toDo = null;
if (button == "Button1")
{
toDo = GetItem(p);
}
if (button == "Button2")
{
toDo = UpdateField2(p);
}
if (button == "Button3")
{
toDo = UpdateField3(p);
}
if (button == "Button4")
{
toDo = UpdateField4(p);
}
return toDo;
}
// [HttpPost]
public IActionResult GetItem(ProductInventory p)
{
//CODE SNIP - DATABASE QUERY, IT ALL WORKS, SO WHY BOTHER YOU WITH THE DETAILS?
return View("Index", p);
}
public IActionResult UpdateField2(ProductInventory p)
{
//CODE SNIP - DATABASE UPDATE, ALL WORKS, NOTHING TO SEE HERE
return View("Index", p);
}
}
}
</code></pre>
<p>And finally, my view:</p>
<pre><code>@model DbTest.Models.ProductInventory
@{
ViewData["Title"] = "Inventory Page";
}
@using (Html.BeginForm("ProcessForm", "Inventory", FormMethod.Post))
{
<div>
Search Item (Field 1):
@Html.TextBoxFor(model => model.Field1)
<input type="submit" name="button" value="Button1" />
</div>
<div>
Field 2:
@Html.TextBoxFor(model => model.Field2)
<input type="submit" name="button" value="Button2" />
</div>
<div>
Field 3:
@Html.TextBoxFor(model => model.Field3)
<input type="submit" name="button" value="Button3" />
</div>
<div>
Field 4:
@Html.TextBoxFor(model => model.Field4)
<input type="submit" name="button" value="Button4" />
</div>
}
</code></pre>
<p>To reiterate, if I close the form after Button1:</p>
<pre><code>@using (Html.BeginForm("ProcessForm", "Inventory", FormMethod.Post))
{
<div>
Search Item (Field 1):
@Html.TextBoxFor(model => model.Field1)
<input type="submit" name="button" value="Button1" />
</div>
}
<div>
Field 2:
//etc.
</code></pre>
<p>the mapping works, but only the first field and button of the form work. With the form around all four fields and buttons, the mapping doesn't work, but the coding of the second button DOES update the database on clicking Button2.</p>
<p>Can someone explain what I've done wrong here?</p>
<p>Thanks!</p>
| 3 | 1,887 |
Why does Kubernetes pod Affinity not work?
|
<p>I have following pods</p>
<pre><code>NAME READY STATUS NODE LABELS
bss-a-0 5/5 Running aks-bss-0 tcb.segment=bss,tcb.zone=centralus-1
four-6mxdk 0/1 Pending <none> job-name=four
rat-a-0 7/7 Running aks-rat-1 tcb.segment=rat,tcb.zone=centralus-1
rat-b-0 7/7 Running aks-rat-2 tcb.segment=rat,tcb.zone=centralus-2
seagull-0 1/1 Running aks-bss-0 tcb.segment=rat
</code></pre>
<p>four-6mxdk is pod with following pod affinity section:</p>
<pre><code> affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: tcb.segment
operator: In
values:
- rat
- key: tcb.zone
operator: In
values:
- centralus-1
namespaces:
- default
topologyKey: k8s.io/hostname
</code></pre>
<p>Node detailes: </p>
<pre><code>apiVersion: v1
kind: Node
metadata:
annotations:
node.alpha.kubernetes.io/ttl: "0"
volumes.kubernetes.io/controller-managed-attach-detach: "true"
labels:
agentpool: rat
beta.kubernetes.io/arch: amd64
beta.kubernetes.io/instance-type: Standard_D32s_v3
beta.kubernetes.io/os: linux
failure-domain.beta.kubernetes.io/region: centralus
failure-domain.beta.kubernetes.io/zone: centralus-1
kubernetes.azure.com/cluster: cluster
kubernetes.azure.com/role: agent
kubernetes.io/arch: amd64
kubernetes.io/hostname: aks-rat-1
kubernetes.io/os: linux
kubernetes.io/role: agent
node-role.kubernetes.io/agent: ""
storageprofile: managed
storagetier: Premium_LRS
name: aks-rat-1
allocatable:
attachable-volumes-azure-disk: "32"
cpu: 31580m
ephemeral-storage: "93492541286"
hugepages-1Gi: "0"
hugepages-2Mi: "0"
memory: 121466760Ki
pods: "30"
nodeInfo:
architecture: amd64
containerRuntimeVersion: docker://3.0.8
kernelVersion: 4.15.0-1069-azure
kubeProxyVersion: v1.15.7
kubeletVersion: v1.15.7
operatingSystem: linux
osImage: Ubuntu 16.04.6 LTS
</code></pre>
<p>My expectation: pod will be scheduled on node: aks-rat-1 due to it's only node where both labels are matched. </p>
<p>Actual result: 3 node(s) didn''t match pod affinity/anti-affinity.</p>
<p>Is it bug? or i do something wrong?</p>
| 3 | 1,409 |
Getting ClassNotFoundException on standard PMD cyclomatic complexity plug-in
|
<p>I'm using PMD version 6.20.0 on Windows 10, and I'm attempting to use the cyclomatic complexity plug-in on what I would consider simple Java code just to see if things work. I have a single .java file, CCExample.java, with the code as follows (provided just so everyone can see the source file I'm using, versus asking for comments on the below code which I know is inefficient and only for purposes of an example in an engineering talk I'm giving):</p>
<pre><code>import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class CCExample
{
public static String reduceString(String s, int index)
{
int lastIndex = s.length() - 1;
if (s.length() == 0)
{
return "Empty String";
}
else if (index >= lastIndex)
{
if (isReduced(s, 0))
{
return s;
}
else
{
return reduceString(s, 0);
}
}
else if (s.charAt(index) == s.charAt(index + 1))
{
if (index + 1 < lastIndex)
{
return reduceString(s.substring(0, index) + s.substring(index + 2, s.length()), index);
}
else
{
return reduceString(s.substring(0, index), index);
}
}
else
{
return reduceString(s, index + 1);
}
}
public static boolean isReduced(String s, int index)
{
int lastIndex = s.length() - 1;
if (index == lastIndex || s.length() == 0)
{
return true;
}
else if (s.charAt(index) != s.charAt(index + 1))
{
return isReduced(s, index + 1);
}
else
{
return false;
}
}
public static void main(final String[] args)
{
if (args.length != 1)
{
System.out.println("Usage: java CCExample <string>");
}
else
{
final String s = args[0];
System.out.println(reduceString(s, 0));
}
}
}
</code></pre>
<p>With this above single .java file I run the following PMD command:</p>
<pre><code>pmd -d CCExample.java -debug -R category/java/design.xml/CyclomaticComplexity -f text
</code></pre>
<p>In the debug log I get the following:</p>
<pre><code>Jan 15, 2020 2:35:58 PM net.sourceforge.pmd.RulesetsFactoryUtils printRuleNamesInDebug
FINER: Loaded rule CyclomaticComplexity
Jan 15, 2020 2:35:58 PM net.sourceforge.pmd.processor.PmdRunnable call
FINE: Processing C:\Temp\CCExample.java
Jan 15, 2020 2:35:58 PM net.sourceforge.pmd.lang.java.typeresolution.ClassTypeResolver visit
FINE: Could not find class CCExample, due to: java.lang.ClassNotFoundException: CCExample
</code></pre>
<p>What am I doing wrong that it cannot find class CCExample? Some .java files I have I get a cyclomatic complexity numbers, others I get the above error. Is there some formatting I'm not doing correctly?</p>
| 3 | 1,382 |
Setting alarm notification for Dates Arrays
|
<p>I am trying to create local notification that's declenche before a given date by 2 hours , 4 hours and at this given date. This is my code, but it doesn't work:</p>
<pre><code>private void alarmnotification(String notificationid, String type, long timemills) {
Random rand = new Random();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timemills);
AlarmManager mgrAlarm = (AlarmManager)getSystemService(ALARM_SERVICE);
ArrayList<PendingIntent> intentArrayd = new ArrayList<PendingIntent>();
for(int i = 0; i < 4; ++i)
{
long timemfills = timemills - 7200000*i ;
Calendar calendadr = Calendar.getInstance();
calendadr.setTimeInMillis(timemfills);
Calendar calendad0r = Calendar.getInstance();
calendad0r.setTimeInMillis(SystemClock.elapsedRealtime()+calendadr.getTimeInMillis());
Intent intent = new Intent(getApplicationContext(), NotificationPublisher.class);
intent.putExtra("type", type);
intent.putExtra("notificationId", notificationid);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Home.this, i, intent, 0);
mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timemfills, pendingIntent);
intentArrayd.add(pendingIntent);
}
}
</code></pre>
<p>And this is My notification Publisher Code :
public class NotificationPublisher extends BroadcastReceiver {</p>
<pre><code>public static String NOTIFICATION_ID = "notificationId";
public static String NOTIFICATION = "type";
private LocalBroadcastManager broadcaster;
public void onReceive(Context context, Intent intent) {
// Get id & message from intent.
String notificationId = intent.getStringExtra("notificationId");
String message = intent.getStringExtra("type");
// When notification is tapped, call MainActivity.
Intent mainIntent = new Intent(context, Home.class);
mainIntent.putExtra("retour", message);
mainIntent.putExtra("element_id", notificationId);
mainIntent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
NotificationManager myNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Prepare notification.
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(R.drawable.icoapp_and)
.setContentTitle(notificationId)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL);
// Notify
Random rand = new Random();
myNotificationManager.notify(rand.nextInt(), builder.build());
}
</code></pre>
<p>}</p>
<p>The problem is that I don't get any notifications at all. </p>
| 3 | 1,050 |
TokenMisMatchException in Laravel Auth
|
<p>I've installed a fresh laravel 5.8.
After that i ran:</p>
<pre><code> php artisan make:auth
</code></pre>
<p>Everything looked fine, but when i'm trying to log in (for example: filling form with incorrect values)
im getting <em>"TokenMismatchException in VerifyCsrfToken.php line 68"</em> error.</p>
<p>Im getting these exceptions in every auth forms!</p>
<p>My view (login):</p>
<pre><code> <form class="form-horizontal" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
@if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</code></pre>
<p>I don't know how, but laravel crashed itself after artisan command...</p>
<p>Changing from {{csrf_field()}} to {!! csrf_field() !!} already tried. Not working...</p>
| 3 | 2,177 |
Closing dialog if post request is sucessful
|
<p>I am using React, Redux, NodeJS, and ExpressJS. I am also using material-ui for the front-end. I have created a dialog where users can input information and signup. Once a user clicks submit, a post req is made. Any errors that are returned would be than put into the errors object in the state. If any errors are returned (ex. passwords don't match) they are stated below the input field. If the submit button is clicked and there are no errors, the dialog stays open. How would I make the dialog be closed if there are no errors returned (the state.open should be turned to false). How would I do this. Here is my code:</p>
<p>authActions.js:</p>
<pre><code>export const registerUser = (userData, history) => dispatch => {
axios
.post("/api/users/register", userData)
.then(res => history.push("/signup/done"))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
</code></pre>
<p>signup.js:</p>
<pre><code>class SignUpD extends Component {
constructor() {
super();
this.state = {
open: false,
username: "",
email: "",
password: "",
password2: "",
errors: {}
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
componentDidMount() {
if (this.props.auth.isAutenticated) {
this.props.history.push("/");
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({ errors: nextProps.errors });
}
}
handleClickOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false, errors: {} });
};
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit(e) {
e.preventDefault();
const newUser = {
username: this.state.username,
email: this.state.email,
password: this.state.password,
password2: this.state.password2
};
this.props.registerUser(newUser, this.props.history);
}
render() {
const { errors } = this.state;
return (
<div>
<ListItem
button
style={{ paddingTop: 60, top: 0 }}
onClick={this.handleClickOpen}
>
<ListItemText primary="Sign Up" />
</ListItem>
<Dialog
fullWidth
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="form-dialog-title"
style={{ width: "100" }}
>
<DialogTitle id="form-dialog-title">Register</DialogTitle>
<DialogContent>
<DialogContentText>
Enter registration details here
</DialogContentText>
<TextField
margin="dense"
name="email"
label="Email Address"
value={this.state.email}
fullWidth
onChange={this.onChange}
/>
{errors.email && <div style={{ color: "red" }}>{errors.email}</div>}
<TextField
margin="dense"
name="username"
label="Username"
type="text"
value={this.state.username}
fullWidth
onChange={this.onChange}
/>
{errors.username && (
<div style={{ color: "red" }}>{errors.username}</div>
)}
<TextField
margin="dense"
name="password"
label="Password"
type="password"
value={this.state.password}
fullWidth
onChange={this.onChange}
/>
{errors.password && (
<div style={{ color: "red" }}>{errors.password}</div>
)}
<TextField
margin="dense"
name="password2"
label="Enter Password Again"
value={this.state.password2}
type="password"
fullWidth
onChange={this.onChange}
/>
{errors.password2 && (
<div style={{ color: "red" }}>{errors.password2}</div>
)}
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Cancel
</Button>
<Button onClick={this.onSubmit} color="primary">
Register
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
SignUpD.propTypes = {
registerUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors
});
export default connect(
mapStateToProps,
{ registerUser }
)(withRouter(SignUpD));
</code></pre>
<p>If you need any clarification, or have questions let me know. Thanks in advance.</p>
| 3 | 2,476 |
Hybris Server showing Garbage collection issue?
|
<p>I had recently installed java adopt JDK 1.8.0_202 version.</p>
<p>It worked fine for the first time and later when i start hybris server getting the below issue again & again on console :</p>
<pre><code>JVMJ9GC063E Unable to open file '/opt/hybris/log/tomcat/java_gc_ger-d-maa-apsp-001.log' for writing
</code></pre>
<p></p>
<pre><code><allocation-stats totalBytes="223210880" >
<allocated-bytes non-tlh="13688" tlh="223197192" />
<largest-consumer threadName="localhost-startStop-1" threadId="0000000002F7B000" bytes="217285784" />
</allocation-stats>
<gc-op id="2563" type="scavenge" timems="53.990" contextid="2560" timestamp="2019-03-14T15:18:57.791">
<scavenger-info tenureage="14" tenuremask="4000" tiltratio="88" />
<memory-copied type="nursery" objects="394430" bytes="16048744" bytesdiscarded="115760" />
<finalization candidates="204" enqueued="174" />
<ownableSynchronizers candidates="3195" cleared="7" />
<references type="soft" candidates="9645" cleared="0" enqueued="0" dynamicThreshold="32" maxThreshold="32" />
<references type="weak" candidates="6673" cleared="84" enqueued="67" />
</gc-op>
<gc-end id="2564" type="scavenge" contextid="2560" durationms="54.398" usertimems="46.801" systemtimems="0.000" timestamp="2019-03-14T15:18:57.791" activeThreads="2">
<mem-info id="2565" free="564246568" total="1073741824" percent="52">
<mem type="nursery" free="224266520" total="268435456" percent="83">
<mem type="allocate" free="224266520" total="240451584" percent="93" />
<mem type="survivor" free="0" total="27983872" percent="0" />
</mem>
<mem type="tenure" free="339980048" total="805306368" percent="42" macro-fragmented="3110739">
<mem type="soa" free="299715344" total="765041664" percent="39" />
<mem type="loa" free="40264704" total="40264704" percent="100" />
</mem>
<pending-finalizers system="174" default="0" reference="67" classloader="0" />
<remembered-set count="33247" />
</mem-info>
</gc-end>
<cycle-end id="2566" type="scavenge" contextid="2560" timestamp="2019-03-14T15:18:57.792" />
<allocation-satisfied id="2567" threadId="0000000002F7B000" bytesRequested="48" />
<af-end id="2568" timestamp="2019-03-14T15:18:57.792" threadId="0000000002F7B988" success="true" from="nursery"/>
<exclusive-end id="2569" timestamp="2019-03-14T15:18:57.792" durationms="55.438" />
<exclusive-start id="2570" timestamp="2019-03-14T15:19:06.478" intervalms="8740.918">
<response-info timems="0.039" idlems="0.039" threads="0" lastid="0000000002F7B000" lastname="localhost-startStop-1" />
</exclusive-start>
<af-start id="2571" threadId="0000000002F7B988" totalBytesRequested="24" timestamp="2019-03-14T15:19:06.478" intervalms="8740.939" type="nursery" />
<cycle-start id="2572" type="scavenge" contextid="0" timestamp="2019-03-14T15:19:06.478" intervalms="8740.941" />
<gc-start id="2573" type="scavenge" contextid="2572" timestamp="2019-03-14T15:19:06.479">
<mem-info id="2574" free="339975744" total="1073741824" percent="31">
<mem type="nursery" free="0" total="268435456" percent="0">
<mem type="allocate" free="0" total="240451584" percent="0" />
<mem type="survivor" free="0" total="27983872" percent="0" />
</mem>
<mem type="tenure" free="339975744" total="805306368" percent="42">
<mem type="soa" free="299711040" total="765041664" percent="39" />
<mem type="loa" free="40264704" total="40264704" percent="100" />
</mem>
<remembered-set count="34712" />
</mem-info>
</gc-start>
</code></pre>
<p>Any help would be appreciated?
Thanks,
Mohammed</p>
| 3 | 1,683 |
Creating a stored procedure that loops around multiple values passed in for parameters
|
<p>So i am having a JAVA program call a stored procedure and passing in data from an XML file to parameters set in my stored procedure. I have tried calling the stored procedure from within oracle and they work for single values. Would this stored procedure work even if there were multiple values? Do i need to include some kind of FOR loop to ensure that all of the values are inserted?
Below is my code:</p>
<pre><code>CREATE OR REPLACE PROCEDURE pega_submission_value (
rsubmission_id IN NUMBER,
rvalue_tx IN VARCHAR,
rutc_offset IN NUMBER,
rdata_date IN VARCHAR,
rhr_utc IN VARCHAR,
rhr IN TIMESTAMP,
rhr_num IN NUMBER,
rdata_code IN VARCHAR,
rdata_type IN VARCHAR
) IS
v_value_id value.value_id%TYPE;
BEGIN
NULL;
INSERT INTO value (
value_id,
product_id,
data_source_id,
unit_cd,
value_tx,
utc_offset,
data_date,
hr_utc,
hr,
hr_num,
data_code,
create_dt,
create_user_id
) VALUES (
NULL,
555,
3,
'NA',
rvalue_tx,
rutc_offset,
rdata_date,
rhr_utc,
rhr,
rhr_num,
rdata_code,
SYSDATE,
'15'
) RETURNING value_id INTO v_value_id;
INSERT INTO submission_value (
submission_id,
value_id,
form_field_id,
create_dt,
create_user_id,
modify_dt,
modify_user_id,
effective_dt,
inactive_dt
) VALUES (
rsubmission_id,
v_value_id,
(
SELECT
form_field_id
FROM
form_field
WHERE
form_field_tx = rdata_type
),
SYSDATE,
'777',
NULL,
NULL,
NULL,
NULL
);
COMMIT;
END pega_submission_value;
/
</code></pre>
| 3 | 1,060 |
facebook java ads sdk how to retrieve "delivery, results,result_rate,cost_per_result", and breakdown by day
|
<p>I'm trying to use facebook's java sdk to generate the ads report. I mainly followed the Sample code, using new AdAccount(ad_account_id, context).getInsights() to retrieve data. But for the java sdk I could only retrieve partially data. I'm not sure I'm using the correct API.</p>
<pre><code> import com.facebook.ads.sdk.*;
import java.util.ArrayList;
import java.util.List;
import config.fbreporting.gettyimages.com.Config;
public class Sample_code {
public static void main(String args[]) throws APIException {
String access_token = Config.ACCESS_TOKEN;
String ad_account_id = Config.AD_ACCOUNT_ID;
String app_secret = Config.APP_SECRET;
APIContext context = new APIContext(access_token).enableDebug(true);
List<AdsInsights.EnumBreakdowns> breakdowns = new ArrayList<>();
List<AdsInsights.EnumSummary> summaries = new ArrayList<>();
APINodeList<AdsInsights> adsInsights = new AdAccount(ad_account_id, context)
.getInsights()
.setLevel(AdsInsights.EnumLevel.VALUE_AD)
.setFiltering("[{\"field\":\"impressions\",\"operator\":\"GREATER_THAN\",\"value\":\"0\"}]")
// .setBreakdowns(List<AdsInsights.EnumBreakdowns.VALUE_>)
.setBreakdowns(breakdowns)
.setTimeRange("{\"since\":\"2017-08-13\",\"until\":\"2017-09-12\"}")
.requestField("account_id")
.requestField("account_name")
.requestField("ad_name")
.requestField("adset_id")
.requestField("adset_name")
.requestField("ad_id")
.requestField("actions")
.requestField("unique_clicks")
.requestField("unique_inline_link_clicks")
.requestField("impressions")
.requestField("reach")
.requestField("relevance_score")
.requestField("campaign_id")
.requestField("campaign_name")
.requestField("total_action_value")
.requestField("social_impressions")
.requestField("spend")
.requestField("total_actions")
.requestField("total_conversion_value")
.requestField("clicks")
.requestField("date_start")
.requestField("date_stop")
// .requestField("delivery")
// .requestField("result_rate")
// .requestField("results")
// .requestField("cost_per_result")
.execute();
}
}
</code></pre>
<p>If I used this way, it would return: </p>
<pre><code>{
"error": {
"message": "(#100) result is not valid for fields param. please check https://developers.facebook.com/docs/marketing-api/reference/ads-insights/ for all valid values",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "ALSFEzwK4YP"
}
}
</code></pre>
<p>delivery
result_rate
results
cost_per_result</p>
<p>Is there anyone know where to get these fields?</p>
<p>Another problem is I cannot set the breakdown by Day. There is no this VALUE in AdsInsights.EnumSummary. </p>
| 3 | 1,537 |
The elements are not fixed on the window
|
<p>On the header, I need to have </p>
<ul>
<li>the logo be located the left side of the banner (without space)</li>
<li>Both banner and logo be always in the middle of the page (regardless of screen size)</li>
<li>Also have four images that should always be on the top right side of
the window (regardless of screen size)</li>
</ul>
<h2><strong><a href="http://jsfiddle.net/jackmoore/b9tbxtLb/10/" rel="nofollow">Demo</a></strong></h2>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<style>
.form-control{
-webkit-border-radius: 5;
-moz-border-radius: 5;
border-radius: 5;
}
#logo{
float:right;
}
@media screen and (min-width: 480px) {
#logo{
float:left;
}
}
@media screen and (min-width: 768px) {
#logo{
float:left;
}
}
.searchinput{
height: 40px;
border:#000 1px solid;
box-shadow: none;
margin-bottom:10px;
}
.btn-search{
background: #777;
width:95%;
height: 40px;
border: 1px solid #777;
border-radius: 4px;
padding:8px 50px;
display: inline-block;
text-align: center;
color: #fff;
font-weight: 100;
letter-spacing: 0.05em;
box-shadow: inset 0 -3px 0 rgba(0,0,0,.1);
}
.btn-search:hover{
color: #fff;
text-decoration: none;
border-color: #3c3c3c;
background: #3c3c3c;
box-shadow: none;
}
.btn-search:a{
padding-top: 50px;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row" >
<div class="col-md-9 col-sm-9 col-xs-2">
<div id="banner">
<div id="logo" style="margin-right:0px;">
<img height="40px" width="40px" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA">
</div>
<img height="40px;" width="300px;" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR-32Ge8DaAq_81IBLPFdRWmKVYgvN9YyDKKjXh6CTTpgey8qbC"></div>
</div>
</div>
</div>
<div class="col-md-3">
<div id="images" style="float:right;">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA" width="20px" height="20px"/>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA" width="20px" height="20px"/>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA" width="20px" height="20px"/>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA" width="20px" height="20px"/>
</div>
</div>
</div>
</code></pre>
<h2>Update</h2>
<p>So far, I could put the images on the top right of the window.</p>
<pre><code><div class="container-fluid">
<div class="row">
<div class="col-md-9 col-sm-9 col-xs-2">
<div id="banner">
<div id="logo" style="margin-right:0px;">
<img height="40px" width="40px" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA">
</div>
<img height="40px;" width="300px;" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR-32Ge8DaAq_81IBLPFdRWmKVYgvN9YyDKKjXh6CTTpgey8qbC"></div>
</div>
<div class="col-md-2 col-sm-3 col-xs-10">
<div id="images" style="float:right; position: absolute;
right: 0;
top: 5px;
z-index: 9999;">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA" width="20px" height="20px"/>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA" width="20px" height="20px"/>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA" width="20px" height="20px"/>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_FCNfsR_UhKGdOTtUKK8XfQXKnlgw5Q0jaBbdiCSBTnCoaGgqIA" width="20px" height="20px"/>
</div>
</div>
</div>
</div>
</code></pre>
| 3 | 2,337 |
Generating dates between 2 given dates and looping in PL/SQL
|
<p>I am very new to PL/SQL. I have created a table in Oracle database and based on that table, I have to generate a report to show the number of open bugs from 5/1/2013 through 5/31/2013, and at the end of the report, need to display the maximum number of open bugs on a single day (using PL/SQL anonymous block).
Table definition and data is below:</p>
<pre><code>CREATE TABLE bugs
(
BUG_ID NUMBER PRIMARY KEY,
REPORTED_DATE DATE NOT NULL,
DESCRIPTION VARCHAR2(20),
PRIORITY NUMBER(2),
ASSIGNED_TO VARCHAR2(10),
CLOSED_DATE DATE,
NOTE VARCHAR2(20)
);
INSERT INTO BUGS VALUES (1230, '25-APR-13', NULL, 3, 'Team 3', '28-APR-13', NULL);
INSERT INTO BUGS VALUES (1231, '29-APR-13', NULL, 1, 'Team 1', '29-APR-13', NULL);
INSERT INTO BUGS VALUES (1232, '03-MAY-13', NULL, 1, 'Team 1', '03-MAY-13', NULL);
INSERT INTO BUGS VALUES (1233, '03-MAY-13', NULL, 1, 'Team 3', '08-MAY-13', NULL);
INSERT INTO BUGS VALUES (1234, '04-MAY-13', NULL, 2, 'Team 5', '15-MAY-13', NULL);
INSERT INTO BUGS VALUES (1235, '04-MAY-13', NULL, 2, 'Team 1', NULL, NULL);
INSERT INTO BUGS VALUES (1236, '05-MAY-13', NULL, 1, 'Team 2', '06-MAY-13', NULL);
INSERT INTO BUGS VALUES (1237, '05-MAY-13', NULL, 3, 'Team 3', '10-MAY-13', NULL);
INSERT INTO BUGS VALUES (1238, '09-MAY-13', NULL, 4, 'Team 5', '16-MAY-13', NULL);
INSERT INTO BUGS VALUES (1239, '09-MAY-13', NULL, 5, 'Team 6', NULL, NULL);
INSERT INTO BUGS VALUES (1240, '12-MAY-13', NULL, 5, 'Team 2', '30-MAY-13', NULL);
INSERT INTO BUGS VALUES (1241, '12-MAY-13', NULL, 1, 'Team 1', '20-MAY-13', NULL);
INSERT INTO BUGS VALUES (1242, '13-MAY-13', NULL, 4, 'Team 4', '25-MAY-13', NULL);
INSERT INTO BUGS VALUES (1243, '14-MAY-13', NULL, 4, 'Team 3', '01-JUN-13', NULL);
INSERT INTO BUGS VALUES (1244, '14-MAY-13', NULL, 2, 'Team 4', '25-MAY-13', NULL);
INSERT INTO BUGS VALUES (1245, '20-MAY-13', NULL, 2, 'Team 4', NULL, NULL);
INSERT INTO BUGS VALUES (1246, '22-MAY-13', NULL, 2, 'Team 4', '25-MAY-13', NULL);
INSERT INTO BUGS VALUES (1247, '25-MAY-13', NULL, 2, 'Team 1', '29-MAY-13', NULL);
INSERT INTO BUGS VALUES (1248, '30-MAY-13', NULL, 1, 'Team 1', '01-JUN-13', NULL);
INSERT INTO BUGS VALUES (1249, '05-JUN-13', NULL, 1, 'Team 2', '07-JUN-13', NULL);
COMMIT;
</code></pre>
<p>“Open Bugs” - A bug is considered open on a given day if (1) its “REPORTED_DATE” is on or before that day, and (2) its “CLOSED_DATE” is on or after that day (or is unknown (NULL)). For example, we have 5 open bugs on 5/5/2013.</p>
<p>The output of the program should look like the following:</p>
<pre><code>Date Number of Open Bugs
01-MAY-13 0
02-MAY-13 0
03-MAY-13 2
04-MAY-13 3
05-MAY-13 5
06-MAY-13 5
07-MAY-13 4
08-MAY-13 4
--------- --
--------- --
The maximum number of open bugs on a single day is 9.
There were 9 open bugs on 14-MAY-13.
There were 9 open bugs on 15-MAY-13.
There were 9 open bugs on 25-MAY-13.
</code></pre>
<p>I have searched and found that there is ADD_MONTHS and CONNECT_BY_LEVEL functions that I can use, to generate the list of days in the month and then use a loop to count the open bugs on that particular day of the month, but do not know how to exactly use them. Can someone please help me get started. Thanks in advance.</p>
| 3 | 1,486 |
My code does not run and i can't seem to get the score to print
|
<pre><code>def tf_quiz():
user_name
user_year
print("Welcome to my true or false divison quiz") #welcome message
user_name=str(input("please enter in your name")) #asks/stores user input
user_year=str(input("please enter in your year")) #asks/stores user input
print("all you have to do is type T/F for each question") #explaning the task
print ("12/3 = 4") #asks the question
if correct_ans == "T" : #correct answer
print ("Correct!") #prints correct if the answer is correct
score = score +1
if correct_ans == "F" : #incorrect answer
print ("incorrect!") #prints incorrect if the answer is incorrect
print ("42/6 = 7")
if correct_ans == "T" :
print ("Correct!")
score = score +1
if correct_ans == "F" :
print ("incorrect!")
print ("18/3 = 4")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print ("40/5 = 9")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print ("90/10 = 9")
if correct_ans == "T" :
print ("Correct!")
score = score +1
if correct_ans == "F" :
print ("incorrect!")
print (" 16/2= 4")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print ("9/3 = 3")
if correct_ans == "T" :
print ("Correct!")
score = score +1
if correct_ans == "F" :
print ("incorrect!")
print ("45/9 =5 ")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print ("81/9 = 7")
if correct_ans == "F" :
print ("Correct!")
score = score +1
if correct_ans == "T" :
print ("incorrect!")
print("49/7 = 7")
if correct_ans == "T" :
print ("Correct!")
score = score +1
if correct_ans == "F" :`enter code here`
print ("incorrect!")
#Main program
tf_quiz()
</code></pre>
<p>I can't print the name and score for the user using this code,
and it also does not run. I have tried multiple different things but i still cannot get it to work no matter what i do to try and fix it. the code also will not run and it will not give me any problems or ways to make it run.</p>
| 3 | 1,440 |
Getting null value from API response with Alamofire
|
<p>I am trying to get response values from an API url using Alamofire. I created a data model and the response is fine but I am getting null for <code>poster_path</code> and <code>release_date</code>. I was wondering how can handle JSON response correctly. here is my code:</p>
<pre><code> let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
func fetchMovies( completion: @escaping(MovieResponse?, AFError?) -> Void) {
let url = URL(string: "url")!
let params = [:]
AF.request(url, method: .get , parameters: params)
.responseDecodable(of: Data.self, decoder: decoder) { response in
switch response.result {
case .success(let movies):
completion(movies, nil)
case .failure(let error):
completion(nil , error)
}
}
}
</code></pre>
<p>Response:</p>
<p><a href="https://i.stack.imgur.com/trYJN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/trYJN.jpg" alt="enter image description here" /></a></p>
<p>JSON example:</p>
<pre><code>"results": [
{
"adult": false,
"backdrop_path": "/5hNcsnMkwU2LknLoru73c76el3z.jpg",
"genre_ids": [
35,
18,
10749
],
"id": 19404,
"original_language": "hi",
"original_title": "दिलवाले दुल्हनिया ले जायेंगे",
"overview": "Raj is a rich, carefree, happy-go-lucky second generation NRI. Simran is the daughter of Chaudhary Baldev Singh, who in spite of being an NRI is very strict about adherence to Indian values. Simran has left for India to be married to her childhood fiancé. Raj leaves for India with a mission at his hands, to claim his lady love under the noses of her whole family. Thus begins a saga.",
"popularity": 27.119,
"poster_path": "/2CAL2433ZeIihfX1Hb2139CX0pW.jpg",
"release_date": "1995-10-20",
"title": "Dilwale Dulhania Le Jayenge",
"video": false,
"vote_average": 8.7,
"vote_count": 3275
},
</code></pre>
| 3 | 1,250 |
MEP System traversal - cannot find BaseEquipment or Openconnector
|
<h2>Intro</h2>
<p>I'm working on a project where I need to traverse though all elements in a MEPSystem from the starting Mechanical Equipment. I found the 2 articles below by Jeremy Tammik which suggest a way to do this:</p>
<ol>
<li><a href="https://thebuildingcoder.typepad.com/blog/2016/06/traversing-and-exporting-all-mep-system-graphs.html" rel="nofollow noreferrer">Traversing and Exporting all MEP System Graphs</a></li>
<li><a href="https://thebuildingcoder.typepad.com/blog/2016/06/store-mep-systems-in-hierarchical-json-graph.html" rel="nofollow noreferrer">MEP System Structure in Hierarchical JSON Graph</a></li>
</ol>
<p>One of the reference I found in this articles in to the GitHub repository for <a href="https://github.com/jeremytammik/TraverseAllSystems" rel="nofollow noreferrer">TraverseAllSystems</a> and found that the release <a href="https://github.com/jeremytammik/TraverseAllSystems/tree/2017.0.0.8" rel="nofollow noreferrer">2017.0.0.8</a> works best for my need to be able to provide the data in a structured json format like below:</p>
MEP System JSON format!
<pre class="lang-json prettyprint-override"><code>{
"id": 392200,
"name": "Mitered Elbows / Taps",
"children": [
{
"id": 392203,
"name": "Standard",
"children": [
{
"id": 392199,
"name": "Mitered Elbows / Taps",
"children": [
{
"id": 386552,
"name": "450 x 200",
"children": []
},
{
"id": 386555,
"name": "450 x 200",
"children": []
}
]
}
]
}
]
}
</code></pre>
<h2>Problem</h2>
<p>Now the problem is that this seems to be working fine in the <a href="https://knowledge.autodesk.com/support/revit/getting-started/caas/CloudHelp/cloudhelp/2022/ENU/Revit-GetStarted/files/GUID-61EF2F22-3A1F-4317-B925-1E85F138BE88-htm.html" rel="nofollow noreferrer">Sample Revit models</a> provided by Autodesk. But when I try this out in my project, I found that its working as expected.</p>
<p>After debugging for quite some time, I found that the <a href="https://github.com/jeremytammik/TraverseAllSystems/blob/2017.0.0.8/TraverseAllSystems/TraversalTree.cs#L400" rel="nofollow noreferrer"><code>m_system.BaseEquipment</code></a> & <a href="https://github.com/jeremytammik/TraverseAllSystems/blob/2017.0.0.8/TraverseAllSystems/TraversalTree.cs#L444" rel="nofollow noreferrer"><code>openConnector</code></a> in the <a href="https://github.com/jeremytammik/TraverseAllSystems/blob/2017.0.0.8/TraverseAllSystems/TraversalTree.cs" rel="nofollow noreferrer"><code>TraversalTree.cs</code></a> class both return null and that's where the code is breaking because its not able to find the starting element which is the Mechanical Equipment. Does anyone know why this is happening and how to solve this?</p>
<p>Below is the starting part of the respective code that is causing this issue:</p>
Code that breaks
<p>m_system.BaseEquipment</p>
<pre class="lang-cs prettyprint-override"><code>private TreeNode GetStartingElementNode()
{
TreeNode startingElementNode = null;
FamilyInstance equipment = m_system.BaseEquipment; // returns null
// ...
</code></pre>
<p>openConnector</p>
<pre class="lang-cs prettyprint-override"><code>private Element GetOwnerOfOpenConnector()
{
Element element = null;
//
// Get an element from the system's terminals
ElementSet elements = m_system.Elements;
foreach (Element ele in elements)
{
element = ele;
break;
}
// Get the open connector recursively
Connector openConnector = GetOpenConnector(element, null); // returns null
return null != openConnector
? openConnector.Owner
: null;
}
</code></pre>
<h3>Other useful resources:</h3>
<ul>
<li><a href="https://forums.autodesk.com/t5/revit-api-forum/how-to-iterate-over-elements-by-mep-system-name/td-p/7386520" rel="nofollow noreferrer">How to Iterate over elements by MEP System Name</a></li>
<li><a href="https://thebuildingcoder.typepad.com/files/cp4108_rme_api-1.pdf" rel="nofollow noreferrer">Revit MEP Programming: All Systems Go</a></li>
</ul>
| 3 | 1,770 |
Using Firebase in Gluon-mobile
|
<p>I want to use Firebase Database in the my <strong>Gluon-mobile Project</strong> , after Reading the <a href="https://firebase.google.com/docs/android/setup/" rel="nofollow noreferrer">Firebase Docs</a>.I tried to this make some modifications to the <em>root</em> level <a href="https://bitbucket.org/guru001/firebase_javafx/src/096da91a5eb51cc4502b665ae0a89ff1b2e0863b/build.gradle?at=master&fileviewer=file-view-default" rel="nofollow noreferrer">build.gradle</a> and <em>App</em> level <a href="https://bitbucket.org/guru001/firebase_javafx/src/096da91a5eb51cc4502b665ae0a89ff1b2e0863b/SampleFirebaseApp/build.gradle?at=master&fileviewer=file-view-default" rel="nofollow noreferrer">build.gradle</a> files.<br>Am trying to use <a href="https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjC14yZiJPYAhXELI8KHURbCDsQFggnMAA&url=https%3A%2F%2Ffirebase.google.com%2Fdocs%2Fstorage%2F&usg=AOvVaw1rIkIFnQ-TiCErZxqKVecb" rel="nofollow noreferrer">Firebase storge</a> in my <a href="https://bitbucket.org/guru001/firebase_javafx" rel="nofollow noreferrer">project</a> and Here's what I Tried.<br></p>
<p>Controller class <em><strong>SignupController.java</em></strong> in package <em>com.application.control</em>.</p>
<pre><code> package com.application.control;
public class SignupController implements Initializable
{
@Override
public void initialize(URL location, ResourceBundle resources)
{
if(Platform.isAndroid())
{
try {
Firebase firebase = (Firebase) Class.forName("com.application.FirebaseInit").newInstance();
firebase.startup();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
System.out.println("Signup");
}
}
</code></pre>
<p>And the <strong><em>FirebaseInit.java</em></strong> which is in <code>android/java/</code> dir and <code>com.application</code> package which performs Initialization of Firebase Storage.</p>
<pre><code> package com.application;
public class FirebaseInit implements Firebase{
public FirebaseInit()
{
}
@Override
public void startup()
{
Context context=FXActivity.getInstance().getApplicationContext();
FirebaseStorage storage =null;
FirebaseApp.initializeApp(context);
storage=FirebaseStorage.getInstance();
if(storage!=null)
{
Toast.makeText(context,"Firebase Storage success",Toast.LENGTH_LONG).show();
}
else
Toast.makeText(context,"Firebase Storage failed",Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p><strong><em>Firebase.java</em></strong> is just a Interface which is used to kick start Initialization in the controller.</p>
<pre><code>package com.application;
public interface Firebase
{
public void startup();
}
</code></pre>
<p>And on startup am getting these below Error on <strong>Android</strong> Device.</p>
<pre><code>12-18 12:01:39.133 4279 4304 W javafx : Loading FXML document with JavaFX API of version 8.0.102 by JavaFX runtime of version 8.0.72-ea
12-18 12:01:39.205 4279 4304 W System.err: Exception in Application start method
12-18 12:01:39.207 4279 4304 I System.out: QuantumRenderer: shutdown
12-18 12:01:39.208 4279 4299 W System.err: java.lang.reflect.InvocationTargetException
12-18 12:01:39.208 4279 4299 W System.err: at java.lang.reflect.Method.invoke(Native Method)
12-18 12:01:39.208 4279 4299 W System.err: at javafxports.android.DalvikLauncher$1.run(DalvikLauncher.java:188)
12-18 12:01:39.208 4279 4299 W System.err: at java.lang.Thread.run(Thread.java:818)
12-18 12:01:39.208 4279 4299 W System.err: Caused by: java.lang.RuntimeException: Exception in Application start method
12-18 12:01:39.208 4279 4299 W System.err: at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
12-18 12:01:39.208 4279 4299 W System.err: at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$138(LauncherImpl.java:182)
12-18 12:01:39.208 4279 4299 W System.err: at com.sun.javafx.application.LauncherImpl.access$lambda$1(LauncherImpl.java)
12-18 12:01:39.208 4279 4299 W System.err: at com.sun.javafx.application.LauncherImpl$$Lambda$2.run(Unknown Source)
12-18 12:01:39.208 4279 4299 W System.err: ... 1 more
12-18 12:01:39.208 4279 4299 W System.err: Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/R$string;
12-18 12:01:39.209 4279 4299 W System.err: at com.google.android.gms.common.internal.zzca.<init>(Unknown Source)
12-18 12:01:39.209 4279 4299 W System.err: at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
12-18 12:01:39.209 4279 4299 W System.err: at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
12-18 12:01:39.209 4279 4299 W System.err: at com.application.FirebaseInit.startup(FirebaseInit.java:21)
12-18 12:01:39.209 4279 4299 W System.err: at com.application.control.SignupController.initialize(SignupController.java:36)
12-18 12:01:39.209 4279 4299 W System.err: at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
12-18 12:01:39.209 4279 4299 W System.err: at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
12-18 12:01:39.209 4279 4299 W System.err: at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
12-18 12:01:39.209 4279 4299 W System.err: at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
12-18 12:01:39.209 4279 4299 W System.err: at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
12-18 12:01:39.209 4279 4299 W System.err: at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
12-18 12:01:39.209 4279 4299 W System.err: at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
12-18 12:01:39.209 4279 4299 W System.err: at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
12-18 12:01:39.209 4279 4299 W System.err: at com.application.scenes.SignupPresenter.getView(SignupPresenter.java:17)
12-18 12:01:39.209 4279 4299 W System.err: at com.application.Main.start(Main.java:40)
12-18 12:01:39.209 4279 4299 W System.err: at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$145(LauncherImpl.java:863)
12-18 12:01:39.209 4279 4299 W System.err: at com.sun.javafx.application.LauncherImpl.access$lambda$8(LauncherImpl.java)
12-18 12:01:39.209 4279 4299 W System.err: at com.sun.javafx.application.LauncherImpl$$Lambda$9.run(Unknown Source)
12-18 12:01:39.209 4279 4299 W System.err: at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$158(PlatformImpl.java:326)
12-18 12:01:39.209 4279 4299 W System.err: at com.sun.javafx.application.PlatformImpl.access$lambda$6(PlatformImpl.java)
12-18 12:01:39.209 4279 4299 W System.err: at com.sun.javafx.application.PlatformImpl$$Lambda$7.run(Unknown Source)
12-18 12:01:39.209 4279 4299 W System.err: at com.sun.javafx.application.PlatformImpl.lambda$null$156(PlatformImpl.java:295)
12-18 12:01:39.210 4279 4299 W System.err: at com.sun.javafx.application.PlatformImpl.access$lambda$18(PlatformImpl.java)
12-18 12:01:39.210 4279 4299 W System.err: at com.sun.javafx.application.PlatformImpl$$Lambda$19.run(Unknown Source)
12-18 12:01:39.210 4279 4299 W System.err: at java.security.AccessController.doPrivileged(AccessController.java:52)
12-18 12:01:39.210 4279 4299 W System.err: at com.sun.javafx.application.PlatformImpl.lambda$runLater$157(PlatformImpl.java:294)
</code></pre>
<p>Please Enlighten me , how to use Firebase with Gluon-mobile.</p>
| 3 | 3,159 |
How to Connect to a Time Server JavaScript
|
<p>I am trying to conenct to any external server in order to display server time instead of the machine time in JavaScript.</p>
<p>I have tried reading</p>
<p><a href="https://stackoverflow.com/questions/7015782/how-do-i-use-access-control-allow-origin-does-it-just-go-in-between-the-html-he">How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?</a>
, <a href="https://stackoverflow.com/questions/13400594/understanding-xmlhttprequest-over-cors-responsetext/13400954#13400954">Understanding XMLHttpRequest over CORS (responseText)</a>
, and <a href="https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work">How does Access-Control-Allow-Origin header work?</a>
but am very limited in knowledge for this subject, so am confused on how to implement the suggestions to get access to a server time.</p>
<p>I am still getting the error:</p>
<pre><code>Access to XMLHttpRequest at 'https://www.stackoverflow.com/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code></pre>
<p>And don't know how to fix it. This is the current code that I have:</p>
<p>HTML:</p>
<pre><code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Server date/time</title>
<script language="javascript" src="main.js"></script>
</head>
<script language="javascript">
document.write("Server time is: " + date);
</script>
<body>
</body>
</code></pre>
<p>JavaScript:</p>
<pre><code>var xmlHttp;
function serverTime(){
try {
//FF, Opera, Safari, Chrome
xmlHttp = new XMLHttpRequest();
}
catch (err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err3) {
// use CPU time.
alert("Using CPU Time");
}
}
}
xmlHttp.open('HEAD',"https://www.stackoverflow.com",false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
return xmlHttp.getResponseHeader("Date");
}
var st = serverTime();
var date = new Date(st);
</code></pre>
<p>Ideas on what I am doing wrong and what I can do to get the server time? Thanks!</p>
| 3 | 1,066 |
How can I create an asp:button iteratively in code behind aspx file?
|
<p>So essentially I am making a "cart" for a website I am doing as an extra side project. In each item in cart, I am attempting to put a button to remove the item from the cart. The issue is, it is not possible to create an asp:button from the code behind. Everything I have read says to make a placeholder or panel and then put a button inside that, but since I wont know how many items the user has in their cart, I cant just put X amount of placeholders in my aspx file.</p>
<p>My aspx code (so far):</p>
<pre><code><asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div id="emptyCart" style="text-align: center;" runat="server">
<h1>Your cart is empty!</h1>
</div>
<div id="cart" runat="server">
</div>
</asp:Content>
</code></pre>
<p>My background writing for making the items appear in cart (this would be for just 1 item):</p>
<pre><code> if (cart.InnerHtml == "")
{
cart.InnerHtml = "<div class='jumbotron'>";
}
else
{
cart.InnerHtml += "<div class='jumbotron'>";
}
cart.InnerHtml += "<div style='display:block;'>";
cart.InnerHtml += "<h3 style='display:inline-block'>Featured</h3>";
cart.InnerHtml += "<h4 style = 'display:inline-block; float:right;' > Special title treatment</h4>";
cart.InnerHtml += "</div>";
cart.InnerHtml += "<div>";
cart.InnerHtml += "<h6>With supporting text below as a natural lead-in to additional content.</h6>";
cart.InnerHtml += "<asp:Button id='remove' Text='Remove' runat='server' OnClick='Remove_Click' class='btn btn-primary btn-lg'></asp:Button>";
cart.InnerHtml += "</div>";
cart.InnerHtml += "</div>";
</code></pre>
<p>How can I make an asp:button or an equivalent feature from the code behind when I don't know how many I am going to need?</p>
| 3 | 1,067 |
Making body background fit the entire screen
|
<p>This is likely a very easy question but I've tried all of the solutions posted and none of them seem to work for me. </p>
<p>I would simply like the gradient applied to my <code><body></code> HTML tag to always fit the screen properly. Whenever I view the browser in a smaller resolution such as this, and try to scroll over, the background appears as such. </p>
<p>Furthermore, if I turn off background-repeat, it just gets filled with white.</p>
<p><a href="https://i.stack.imgur.com/vBbiG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vBbiG.png" alt="Web page error"></a></p>
<p>Here is my base.html:</p>
<pre><code><html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{% endblock %}</title>
<link rel="shortcut icon" href="{% static 'assets/favicon.png' %}"/>
<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
<link href="{% static 'css/font-awesome.css' %}" rel="stylesheet">
<link href="{% static 'css/bootstrap-social.css' %}" rel="stylesheet">
<link href="{% static 'base.css' %}" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Aladin" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Noto+Serif" rel="stylesheet">
{% block head-extras %}{% endblock %}
</head>
<body>
<nav class="navbar navbar-toggleable-md bg-white">
<div class="container">
<a href="/home" class="navbar-brand">
<h1 id="logo" class="nav-wel">Pomodoro</h1>
</a>
{% if request.user.is_authenticated %}
<div class="status">Balance:&nbsp;{{ request.user.profile.coins }}<img class="coin-img" src="{% static 'assets/coin.png' %}" height="40px" width="auto"></div>
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle welcome nav-wel" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false" id="welcome">Welcome {{ user.get_username }}</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="/shop">Shop</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/leaderboard">Leaderboard</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/users/change-password">Change Password</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/users/logout">Logout</a>
</div>
</li>
</ul>
{% endif %}
</div>
</nav>
{% block content %}
{% endblock %}
<script src="{% static 'js/jquery-3.2.1.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="{% static 'js/bootstrap.js' %}"></script>
<script src="{% static 'js/pomodoro.js' %}"></script>
</body>
</html>
</code></pre>
<p>and the css:</p>
<pre><code>body {
background: #c2e59c;
background: -webkit-linear-gradient(to right, #c2e59c, #64b3f4);
background: linear-gradient(to right, #c2e59c, #64b3f4);
}
</code></pre>
| 3 | 1,778 |
response after ajax post request in ember
|
<p>I am new to ember .I designed an ember app and integrate the fb login in it and have to send facebook accesstoken to app backend (post request) and fetch the token generated by backend(rails).</p>
<p>My Post request response is:</p>
<pre><code>{
"token":"71fcb8c39dc6449e2ac8e88d21e4d008cf746e16a774aa8755f6be0dbc43849265f9010111986a912fde60de4f76eb5a600ec286b26ea0a865cc7f5cab49330a",
"user":{"role":"unverified"}
}
</code></pre>
<p>and the component is </p>
<pre><code> import Ember from 'ember';
export default Ember.Component.extend({
fb: Ember.inject.service(),
session: Ember.inject.service(),
authenticate: function(accessToken) {
console.log("accesstoken: "+accessToken);
Ember.$.ajax({
url: "http://localhost:3000/v1/sessions/fb_login",
accepts: 'application/json',
data: { token: accessToken},
crossDomain: true,
headers: {
'Client-Key': '403cb982d0c48473bee32b41b6765e15a26c595c689c620cece5fc15370c33c9c9f6d071f84bf6b88baf466f653f44b4524634bde6fbe68f065f06268f7ed7e2',
},
type: 'post',
success:function(data){
console.log('data is '+data);
}
});
},
actions: {
fb_login() {
this.get('fb').login().then((response) => {
if (response.status === 'connected') {
let fbToken = response.authResponse.accessToken;
this.authenticate(fbToken);
} else if( response.status === 'not_authorized') {
// code for not authrized
// this.transitionTo('/');
} else {
// code for facebook login
// this.transitionTo('/');
}
}).catch(() => {
// this.sendAction('check','/');
});
},
}
});
</code></pre>
<p>But after ajax call success is never get called to I am unable to get the the response and browser always responds with:</p>
<pre><code>pretender.js:132 XHR finished loading: POST "http://localhost:3000/v1/sessions/fb_login".
</code></pre>
<p>Somebody please explain me how the ajax work in ember for api calls.</p>
| 3 | 1,102 |
PillPool/KellyPool with java arrays
|
<p>I have been trying to work on a Pill Pool program recently, and have experienced some troubles. First off, for those who don't know: Kelly Pool is a form of pool where each player picks three numbered pills at random (1-15), and knock everyone's numbers in without telling them your pills. I first tried to use the Math.random() method to program this, then I realized I would have to use the shuffle() method on an array. Now I still can't get my two JButtons to effectively display 3 numbers from the shuffled array each time I press a button. </p>
<p>Im a bit of a beginner I guess, so Im new with arrays. Ill add detail if this is to vague a problem.</p>
<pre><code> import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.Random;
public class Display05 extends JPanel
{
Random r = new Random();
private JLabel label1, label2, label;
public int v, v1, v2, x, k, a;
public Display05()
{
setLayout(new GridLayout(3, 1));
Font f = new Font("Serif", Font.BOLD, 30);
//total = value = 0;
label1 = new JLabel("First Pill: " + v);
label1.setFont(f);
label1.setForeground(Color.blue);
add(label1);
label2 = new JLabel("Second Pill: " + v1);
label2.setFont(f);
label2.setForeground(Color.blue);
add(label2);
label = new JLabel("Third Pill: " + v2);
label.setFont(f);
label.setForeground(Color.blue);
add(label);
}
public static int[] rA(int[] array){
Random rgen = new Random();
for(int k=0; k<array.length; k++){
int randPos = rgen.nextInt(array.length);
int temp = array[k];
array[k] = array[randPos];
array[randPos] = temp;
}
return array;
}
public void udate()
{
Arrays.copyOfRange(obj, 0, 3);
Arrays.copyOfRange(obj, 4, 7);
Arrays.copyOfRange(obj, 8, 11);
Arrays.copyOfRange(obj, 12, 15);
label1.setText("First Pill " + );
label2.setText("Second Pill: " + );
label.setText("Third Pill: " + );
}
public void list()
{
ArrayList<String> obj = new ArrayList<String>();
obj.add("1");
obj.add("2");
obj.add("3");
obj.add("4");
obj.add("5");
obj.add("6");
obj.add("7");
obj.add("8");
obj.add("9");
obj.add("10");
obj.add("11");
obj.add("12");
obj.add("13");
obj.add("14");
obj.add("15");
Collections.shuffle(obj);
}
}
</code></pre>
<p>I cut out some stuff from my first attempts. Next is the Panel, which I'm pretty sure doesn't need any work.</p>
<pre><code> import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Panel05 extends JPanel
{
private Display05 display;
public Panel05()
{
setLayout(new FlowLayout());
display = new Display05();
add(display);
JButton button = new JButton("Choose pills");
button.addActionListener(new Listener());
add(button);
JButton utton = new JButton("Shuffle Pills");
utton.addActionListener(new istener());
add(utton);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
display.update();
}
}
private class istener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
display.list();
}
}
}
</code></pre>
<p>I won't include the driver file unless someone thinks it might be useful. It's only like 10 lines of code, and is mostly the same as all my other drivers.
Thanks for any help!</p>
| 3 | 1,510 |
Use Angular Cli with Webpack
|
<p>I am trying to incorporate cli generate commands in my angular2 project but it gives me a error</p>
<p>I am using the angular2-webpack-starter from git </p>
<p>You have to be inside an angular-cli project in order to use the generate command.</p>
<p>I did npm install-g angular-cli</p>
<p>also in my package.json there i have added the dependency but it dosent work,how to make it work</p>
<p>My package.json</p>
<pre><code>{
"name": "angular2-webpack-starter",
"version": "5.4.1",
"description": "An Angular 2 Webpack Starter kit featuring Angular 2 (Router, Http, Forms, Services, Tests, E2E, Coverage), Karma, Protractor, Jasmine, Istanbul, TypeScript, and Webpack by AngularClass",
"keywords": [
"angular2",
"webpack",
"typescript"
],
"author": "Patrick Stapleton <patrick@angularclass.com>",
"homepage": "https://github.com/angularclass/angular2-webpack-starter",
"license": "MIT",
"scripts": {
"build:aot:prod": "npm run clean:dist && npm run clean:aot && webpack --config config/webpack.prod.js --progress --profile --bail",
"build:aot": "npm run build:aot:prod",
"build:dev": "npm run clean:dist && webpack --config config/webpack.dev.js --progress --profile",
"build:docker": "npm run build:prod && docker build -t angular2-webpack-start:latest .",
"build:prod": "npm run clean:dist && webpack --config config/webpack.prod.js --progress --profile --bail",
"build": "npm run build:dev",
"ci:aot": "npm run lint && npm run test && npm run build:aot && npm run e2e",
"ci:jit": "npm run lint && npm run test && npm run build:prod && npm run e2e",
"ci:nobuild": "npm run lint && npm test && npm run e2e",
"ci:testall": "npm run lint && npm run test && npm run build:prod && npm run e2e && npm run build:aot && npm run e2e",
"ci:travis": "npm run lint && npm run test && npm run build:dev && npm run e2e:travis && npm run build:prod && npm run e2e:travis && npm run build:aot && npm run e2e:travis",
"ci": "npm run ci:testall",
"clean:dll": "npm run rimraf -- dll",
"clean:aot": "npm run rimraf -- compiled",
"clean:dist": "npm run rimraf -- dist",
"clean:install": "npm set progress=false && npm install",
"clean": "npm cache clean && npm run rimraf -- node_modules doc coverage dist compiled dll",
"docker": "docker",
"docs": "npm run typedoc -- --options typedoc.json --exclude '**/*.spec.ts' ./src/",
"e2e:live": "npm-run-all -p -r server:prod:ci protractor:live",
"e2e:travis": "npm-run-all -p -r server:prod:ci protractor:delay",
"e2e": "npm-run-all -p -r server:prod:ci protractor",
"github-deploy:dev": "webpack --config config/webpack.github-deploy.js --progress --profile --env.githubDev",
"github-deploy:prod": "webpack --config config/webpack.github-deploy.js --progress --profile --env.githubProd",
"github-deploy": "npm run github-deploy:dev",
"lint": "npm run tslint \"src/**/*.ts\"",
"postinstall": "npm run webdriver:update",
"postversion": "git push && git push --tags",
"preclean:install": "npm run clean",
"preversion": "npm test",
"protractor": "protractor",
"protractor:delay": "sleep 3 && npm run protractor",
"protractor:live": "protractor --elementExplorer",
"rimraf": "rimraf",
"server:dev:hmr": "npm run server:dev -- --inline --hot",
"server:dev": "webpack-dev-server --config config/webpack.dev.js --progress --profile --watch --content-base src/",
"server:prod": "http-server dist -c-1 --cors",
"server:prod:ci": "http-server dist -p 3000 -c-1 --cors",
"server": "npm run server:dev",
"start:hmr": "npm run server:dev:hmr",
"start": "npm run server:dev",
"test": "npm run lint && karma start",
"tslint": "tslint",
"typedoc": "typedoc",
"version": "npm run build",
"watch:dev:hmr": "npm run watch:dev -- --hot",
"watch:dev": "npm run build:dev -- --watch",
"watch:prod": "npm run build:prod -- --watch",
"watch:test": "npm run test -- --auto-watch --no-single-run",
"watch": "npm run watch:dev",
"webdriver-manager": "webdriver-manager",
"webdriver:start": "npm run webdriver-manager start",
"webdriver:update": "webdriver-manager update",
"webpack-dev-server": "webpack-dev-server",
"webpack": "webpack"
},
"dependencies": {
"@angular/common": "~2.4.3",
"@angular/compiler": "~2.4.3",
"@angular/compiler-cli": "~2.4.3",
"@angular/core": "~2.4.3",
"@angular/forms": "~2.4.3",
"@angular/http": "~2.4.3",
"@angular/platform-browser": "~2.4.3",
"@angular/platform-browser-dynamic": "~2.4.3",
"@angular/platform-server": "~2.4.3",
"@angular/router": "~3.4.3",
"@angularclass/conventions-loader": "^1.0.2",
"@angularclass/hmr": "~1.2.2",
"@angularclass/hmr-loader": "~3.0.2",
"core-js": "^2.4.1",
"http-server": "^0.9.0",
"ie-shim": "^0.1.0",
"jasmine-core": "^2.5.2",
"reflect-metadata": "^0.1.9",
"rxjs": "~5.0.2",
"zone.js": "~0.7.4"
},
"devDependencies": {
"@types/hammerjs": "^2.0.33",
"@types/jasmine": "^2.2.34",
"@types/node": "^7.0.0",
"@types/selenium-webdriver": "~2.53.39",
"@types/source-map": "^0.5.0",
"@types/uglify-js": "^2.0.27",
"@types/webpack": "^2.0.0",
"add-asset-html-webpack-plugin": "^1.0.2",
"angular2-template-loader": "^0.6.0",
"assets-webpack-plugin": "^3.4.0",
"awesome-typescript-loader": "~3.0.0-beta.18",
"codelyzer": "~2.0.0-beta.4",
"copy-webpack-plugin": "^4.0.0",
"css-loader": "^0.26.0",
"exports-loader": "^0.6.3",
"expose-loader": "^0.7.1",
"extract-text-webpack-plugin": "~2.0.0-beta.4",
"file-loader": "^0.9.0",
"find-root": "^1.0.0",
"gh-pages": "^0.12.0",
"html-webpack-plugin": "^2.21.0",
"imports-loader": "^0.7.0",
"istanbul-instrumenter-loader": "1.2.0",
"jasmine-core": "^2.5.2",
"json-loader": "^0.5.4",
"karma": "^1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-coverage": "^1.1.1",
"karma-jasmine": "^1.0.2",
"karma-mocha-reporter": "^2.0.0",
"karma-remap-coverage": "^0.1.4",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "2.0.1",
"ng-router-loader": "^1.0.2",
"ngc-webpack": "1.1.0",
"node-sass": "^4.2.0",
"npm-run-all": "^4.0.0",
"parse5": "^3.0.1",
"protractor": "^4.0.14",
"raw-loader": "0.5.1",
"rimraf": "~2.5.4",
"sass-loader": "^4.1.1",
"script-ext-html-webpack-plugin": "^1.3.2",
"source-map-loader": "^0.1.5",
"string-replace-loader": "1.0.5",
"style-loader": "^0.13.1",
"to-string-loader": "^1.1.4",
"ts-helpers": "1.1.2",
"ts-node": "^2.0.0",
"tslint": "~4.3.1",
"typedoc": "^0.5.3",
"typescript": "~2.1.5",
"url-loader": "^0.5.7",
"v8-lazy-parse-webpack-plugin": "^0.3.0",
"webpack": "2.2.0",
"webpack-dev-middleware": "^1.9.0",
"webpack-dev-server": "2.2.0",
"webpack-dll-bundles-plugin": "^1.0.0-beta.5",
"webpack-md5-hash": "^0.0.5",
"webpack-merge": "~2.4.0"
},
"repository": {
"type": "git",
"url": "https://github.com/angularclass/angular2-webpack-starter.git"
},
"bugs": {
"url": "https://github.com/angularclass/angular2-webpack-starter/issues"
},
"engines": {
"node": ">= 4.2.1",
"npm": ">= 3"
}
}
</code></pre>
| 3 | 3,478 |
How to apply events on cloned elements?
|
<p>Can someone please help me with this?</p>
<p>I am trying to make an ordering system, it's all going good and well, but our adviser pointed out that we need to let the user have an option to order multiple items on one transaction. That messed me up. I googled a lot about JQueries and JScripts, but I've finally hit a dead end.</p>
<p>What I have right now are:</p>
<p>HTML(orderform.html):</p>
<pre><code><html>
<head> <link rel="stylesheet"
type="text/css"
href="css/contentFrame.css">
<script src="jscript/protoScript.js"></script>
<script src="jscript/jquery-1.11.3.js"></script>
<script src="jscript/JQueryTest.js"></script>
</head>
<meta charset="utf-8">
<title>Untitled Document</title>
<body>
<div class="formBlock">
<h2 id="formHeader">Order Form</h2>
<form method="POST" action="orderInfoReceiver.php">
<table align="center">
<tr>
<td height="100%">
<fieldset>
<legend>Contact Details</legend>
Last Name:
<br>
<input type="text" name="lName">
<br>
First Name:
<br>
<input type="text" name="fName">
<br>
Middle Name:
<br>
<input type="text" name="mName">
<br>
Email Address:
<br>
<input type="text" name="email">
</fieldset>
</td>
<td height="100%">
<fieldset>
<br>
<legend>Product Information</legend>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Item Name:
<br>
<select id="product" name="product" onchange="setOptions()">
<option>Please Select an Item
<option>Dry Chemical
<option>HCFC 123 (Manual)
<option>HCFC 123 (Therman)
<option>HCFC 123 (Ceiling)
<option>HCFC 236 fa (Manual)
<option>HCFC 236 fa (Therman)
<option>HCFC 236 fa (Ceiling)
<option>AFFF (Steel Cylinder)
<option>AFFF (Stainless Cylinder)
<option>CO2 (Carbon Dioxide)
</select>
<br>
Capacity:
<br>
<select id="capacity" name="capacity">
<option> --
</select>
<input type="radio" name="type" value="New">New <input type="radio" name="type" value="Refill">Refill
<br>
<br>
Quantity:
<br>
<input type="number" min="0" name="quantity">
<br>
<br>
<br>
</div>
<input type="button" id="btnAdd" value="+"> <input type="button" id="btnDel" value="-">
</fieldset>
</td>
<td height="100%">
<fieldset>
<br>
<br>
<legend>Address</legend>
Street:
<br>
<input type="text" name="street">
<br>
<br>
City:
<br>
<input type="text" name="city">
<br>
<br>
<br>
</fieldset>
</td>
</tr>
</table>
<center><input type="submit" value="Submit"></center>
</form>
<br>
</div>
</body>
</code></pre>
<p></p>
<p><br>
JQuery(JQueryTest.js) taken from <a href="http://charlie.griefer.com" rel="nofollow">http://charlie.griefer.com</a> and modified a bit. I got a lot of codes for cloning, but this is the only one I managed to get working with my current forms.</p>
<pre><code> $(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone(true, true).attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').removeAttr('disabled');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').removeAttr('disabled');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</code></pre>
<p><br>
JScript(protoScript.js) I also got this from searching, but I forgot what site:</p>
<pre><code>function addOption(selectId) {
var x = document.getElementById(selectId);
var y = new Option('Test option W3C');
x.add(y,x.options[x.options.length]);
// for IE use x.add(y,2);
}
function appendOptionLast(selectID, num){
var elSel = document.getElementById(selectID);
var elOptNew = document.createElement('option');
elOptNew.text = num;
elOptNew.value = num;
try {
elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOptNew); // IE only
}
}
function removeAllOptions(selectID){
var elSel = document.getElementById(selectID);
elSel.options.length = 0
if (elSel.length > 0){
elSel.remove(0);
}
}
function addAllOptions(selectID, values){
var arrayLength = values.length;
for (var i = 0; i < arrayLength; i++) {
appendOptionLast(selectID,values[i]);
}
}
function setOptions(){
var product = document.getElementById("product");
// removeAllOptions('capacity');
document.getElementById('capacity').options.length = 0
var selIndex = product.selectedIndex;
if(selIndex == 1)
addAllOptions('capacity', ["2 lbs","3 lbs", "5 lbs", "10 lbs", "15 lbs", "20 lbs", "50 lbs", "100 lbs", "150 lbs", "200 lbs"]);
else if(selIndex == 2){
addAllOptions('capacity', ["3 lbs", "5 lbs", "10 lbs", "15 lbs", "20 lbs", "50 lbs"]);
}
else if(selIndex == 3){
addAllOptions('capacity', ["10 lbs", "15 lbs", "20 lbs"]);
}
else if(selIndex == 4){
addAllOptions('capacity', ["10 lbs", "20 lbs"]);
}
else if(selIndex == 5){
addAllOptions('capacity', ["3 lbs", "5 lbs", "10 lbs", "15 lbs", "20 lbs", "50 lbs"]);
}
else if(selIndex == 6){
addAllOptions('capacity', ["3 lbs", "5 lbs", "10 lbs", "15 lbs", "20 lbs", "50 lbs"]);
}
else if(selIndex == 7){
addAllOptions('capacity', ["3 lbs", "5 lbs", "10 lbs", "15 lbs", "20 lbs", "50 lbs"]);
}
else if(selIndex == 8){
addAllOptions('capacity', ["10 lbs", "15 lbs", "20 lbs", "25 lbs", "50 lbs", "100 lbs", "200 lbs"]);
}
else if(selIndex == 9){
addAllOptions('capacity', ["20 lbs", "25 lbs", "50 lbs"]);
}
else if(selIndex == 10){
addAllOptions('capacity', ["5 lbs", "10 lbs", "15 lbs", "50 lbs"]);
}
else{
addAllOptions('capacity', ["--"]);
}
}
</code></pre>
<p><br>
<strong>I hit a dead end with having the event <code>onchange</code> on <code><select id='product>'</code> to work with the cloned forms too.</strong></p>
<p>I have also tried using <code>clone(true, true)</code> but could not make it work.</p>
<p>I got custom css too, it only contains very basic design, so I will deem it unnecessary to include.</p>
<p>Please note that we were only taught basic HTML -up until forms if I recall, basic PHP, Java, C#, and SQL. This is my first try to code JScripts and JQueries and I am having a hard time which is which.</p>
| 3 | 5,572 |
What drives numerical instability in eigenvalue computations in python?
|
<p>Let's say I have a data matrix X with num_samples = 1600, dim_data = 2, from which I can build a 1600*1600 similarity matrix S using the <a href="https://en.wikipedia.org/wiki/Radial_basis_function_kernel" rel="nofollow noreferrer">rbf kernel</a>. I can normalize each row of the matrix, by multiplying all entries of the row by (1 / sum(entries of the row)). This procedure gives me a (square) <a href="https://en.wikipedia.org/wiki/Stochastic_matrix" rel="nofollow noreferrer">right stochastic matrix</a>, which we expect to have an eigenvalue equal to 1 associated to a constant eigenvector full of 1s.</p>
<p>We can easily check that this is indeed an eigenvector by taking its product with the matrix. However, using <code>scipy.linalg.eig</code> the obtained eigenvector associated to eigenvalue 1 is only piecewise constant.</p>
<p>I have tried <code>scipy.linalg.eig</code> on similarly sized matrices with randomly generated data which I transformed into stochastic matrices and consistently obtained a constant eigenvector associated to eigenvalue 1.</p>
<p>My question is then, what factors may cause numerical instabilities when computing eigenvalues of stochastic matrices using <code>scipy.linalg.eig</code>?</p>
<p>Reproducible example:</p>
<pre><code>def kernel(sigma,X):
"""
param sigma: variance
param X: (num_samples,data_dim)
"""
squared_norm = np.expand_dims(np.sum(X**2,axis=1),axis=1) + np.expand_dims(np.sum(X**2,axis=1),axis=0)-2*np.einsum('ni,mi->nm',X,X)
return np.exp(-0.5*squared_norm/sigma**2)
</code></pre>
<pre><code>def normalize(array):
degrees = []
M = array.shape[0]
for i in range(M):
norm = sum(array[i,:])
degrees.append(norm)
degrees_matrix = np.diag(np.array(degrees))
P = np.matmul(np.linalg.inv(degrees_matrix),array)
return P
</code></pre>
<pre><code>#generate the data
points = np.linspace(0,4*np.pi,1600)
Z = np.zeros((1600,2))
Z[0:800,:] = np.array([2.2*np.cos(points[0:800]),2.2*np.sin(points[0:800])]).T
Z[800:,:] = np.array([4*np.cos(points[0:800]),4*np.sin(points[0:800])]).T
X = np.zeros((1600,2))
X[:,0] = np.where(Z[:,1] >= 0, Z[:,0] + .8 + params[1], Z[:,0] - .8 + params[2])
X[:,1] = Z[:,1] + params[0]
#create the stochastic matrix P
P = normalize(kernel(.05,X))
#inspect the eigenvectors
e,v = scipy.linalg.eig(P)
p = np.flip(np.argsort(e))
e = e[p]
v = v[:,p]
plot_array(v[:,0])
#check on synthetic data:
Y = np.random.normal(size=(1600,2))
P = normalize(kernel(Y))
#inspect the eigenvectors
e,v = scipy.linalg.eig(P)
p = np.flip(np.argsort(e))
e = e[p]
v = v[:,p]
plot_array(v[:,0])
</code></pre>
<p>Using the code provided by <a href="https://stackoverflow.com/users/15649230/ahmed-aek">Ahmed AEK</a>, here are some results on the divergence of the obtained eigenvector from the constant eigenvector.</p>
<pre><code>[-1.36116641e-05 -1.36116641e-05 -1.36116641e-05 ... 5.44472888e-06
5.44472888e-06 5.44472888e-06]
norm = 0.9999999999999999
max difference = 0.04986484253966891
max difference / element value -3663.3906291852545
</code></pre>
<p>UPDATE:</p>
<p>I have observed that a low value of sigma in the construction of the kernel matrix produces a less sharp decay in the (sorted) eigenvalues. In fact, for sigma=0.05, the first 4 eigenvalues produced by <code>scipy.linalg.eig</code> are rounded up to 1. This may be linked to the imprecision in the eigenvectors. When sigma is increased to 0.5, I do obtain a constant eigenvector.</p>
<p>First 5 eigenvectors in the sigma=0.05 case</p>
<p><a href="https://i.stack.imgur.com/gOX3z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gOX3z.png" alt="First 5 eigenvectors in the sigma=0.05 case" /></a></p>
<p>First 5 eigenvectors in the sigma=0.5 case</p>
<p><a href="https://i.stack.imgur.com/jwiAJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jwiAJ.png" alt="First 5 eigenvectors in the sigma=0.5 case" /></a></p>
| 3 | 1,557 |
Calling Partial View from Home/Index problem
|
<p>I am creating a web page that displays 3 different kind of followers (Red, Blue, Yellow) and a Filter form that users can use to filter.</p>
<p>For instance, if the customer selects a Red option from the dropdown list, I wanna show them only the red followers.</p>
<p>I am creating the select part for now, but I am getting an error which reads like this.</p>
<blockquote>
<p>The controller for path '/' was not found or does not implement IController.</p>
</blockquote>
<p>This is the </p>
<p>AND this is the FilterController:</p>
<pre><code> public class HomeController : Controller
{
private asp6Entities db = new asp6Entities();
public ActionResult Index()
{
var allFlowers = db.FLOWERs.ToList();
List<FLOWER> result = new List<FLOWER>();
foreach (var flower in allFlowers)
{
FLOWER model = new FLOWER();
model = flower;
result.Add(model);
}
return View(result);
}
public ActionResult About()
{
ViewBag.Message = "Our History";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Main Store and Distribution Center.";
return View();
}
[HttpPost]
public ActionResult Index(FilterModel fromColorFilter)
{
string SelectedColor = (fromColorFilter.ColorSelected);
var allFlowers = db.FLOWERs.ToList();
List<FLOWER> result = new List<FLOWER>();
foreach (var flower in allFlowers)
{
if (flower.COLOR.COLOR_NAME == SelectedColor)
{
FLOWER model = new FLOWER();
model = flower;
result.Add(model);
}
}
return View(result);
}
}
</code></pre>
<p>THis is the Filter Controller:</p>
<pre><code> public class FilterController : Controller
{
// GET: FilterModel
private asp6Entities db = new asp6Entities();
public ActionResult Index()
{
FilterModel model = new FilterModel();
var color = db.COLORs.ToList().Select(s => new SelectListItem
{
Text = s.COLOR_NAME,
Value = s.COLOR_ID.ToString()
});
return PartialView("~/Views/Shared/_FilterForm.cshtml", new FilterModel { AllColorOptions = color});
}
}
</code></pre>
<p>And This is the FilterMethod :</p>
<pre><code> public class FilterModel
{
//declaring the colors selection
public string ColorSelected { get; set; }
//Creating the Size selection
public string SizeSelected { get; set; }
//Creating the starting price selection
public int StartingPriceSelection { get; set; }
//Creating Ends price Selection
public int EndingPriceSelection { get; set; }
//creating IEnumerable of all color options
public IEnumerable<SelectListItem> AllColorOptions { get; set; }
//creating IEnumerable of all Size Options
public IEnumerable<SelectListItem> AllSizeOptions { get; set; }
//creating IEnumerable of Starting Price Options
public IEnumerable<SelectListItem> AllStartingPriceOptions { get; set; }
//creating IEnumerable of Ending Price Options
public IEnumerable<SelectListItem> AllEndingPriceOptions { get; set; }
}
</code></pre>
<p>This is the Home Index:</p>
<p>In this Home Index</p>
<pre><code>@Html.Action("Index","FilterForm");
</code></pre>
| 3 | 1,331 |
Catching DisabledException when using Custom User Checker in Symfony 4.1
|
<p>I've implemented a Custom User Checker in Symfony following <a href="https://symfony.com/doc/current/security/user_checkers.html" rel="nofollow noreferrer">this guide</a>. I need it to perform the additional check of determining if the account trying to log in is active.</p>
<p>Here's my User Checker code:</p>
<pre><code>class UserChecker implements UserCheckerInterface {
public function checkPreAuth(UserInterface $user) {
if (!$user->getUser()->getIsActive()) {
throw new DisabledException("Account is disabled.");
} else {
return;
}
}
public function checkPostAuth(UserInterface $user) {
return;
}
}
</code></pre>
<p>In this case, the <code>$user</code> object that gets passed in by DI, is simply a wrapper (which implements UserInterface) of my User object. My user object has a bool flag of <code>isActive</code>. if <code>getIsActive</code> returns false, my condition negates that, and it should throw the <code>DisabledException</code>.</p>
<p>This is not the behavior I'm seeing, however. If I log in with an active user, I can log in fine. If I log in with a disabled user, it simply returns me back to the log in screen (no exception thrown).</p>
<p>If I change <code>DisabledException</code> to simply <code>Exception</code>, the exception is thrown, but I don't see a spot in my code where I can catch it so that I can show a pretty 'account is disabled' message to the user above the login screen.</p>
<p>I'm assuming that Symfony is catching and swallowing the <code>DisabledException</code> somewhere.</p>
<p>Here is my <code>security.yaml</code>:</p>
<pre><code>security:
providers:
db_provider:
id: database_user_provider
encoders:
App\Utility\Security\DatabaseUser: bcrypt
firewalls:
main:
pattern: ^/
form_login:
provider: db_provider
login_path: login
check_path: process_login
default_target_path: do_some_stuff
use_referer: true
user_checker: App\Utility\Security\UserChecker
anonymous: ~
logout:
path: logout
target: login
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/userRegister, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_USER }
</code></pre>
<p>My question is: Where is that exception being caught / what do I need to override or implement so that I can get a message out to the user?</p>
<p>or</p>
<p>Where can I catch <code>Exception</code> to do the same thing?</p>
| 3 | 1,081 |
Vectorized comparison of values against a set of values
|
<p>I have a <code>pd.Dataframe</code> with a column that contains a value such as </p>
<pre><code>df.iloc[:10]['occ']
Out[18]:
0 4220
1 205
2 7630
3 8965
4 430
5 3930
6 4230
7 5620
8 4040
9 4130
</code></pre>
<p>I then have another dataframe with <code>start</code> and <code>end</code> values for different groups. I want to assign groups to the first dataframe based on their <code>occ</code> value.</p>
<pre><code> start end
group
10 10 950
11 1000 3540
12 3600 3655
13 3700 3955
14 4000 4160
</code></pre>
<p>Since these groups are not intersecting, we have a simple bijection. I was planning to for each <code>occ</code> value, take the group-index of the last row that is smaller than the said <code>occ</code> value.</p>
<pre><code>testAgainst = np.repeat(dfGroups['start'].values[np.newaxis, :], repeats=10, axis=0)
array([[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000],
[ 10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200,
7000, 7700, 9000]])
</code></pre>
<p>And now, since the dimensions are <code>(10,)</code> and <code>(10, 14)</code>, there should automatic broadcasting happening. I am expecting to be able to do</p>
<pre><code>df.iloc[:10]['occ'] < testAgainst
</code></pre>
<p>and get as a result</p>
<pre><code>0 False False False False False False True True True True True True True True
1 False True True True True True True True True True True True True True
</code></pre>
<p>for the first two rows, because <code>4220</code> is larger than <code>4200</code> (and all numbers thereafter), and <code>205</code> is larger than <code>10</code>.</p>
<p>However, I get</p>
<pre><code>Traceback (most recent call last):
File "/home/foo/.conda/envs/myenv3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-28-1bce7761846c>", line 1, in <module>
df.iloc[:10]['occ'] < testAgainst
File "/home/foo/.conda/envs/myenv3/lib/python3.5/site-packages/pandas/core/ops.py", line 832, in wrapper
return self._constructor(na_op(self.values, np.asarray(other)),
File "/home/foo/.conda/envs/myenv3/lib/python3.5/site-packages/pandas/core/ops.py", line 792, in na_op
result = getattr(x, name)(y)
ValueError: operands could not be broadcast together with shapes (10,) (10,14)
</code></pre>
<ol>
<li>Why is the broadcasting not working here?</li>
<li>Given that this fails to work, what is the most efficient way to assign groups to my dataframe (real case: 10-15, groups, but 25 million rows in <code>df</code>).</li>
</ol>
| 3 | 1,519 |
Dynamically loading large data in jTable using SwingWorker
|
<p>In Netbeans, I am trying to create a Desktop Application whose UI looks like below:</p>
<p><a href="https://i.stack.imgur.com/3b0vP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3b0vP.png" alt="enter image description here"></a></p>
<p>I am executing "adb logcat command" through Java code which loads 1000s of lines of logs in few seconds & I intend to display all of this information through jTable in NetBeans. </p>
<p>Using parameter: adb logcat -t 100 -> I am restricting the logs to 100 lines only right now.
However the applet becomes unresponsive (or gets stuck in process() method) for 1000 lines or when removing such restriction on number of lines.</p>
<p>I am not sure whether I have properly implemented the SwingWorker thread in my code. I am looking for suggestions on how to improve the code for loading large amount of data dynamically without applet becoming unresponsive.</p>
<p>Following is the implemented code for the applet... with 2 functions:</p>
<ol>
<li>viewLogs() called from init() method of applet.</li>
<li><p>SwingWorker implementation.</p>
<pre><code> public void viewLogs() throws IOException {
String[] command = {"CMD","/C", "adb logcat -t 100"};
ProcessBuilder probuilder = new ProcessBuilder( command );
probuilder.directory(new File("c:\\Users\\k.garg\\Desktop\\"));
Process process = probuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
worker.execute();
try {
int exitVal = process.waitFor();
System.out.println("exitVal = " + exitVal);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public class TableSwingWorker extends SwingWorker<DefaultTableModel, Object[]>{
private DefaultTableModel tableModel;
public TableSwingWorker(DefaultTableModel tableModel){
this.tableModel = tableModel;
}
@Override
protected DefaultTableModel doInBackground() throws Exception {
Thread.sleep(2000); //added for initial UI to load
System.out.println("Start populating");
String line, date, time, loglevel, PID, TID, tag, message="";
String log;
int count = 0;
while ((log = br.readLine()) != null) {
count++;
String[] splitLog = log.trim().split("\\s+");
line = Integer.toString(count);
date = splitLog[0];
time = splitLog[1];
PID = splitLog[2];
TID = splitLog[3];
loglevel = splitLog[4];
tag = splitLog[5];
for(int i=6; i<splitLog.length;i++){
message += splitLog[i];
}
publish(new Object[]{line, date, time, PID, TID, loglevel, tag, message});
}
return tableModel;
}
@Override
protected void process(List<Object[]> chunks) {
System.out.println("Adding " + chunks.size() + " rows");
for(Object[] row: chunks)
tableModel.insertRow(0,row);
}
</code></pre>
<p>}</p></li>
</ol>
| 3 | 1,093 |
Copying Data to another workbook
|
<p>I use two workbooks (obviously based on the question:)), from the first one (as you will see in the code below) gets sorted by the data in column "B". The data in this column is just a number based on the month (11=November, December=12, etc.). For this question (and it will provide the answer for my other monthly workbooks), need to copy all the rows of data (columns A:AE) in column B to another workbook (which is already open), and paste the data into the empty row at the bottom. I have the sort part working fine. I am trying to add in the copy & paste function into the code, but can't get it to work. HELP!</p>
<p>Here is the code I have tried (but can't figure out how to get focus to the target workbook):</p>
<pre><code>Sub Extract_Sort_1512_December()
' This line renames the worksheet to "Extract"
Application.ScreenUpdating = False
ActiveSheet.Name = "Extract"
' This line autofits the columns C, D, O, and P
Range("C:C,D:D,O:O,P:P").Columns.AutoFit
' This unhides any hidden rows
Cells.EntireRow.Hidden = False
Dim LR As Long
With ActiveWorkbook.Worksheets("Extract").Sort
With .SortFields
.Clear
.Add Key:=Range("B2:B2000"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
End With
.SetRange Range("A2:Z2000")
.Apply
End With
For LR = Range("B" & Rows.Count).End(xlUp).Row To 2 Step -1
If Range("B" & LR).Value <> "12" Then
Rows(LR).EntireRow.Hidden = True
End If
Next LR
Cells.WrapText = False
Sheets("Extract").Range("A2").Select
Dim LastRow As Integer, i As Integer, erow As Integer
LastRow = ActiveSheet.Range(“A” & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Cells(i, 2) = “12” Then
Range(Cells(i, 1), Cells(i, 31)).Select
Selection.Copy
ActiveWorkbook(“Master File - Swivel - December 2015.xlsm”).Select
Worksheets(“Master”).Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
End If
Next i
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>I have found this code below, but do not know how to insert it properly into my code above. The thing that makes me weary is that the workbooks are already open. The target workbook is located on our SharePoint site and I do not know how (or if) you can use VBA code to open it to your desktop.</p>
<p>Here is the other code:</p>
<pre><code>Sub Demo()
Dim wbSource As Workbook
Dim wbTarget As Workbook
' First open both workbooks :
Set wbSource = Workbooks.Open(" ") ' <<< path to source workbook
Set wbTarget = ActiveWorkbook ' Workbooks.Open(" ") ' <<< path to destination workbook
'Now, transfer values from wbSource to wbTarget:
wbTarget.Sheets("Sheet1").Range("B2").Value = wbSource.Sheets("Sheet3").Range("H4")
wbTarget.Sheets("Sheet1").Range("B3").Value = wbSource.Sheets("Sheet3").Range("J10")
'Close source:
wbSource.Close
End Sub
</code></pre>
| 3 | 1,153 |
gqlgen coding style code is tightly coupled to neo4j golang
|
<p>I am just starting to get used to gqlgen to create a golang based graphql api for a personal project I am working on. This is my first attempt at adding a user node into the db, the code works (it took a while, I am new to go neo4j and graphql).</p>
<p>My problem is it feels very coupled to the db, my coding style would be to abstract away the db operations from this code. I don't feel sufficiently experienced to achieve this so I am looking for advice to improve before heading into further programming. I have 25+ years experience of different languages SQL, C++, PHP, Basic, Java, Javascript, Pascal, etc so happy with programming and databases (not so much graph databases).</p>
<p><strong>Code from schema.resolvers.go</strong></p>
<pre><code>// UpsertUser adds or updates a user in the system
func (r *mutationResolver) UpsertUser(ctx context.Context, input model.UserInput) (*model.User, error) {
// Update or insert?
var userId string
if input.ID != nil {
userId = *input.ID
} else {
newUuid, err := uuid.NewV4() // Create a Version 4 UUID.
if err != nil {
return nil, fmt.Errorf("UUID creation error %v", err)
}
userId = newUuid.String()
}
// Open session
session := r.DbDriver.NewSession(neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite})
defer func(session neo4j.Session) {
err := session.Close()
if err != nil {
}
}(session)
// Start write data to neo4j
neo4jWriteResult, neo4jWriteErr := session.WriteTransaction(
func(transaction neo4j.Transaction) (interface{}, error) {
transactionResult, driverNativeErr :=
transaction.Run(
"MERGE (u:User {uuid: $uuid}) ON CREATE SET u.uuid = $uuid, u.name = $name, u.userType = $userType ON MATCH SET u.uuid = $uuid, u.name = $name, u.userType = $userType RETURN u.uuid, u.name, u.userType",
map[string]interface{}{"uuid": userId, "name": input.Name, "userType": input.UserType})
// Raw driver error
if driverNativeErr != nil {
return nil, driverNativeErr
}
// If result returned
if transactionResult.Next() {
// Return the created nodes data
return &model.User{
ID: transactionResult.Record().Values[0].(string),
Name: transactionResult.Record().Values[1].(string),
UserType: model.UserType(transactionResult.Record().Values[2].(string)),
}, nil
}
// Node wasn't created there was an error return this
return nil, transactionResult.Err()
})
// End write data to neo4j
// write failed
if neo4jWriteErr != nil {
return nil, neo4jWriteErr
}
// write success
return neo4jWriteResult.(*model.User), nil
}
</code></pre>
<p><strong>Code from resolver.go</strong></p>
<pre><code>type Resolver struct {
DbDriver neo4j.Driver
}
</code></pre>
<p><strong>schema.graphqls</strong></p>
<pre><code>enum UserType {
"Administrator account"
ADMIN
"Tutor account"
TUTOR
"Student account"
STUDENT
"Unvalidated Account"
UNVALIDATED
"Suspended Account"
SUSPENDED
"Retired account"
RETIRED
"Scheduled for deletion"
DELETE
}
type User {
id: ID!
name: String!
userType: UserType!
}
input UserInput {
id: String
name: String!
userType: UserType!
}
type Mutation {
upsertUser(input: UserInput!) : User!
}
</code></pre>
| 3 | 1,367 |
Possible Multiple AuthenticationSchemes in request header?
|
<p>I have two webapis A and B. From A i make a request to B. A contains user info from identityserver4 where i just need to pass the token to the request header. Beside identityserver token, A also uses AAD(Azure Active Directory) where i have registred B. So from A, i also check my AAD so that i can retrieve The token from Azure to send to B, This is just so B can trust that a request is coming from a trusted registred source. As you can understand From A i have two tokens, one to check the loged in user and the other to check registred application. My A startup class look like this:</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
Config = services.ConfigureAuthConfig<AuthConfig>(Configuration.GetSection("AuthConfig"));
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<ICurrentUser, CurrentUser>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(//this coming with identityserver token and user info
idt =>
{
idt.Authority = "https://gnoauth.se:5005";
idt.ApiName = "globalnetworkApi";
idt.SaveToken = true;
idt.RequireHttpsMetadata = true;
}
);
</code></pre>
<p>So here is my A httpclienthelper, where i setup my client headers to send to B, As i already have the token and user from identity server so the other thing i do here is to send B authority, client id and secret to AAD for retrieving the second token:</p>
<pre><code>var context = new HttpContextAccessor().HttpContext;
var accessTokenFromIdentityserver = await
context.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
var tokenfromAAD = result.AccessToken;
defaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("AAD_Authentication", tokenfromAAD);
</code></pre>
<p>from here i actualy have all i need, both the tokens and all claims. As you can see to the defaultrequestheaders i only cansend one token but i would like to send both tokens to B, how can i configure the request headers to be able to do that?</p>
<p>So here is the B startup</p>
<pre><code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer("AAD_Authentication", opt =>
{
opt.Audience = Configuration["AAD:ResourceId"];
opt.Authority = $"{Configuration["AAD:InstanceId"]}{Configuration["AAD:TenantId"]}";
opt.RequireHttpsMetadata = true;
})
.AddJwtBearer("IDS4_Authentication",
idt =>
{
idt.Authority = "https://gnoauth.se:5005";
idt.Audience = "globalnetworkApi";
idt.SaveToken = true;
idt.RequireHttpsMetadata = true;
}
);
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("AAD_Authentication", "IDS4_Authentication")
.Build();
</code></pre>
<p>But i also setup a policy so that from some of my controllers i need to authorize both logedin user and application registration like this</p>
<pre><code>[Authorize(AuthenticationSchemes = "AAD_Authentication,IDS4_Authentication", Policy = "MyPolicy")]
</code></pre>
<p>the big problem i have been facing is how from A to send both tokens and how to setup authenticationschemes so that B actually get two bearer authenticationschemes</p>
<p>ANY HELP PLEASE</p>
| 3 | 1,606 |
React native typescript : adding automatic hyphen and mask
|
<p>I’m doing project in React Native.</p>
<ol>
<li><p>How can i add hyphen automatically while typing the social security numbers like <code>123456789</code> to <code>123-45-6789</code>.</p>
</li>
<li><p>How can i mask the specific number into any symbol from left or right like <code>123456789</code> to <code>xxx-45-6789</code> or <code>123-45-xxxx</code>.</p>
</li>
</ol>
<p>My code :</p>
<pre><code>import React, {useEffect, useRef} from 'react';
import { StyleProp, ViewStyle } from 'react-native';
import { Controller } from 'react-hook-form';
import { useSelector } from 'react-redux';
import { Layout, Input, Icon } from '_atoms';
import { fillColor } from '_utils';
import { Label } from '_organisms';
import { style } from '../style';
let Mask = ({ attribute, data, formOptions, disable }: any) => {
const { name, required, title, info, placeHolder, validationRegEx, defaultValue, canUpdate,
unique, splitBy, pattern, numOfSplits, position, mask, length, maskBy,
...others } = attribute;
const { control }: any = formOptions || {};
let regEx = /^(?!(000|666|9))\d{3}-?(?!(00))\d{2}-?(?!(0000))\d{4}$/
const { theme } = useSelector((state: any) => state.app);
let color = fillColor(disable, theme);
return (
<Layout style={style.container as StyleProp<ViewStyle>}>
<>
<Label isRequired={required} title={title} description={info} />
</>
<Controller
control={control}
render={({ field, fieldState }: any) => {
let { onChange, value } = field || {};
let { error } = fieldState || {};
let { message } = error || {};
return (
<Input
placeholder={placeHolder}
testID={name}
disabled={disable}
onChangeText={(value: any) => { onChange(value); }}
value={value ? value : ''}
status={error ? 'danger' : 'primary'}
caption={error ? message || 'Required' : ''}
accessoryRight={(props: any) => {
if (value) {
return (
<Icon
{...props}
fill={color}
name={'close'}
disabled={disable}
onPress={() => onChange('')}
/>
);
} else return <></>;
}}
/>
)
}}
name={name}
rules={{
required: required,
pattern: {
value: validationRegEx || regEx,
message: 'Enter a valid SSN',
},
maxLength: {
value: 11,
message: "SSN length should be < 9",
},
}}
defaultValue={data || defaultValue || ''}
/>
</Layout>
);
};
export default Mask;
</code></pre>
| 3 | 2,095 |
How to obtain underlying checkbox values in a reactive?
|
<p>I have the following shiny dashboard app, this app currently generates checkboxes from a dataframe which i have created in the server section - there is also a select all button, what i want to do is the following: </p>
<p>1) create a reactive - (there is an example of a commented section in the code where i have attempted this, but it did not work) - this reactive should contain the "id" values of the selected checkbox (so this the values in the first column of the underlying data frame) </p>
<p>2) Make sure that this works for these scenarios - when a user selects checkboxes on their own, and then it also works when a user presses the "select all" button - so this reactive will update and populate itself in either of those situations </p>
<p>I have commented out some code where i attempted this but ran into errors and issues - does anyone know how to actually get those id values for what you select in the checkboxes? this has to work across all tabs and also work if the select all button is pressed or un pressed </p>
<p>code for reference! </p>
<pre><code>library(shiny)
library(shinydashboard)
library(tidyverse)
library(magrittr)
header <- dashboardHeader(
title = "My Dashboard",
titleWidth = 500
)
siderbar <- dashboardSidebar(
sidebarMenu(
# Add buttons to choose the way you want to select your data
radioButtons("select_by", "Select by:",
c("Work Pattern" = "Workstream"))
)
)
body <- dashboardBody(
fluidRow(
uiOutput("Output_panel")
),
tabBox(title = "RESULTS", width = 12,
tabPanel("Visualisation",
width = 12,
height = 800
)
)
)
ui <- dashboardPage(header, siderbar, body, skin = "purple")
server <- function(input, output, session){
nodes_data_1 <- data.frame(id = 1:15,
Workstream = as.character(c("Finance", "Energy", "Transport", "Health", "Sport")),
Product_name = as.character(c("Actuary", "Stock Broker", "Accountant", "Nuclear Worker", "Hydro Power", "Solar Energy", "Driver", "Aeroplane Pilot", "Sailor", "Doctor", "Nurse", "Dentist", "Football", "Basketball","Cricket")),
Salary = c(1:15))
# build a edges dataframe
edges_data_1 <- data.frame(from = trunc(runif(15)*(15-1))+1,
to = trunc(runif(15)*(15-1))+1)
# create reactive of nodes
nodes_data_reactive <- reactive({
nodes_data_1
}) # end of reactive
# create reacive of edges
edges_data_reactive <- reactive({
edges_data_1
}) # end of reactive"che
# The output panel differs depending on the how the data is selected
# so it needs to be in the server section, not the UI section and created
# with renderUI as it is reactive
output$Output_panel <- renderUI({
# When selecting by workstream and issues:
if(input$select_by == "Workstream") {
box(title = "Output PANEL",
collapsible = TRUE,
width = 12,
do.call(tabsetPanel, c(id='t',lapply(1:length(unique(nodes_data_reactive()$Workstream)), function(i) {
testing <- unique(sort(as.character(nodes_data_reactive()$Workstream)))
tabPanel(testing[i],
checkboxGroupInput(paste0("checkbox_", i),
label = "Random Stuff",
choiceNames = unique(nodes_data_reactive()$Product_name[
nodes_data_reactive()$Workstream == unique(nodes_data_reactive()$testing)[i]]), choiceValues = unique(nodes_data_reactive()$Salary[
nodes_data_reactive()$Workstream == unique(nodes_data_reactive()$testing)[i]])
),
checkboxInput(paste0("all_", i), "Select all", value = FALSE)
)
})))
) # end of Tab box
} # end if
}) # end of renderUI
observe({
lapply(1:length(unique(nodes_data_reactive()$Workstream)), function(i) {
testing <- unique(sort(as.character(nodes_data_reactive()$Workstream)))
product_choices <- nodes_data_reactive() %>%
filter(Workstream == testing[i]) %>%
select(Product_name) %>%
unlist(use.names = FALSE) %>%
as.character()
product_prices <- nodes_data_reactive() %>%
filter(Workstream == testing[i]) %>%
select(Salary) %>%
unlist(use.names = FALSE)
if(!is.null(input[[paste0("all_", i)]])){
if(input[[paste0("all_", i)]] == TRUE) {
updateCheckboxGroupInput(session,
paste0("checkbox_", i),
label = NULL,
choiceNames = product_choices,
choiceValues = product_prices,
selected = product_prices)
} else {
updateCheckboxGroupInput(session,
paste0("checkbox_", i),
label = NULL,
choiceNames = product_choices,
choiceValues = product_prices,
selected = c()
)
}
}
})
})
# this code here is what i want to adapt or change
# What i want is to create two things
# one is a reactive that will update when a user selects checkboxes (but not the all checkbox)
# this will then result in the unique id values from the id column to appear
# i would also want this reactive to work in conjuction with the select all button
# so that if a user hits the button - then this reactive will populate with the rest of the unique ids
# is this possible?
# got the following code in shiny it doesnt work but i am close!
# chosen_items <- reactive({
#
# if(input$select_by == "Food"){
#
# # obtain all of the underlying price values
# unlist(lapply(1:length(unique(na.omit(nodes_data_reactive()$Food ))),
# function(i){
#
# eval(parse(text = paste("input$`", unique(na.omit(
#
# nodes_data_reactive()$Food
#
# ))[i], "`", sep = ""
#
#
# )))
#
# } # end of function
#
#
#
# )) # end of lapply and unlist
#
# }
# })
} # end of server
# Run the application
shinyApp(ui = ui, server = server)
</code></pre>
| 3 | 3,136 |
What is the equivalent command in openssl to API of DES_ncbc_encrypt?
|
<p>Suppose I have this command in shell</p>
<pre><code>> echo -n "abc" | openssl enc -e -K 4a08805813ad4689 -iv 1112131415161718 -des-cbc -a -p -v
salt=E0BE670000000000
key=4A08805813AD4689
iv =1112131415161718
lb5mBZNE/nU=
bytes read : 3
bytes written: 13
> echo -n "abc" | openssl enc -e -K 4a08805813ad4689 -iv fadced8beb69425b -des-cbc -a -p -v
salt=E0BE670000000000
key=4A08805813AD4689
iv =FADCED8BEB69425B
XXlljYbfJYg=
bytes read : 3
bytes written: 13
</code></pre>
<p>and the c++ code</p>
<pre><code>#include <string.h>
#include <iostream>
#include <string>
#include <openssl/bio.h>
#include <openssl/des.h>
#include <openssl/evp.h>
int b64encode(char* in, int in_len, char* out, int out_cap_len);
int b64decode(char* in, int in_len, char* out, int out_cap_len);
int b64code(char* in, int in_len, char* out, int out_cap_len, bool way);
int b64encode(char* in, int in_len, char* out, int out_cap_len)
{
return b64code(in, in_len, out, out_cap_len, true);
}
int b64decode(char* in, int in_len, char* out, int out_cap_len)
{
return b64code(in, in_len, out, out_cap_len, false);
}
int b64code(char* in, int in_len, char* out, int out_cap_len, bool way)
{
BIO* b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO* bio = BIO_new(BIO_s_mem());
BIO_push(b64, bio);
int out_len = 0;
if (way)
{
BIO_write(b64, in, in_len);
BIO_flush(b64);
out_len = BIO_read(bio, out, out_cap_len);
}
else
{
BIO_write(bio, in, in_len);
BIO_flush(bio);
out_len = BIO_read(b64, out, out_cap_len);
}
BIO_free_all(b64);
return out_len;
}
void hexdump(unsigned char* ptr, int len)
{
for (int i = 0; i < len; ++i)
{
printf("%02x", *(ptr + i));
}
printf("\n");
return;
}
int main(int argc, char* argv[])
{
std::string text("abc");
unsigned char cipher[1024] = "";
DES_key_schedule schedule;
DES_cblock key = { 0x4a, 0x08, 0x80, 0x58, 0x13, 0xad, 0x46, 0x89 };
DES_cblock ivec = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 };
DES_set_key_checked(&key, &schedule);
printf("initialized:\n");
printf("key=");
hexdump(key, sizeof key);
printf("iv =");
hexdump(ivec, sizeof ivec);
DES_ncbc_encrypt((unsigned char*)text.c_str(), cipher, (long)text.length(), &schedule, &ivec, DES_ENCRYPT);
printf("updated:\n");
printf("key=");
hexdump(key, sizeof key);
printf("iv =");
hexdump(ivec, sizeof ivec);
char b64encoded[1024] = "";
b64encode((char*)cipher, strlen((char*)cipher), b64encoded, sizeof b64encoded - 1);
std::cout << b64encoded << std::endl;
return 0;
}
</code></pre>
<p>Then I build and run it</p>
<pre><code>> g++ -o zdex.bex zdes.cpp -lcrypto && ./zdex.bex
initialized:
key=4a08805813ad4689
iv =1112131415161718
updated:
key=4a08805813ad4689
iv =fadced8beb69425b
+tzti+tpQls=
</code></pre>
<p>So if I want to get the identical result <code>+tzti+tpQls=</code> using <code>openssl</code> utility, how to change the way using it, do I need to change the endianness of <code>key</code> or <code>iv</code> or maybe the cipher name I don't know. Thanks in advance.</p>
| 3 | 1,608 |
I want to go to my filtered source model tree view when I click on Pivot View Data
|
<p>When I click on the Pivot View Data , it usually goes to the clicked data's tree view in the Pivot View's model (<code>pivot.analysis</code>) .
Instead of this I want to go to my Source Model's Tree View (<code>account.move.line</code>).</p>
<p><strong>Code XML</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<odoo>
<data>
<record id="view_pivot" model="ir.ui.view">
<field name="name">name_pivot</field>
<field name="model">pivot.analysis</field>
<field name="arch" type="xml">
<pivot string="Analysis">
<field name="user_type_id" type="row"/>
<field name="balance" type="measure"/>
</pivot>
</field>
</record>
<record id="view_analysis_tree" model="ir.ui.view">
<field name="name">analysis_tree</field>
<field name="model">pivot.analysis</field>
<field name="arch" type="xml">
<tree string="Analysis">
<field name="date"/>
<field name="account_id"/>
<field name="name"/>
<field name="ref"/>
<field name="payment_id"/>
<field name="partner_id"/>
<field name="journal_id"/>
<field name="invoice_id"/>
<field name="cost_center_id"/>
<field name="analytic_account_id"/>
<field name="product_id"/>
<field name="debit" sum="Total"/>
<field name="credit" sum="Total"/>
</tree>
</field>
</record>
<record id="menu_action_orchid_entry_analysis" model="ir.actions.act_window">
<field name="name">Entry Analysis</field>
<field name="res_model">pivot.analysis</field>
<field name="view_type">form</field>
<field name="view_mode">pivot,tree</field>
</record>
</code></pre>
<p>Thanks in Advance.</p>
| 3 | 1,403 |
All possible combinations of N elements from one list, with M elements from another list
|
<p>I want to make a method in java that receives two String Lists: <code>list1</code>, <code>list2</code>, and two integers: <code>i1</code> and <code>i2</code>. The method has to return a list of lists (<code>List<List<String>></code>) with all possible distinct list combinations of (<code>i1</code>+<code>i2</code>) elements, so that these combinations has <code>i1</code> elements from <code>list1</code>, and <code>i2</code> elements from <code>list2</code>.</p>
<p>Examples:</p>
<pre><code>list1 = {A,B,C}; list2 = {1,2,3,4};
example1:
i1 = 1; i2 = 3;
method(lis1,i1,list2,i2) results:
{{A,1,2,3};{A,2,3,4};{A,1,3,4};{A,1,2,3}
{B,1,2,3};{B,2,3,4};{B,1,3,4};{B,1,2,3}
{C,1,2,3};CA,2,3,4};{C,1,3,4};{C,1,2,3}}
////////////////////////////////////////////////////////////////////
example2:
i1 = 2; i2 = 2;
method(lis1,i1,list2,i2) results:
{{A,B,1,2};{A,B,1,3};{A,B,1,4};{A,B,2,3};{A,B,2,4};{A,B,3,4};
{A,C,1,2};{A,C,1,3};{A,C,1,4};{A,C,2,3};{A,C,2,4};{A,C,3,4};
{B,C,1,2};{B,C,1,3};{B,C,1,4};{B,C,2,3};{B,C,2,4};{B,C,3,4}}
///////////////////////////////////////////////////////////////
example3:
i1 = 2; i2 = 1;
method(lis1,i1,list2,i2) results:
{{A,B,1};{A,B,2};{A,B,3};{A,B,4}
{A,C,1};{A,C,2};{A,C,3};{A,C,4};
{B,C,1};{B,C,2};{B,C,3};{B,C,4};}
///////////////////////////////////////////////////////////////
example4:
i1 = 0; i2 = 1;
method(lis1,i1,list2,i2) results:
{{1};{2};{3};{4}}
///////////////////////////////////////////////////////////////
</code></pre>
<p>-Lists has not duplicate elements.</p>
<p>-Elements in one list do not appear in the other one.</p>
<p>-I don't need two different lists with same elements:(if i have {A,1} i don't need {1,A}).</p>
<hr>
<p>My current solution only works with fixed size of <code>i1</code> and <code>i2</code>, and i adapt it from this question: ( <a href="https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n">Algorithm to return all combinations of k elements from n</a> )</p>
<p>Can anybody please tell me any algorithm or structure for this problem?.</p>
<p>thanks!</p>
<hr>
<p>EDIT: (added some of my code)</p>
<pre><code>//This method returns a list containing, all possible distinct combinations
//of 3 items from the elemnts of "someList".
private List<List<String>> combinationOfThree(List<String> someList){
List<List<String>> toReturn = new ArrayList<>();
List<String> oneCombination = new ArrayList<>();
int i, j, k;
int len = someList.size();
if (len<=3){
for(String s :someList){
oneCombination.add(s);
}
toReturn.add(oneCombination);
}
else{
for (i = 0; i < len - 2; i++){
for (j = i + 1; j < len - 1; j++){
for (k = j + 1; k < len; k++){
oneCombination = new ArrayList<>();
oneCombination.add(someList.get(i));
oneCombination.add(someList.get(j));
oneCombination.add(someList.get(k));
toReturn.add(oneCombination);
}
}
}
}
return toReturn;
}
private List<List<String>> allPosibleCombinations(List<String> list1, int list1_Amount, List<String> list2, int list2_Amount){
List<List<String>> toReturn = new ArrayList<>();
//currently i can only make combinations of 3 items.
//I can implement "combinationOfTwo" , "combinationOfFour" and so on, but it is nasty as hell.
if (list1_Amount == list2_Amount == 3){
List<List<String>> combinationOfThreeFromList1 = combinationOfThree(list1);
List<List<String>> combinationOfThreeFromList2 = combinationOfThree(list2);
for (List<String> a_l1_comb : combinationOfThreeFromList_1){
for (List<String> a_l2_comb : combinationOfThreeFromList_2){
toReturn.add(appendLists(a_l1_comb , a_l2_comb);
}
}
}
return toReturn;
}
</code></pre>
| 3 | 1,935 |
Next.js "jQuery requires a window with a document", defining jsdom yields Unexpected token
|
<p>I started with the following code, which is intended to create a multi-select button box using Tailwind and DaisyUI in Next.js (The filename of the problematic code snippet is install.js).</p>
<p>I'm rendering it with webpack by running <code>npx next</code>, and <code>index.js</code> works perfectly. However, <code>install.js</code>is not rendered, and shows a "jQuery requires a window..." error.</p>
<pre><code>import Head from 'next/head'
import React from 'react';
import $ from 'jquery';
export default function Home() {
return (
<div class="flex-1 p-10 w-full max-w-4xl my-2">
(function ($, cmdMap) {
var cmdTxt = $('.command .text');
var opts = {
version: 'stable (recommended)',
pm: 'pip',
gpu: 'YES',
};
function buildMatcher() {
return opts.version.toLowerCase() + ',' + opts.pm.toLowerCase() + ','
+ opts.gpu.toLowerCase()
}
function updateCommand() {
var match = cmdMap[buildMatcher(opts)];
cmdTxt.html(match);
}
function selectOption(ev) {
var el = $(this);
el.siblings().removeClass('btn-active');
el.addClass('btn-active');
opts[el.parents('.option-row').data('key')] = el.text();
updateCommand();
}
$('.option-set').on('click', '.btn', selectOption);
updateCommand();
}(jQuery, {
'stable,conda,no': 'a string',
/* ... */
}))
}
<div class="shadow-lg mockup-code">
<pre><code>{/* TODO: figure out what to put here */}</code></pre>
<pre class="pt-3 link"><code><a href="help">What is this?</a></code></pre>
</div>
<div class="pt-5 btns">
<div class="btn-group">
<button class="btn btn-active">stable (recommended)</button>
<button class="btn">nightly</button>
</div>
<div class="pt-3 btn-group">
<button class="btn btn-active">pip</button>
<button class="btn">docker</button>
<button class="btn">conda</button>
</div>
<div class="pt-3 btn-group">
<button class="btn btn-active">GPU Enabled</button>
<button class="btn">No GPU</button>
</div>
</div>
</div>
)
}
</code></pre>
<p>Which yields the following server error: <code>Error: jQuery requires a window with a document</code> at line 14</p>
<pre><code> | (function ($, cmdMap) {
> | var cmdTxt = $('.command .text');
^
| var opts = {
</code></pre>
<p>When I followed the answers <a href="https://stackoverflow.com/questions/21358015/error-jquery-requires-a-window-with-a-document">here</a>, by adding the following snippet at the specified line numbers:</p>
<pre><code>7 var jsdom = require('jsdom');
8 $ = require('jquery')(new jsdom.JSDOM().window);
</code></pre>
<p>I receive an unexpected token error. Sorry if this is silly, I'm really new to JS.</p>
<p>How should I proceed?</p>
<p>Edit: The jQuery function was non-critical for me so I ended up working around it. I still am not too clear on how to resolve this.</p>
| 3 | 1,909 |
No translator error while running Apache Beam job on Flink cluster
|
<p>I created a very simple apache beam job for test, it is written in scala and looks like this:</p>
<pre><code>object Test {
def main(args: Array[String]): Unit = {
val options = PipelineOptionsFactory.fromArgs(args: _*).create()
val p = Pipeline.create(options)
println(s"--------> $options")
val printDoFn = new DoFn[String, Void] {
@ProcessElement
def processElement(c: ProcessContext): Unit = {
val e = c.element()
logger.info(e)
println(s"===> $e")
}
}
p.apply(Create.of[String]("A", "B", "CCC"))
.apply(ParDo.of(printDoFn))
p.run()
}
}
</code></pre>
<p>Now I deployed a flink cluster with the official flink docker image.</p>
<p>I created a uber-jar of my test program using maven shaded plugin.</p>
<p>I uploaded this uber-jar with the web UI interface of Job Manager.</p>
<p>I login into the JobManager machine, and find the uploaded uber-jar, and I run the job with:</p>
<pre><code>flink run -c myapps.Test \
./52649b36-aa57-4f2b-95c7-2552fd737ea6_pipeline_beam-1.0.0-SNAPSHOT.jar \
--runner=FlinkRunner
</code></pre>
<p>But I got this error:</p>
<pre><code>org.apache.flink.client.program.ProgramInvocationException: The main method caused an error.
at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:545)
at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:420)
at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:404)
at org.apache.flink.client.cli.CliFrontend.executeProgram(CliFrontend.java:798)
at org.apache.flink.client.cli.CliFrontend.runProgram(CliFrontend.java:289)
at org.apache.flink.client.cli.CliFrontend.run(CliFrontend.java:215)
at org.apache.flink.client.cli.CliFrontend.parseParameters(CliFrontend.java:1035)
at org.apache.flink.client.cli.CliFrontend.lambda$main$9(CliFrontend.java:1111)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1836)
at org.apache.flink.runtime.security.HadoopSecurityContext.runSecured(HadoopSecurityContext.java:41)
at org.apache.flink.client.cli.CliFrontend.main(CliFrontend.java:1111)
Caused by: java.lang.IllegalStateException: No translator known for org.apache.beam.sdk.io.Read$Bounded
at org.apache.beam.runners.core.construction.PTransformTranslation.urnForTransform(PTransformTranslation.java:164)
at org.apache.beam.runners.flink.FlinkBatchPipelineTranslator.visitPrimitiveTransform(FlinkBatchPipelineTranslator.java:93)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:657)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:649)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:649)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.access$600(TransformHierarchy.java:311)
at org.apache.beam.sdk.runners.TransformHierarchy.visit(TransformHierarchy.java:245)
at org.apache.beam.sdk.Pipeline.traverseTopologically(Pipeline.java:458)
at org.apache.beam.runners.flink.FlinkPipelineTranslator.translate(FlinkPipelineTranslator.java:38)
at org.apache.beam.runners.flink.FlinkBatchPipelineTranslator.translate(FlinkBatchPipelineTranslator.java:49)
at org.apache.beam.runners.flink.FlinkPipelineExecutionEnvironment.translate(FlinkPipelineExecutionEnvironment.java:119)
at org.apache.beam.runners.flink.FlinkRunner.run(FlinkRunner.java:110)
at org.apache.beam.sdk.Pipeline.run(Pipeline.java:313)
at org.apache.beam.sdk.Pipeline.run(Pipeline.java:299)
...
</code></pre>
<p>I think the key error is: <code>No translator known for org.apache.beam.sdk.io.Read$Bounded</code></p>
<p>I compiled my program with apache beam 2.7.0, and from the flink runner page: <a href="https://beam.apache.org/documentation/runners/flink/" rel="nofollow noreferrer">https://beam.apache.org/documentation/runners/flink/</a> , I deployed flink 1.5.5 version, with the flink official image: <code>flink:1.5.5-hadoop28-scala_2.11-alpine</code></p>
<p>I couldn't find any useful information on Google. </p>
| 3 | 1,631 |
Why is not the state updated?
|
<p>I have a function that updates a state with a change and adds a value, but the state in the 'addResponse' function does not always change:</p>
<pre><code>handleSelected (e, item) {
this.setState({
current_component_id: item.id,
}, () => this.addResponse()
);
};
</code></pre>
<p>Call function above:</p>
<pre><code>addResponse (e) {
const { enrollment_id, evaluation_id, user_id, question_id, current_component_id,
responses, current_question, current_question_id
} = this.state;
console.log(current_component_id)
if (current_component_id != 0) {
const newResponse = {
enrollment_id: enrollment_id,
evaluation_id: evaluation_id,
user_id: user_id,
question_id: current_question_id,
answer_component: current_component_id,
};
function hasAnswer(res) {
const list_question_id = res.map((item) => {
return item.question_id
});
if (list_question_id.includes(current_question_id)) {
return true
} else {
return false
}
}
if (responses === undefined) {
this.setState({
responses: [newResponse]
}
, () => console.log('---------> primeiro', this.state.responses)
)
} else {
const check = hasAnswer(responses);
if (check) {
this.setState(prevState => {
prevState.responses.map((item, j) => {
if (item.question_id === current_question_id) {
return item.answer_component = current_component_id
}
return item ;
})
}
, () => { console.log('----> questao alterada ', this.state.responses)}
)
} else {
this.setState({
responses: [...this.state.responses, newResponse]
}
, () => console.log('------> questao nova', this.state.responses)
);
}
}
}
// this.nextQuestion();
};
</code></pre>
<p>the first console.log is always correct, but the others do not always change, I know that setState is asyn, but I thought that as I call the addResponse function it would be async</p>
| 3 | 1,245 |
Controlling the Css3 cube effect using javascript
|
<p>Hello guys i have been trying to take the control of the CSS3 cube using javascript but it's haven't worked with me i don't know what is the problem here is my code :</p>
<pre><code> <div id="expierment">
<div id="cube">
<div class="face front">
Front face
</div>
<div class="face left">
left side face
</div>
<div class="face right">
Right face
</div>
<div class="face back">
back face
</div>
<div class="face down">
down face
</div>
<div class="face up">
up face
</div>
</div>
</div>
<button id="up"><p>up</p></button>
<button id="down"><p>down</p></button>
<button id="left"><p>left</p></button>
<button id="right"><p>right</p></button>
<style type="text/css">
#expierment{
-webkit-perspective: 800;
-webkit-perspective-origin: 50% 200px;
-moz-perspective: 800;
-moz-perspective-origin: 50% 200px;
}
#cube{
position: relative;
margin: 100px auto 0 ;
height:300px;
width:300px;
-webkit-transition: -webkit-transform .5s linear;
-webkit-transform-style: preserve-3d;
-moz-transition: -webkit-transform .5s linear;
-moz-transform-style: preserve-3d;
}
.face{
position: absolute;
height:300px;
width:300px;
padding: 0px;
font-size: 27px;
line-height: 1em;
color: #fff;
border: 1px solid #555;
border-radius: 3px ;
}
#cube .front {
-webkit-transform: translateZ(150px);
-moz-transform: translateZ(150px);
background-color:red;
</code></pre>
<p>}</p>
<pre><code> #cube .left{
-webkit-transform: rotateY(-90deg) translateZ(150px);
-moz-transform: rotateY(-90deg) translateZ(150px);
background-color: orange ;
}
#cube .right{
-webkit-transform: rotateY(90deg) translateZ(150px);
-moz-transform: rotateY(90deg) translateZ(150px);
background-color: green ;
}
#cube .back{
-webkit-transform: rotateY(-180deg) translateZ(150px);
-moz-transform: rotateY(-180deg) translateZ(150px);
background-color: blue ;
}
#cube .up{
-webkit-transform: rotateX(90deg) translateZ(150px);
-moz-transform: rotateX(90deg) translateZ(150px);
background-color: gray ;
}
#cube .down{
-webkit-transform: rotateX(-90deg) translateZ(150px);
-moz-transform: rotateX(-90deg) translateZ(150px);
background-color: #AA00CC ;
}
/* #cube:hover {
-webkit-transform: rotatey(90deg);
} */
button{
width: 50px;
height: 50px;
text-align : center;
padding-bottom :15px;
}
</style>
</code></pre>
<p>as you notice i have make the (hover) as a comment cause i don't want to use it any more </p>
<p>and here is the Javascript code :</p>
<pre><code> <script type="text/javascript">
var cube_node = document.getElementById("cube");
var but_up = document.getElementById("up") ;
var but_down = document.getElementById("down");
var but_right = document.getElementById("right");
var but_left = document.getElementById("left");
but_up.onclick = up();
but_down.onclick = down();
but_right.onclick = right();
but_left.onclick = left();
function up(){
cube_node.style.webkitTransform="rotateX(-90deg)";
}
function down(){
cube_node.style.webkitTransform="rotateX(90deg)";
}
function left(){
cube_node.style.webkitTransform="rotateY(90deg)";
}
function right(){
cube_node.style.webkitTransform="rotateY(-90deg)";
}
</script>
</code></pre>
<p>so please correct my code also if anyone know how can i take this effect a step forward like how to control the cube by mouse holder i will appreciate it and thanks </p>
| 3 | 2,272 |
Why is my program repeating itself. Java Error
|
<p>I am supposed to make the program give the number of pets and the percentage of how many that are below 5lbs, 5-10lbs, and over 10lbs. The program keeps repeating the statements and I don't know why. I've been working on this problem for the past couple of days and I still can't figure it out. At times it seems like I fixed it but then later on it happens again. Can anyone clarify why this is happening? I need help please.</p>
<pre><code>import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.lang.Object;
public class SetPetWeight
{
public static void main(String[] args) {
ArrayList<Pet> list = new ArrayList<Pet>();
String name;
String answer;
int age;
Double weight;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter a String for Pet name: ");
name = keyboard.next();
System.out.println("Enter an int for Pet age: ");
age = keyboard.nextInt();
if(age <= 0)
System.out.println("Error! Enter a real age");
System.out.println("Enter a double for Pet weight: ");
weight = keyboard.nextDouble();
if(weight <= 0)
System.out.println("Error! Enter a real weight");
do
{
System.out.println("Do you want to enter another pet? Y/N");
answer = keyboard.nextLine();
keyboard.nextLine();
} while (answer.equalsIgnoreCase("Y"));
} while (name.length() < 0 && age < 0 && weight < 0);
System.out.println("The weight is now sorted by weight!");
Collections.sort(list, Pet.SortByWeight);
for (Pet p2 : list)
p2.writeOutput();
int average1 = 0;
int average2 = 0;
int average3 = 0;
for (Pet p : list)
{
if(p.getWeight() >= 0 && p.getWeight() <= 5)
{
++average1;
}
else if(p.getWeight() >= 5 && p.getWeight() <= 10)
{
++average2;
}
else if(p.getWeight() > 10)
{
++average3;
}
System.out.println("The average of pets under 5 pounds:" + average1);
System.out.println("The average of pets between 5 and 10 pounds:" + average2);
System.out.println("The average of pets over 10 pounds:" + average3);
}
}
}
</code></pre>
<p>Pet Class that is used for the SetPetWeight class and is compiled correctly and is used for the array.</p>
<pre><code> import java.util.*;
public class Pet {
private String name;
private Integer age; // in years
private double weight; // in pounds
public void writeOutput() {
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName) {
name = newName;
// age and weight are unchanged.
}
public void set(int newAge) {
if (newAge <= 0) {
System.out.println("Error: illegal age.");
System.exit(0);
} else
age = newAge;
// name and weight are unchanged.
}
public void set(double newWeight) {
if (newWeight <= 0) {
System.out.println("Error: illegal weight.");
System.exit(0);
} else
weight = newWeight;
// name and age are unchanged.
}
public Pet(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
public static Comparator<Pet> SortByWeight = new Comparator<Pet>()
{
public int compare(Pet pet1, Pet pet2)
{
return (int)(pet1.getWeight() - pet2.getWeight());
}
};
}
</code></pre>
| 3 | 1,826 |
Python dictionary merge values and delete previous
|
<p>I have a dictionary of characters and their position on a page keyed by their y position (so all characters in a row are under a single key in the dictionary). The data comes from a table from a pdf and I am trying to combine the characters in rows into words based on spacing so that columns are separated as values. So this:</p>
<pre><code>380.822: [[u'1', [61.2, 380.822, 65.622, 391.736]],
[u' ', [65.622, 380.822, 67.834, 391.736]],
[u'p', [81.738, 380.822, 83.503, 391.736]],
[u'i', [84.911, 380.822, 89.333, 391.736]],
[u'e', [90.741, 380.822, 95.163, 391.736]],
[u'c', [96.571, 380.822, 100.548, 391.736]],
[u'e', [100.548, 380.822, 104.97, 391.736]],
[u' ', [104.97, 380.822, 107.181, 391.736]],
[u'8', [122.81, 380.822, 127.232, 391.736]],
[u'9', [127.723, 380.822, 132.146, 391.736]],
[u'0', [132.636, 380.822, 137.059, 391.736]],
[u'1', [137.55, 380.822, 141.972, 391.736]],
[u'S', [142.463, 380.822, 146.885, 391.736]],
[u'Y', [147.376, 380.822, 152.681, 391.736]],
[u'R', [153.172, 380.822, 157.595, 391.736]],
[u'8', [157.595, 380.822, 162.017, 391.736]]]
</code></pre>
<p>would become this:</p>
<pre><code>380.822: [[u'1 ', [61.2, 380.822, 67.834, 391.736]],
[u'piece ', [81.738, 380.822, 107.181, 391.736]],
[u'8901SYR8', [122.81, 380.822, 162.017, 391.736]]]
</code></pre>
<p>I thought I could iterate through the values for each key and merge the text and coordinates if the space was less than some value and then delete the value that got merged, but this would throw off the iteration. All the possibilities I come up with are really clunky, such as marking the leftovers from merges with a character to indicate deletion later but my function started merging these as well.</p>
<p>Thanks</p>
<p>@Lattyware, thanks again for your help. I tried implementing your suggestions and they are mostly working, but I think I am not fully grasping the idea of the groupby. Specifically why in your example it did not do a merge without a group change, but it does with my modifications (such as the merge after the 8 in the 8901SYR8)? The result in my code is that some of my lines split the first letter of the string from the rest:</p>
<pre><code>{380.822: [
(u'1 ', [61.2, 380.822, 65.622, 391.736]),
(u'p', [81.738, 380.822, 83.503, 391.736]),
(u'iece ', [84.911, 380.822, 89.333, 391.736]),
(u'8', [122.81, 380.822, 127.232, 391.736]),
(u'901SYR8 ', [127.723, 380.822, 132.146, 391.736]),
(u'M', [172.239, 380.822, 178.864, 391.736]),
(u'ultipurpose Aluminum (Alloy 6061) .125" Thick Sheet, 12"'...]}
</code></pre>
<p>The adaptations I made are:</p>
<pre><code>xtol=7
def xDist(rCur,rPrv):
if rPrv == None: output=False
else: return not rCur[1][0]-rPrv[1][2] < xtol
def split(row):
ret = xDist(row, split.previous)
print "split",ret,row,split.previous
split.previous = row
return ret
split.previous = None
def merge(group):
letters, position_groups = zip(*group)
return "".join(letters), next(iter(position_groups))
def group(value):
return [merge(group) for isspace, group in
itertools.groupby(value, key=split)]
print({key: group(value) for key, value in old.items()})
</code></pre>
<p>and the print output is:</p>
<pre><code>...
split False [u'9', [127.723, 380.822, 132.146, 391.736]] [u'8', [122.81, 380.822, 127.232, 391.736]]
merge (u'8',) ([122.81, 380.822, 127.232, 391.736],)
split False [u'0', [132.636, 380.822, 137.059, 391.736]] [u'9', [127.723, 380.822, 132.146, 391.736]]
split False [u'1', [137.55, 380.822, 141.972, 391.736]] [u'0', [132.636, 380.822, 137.059, 391.736]]
split False [u'5', [142.463, 380.822, 146.885, 391.736]] [u'1', [137.55, 380.822, 141.972, 391.736]]
split False [u'K', [147.376, 380.822, 152.681, 391.736]] [u'5', [142.463, 380.822, 146.885, 391.736]]
split False [u'2', [153.172, 380.822, 157.595, 391.736]] [u'K', [147.376, 380.822, 152.681, 391.736]]
split False [u'8', [157.595, 380.822, 162.017, 391.736]] [u'2', [153.172, 380.822, 157.595, 391.736]]
split False [u' ', [162.017, 380.822, 164.228, 391.736]] [u'8', [157.595, 380.822, 162.017, 391.736]]
split True [u'M', [172.239, 380.822, 178.864, 391.736]] [u' ', [162.017, 380.822, 164.228, 391.736]]
merge (u'9', u'0', u'1', u'S', u'Y', u'R', u'8', u' ') ([127.723, 380.822, 132.146, 391.736], [132.636, 380.822, 137.059, 391.736], [137.55, 380.822, 141.972, 391.736], [142.463, 380.822, 146.885, 391.736], [147.376, 380.822, 152.681, 391.736], [153.172, 380.822, 157.595, 391.736], [157.595, 380.822, 162.017, 391.736], [162.017, 380.822, 164.228, 391.736])
split False [u'u', [179.292, 380.822, 183.714, 391.736]] [u'M', [172.239, 380.822, 178.864, 391.736]]
merge (u'M',) ([172.239, 380.822, 178.864, 391.736],)
split False [u'l', [184.142, 380.822, 185.908, 391.736]] [u'u', [179.292, 380.822, 183.714, 391.736]]
</code></pre>
| 3 | 2,148 |
c++11 thread unknown output
|
<p>I return to c++ programming, therefore, I am trying a lot of things to master new c++ standard. I know the code I provided is very bad. I think I know how to fix it. </p>
<p>code:</p>
<pre><code>#include <iostream>
#include <thread>
using namespace std;
void apple (string const& x)
{
cout << "aaa" << endl;
}
void orange()
{
//string s = "hello";
thread t(apple,"hello");
t.detach();
}
int main() {
orange();
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
</code></pre>
<p>one kind of outputs:</p>
<pre><code>!!!Hello World!!!
aaa
aaa
</code></pre>
<p>from the code, we can see the "aaa" should be printed once.
my question is why there are two "aaa" on the output. what cause this problem?</p>
<p>many thanks</p>
<p>edit:
added system info:</p>
<pre><code>Using built-in specs.
COLLECT_GCC=/usr/bin/g++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.6.3/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-java-awt=gtk --disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib --with-ppl --with-cloog --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.6.3 20120306 (Red Hat 4.6.3-2) (GCC)
</code></pre>
<p>some other outputs:</p>
<p>type A:</p>
<pre><code>!!!Hello World!!!
aaaaaa
</code></pre>
<p>typeB:</p>
<pre><code>!!!Hello World!!!
</code></pre>
<p>typeC:</p>
<pre><code>!!!Hello World!!!
aaaaaa
</code></pre>
<p>typeD:</p>
<pre><code>!!!Hello World!!!
aaa
<empty line>
</code></pre>
<p>edit:
according @mark's answer. this is an undefined behavior.<br>
I added a "sleep(1);" before main return. it gives me only one type of output. now i got confused, if it is undefined, why i didnt see other types of output?</p>
<p>output:</p>
<pre><code>!!!Hello World!!!
aaa
</code></pre>
| 3 | 1,071 |
How to extract value from html via BeautifulSoup
|
<p>I have parsed my string via BeautifulSoup.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import re
def otoMoto(link):
URL = link
page = requests.get(URL).content
bs = BeautifulSoup(page, 'html.parser')
for offer in bs.find_all('div', class_= "offer-item__content ds-details-container"):
# print(offer)
# print("znacznik")
linkOtoMoto = offer.find('a', class_="offer-title__link").get('href')
# title = offer.find("a")
titleOtoMoto = offer.find('a', class_="offer-title__link").get('title')
rokProdukcji = offer.find('li', class_="ds-param").get_text().strip()
rokPrzebPojemPali = offer.find_all('li',class_="ds-param")
print(linkOtoMoto+" "+titleOtoMoto+" "+rokProdukcji)
print(rokPrzebPojemPali)
break
URL = "https://www.otomoto.pl/osobowe/bmw/seria-3/od-2016/?search%5Bfilter_float_price%3Afrom%5D=50000&search%5Bfilter_float_price%3Ato%5D=65000&search%5Bfilter_float_year%3Ato%5D=2016&search%5Bfilter_float_mileage%3Ato%5D=100000&search%5Bfilter_enum_financial_option%5D=1&search%5Border%5D=filter_float_price%3Adesc&search%5Bbrand_program_id%5D%5B0%5D=&search%5Bcountry%5D="
otoMoto(URL)
</code></pre>
<p>Result:</p>
<pre><code>https://www.otomoto.pl/oferta/bmw-seria-3-x-drive-nowe-opony-ID6Dr4JE.html#d51bf88c70 BMW Seria 3 2016
[<li class="ds-param" data-code="year">
<span>2016 </span>
</li>, <li class="ds-param" data-code="mileage">
<span>50 000 km</span>
</li>, <li class="ds-param" data-code="engine_capacity">
<span>1 998 cm3</span>
</li>, <li class="ds-param" data-code="fuel_type">
<span>Benzyna</span>
</li>]
</code></pre>
<p>So I can extract single strings, but if I see this same class</p>
<pre><code>class="ds-param"
</code></pre>
<p>I can't assigne, for example, production date to variable. Please let me know if you have any ideas :).</p>
<p>Have a nice day !</p>
| 3 | 1,059 |
How to avoid TP being fired with SL, if TP has not yet been reached?
|
<p>The script sends messages to the broker for each action. Therefore to avoid errors, a TP order can not fire when an SL order does.</p>
<p>I'd be extremely grateful for any concrete examples with the code below, on how to have TP fire only if it reaches target, otherwise have SL close entire (or remaining position) by itself.</p>
<p>I tried various strategy.order combinations but I just can not get my head around this one.</p>
<pre><code>//@version=5
//©duronic12
strategy('TP/STOP ISSUE', overlay=true, max_bars_back=5000, process_orders_on_close=true)
// MANAGE RISK
tradeDirection = input.string(title='Trade Direction', options=['Long', 'Short', 'Both'], defval='Long', group='Risk Management')
longOK = tradeDirection == 'Long' or tradeDirection == 'Both'
shortOK = tradeDirection == 'Short' or tradeDirection == 'Both'
stopPer = input(2.0, title='SL (%)', group='Risk Management') / 100
bep = input(4.0, title='Move SL to Breakeven (%)', group='Risk Management')
takePer = input(6.0, title='TP (%)', group='Risk Management') / 100
qt = input(50.0, title='% to close on TP', group='Risk Management')
closeTC = input(true,"Trail after TP", group='Risk Management')
////
// ENTER
HPeriod = 13
LPeriod = 21
hsma = 0.0
lsma = 0.0
hsma := ta.sma(high, HPeriod)
lsma := ta.sma(low, LPeriod)
iff_1 = close < nz(lsma[1]) ? -1 : 0
HLd = close > nz(hsma[1]) ? 1 : iff_1
HLv = ta.valuewhen(HLd != 0, HLd, 0)
HiLo = HLv == -1 ? hsma : lsma
HLcolor = HLv == -1 ? color.maroon : color.blue
plot(HiLo, title="Entry/Trail", linewidth=1, color=HLcolor)
enterLong = (HLv == 1 and HLv[1] == -1)
enterShort = (HLv == -1 and HLv[1] == 1)
if longOK and enterLong
strategy.entry(id='EL', comment='BUY', direction=strategy.long)
if shortOK and enterShort
strategy.entry(id='ES', comment='SELL', direction=strategy.short)
////
// EXIT
longStop = strategy.position_avg_price * (1 - stopPer)
shortStop = strategy.position_avg_price * (1 + stopPer)
shortTake = strategy.position_avg_price * (1 - takePer)
longTake = strategy.position_avg_price * (1 + takePer)
shortTake1 = strategy.position_avg_price * (1 - (99/100))
ExitSell()=>
(bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades-1)) == 0 and strategy.position_size[1]<0
ExitBuy()=>
(bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades-1)) == 0 and strategy.position_size[1]>0
EntryBuy()=>
(strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na) == 1 and strategy.position_size>0
EntrySell()=>
(strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na) == 1 and strategy.position_size<0
H = ta.highest(high,nz(ta.barssince(EntryBuy()),1)+1)
L = ta.lowest(low,nz(ta.barssince(EntrySell()),1)+1)
profit = strategy.position_size>0?((H-strategy.position_avg_price)/strategy.position_avg_price)*100:strategy.position_size<0?((L-strategy.position_avg_price)/strategy.position_avg_price)*-100:na
SL_long = profit>=bep?strategy.position_avg_price:longStop
SL_short = profit>=bep?strategy.position_avg_price:shortStop
plot_sl1 = plot(strategy.position_size>0?SL_long:na,"Long SL",color=color.orange,linewidth=1,style=plot.style_linebr)
plot_sl2 = plot(strategy.position_size<0?SL_short:na,"Short SL",color=color.orange,linewidth=1,style=plot.style_linebr)
//Partial Exit via Take Profit
if strategy.position_size > 0
strategy.exit(id='TP', qty_percent=qt, stop=SL_long, limit=longTake)
if strategy.position_size < 0
strategy.exit(id='TP', qty_percent=qt, stop=SL_short, limit=shortTake)
//Full Exit via Stop Loss
if strategy.position_size > 0
strategy.exit(id='SL', qty_percent=100, stop=SL_long, limit=longTake*1000)
if strategy.position_size < 0
strategy.exit(id='SL', qty_percent=100, stop=SL_short, limit=shortTake1)
//Full Exit via Trailing Stop
if profit>=(takePer*100) and strategy.position_size > 0 and HLv == -1 and closeTC
strategy.close('EL',comment='TSL')
if profit>=(takePer*100) and strategy.position_size < 0 and HLv == 1 and closeTC
strategy.close('ES',comment='TSL')
////
</code></pre>
| 3 | 1,627 |
Different font on strong elements for Internet Explorer 11 and Safari on iOS 9
|
<p>I have a web app with two fonts, Amatic SC for <code>h1</code> and <code>h2</code> and Open Sans for the rest. The webpage displays <code>strong</code> text fine on most browsers:</p>
<p><a href="https://i.stack.imgur.com/Q1Cov.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q1Cov.png" alt="Display on Firefox and most browsers" /></a></p>
<p>For Safari on iOS 9 (tested on iPhone 4S) and Internet Explorer 11 on Windows 8.1 (tested on LambdaTest), the <code>strong</code> elements use the font from the <code>h1</code> and <code>h2</code> elements:</p>
<p><a href="https://i.stack.imgur.com/OU47j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OU47j.png" alt="Display on iOS 9 Safari and Internet Explorer 11" /></a></p>
<p>The relevant CSS for these elements is:</p>
<pre><code>@font-face {
font-family: 'Amatic SC';
font-style: normal;
font-weight: 400;
src: url(/fonts/amatic-sc-v13-latin-regular.woff2) format('woff2'), url(/fonts/amatic-sc-v13-latin-regular.woff) format('woff'); }
@font-face {
font-family: 'Amatic SC';
font-style: bold;
font-weight: 700;
src: url(/fonts/amatic-sc-v13-latin-700.woff2) format('woff2'), url(/fonts/amatic-sc-v13-latin-700.woff) format('woff'); }
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: url(/fonts/open-sans-v17-latin-regular.woff2) format('woff2'), url(/fonts/open-sans-v17-latin-regular.woff) format('woff');
}
@font-face {
font-family: 'Open Sans';
font-style: bold;
font-weight: 700;
src: url(/fonts/open-sans-v17-latin-700.woff2) format('woff2'), url(/fonts/amatic-sc-v13-latin-regular.woff) format('woff');
}
body {
font-family: 'Open Sans', sans-serif;
}
h1, h2 {
margin: 0.5rem 0 0.5rem 0;
text-align: left;
font-family: Amatic SC, cursive;
font-weight: bold;
}
</code></pre>
<p>The website is at <a href="http://www.emotionathletes.org" rel="nofollow noreferrer">www.emotionathletes.org</a> if you want to further inspect.</p>
<p>What is the reason for the use of a different font on iOS Safari and Internet Explorer?</p>
<h2>Minimal reproducible example</h2>
<p>Following the comment, I narrowed the issue to the loading of the fonts. If I load them in the <code>head</code> of the HTML, linked to Google Fonts, then the page displays well. If I load them locally in the CSS with <code>@font-face</code> from a <code>woff</code> or <code>woff2</code> file, then the strong elements display with a different font on iOS 9 on iPhone 4S and on Internet Explorer 11 on Windows 8.1. The order of loading the fonts in the CSS does not change the result.</p>
<p>A minimal reproducible example has HTML file <code>strong.html</code>:</p>
<pre><code><!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta charset="utf-8"><meta name="viewport" content="width=device-width, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<link rel="stylesheet" type="text/css" href="strong.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Amatic+SC&display=swap" rel="stylesheet">
</head>
<body>
<h2>Summary</h2>
<p>The Bulgy series, whose first season is "Emotion Athletes", has the following purposes:</p>
<ul>
<li>
transform the <strong>difficulties</strong> of the <strong>pandemic</strong> into <strong>opportunities</strong> for children to <strong>recognise what they are feeling, understand the reason, and use their emotions</strong>;
</li>
</ul>
</body>
</html>
</code></pre>
<p>and CSS file <code>strong.css</code>:</p>
<pre><code>/*
Amatic SC and Open Sans are Google Fonts:
https://fonts.google.com/specimen/Amatic+SC?sidebar.open=true&selection.family=Open+Sans#about
https://fonts.google.com/specimen/Open+Sans?sidebar.open=true&selection.family=Open+Sans#about
*/
/* comment these @font-faces for the page to work properly. */
@font-face {
font-family: 'Amatic SC';
font-style: normal;
font-weight: 400;
src: url(/fonts/amatic-sc-v13-latin-regular.woff2) format('woff2'), url(/fonts/amatic-sc-v13-latin-regular.woff) format('woff'); }
@font-face {
font-family: 'Amatic SC';
font-style: bold;
font-weight: 700;
src: url(/fonts/amatic-sc-v13-latin-700.woff2) format('woff2'), url(/fonts/amatic-sc-v13-latin-700.woff) format('woff'); }
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: url(/fonts/open-sans-v17-latin-regular.woff2) format('woff2'), url(/fonts/open-sans-v17-latin-regular.woff) format('woff');
}
@font-face {
font-family: 'Open Sans';
font-style: bold;
font-weight: 700;
src: url(/fonts/open-sans-v17-latin-700.woff2) format('woff2'), url(/fonts/amatic-sc-v13-latin-regular.woff) format('woff');
}
body {
font-family: 'Open Sans', sans-serif;
}
h1, h2 {
font-family: 'Amatic SC', cursive;
}
</code></pre>
<p>I put a live version at <a href="https://www.emotionathletes.org/strong.html" rel="nofollow noreferrer">www.emotionathletes.org/strong.html</a>, with CSS file at <a href="https://www.emotionathletes.org/strong.css" rel="nofollow noreferrer">www.emotionathletes.org/strong.css</a>.</p>
<p>For my own reasons, I prefer to serve the font files from my server than query them from Google Fonts. How can I serve the font files locally and still display them properly on Safari and Internet Explorer?</p>
| 3 | 2,367 |
Spark MapGroupsWithState Update function doesn't allow action queries like filter, count, show etc
|
<p>I have an IoT application where I receive the data from different Energy Meters and Inverter Meters. These meters continuously sends meter value as no of units consumed. This value continuously increments over period of time and I have to calculate One hour Energy Consumption for each meter.</p>
<p>I get all this data in a kafka topic from which I create Structured Streaming Dataframe. </p>
<p>On this expanded dataframe I am applying mapGroupsWithState function. This should return me one hour generation. </p>
<p>The Problem:
I am not able to do any of the count, show, filter, aggregation operations inside update function using spark dataframe.</p>
<pre><code> val df_output = final_df
.selectExpr("*")
.as[input_row_druid]
.groupByKey(_.plant_slug)
.mapGroupsWithState(GroupStateTimeout.ProcessingTimeTimeout)(updateAcrossEvents)
.writeStream
.format("console")
.outputMode("update")
.start()
df_output.awaitTermination()
def updateAcrossEvents(plant_slug:String, inputs: Iterator[input_row_druid],
oldState: GroupState[source_state]):out_state = {
val spark_session = SparkSession.builder().getOrCreate()
import spark_session.implicits._
val list_of_list = inputs.toList
val new_df = list_of_list.toDF
var my_state:source_state = if (oldState.exists) oldState.get else source_state(plant_slug,list_of_list)
println("Printing inverter and merter df with counts")
val inverter_df = new_df.filter($"device_type" === "INVERTER")
val meter_df = new_df.filter($"device_type" === "METER")
println(inverter_df.show())
val inv_count = inverter_df.count()
println(meter_df.show())
val meter_count = meter_df.count()
println(inv_count)
println(meter_count)
val new_state = source_state(plant_slug, list_of_list)
oldState.update(new_state)
var out = out_state(plant_slug,inv_count.toString,meter_count.toString)
out
}
</code></pre>
<p>If I do not do any filter operation new_df.show prints all data in dataframe. But count, show, filter not functioning.</p>
<p>One thing I noticed that is whenever I submit job to spark it runs in multiple batches, batch 0 is always successful but it hangs on batch 0. It never proceeds in next batch.</p>
<p>This is expected Result</p>
<pre><code>+--------------------+-------+---------+
| plant_slug|inv_gen|meter_gen|
+--------------------+-------+---------+
| plant1| 11| 10|
| plant2| 20| 19|
| plant3| 40| 38|
| plant4| 59| 57|
| plant5| 37| 35|
+--------------------+-------+---------+
</code></pre>
| 3 | 1,035 |
how to let only one side column to work as tabbed content Bootstrap 3.?
|
<p>I have tried to make tabbed content using bootstrap it works when i used it in single column but when i made one side column globally to be present on page always when tab be change only right side column content can be change. </p>
<p>Here is my Code. </p>
<pre><code><div class="container" >
<div class="row">
<ul class="nav nav-pills nav-centered img-tab">
<li class="active"><a data-toggle="pill" href="#home"> <i class="cooking"></i> <br>
Cooking</a></li>
<li><a data-toggle="pill" href="#menu1"> <i class="wrtiting"></i> <br>
Reading Writing</a></li>
<li><a data-toggle="pill" href="#menu2"> <i class="cooking"></i> <br>
volunteering</a></li>
<li><a data-toggle="pill" href="#menu3"> <i class="sports"></i> <br>
Sports</a></li>
<li><a data-toggle="pill" href="#menu4"> <i class="art"></i> <br>
Art</a></li>
<li><a data-toggle="pill" href="#menu5"> <i class="music"></i> <br>
Music</a></li>
</ul>
</div>
<div class="row">
<div class="col-lg-3 form-bg">
<form class="filter-form">
<div class="input-group search-input">
<input id="search" type="text" class="form-control" name="search" placeholder="Search">
<span class="input-group-addon"><i class="fa fa-search"></i></span> </div>
<div class="form-group">
<label class="s-label">SELECT PERIOD</label>
<div class="row">
<div class="col-md-6">
<input type="date" id="fdatepicker" class="form-control width100 d-widthf" placeholder="From">
</div>
<div class="col-md-6">
<input type="date" id="datetimepicker4" class="form-control d-widthl" placeholder="To">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<label class="s-label">FILTER BY DAY OF THE WEEK</label>
<label class="checkbox-inline">
<input type="checkbox" class="d-check" />
<label for="days"></label>
</label>
<label class="checkbox-inline">
<input type="checkbox" class="d-check" />
<label for="days"></label>
</label>
<label class="checkbox-inline">
<input type="checkbox" class="d-check" />
<label for="days"></label>
</label>
<label class="checkbox-inline">
<input type="checkbox" class="d-check" />
<label for="days"></label>
</label>
<label class="checkbox-inline">
<input type="checkbox" class="d-check" />
<label for="days"></label>
</label>
<label class="checkbox-inline">
<input type="checkbox" class="d-check" />
<label for="days"></label>
</label>
<label class="checkbox-inline">
<input type="checkbox" class="d-check" />
<label for="days"></label>
</label>
<br>
<label class="label-inline"> MO </label>
<label class="label-inline"> TU </label>
<label class="label-inline"> WE </label>
<label class="label-inline"> TH </label>
<label class="label-inline"> FR </label>
<label class="label-inline"> SA </label>
<label class="label-inline"> SU </label>
</div>
<div class="row">
<div class="col-md-12 text-center">
<input type="submit" value="Search" class="search-btn">
</div>
</div>
</div>
</form>
</div>
<div class="tab-content">
<div id="home" class="tab-pane active">
<div class="col-lg-9">
<div class="row">
<div class="col-lg-3 ">
<div class="post-image"> <img class="img img-responsive" src="images/activites/activity-01.jpg" alt="menu">
<div class="caption post-content"> <a href="activity-detail.html">
<h4>Enter Title Here</h4>
</a>
<p>Lorem ipsum dolor sit amet</p>
<div class="date"> <a href="#"><i class="fa fa-map-marker" aria-hidden="true"></i> Dubai</a> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> Flexible Dates</a> </div>
</div>
</div>
</div>
<div class="col-lg-3 ">
<div class="post-image"> <img class="img img-responsive" src="images/activites/activity-01.jpg" alt="menu">
<div class="caption post-content"> <a href="activity-detail.html">
<h4>Enter Title Here</h4>
</a>
<p>Lorem ipsum dolor sit amet</p>
<div class="date"> <a href="#"><i class="fa fa-map-marker" aria-hidden="true"></i> Dubai</a> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> Flexible Dates</a> </div>
</div>
</div>
</div>
<div class="col-lg-3 ">
<div class="post-image"> <img class="img img-responsive" src="images/activites/activity-01.jpg" alt="menu">
<div class="caption post-content"> <a href="activity-detail.html">
<h4>Enter Title Here</h4>
</a>
<p>Lorem ipsum dolor sit amet</p>
<div class="date"> <a href="#"><i class="fa fa-map-marker" aria-hidden="true"></i> Dubai</a> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> Flexible Dates</a> </div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3 ">
<div class="post-image"> <img class="img img-responsive" src="images/activites/activity-01.jpg" alt="menu">
<div class="caption post-content"> <a href="activity-detail.html">
<h4>Enter Title Here</h4>
</a>
<p>Lorem ipsum dolor sit amet</p>
<div class="date"> <a href="#"><i class="fa fa-map-marker" aria-hidden="true"></i> Dubai</a> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> Flexible Dates</a> </div>
</div>
</div>
</div>
<div class="col-lg-3 ">
<div class="post-image"> <img class="img img-responsive" src="images/activites/activity-01.jpg" alt="menu">
<div class="caption post-content"> <a href="activity-detail.html">
<h4>Enter Title Here</h4>
</a>
<p>Lorem ipsum dolor sit amet</p>
<div class="date"> <a href="#"><i class="fa fa-map-marker" aria-hidden="true"></i> Dubai</a> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> Flexible Dates</a> </div>
</div>
</div>
</div>
<div class="col-lg-3 ">
<div class="post-image"> <img class="img img-responsive" src="images/activites/activity-01.jpg" alt="menu">
<div class="caption post-content"> <a href="activity-detail.html">
<h4>Enter Title Here</h4>
</a>
<p>Lorem ipsum dolor sit amet</p>
<div class="date"> <a href="#"><i class="fa fa-map-marker" aria-hidden="true"></i> Dubai</a> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> Flexible Dates</a> </div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>I just did not added content of rest of tabs yet because only first one is not working when i add more tab content it be visible like with rest of content not getting hide and displaying on click of another tab. </p>
| 3 | 4,769 |
Q: IBM Cloud Private CE - fatal: [9.29.100.159] => The Etcd component failed to start
|
<p>First install of ICP CE 2.1.0 on Ubuntu 16.04.03 VM running on ESXi5.5. The VM has 4vCPU with 16GB ram and 170GB (small I know). The install runs 10 min and fails. I ran the install with the -vvv and it's doesn't really provide any significant insights. </p>
<pre><code>TASK [master : Waiting for Etcd to start] **************************************
task path: /installer/playbook/roles/master/tasks/kube-service.yaml:6
Using module file /installer/playbook/library/cfc_wait_for.py
<9.29.100.159> ESTABLISH SSH CONNECTION FOR USER: root
<9.29.100.159> SSH: EXEC ssh -C -o CheckHostIP=no -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o 'IdentityFile="cluster/ssh_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=10 9.29.100.159 '/bin/bash -c '"'"'echo ~ && sleep 0'"'"''
<9.29.100.159> (0, '/root\n', '')
<9.29.100.159> ESTABLISH SSH CONNECTION FOR USER: root
<9.29.100.159> SSH: EXEC ssh -C -o CheckHostIP=no -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o 'IdentityFile="cluster/ssh_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=10 9.29.100.159 '/bin/bash -c '"'"'( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067 `" && echo ansible-tmp-1511385912.24-67181235419067="` echo /root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067 `" ) && sleep 0'"'"''
<9.29.100.159> (0, 'ansible-tmp-1511385912.24-67181235419067=/root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067\n', '')
<9.29.100.159> PUT /tmp/tmp_LQQz6 TO /root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067/cfc_wait_for.py
<9.29.100.159> SSH: EXEC sftp -b - -C -o CheckHostIP=no -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o 'IdentityFile="cluster/ssh_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=10 '[9.29.100.159]'
<9.29.100.159> (0, 'sftp> put /tmp/tmp_LQQz6 /root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067/cfc_wait_for.py\n', '')
<9.29.100.159> ESTABLISH SSH CONNECTION FOR USER: root
<9.29.100.159> SSH: EXEC ssh -C -o CheckHostIP=no -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o 'IdentityFile="cluster/ssh_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=10 9.29.100.159 '/bin/bash -c '"'"'chmod u+x /root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067/ /root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067/cfc_wait_for.py && sleep 0'"'"''
<9.29.100.159> (0, '', '')
<9.29.100.159> ESTABLISH SSH CONNECTION FOR USER: root
<9.29.100.159> SSH: EXEC ssh -C -o CheckHostIP=no -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o 'IdentityFile="cluster/ssh_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=10 -tt 9.29.100.159 '/bin/bash -c '"'"'/usr/bin/python /root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067/cfc_wait_for.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1511385912.24-67181235419067/" > /dev/null 2>&1 && sleep 0'"'"''
<9.29.100.159> (0, '\r\n{"msg": "The Etcd component failed to start. For more details, see https://ibm.biz/etcd-fails.", "failed": true, "elapsed": 1965, "invocation": {"module_args": {"active_connection_states": ["ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1", "FIN_WAIT2", "TIME_WAIT"], "state": "started", "port": 4001, "delay": 0, "msg": "The Etcd component failed to start. For more details, see https://ibm.biz/etcd-fails.", "host": "9.29.100.159", "sleep": 1, "timeout": 600, "exclude_hosts": null, "search_regex": null, "path": null, "connect_timeout": 5}}}\r\n', 'Connection to 9.29.100.159 closed.\r\n')
fatal: [9.29.100.159] => The Etcd component failed to start. For more details, see https://ibm.biz/etcd-fails.
</code></pre>
<p>The link <a href="https://ibm.biz/etcd-fails" rel="nofollow noreferrer">https://ibm.biz/etcd-fails</a> takes you to a 1.2.0 Knowledge Center entry about flannel fails to start on worker node. </p>
<p>Whats odd is a docker ps shows that etcd is running</p>
<pre><code>root@sysicpce:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
652aab0c1cee ibmcom/mariadb "start.sh docker-e..." 17 hours ago Up 17 hours k8s_mariadb_k8s-mariadb-9.29.100.159_kube-system_3b21d2ed8c3e2047c0e457af0e948b97_0
80201425a077 ibmcom/etcd "etcd --name=etcd0..." 17 hours ago Up 17 hours k8s_etcd_k8s-etcd-9.29.100.159_kube-system_b674f0dc7c07780868387aaea0ba7acc_0
a5be8a1e0c25 ibmcom/pause:3.0 "/pause" 17 hours ago Up 17 hours k8s_POD_k8s-mariadb-9.29.100.159_kube-system_3b21d2ed8c3e2047c0e457af0e948b97_0
d82b0c6e5fa0 ibmcom/pause:3.0 "/pause" 17 hours ago Up 17 hours k8s_POD_k8s-etcd-9.29.100.159_kube-system_b674f0dc7c07780868387aaea0ba7acc_0
6574c3760499 ibmcom/kubernetes "/hyperkube proxy ..." 18 hours ago Up 18 hours k8s_proxy_k8s-proxy-9.29.100.159_kube-system_708dfdafb2a5d66e99356e10e609f6b1_0
3b4621d57fef ibmcom/pause:3.0 "/pause" 18 hours ago Up 18 hours k8s_POD_k8s-proxy-9.29.100.159_kube-system_708dfdafb2a5d66e99356e10e609f6b1_0
root@sysicpce:~#
</code></pre>
<p>How can I resolve this? Where can/should I look next?</p>
| 3 | 2,882 |
how do i take a generated value and insert into a graph?
|
<p>Hi I'm new to web designing and some of my jargon may be wrong. I'm trying to create a graph for lectures that shows the average rating each lecture gets. I have already calculated the average for each of the 18 lectures. Now I want to take the value for each one and insert it as the value in the graph.</p>
<p>Here is how I query and output my lectures:</p>
<pre class="lang-php prettyprint-override"><code><?php
ini_set('display_errors', 1);
include ('connection.php');
$queryLecture = "SELECT DISTINCT lectureID FROM LectureReview ORDER BY lectureID";
$resultLecture = $mysqli->query($queryLecture);
while ($rowLecture = $resultLecture->fetch_assoc()) {
echo "<div class=\"row\">";
echo "<div class=\"box\">Lecture{$rowLecture['lectureID']}:</div>";
$lectureID = $rowLecture['lectureID'];
$mysqli2 = new mysqli($hostname, $username, $password, $database);
$stmt = $mysqli2->prepare("SELECT AVG( lectureReview ) AS lectureAvg FROM LectureReview WHERE lectureID = ?");
$stmt->bind_param('i', $lectureID);
$stmt->execute();
$stmt->bind_result($lectureAvg);
$stmt->fetch();
echo "<div class=\"box\">Average Lecture Rating: {$lectureAvg}</div>";
echo "</div>";
}
?>
</code></pre>
<p>Then, <code>OnLoad</code> I do this:</p>
<pre class="lang-js prettyprint-override"><code>var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme1",
title:{
text: "Average Lecture Score"
},
animationEnabled: true,
data: [
{
// Change type to "bar", "area", "spline", "pie",etc.
type: "column",
dataPoints: [
{ label: "Lecture 1", y: 4.5 },
{ label: "Lecture 2", y: 4.5 },
{ label: "Lecture 3", y: 5.0 },
{ label: "Lecture 4", y: 5.0 },
{ label: "Lecture 5", y: 5.0 },
{ label: "Lecture 6", y: 5.0 },
{ label: "Lecture 7", y: 5.0 },
{ label: "Lecture 8", y: 5.0 },
{ label: "Lecture 9", y: 5.0 },
{ label: "Lecture 10", y: 5.0 },
{ label: "Lecture 11", y: 5.0 },
{ label: "Lecture 12", y: 5.0 },
{ label: "Lecture 13", y: 5.0 },
{ label: "Lecture 14", y: 5.0 },
{ label: "Lecture 15", y: 5.0 },
{ label: "Lecture 16", y: 5.0 },
{ label: "Lecture 17", y: 5.0 },
{ label: "Lecture 18", y: 5.0 },
]
}
]
});
chart.render();
</code></pre>
<p>And my target container:</p>
<pre class="lang-html prettyprint-override"><code><div id="chartContainer"
style="height: 300px; width: 90%; position: absolute; padding-top:50px;">
</div>
</code></pre>
<p><a href="http://i.stack.imgur.com/4WkjN.png" rel="nofollow">At the moment it looks like this</a></p>
<p>How can I use the values from the database for the CanvasJS graph?</p>
| 3 | 1,515 |
Loading images dynamically using JQuery
|
<p>I have a scenario where I have a user select an image to upload to his/her user profile on my webpage. I'm using .net's MVC3 architecture for my website. What i need is for the image to show on the page after he chooses the one he wants but before i store it in the database. I searched around and ended up trying this which a friend of mine said worked for him:</p>
<p>In the view I tried:</p>
<pre><code><div class="floatRight">
<a onclick="opendialogbox('imageLoad2');" style="cursor: pointer">Photo</a>
<img src="… " width="16" height="16" id="imgThumbnail2" alt="photo" />
<input type="file" name="imageLoad2" accept="image/*" id="imageLoad2" onchange="ChangeImage('imageLoad2','#imgThumbnail2')" hidden="hidden" />
</div>
<script type="text/javascript">
function opendialogbox(inputid) {
document.getElementById(inputid).click();
}
function ChangeImage(fileId, imageId) {
var ext = document.getElementById(fileId).value.match(/\.(.+)$/)[1];
switch (ext.toLowerCase()) {
case 'jpg':
case 'bmp':
case 'png':
case 'gif':
case 'jpeg':
{
var myform = document.createElement("form");
myform.style.display = "none";
myform.action = "/ImagePreview/AjaxSubmit";
myform.enctype = "multipart/form-data";
myform.method = "post";
var imageLoad;
var imageLoadParent;
//test browser used then submit form
$(myform).ajaxSubmit({ success:
function (responseText) {
var d = new Date();
$(imageId)[0].src = "/ImagePreview/ImageLoad?a=" + d.getMilliseconds();
if (document.all || is_chrome)//IE
imageLoadParent.appendChild(myform.firstChild);
else//FF
document.body.removeChild(myform);
}
});
}
break;
default:
alert('Error, please select an image.');
}
}
</script>
</code></pre>
<p>And in the controller i tried:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AjaxSubmit(int? id)
{
Session["ContentLength"] = Request.Files[0].ContentLength;
Session["ContentType"] = Request.Files[0].ContentType;
byte[] b = new byte[Request.Files[0].ContentLength];
Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength);
Session["ContentStream"] = b;
HttpPostedFileBase file = Request.Files[0];
string myFilePath = Server.MapPath(Url.Content("~/Content/themes/base/images/Auxiliar.png"));
file.SaveAs(myFilePath);
return Content(Request.Files[0].ContentType + ";" + Request.Files[0].ContentLength);
}
public ActionResult ImageLoad(int? id)
{
byte[] b = (byte[])Session["ContentStream"];
int length = (int)Session["ContentLength"];
string type = (string)Session["ContentType"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = type;
Response.BinaryWrite(b);
Response.Flush();
Response.End();
Session["ContentLength"] = null;
Session["ContentType"] = null;
Session["ContentStream"] = null;
return Content("");
}
</code></pre>
<p>now all this i thought made sense but when i try it in my website the method never reaches the server (I placed a break-point at the beginning of both methods in the controller). I also used firefox's firebug to trace the script on the page until it reaches the line:</p>
<pre><code>$(myform).ajaxSubmit({ success:
function (responseText) {
var d = new Date();
$(imageId)[0].src = "/ImagePreview/ImageLoad?a=" + d.getMilliseconds();
if (document.all || is_chrome)//IE
imageLoadParent.appendChild(myform.firstChild);
else//FF
document.body.removeChild(myform);
}
});
</code></pre>
<p>here it continues but never enters the success condition. I thought it might be a problem with the JQuery versions included on the page and noticed that my friends site included: jquery-1.5.1.min.js, jquery-1.3.2.js and jquery_form.js</p>
<p>I added these to my website (which was using jquery-1.7.2.min.js) but the problem continued. Not sure if including various versions of jquery would cause some kind of conflict with the methods or if the problem is somewhere else.</p>
<p>I would greatly appreciate any help on the matter.
Thanks in advance.</p>
| 3 | 2,445 |
How to use swiftUI matched geometry to present a detail card view on top of elements (instead of increasing frame height)
|
<p>I am attempting my first steps using matchedgeometry and have followed some tutorials to get a simple view to expand when selected.I have two files, a card view and a content view. I would like to place all of my card views in a horizontal scrollview.</p>
<pre><code>import SwiftUI
struct smallCard: View {
@State private var flag: Bool = true
@Namespace var nspace
var body: some View {
if flag {
VStack{
Image("chemex.jpg")
.resizable()
.matchedGeometryEffect(id: "image", in: nspace)
.scaledToFill()
Spacer()
Button("CHEMEX") { withAnimation(.default) { flag.toggle() } }
.matchedGeometryEffect(id: "text", in: nspace)
Spacer()
.frame(height:8)
}
.matchedGeometryEffect(id: "geoeffect1", in: nspace)
.frame(width: 100, height: 100, alignment: .center)
.background(Color.white)
.cornerRadius(20)
.shadow(color: .gray, radius: 9, x: 0, y: 9)
}
if !flag {
VStack{
Image("chemex.jpg")
.resizable()
.matchedGeometryEffect(id: "image", in: nspace)
.scaledToFit()
Spacer()
Button("CHEMEX") { withAnimation(.default) { flag.toggle() } }
.matchedGeometryEffect(id: "text", in: nspace)
Spacer()
.frame(height:20)
}
.matchedGeometryEffect(id: "geoeffect1", in: nspace)
.layoutPriority(1)
.frame(width: 300, height: 600, alignment: .center)
.background(Color.white)
.cornerRadius(20)
.shadow(color: .gray, radius: 9, x: 0, y: 9)
}
}
</code></pre>
<p>I the have my main content view:</p>
<pre><code>import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
HStack{
Text("My App")
.font(.title)
.padding(.leading, 25)
Spacer()
}
ScrollView(.horizontal){
HStack{
smallCard()
.padding(.horizontal)
smallCard()
.padding(.horizontal)
smallCard()
.padding(.horizontal)
}
}
}
.frame(alignment: .center)
}
</code></pre>
<p>This currently works for clicking on the small card and the matched geometry animates this to the larger card. The issue I have is that this changes the height of my scrollview and as such this moves everything else such as my title up and out of view.</p>
<p>Effectively what I would like to achieve is like a popover view, so that this detail view is on top of all of the elements in my content view, but whilst using matchedgeometry (or an alternative solution) to animate nicely between the views.</p>
<p>Is this possible? I am at the point where I do not know if there is a solution to this.</p>
| 3 | 1,512 |
Determine if dynamic selects are defined with javascript
|
<p>I've stumbled across a problem and could use your help figuring out some logic here to deal with it. Basically I have a dynamic order form where the price is updated real time on the user side using javascript based on what options the user selects. The issue is that there are 3 dynamic dropdowns that might not all exist, ie sometimes there will be drop down a - c, sometimes there will only be a, or just a and b, etc. The error I'm getting is that the variable for any undefined select is undefined (obviously). I've implemented some js to deal with that but with no success. Here is the code I'm working with:</p>
<p>PHP: </p>
<pre><code> $a_sql = ("SELECT * FROM prod_add WHERE pid = '$id' AND `group` = 'a'");
$a_query = mysqli_query($dbconx, $a_sql);
$a_Count = mysqli_num_rows($a_query);
if ($a_Count > 0) {
while($row = mysqli_fetch_array($a_query)) {
$a_option = $row["option"];
$a_value = $row["value"];
$a_results .= "<option value='$a_value'>$a_option</option>";
}
}
if($a_Count > 0) {
$a_opt = "<select class='opt_drop' id='optA' name='optA' onchange='getTotal()'>$a_results</select>";
} else {
$a_opt = "";
}
</code></pre>
<p>Rinse and repeat for b & c</p>
<p>HTML: </p>
<pre><code> <h2 id="totalPrice">$<?php echo $base_cost ?></h2> <br />
<input type="hidden" name="base_cost" id="base_cost" value="<?php echo $base_cost ?>" />
<?php echo $a_opt; ?><br />
<?php echo $b_opt; ?><br />
<?php echo $c_opt; ?>
Quantity:
<select name="quantity" id="quantity" onchange="getTotal()">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4</option>
<option value="5"> 5 </option>
<option value="6"> 6 </option>
<option value="7"> 7 </option>
<option value="8"> 8 </option>
<option value="9"> 9 </option>
<option value="10"> 10 </option>
</select>
</code></pre>
<p>Javascript:</p>
<pre><code> <script type="text/javascript">
function getDDValue(elementID){
var value = 0;
var element = document.getElementById(elementID);
value = element.options[element.selectedIndex].value;
console.log(value);
return parseFloat(value);
}
function getBase (elementID) {
var value = 0;
var element = document.getElementById(elementID);
value = element.value;
return parseFloat(value);
}
function getTotal(){
if (typeof optA != "undefined") {
var optA = getDDValue("optA");
} else {
var optA = "0";
}
if (typeof optB != "undefined") {
var optB = getDDValue("optB");
} else {
var optB = "0";
}
if (typeof optC != "undefined") {
var optC = getDDValue("optC");
} else {
var optC = "0";
}
var quantity = getDDValue("quantity");
var base_cost = getBase ("base_cost")
var totalPrice = '0';
totalPrice = parseFloat((+base_cost + +optA + +optB + +optC) * +quantity);
console.log(totalPrice);
document.getElementById('totalPrice').innerHTML = "$" + totalPrice;
}
getTotal();
</script>
</code></pre>
<p>As you can see above I tried determining if the value was undefined and if it was to just give it a value of 0. That didn't work though I can't be sure why. </p>
| 3 | 1,804 |
Simple Tensorflow 2 classifier won't learn
|
<p>It's a simple model architecture based on <a href="https://github.com/dragen1860/TensorFlow-2.x-Tutorials/tree/master/01-TF2.0-Overview" rel="nofollow noreferrer">this tutorial</a>. The dataset would look like this, although in 10 dimensions:
<a href="https://i.stack.imgur.com/KSNGX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KSNGX.png" alt="enter image description here"></a></p>
<pre><code>import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers, optimizers
from sklearn.datasets import make_blobs
def pre_processing(inputs, targets):
inputs = tf.cast(inputs, tf.float32)
targets = tf.cast(targets, tf.int64)
return inputs, targets
def get_data():
inputs, targets = make_blobs(n_samples=1000, n_features=10, centers=7, cluster_std=1)
data = tf.data.Dataset.from_tensor_slices((inputs, targets))
data = data.map(pre_processing)
data = data.take(count=1000).shuffle(buffer_size=1000).batch(batch_size=256)
return data
model = Sequential([
layers.Dense(8, input_shape=(10,), activation='relu'),
layers.Dense(16, activation='relu'),
layers.Dense(32, activation='relu'),
layers.Dense(7)])
@tf.function
def compute_loss(logits, labels):
return tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=labels))
@tf.function
def compute_accuracy(logits, labels):
predictions = tf.argmax(logits, axis=1)
return tf.reduce_mean(tf.cast(tf.equal(predictions, labels), tf.float32))
@tf.function
def train_step(model, optim, x, y):
with tf.GradientTape() as tape:
logits = model(x)
loss = compute_loss(logits, y)
grads = tape.gradient(loss, model.trainable_variables)
optim.apply_gradients(zip(grads, model.trainable_variables))
accuracy = compute_accuracy(logits, y)
return loss, accuracy
def train(epochs, model, optim):
train_ds = get_data()
loss = 0.
acc = 0.
for step, (x, y) in enumerate(train_ds):
loss, acc = train_step(model, optim, x, y)
if step % 500 == 0:
print(f'Epoch {epochs} loss {loss.numpy()} acc {acc.numpy()}')
return loss, acc
optim = optimizers.Adam(learning_rate=1e-6)
for epoch in range(100):
loss, accuracy = train(epoch, model, optim)
</code></pre>
<pre><code>Epoch 85 loss 2.530677080154419 acc 0.140625
Epoch 86 loss 3.3184046745300293 acc 0.0
Epoch 87 loss 3.138179063796997 acc 0.30078125
Epoch 88 loss 3.7781732082366943 acc 0.0
Epoch 89 loss 3.4101686477661133 acc 0.14453125
Epoch 90 loss 2.2888522148132324 acc 0.13671875
Epoch 91 loss 5.993691444396973 acc 0.16015625
</code></pre>
<p>What have I done wrong?</p>
| 3 | 1,106 |
How to redirect to success page after uploading file using php?
|
<p>I am trying to redirect to another page after a successful upload.</p>
<p>So I searched for similar answers on stackoverflow but non seems to solve my problem.</p>
<p>This is my form:</p>
<pre><code> <form enctype="multipart/form-data"
action="<?php print $_SERVER['PHP_SELF']?>" method="post">
<p><input type="hidden" name="MAX_FILE_SIZE" value="9000000" /> <input
type="file" name="pdfFile" /><br />
<br />
<input type="submit" value="upload" /></p>
</form>
</code></pre>
<p>This is my php which includes the header that redirects</p>
<pre><code><?php
if ( isset( $_FILES['pdfFile'] ) ) {
if ($_FILES['pdfFile']['type'] == "application/pdf") {
$source_file = $_FILES['pdfFile']['tmp_name'];
$dest_file = "upload/".$_FILES['pdfFile']['name'];
if (file_exists($dest_file)) {
print "The file name already exists!!";
}
else {
move_uploaded_file( $source_file, $dest_file )
or die ("Error!!");
if($_FILES['pdfFile']['error'] == 0) {
print "Pdf file uploaded successfully!";
print "<b><u>Details : </u></b><br/>";
print "File Name : ".$_FILES['pdfFile']['name']."<br.>"."<br/>";
print "File Size : ".$_FILES['pdfFile']['size']." bytes"."<br/>";
print "File location : upload/".$_FILES['pdfFile']['name']."<br/>";
header('Location: success.php');
}
}
}
else {
if ( $_FILES['pdfFile']['type'] != "application/pdf") {
print "Error occured while uploading file : ".$_FILES['pdfFile']['name']."<br/>";
print "Invalid file extension, should be pdf !!"."<br/>";
print "Error Code : ".$_FILES['pdfFile']['error']."<br/>";
}
}
}
?>
</code></pre>
| 3 | 1,188 |
How to raise error message if data does not exist in django table
|
<p>I have my table and filter all set up and working but I wish to have an error functionality added to it in such a way that when I query a data which exist in the db, it should show me the result normally, however, when I input a qs which does not exist, it should show me a message on the table that says "record does not exist" instead of a blank table.</p>
<p>Here is my view:</p>
<pre><code>from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from django_tables2 import RequestConfig
from django_tables2.export import TableExport
from .models import Employee
from .models import EmployeeFilter
from .tables import EmployeeTable
@login_required()
def employees(request):
filter = EmployeeFilter(request.GET, queryset=Employee.objects.all())
table = EmployeeTable(filter.qs)
RequestConfig(request).configure(table)
count = Employee.objects.all().count()
male_count = Employee.objects.filter(gender__contains='Male').count()
female_count = Employee.objects.filter(gender__contains='Female').count()
user_count = User.objects.all().count()
export_format = request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response("table.{}".format("csv", "xlsx"))
return render(request, "employees/employees.html", {
"table": table,
"filter": filter,
"count": count,
"male_count": male_count,
"female_count": female_count,
"user_count": user_count,
})
</code></pre>
<p>Form Template:</p>
<pre><code><!--filter form-->
<form action="" class="form form-inline employee-filter-form" method="get">
<legend class="mb-2">Filter employee records</legend>
<div class="fieldWrapper">
{{ filter.form.first_name }}
</div>
<div class="fieldWrapper">
{{ filter.form.last_name }}
</div>
<button aria-expanded="false" aria-haspopup="true"
class="ml-2 btn btn-danger filter-btn" type="submit">
Filter
</button>
</form>
</code></pre>
| 3 | 1,185 |
How van I allow index only for same profile?
|
<p>My app is a weight loss app. It uses Devise for user authentication. </p>
<p>A user <code>has_one :profile</code> (the profile table holds the <code>user_id</code> as foreign key) that stores data like prename, surname etc. and is created automatically when a user signs up. A profile <code>has_many :weights</code> (users of the app should weigh themselves regularly and store their new weight in this table). So far so good. </p>
<p>I have the following problem:
If a logged in user goes to the index page of the weight controller he sees only his own weights. However, if this user now changes the profile_id in the URL bar he can also see the weights of that other profile (although it is not "his" profile). Additionally, he can now create a new weight, which then holds the other profile_id (which is obviously not his own).</p>
<p>What I managed to do is to generally restrict users to edit or destroy weights which do not hold their own profile_id (through <code>before_action :require_same_weight_profile</code> in my weights_controller.rb).</p>
<p>My question now: how can I prevent this user (that has a certain profile) to do the stuff described above?</p>
<p>I'm sure the answer is pretty simple (I started coding just a few months ago).</p>
<blockquote>
<p><strong>UPDATE</strong> In the meanwhile I found a solution. Unfortunately the suggested solutions in the comments did not work for me. What does
work is the following:</p>
<p><strong>My update in weights_controller.rb</strong></p>
<pre><code>before_action :require_permission
...
def require_permission
if current_user != Profile.find(params[:profile_id]).user
redirect_to root_path
end
end
</code></pre>
</blockquote>
<p><strong>routes.rb</strong></p>
<pre><code>Rails.application.routes.draw do
devise_for :users
resources :profiles, only: [:index, :show, :edit, :update] do
resources :weights
end
</code></pre>
<p><strong>profile.rb</strong></p>
<pre><code>class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :pal
has_many :weights, dependent: :destroy
belongs_to :goal
end
</code></pre>
<p><strong>weight.rb</strong></p>
<pre><code>class Weight < ActiveRecord::Base
belongs_to :profile
end
</code></pre>
<p><strong>weights_controller.rb</strong></p>
<pre><code>class WeightsController < ApplicationController
before_action :set_profile
before_action :load_profile
before_action :set_weight, only: [:show, :edit, :update, :destroy]
before_action :require_same_weight_profile, only: [:show, :edit, :update, :destroy]
# GET /weights
# GET /weights.json
def index
@weights = Profile.find(params[:profile_id]).weights
end
# GET /weights/1
# GET /weights/1.json
def show
end
# GET /weights/new
def new
@weight = Weight.new(:profile_id => params[:profile_id])
end
# GET /weights/1/edit
def edit
end
# POST /weights
# POST /weights.json
def create
@weight = Weight.new(weight_params)
respond_to do |format|
if @weight.save
format.html { redirect_to profile_weights_path, notice: 'Weight was successfully created.' }
format.json { render :show, status: :created, location: @weight }
else
format.html { render :new }
format.json { render json: @weight.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /weights/1
# PATCH/PUT /weights/1.json
def update
respond_to do |format|
if @weight.update(weight_params)
format.html { redirect_to profile_weights_path, notice: 'Weight was successfully updated.' }
format.json { render :show, status: :ok, location: @weight }
else
format.html { render :edit }
format.json { render json: @weight.errors, status: :unprocessable_entity }
end
end
end
# DELETE /weights/1
# DELETE /weights/1.json
def destroy
@weight.destroy
respond_to do |format|
format.html { redirect_to profile_weights_path, notice: 'Weight was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_weight
@weight = Weight.find(params[:id])
end
def set_profile
@profile = Profile.find_by(user_id: params[:id])
end
def load_profile
@profile = current_user.profile #|| current_user.build_profile
end
# Never trust parameters from the scary internet, only allow the white list through.
def weight_params
params.require(:weight).permit(:profile_id, :weight, :weight_day)
end
# This checks if the current user wants to deal with weights other than his own
def require_same_weight_profile
if @weight.profile_id != current_user.profile.id
flash[:danger] = "You can only edit or delete your own weights"
redirect_to profile_weights_path(current_user.profile)
end
end
end
</code></pre>
<p><strong>profiles_controller.rb</strong></p>
<pre><code>class ProfilesController < ApplicationController
before_action :set_profile, only: [:show, :edit, :update, :destroy]
before_action :load_profile
# GET /profiles
# GET /profiles.json
def index
@profiles = Profile.all
end
# GET /profiles/1
# GET /profiles/1.json
def show
end
# GET /profiles/new
def new
@profile = Profile.new
end
# GET /profiles/1/edit
def edit
end
# POST /profiles
# POST /profiles.json
def create
@profile = Profile.new(profile_params)
@profile.user = current_user
respond_to do |format|
if @profile.save
format.html { redirect_to @profile, notice: 'Profile was successfully created.' }
format.json { render :show, status: :created, location: @profile }
else
format.html { render :new }
format.json { render json: @profile.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /profiles/1
# PATCH/PUT /profiles/1.json
def update
respond_to do |format|
if @profile.update(profile_params)
format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }
format.json { render :show, status: :ok, location: @profile }
else
format.html { render :edit }
format.json { render json: @profile.errors, status: :unprocessable_entity }
end
end
end
# DELETE /profiles/1
# DELETE /profiles/1.json
def destroy
@profile.destroy
respond_to do |format|
format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_profile
@profile = Profile.find_by(user_id: params[:id])
end
def load_profile
@profile = current_user.profile #|| current_user.build_profile
end
# Never trust parameters from the scary internet, only allow the white list through.
def profile_params
params.fetch(:profile, {}).permit(:prename, :surname, :birthdate, :gender, :size, :pal_id)
end
end
</code></pre>
| 3 | 2,490 |
"active" class somehow being removed from ".caret"
|
<p>Even though in my mouseover function, it explicitly says to add the class <code>active</code> to <code>.caret</code> <em>(make it grey)</em> when "Dropdown" is hovered over and the dropdown menu hidden, when you click on "Dropdown" twice (once to show menu; once to hide) and still have your cursor over "Dropdown", the caret fails to change color (turn grey), which is odd.</p>
<p>The only way to rectify this is by leaving the <code><span></code> element and then re-entering it, at which point, it turns grey as it should. However, I would like it to turn grey under every circumstance, as long as the span element is being hovered over and the dropdown is hidden.</p>
<p>The problem nevertheless seems to be that the <code>active</code> class is being removed somewhere, whenever "Dropdown" is clicked on twice, but I don't know where.</p>
<p>Anyone know how to fix this?</p>
<p><a href="http://www.bootply.com/711DqjsqtS#" rel="nofollow">Bootply</a>.</p>
<p>HTML:</p>
<pre><code> <div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><span>Dropdown</span><b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#subtab1">1</a></li>
<li><a href="#subtab2">2</a></li>
</ul><!-- END: "dropdown-menu" -->
</li><!-- END: "dropdown" -->
</ul><!-- END: "nav navbar-nav navbar-right" -->
</div><!-- END: "collapse navbar-collapse navHeaderCollapse" -->
</div><!-- END: "container" -->
</div><!-- END: "navbar navbar-inverse navbar-fixed-top" -->
</code></pre>
<p>CSS:</p>
<pre><code>span {
color:#ffffff;
}
span.active{
color:#bdbcae;
}
.caret{
color:#ffffff;
}
.caret.active{
color:#bdbcae;
}
</code></pre>
<p>JavaScript:</p>
<pre><code>/* START: ACCOMPLISHMENTS TELEPORT */
var counter = 0;
const EMPTY_COUNTER = 0, FULL_COUNTER = 2;
var shouldOpen = function () {
return counter === FULL_COUNTER;
};
var resetCounter = function () {
counter = EMPTY_COUNTER;
};
var incrementCounter = function () {
counter++;
};
$(document).on("click", "span", function (e) {
e.preventDefault();
if (counter==1 && !$('.dropdown-menu').is(":visible")) {
resetCounter();
}
incrementCounter();
if (shouldOpen() || counter==1 && $('.dropdown-menu').is(":visible")) {
$("span ").removeClass("active");
resetCounter();
} else {
$( ".caret" ).removeClass( "active" );
}
});
/* END: ACCOMPLISHMENTS TELEPORT */
/* START: CLICK ON SPAN/CARET */
$( "a.dropdown-toggle" ).mousedown(function() {
if ($(event.target).closest("span").length) {
if ($('.dropdown-menu').is(":visible") && !$( ".dropdown" ).hasClass( "active" )) {
$( "span" ).addClass( "active" );
}
if (!$('.dropdown-menu').is(":visible")) {
$( ".caret" ).addClass( "active" );
}
} else {
$( ".caret" ).addClass( "active" );
}
});
/* END: SPAN/CARET ON CLICK */
/* START: CARET ON HOVER */
$(document).mouseover(function() {
if ($(event.target).closest("a.dropdown-toggle").length) {
if ($(event.target).closest("span").length) {
if (!$('.dropdown-menu').is(":visible")) {
$( ".caret" ).addClass( "active" );
} else {
$( ".caret" ).removeClass( "active" );
}
} else {
$( ".caret" ).addClass( "active" );
$( "span" ).removeClass( "active" );
}
} else {
$( "span" ).removeClass( "active" );
$( ".caret" ).removeClass( "active" );
}
});
/* END: CARET ON HOVER */
</code></pre>
| 3 | 1,923 |
How did I make recursive copies of my repo inside of itself?
|
<p>I forgot what I typed exactly last night, but I remember typing a git command incorrectly and wondering if I messed something up. I figured everything was fine, made a commit then went to sleep. </p>
<p>Now today, when I <code>git status</code> I get 100+ lines of </p>
<pre><code>new file: MyProject/MyProject/
new file: MyProject/MyProject/MyProject/
new file: MyProject/MyProject/MyProject/MyProject/
</code></pre>
<p>and so on. Every directory has a copy of all my code and resources, too.
<code>git checkout -- .</code> did not fix this. I can rebase to a previous commit since I remember all the changes from my last commit, but I'd like to know how I caused such a mess. </p>
<p>What the hell did I do and how can I fix this and never do it again?</p>
<p>My commit:
commit 82a828d4bcdb74248f2183e4092974399ecfb4d2
Author: ----- ---
Date: Wed Aug 28 20:03:02 2013 -0400</p>
<pre><code> Added background(s) to table view
diff --git a/Spots.xcodeproj/.LSOverride b/Spots.xcodeproj/.LSOverride
new file mode 100644
index 0000000..5d27049
Binary files /dev/null and b/Spots.xcodeproj/.LSOverride differ
diff --git a/Spots.xcodeproj/project.pbxproj b/Spots.xcodeproj/project.pbxproj
index 4ccff74..164b0b2 100644
--- a/Spots.xcodeproj/project.pbxproj
+++ b/Spots.xcodeproj/project.pbxproj
@@ -11,6 +11,18 @@
943BDCB217C96F8900923C1C /* SpotViewController.m in Sources */ =
943BEE6017A5DBBB00E16CDE /* ECSlidingViewController.m in Sources
943BEE6117A5DBBB00E16CDE /* UIImage+ImageWithUIView.m in Sources
+ 944DDFC517CEC0BF00F12B42 /* wood_pattern_@2X.png in Resources */
+ 944DDFC617CEC0BF00F12B42 /* wood_pattern.png in Resources */ = {
+ 944DDFCD17CEC53C00F12B42 /* purty_wood_@2X.png in Resources */ =
+ 944DDFCE17CEC53C00F12B42 /* purty_wood.png in Resources */ = {is
+ 944DDFCF17CEC53C00F12B42 /* retina_wood_@2X.png in Resources */
+ 944DDFD017CEC53C00F12B42 /* retina_wood.png in Resources */ = {i
+ 944DDFD117CEC53C00F12B42 /* wood_1_@2X.png in Resources */ = {is
+ 944DDFD217CEC53C00F12B42 /* wood_1.png in Resources */ = {isa =
+ 944DDFD717CEC5F600F12B42 /* concrete_wall_@2X.png in Resources *
+ 944DDFD817CEC5F600F12B42 /* concrete_wall.png in Resources */ =
+ 944DDFD917CEC5F600F12B42 /* noisy_@2X.png in Resources */ = {isa
+ 944DDFDA17CEC5F600F12B42 /* noisy.png in Resources */ = {isa = P
94779A5717B43D5600D209A3 /* AddViewController.m in Sources */ =
94779A5E17B44DFC00D209A3 /* Notes.txt in Resources */ = {isa = P
94B794CA17CC3FDE003CA531 /* placeholder.png in Resources */ = {i
@@ -64,11 +76,23 @@
943BEE5D17A5DBBB00E16CDE /* ECSlidingViewController.m */ = {isa
943BEE5E17A5DBBB00E16CDE /* UIImage+ImageWithUIView.h */ = {isa
943BEE5F17A5DBBB00E16CDE /* UIImage+ImageWithUIView.m */ = {isa
+ 944DDFC317CEC0BF00F12B42 /* wood_pattern_@2X.png */ = {isa = PBX
+ 944DDFC417CEC0BF00F12B42 /* wood_pattern.png */ = {isa = PBXFile
+ 944DDFC717CEC53C00F12B42 /* purty_wood_@2X.png */ = {isa = PBXFi
+ 944DDFC817CEC53C00F12B42 /* purty_wood.png */ = {isa = PBXFileRe
+ 944DDFC917CEC53C00F12B42 /* retina_wood_@2X.png */ = {isa = PBXF
+ 944DDFCA17CEC53C00F12B42 /* retina_wood.png */ = {isa = PBXFileR
+ 944DDFCB17CEC53C00F12B42 /* wood_1_@2X.png */ = {isa = PBXFileRe
+ 944DDFCC17CEC53C00F12B42 /* wood_1.png */ = {isa = PBXFileRefere
+ 944DDFD317CEC5F600F12B42 /* concrete_wall_@2X.png */ = {isa = PB
+ 944DDFD417CEC5F600F12B42 /* concrete_wall.png */ = {isa = PBXFil
+ 944DDFD517CEC5F600F12B42 /* noisy_@2X.png */ = {isa = PBXFileRef
+ 944DDFD617CEC5F600F12B42 /* noisy.png */ = {isa = PBXFileReferen
94779A5517B43D5600D209A3 /* AddViewController.h */ = {isa = PBXF
94779A5617B43D5600D209A3 /* AddViewController.m */ = {isa = PBXF
94779A5D17B44DFC00D209A3 /* Notes.txt */ = {isa = PBXFileReferen
- 94B794C817CC3FDE003CA531 /* placeholder.png */ = {isa = PBXFileR
- 94B794C917CC3FDE003CA531 /* placeholder@2x.png */ = {isa = PBXFi
+ 94B794C817CC3FDE003CA531 /* placeholder.png */ = {isa = PBXFileR
+ 94B794C917CC3FDE003CA531 /* placeholder@2x.png */ = {isa = PBXFi
94D27623179C790F0061E55E /* Spots.app */ = {isa = PBXFileReferen
94D27626179C790F0061E55E /* UIKit.framework */ = {isa = PBXFileR
94D27628179C790F0061E55E /* Foundation.framework */ = {isa = PBX
@@ -373,6 +397,18 @@
D3BC34E617B993770026A32E /* Graphics */ = {
isa = PBXGroup;
children = (
+ 944DDFD317CEC5F600F12B42 /* concrete_wall_@2X.pn
+ 944DDFD417CEC5F600F12B42 /* concrete_wall.png */
+ 944DDFD517CEC5F600F12B42 /* noisy_@2X.png */,
+ 944DDFD617CEC5F600F12B42 /* noisy.png */,
+ 944DDFC717CEC53C00F12B42 /* purty_wood_@2X.png *
+ 944DDFC817CEC53C00F12B42 /* purty_wood.png */,
+ 944DDFC917CEC53C00F12B42 /* retina_wood_@2X.png
+ 944DDFCA17CEC53C00F12B42 /* retina_wood.png */,
+ 944DDFCB17CEC53C00F12B42 /* wood_1_@2X.png */,
+ 944DDFCC17CEC53C00F12B42 /* wood_1.png */,
+ 944DDFC317CEC0BF00F12B42 /* wood_pattern_@2X.png
+ 944DDFC417CEC0BF00F12B42 /* wood_pattern.png */,
94B794C817CC3FDE003CA531 /* placeholder.png */,
94B794C917CC3FDE003CA531 /* placeholder@2x.png *
D3E43F1D17B9CEE400736C51 /* leftArrow.png */,
@@ -442,6 +478,18 @@
D3E43F2017B9CEE400736C51 /* leftArrow@2x.png in
94B794CA17CC3FDE003CA531 /* placeholder.png in R
94B794CB17CC3FDE003CA531 /* placeholder@2x.png i
+ 944DDFC517CEC0BF00F12B42 /* wood_pattern_@2X.png
+ 944DDFC617CEC0BF00F12B42 /* wood_pattern.png in
+ 944DDFCD17CEC53C00F12B42 /* purty_wood_@2X.png i
+ 944DDFCE17CEC53C00F12B42 /* purty_wood.png in Re
+ 944DDFCF17CEC53C00F12B42 /* retina_wood_@2X.png
+ 944DDFD017CEC53C00F12B42 /* retina_wood.png in R
+ 944DDFD117CEC53C00F12B42 /* wood_1_@2X.png in Re
+ 944DDFD217CEC53C00F12B42 /* wood_1.png in Resour
+ 944DDFD717CEC5F600F12B42 /* concrete_wall_@2X.pn
+ 944DDFD817CEC5F600F12B42 /* concrete_wall.png in
+ 944DDFD917CEC5F600F12B42 /* noisy_@2X.png in Res
+ 944DDFDA17CEC5F600F12B42 /* noisy.png in Resourc
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/Spots/Graphics/concrete_wall.png b/Spots/Graphics/concrete_wall.png
new file mode 100644
index 0000000..2de2c96
Binary files /dev/null and b/Spots/Graphics/concrete_wall.png differ
diff --git a/Spots/Graphics/concrete_wall_@2X.png b/Spots/Graphics/concrete_wall
new file mode 100644
index 0000000..a1241e1
Binary files /dev/null and b/Spots/Graphics/concrete_wall_@2X.png differ
diff --git a/Spots/Graphics/noisy.png b/Spots/Graphics/noisy.png
new file mode 100644
index 0000000..8aa2f7a
Binary files /dev/null and b/Spots/Graphics/noisy.png differ
diff --git a/Spots/Graphics/noisy_@2X.png b/Spots/Graphics/noisy_@2X.png
new file mode 100644
index 0000000..0dbdcdd
Binary files /dev/null and b/Spots/Graphics/noisy_@2X.png differ
diff --git a/Spots/Graphics/placeholder.png b/Spots/Graphics/placeholder.png
new file mode 100644
index 0000000..a081ba6
Binary files /dev/null and b/Spots/Graphics/placeholder.png differ
diff --git a/Spots/Graphics/placeholder@2x.png b/Spots/Graphics/placeholder@2x.p
new file mode 100644
index 0000000..f4ffb48
Binary files /dev/null and b/Spots/Graphics/placeholder@2x.png differ
diff --git a/Spots/Graphics/purty_wood.png b/Spots/Graphics/purty_wood.png
new file mode 100644
index 0000000..37fcd07
Binary files /dev/null and b/Spots/Graphics/purty_wood.png differ
diff --git a/Spots/Graphics/purty_wood_@2X.png b/Spots/Graphics/purty_wood_@2X.p
new file mode 100644
index 0000000..943c83c
Binary files /dev/null and b/Spots/Graphics/purty_wood_@2X.png differ
diff --git a/Spots/Graphics/retina_wood.png b/Spots/Graphics/retina_wood.png
new file mode 100644
index 0000000..22f2450
Binary files /dev/null and b/Spots/Graphics/retina_wood.png differ
diff --git a/Spots/Graphics/retina_wood_@2X.png b/Spots/Graphics/retina_wood_@2X
new file mode 100644
index 0000000..83f2ceb
Binary files /dev/null and b/Spots/Graphics/retina_wood_@2X.png differ
diff --git a/Spots/Graphics/wood_1.png b/Spots/Graphics/wood_1.png
new file mode 100644
index 0000000..d2e51e0
Binary files /dev/null and b/Spots/Graphics/wood_1.png differ
diff --git a/Spots/Graphics/wood_1_@2X.png b/Spots/Graphics/wood_1_@2X.png
new file mode 100644
index 0000000..d1fa60d
Binary files /dev/null and b/Spots/Graphics/wood_1_@2X.png differ
diff --git a/Spots/Graphics/wood_pattern.png b/Spots/Graphics/wood_pattern.png
new file mode 100644
index 0000000..fcc321d
Binary files /dev/null and b/Spots/Graphics/wood_pattern.png differ
diff --git a/Spots/Graphics/wood_pattern_@2X.png b/Spots/Graphics/wood_pattern_@
new file mode 100644
index 0000000..4c807e1
Binary files /dev/null and b/Spots/Graphics/wood_pattern_@2X.png differ
diff --git a/Spots/NearbyTableViewController.m b/Spots/NearbyTableViewController
index 7224b0c..e80eeb2 100644
--- a/Spots/NearbyTableViewController.m
+++ b/Spots/NearbyTableViewController.m
@@ -52,9 +52,12 @@ static NSString* const kBCURL = @"xxx.xxxxxxxxx.xxx/xxxxxx.xxx";
self.refreshControl = refreshControl;
self.tableView.rowHeight = 180.0;
- self.tableView.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0
self.tableView.scrollsToTop = YES;
- self.tableView.separatorColor = [UIColor clearColor];
+
+ UIView *patternView = [[UIView alloc] initWithFrame:self.tableView.frame];
+ patternView.backgroundColor = [UIColor colorWithPatternImage:[UIImage image
+ patternView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAuto
+ self.tableView.backgroundView = patternView;
if (!self.spotDictionary)
{
diff --git a/Spots/placeholder.png b/Spots/placeholder.png
deleted file mode 100644
index a081ba6..0000000
Binary files a/Spots/placeholder.png and /dev/null differ
diff --git a/Spots/placeholder@2x.png b/Spots/placeholder@2x.png
deleted file mode 100644
index f4ffb48..0000000
Binary files a/Spots/placeholder@2x.png and /dev/null differ
</code></pre>
<p>seems pretty innocuous. </p>
| 3 | 5,768 |
Adding attributes to the root xml stream
|
<p>Tried to look around for solutions but could not find any easy way to add attributes to root xml tag in beanIO 1.2.</p>
<p>I need to implement something like below:</p>
<pre><code><?xml version='1.0' encoding='utf-8'?>
<MyRootNode clientCode="German" recordCount="1">
<referrals>
<Individual>
<indvId>50853</indvId>
<firstName>Dad</firstName>
<middleName/>
<lastName>Test</lastName>
<suffixName/>
<gender>M</gender>
<race>WH</race>
<ethnicity>UN</ethnicity>
<DOB>2000-02-02</DOB>
<caseNumber>710645</caseNumber>
</Individual>
</referrals>
</MyRootNode>
</code></pre>
<p>As of now my beanio mapping file looks like :</p>
<pre><code><stream name="MyRootNode" format="xml">
<record name="referrals" class="example.test.TestBean">
<bean name="individual" class="example.test.Individual" xmlName="Individual">
<field name="indvId" />
<field name="firstName" minOccurs="1" />
<field name="middleName" minOccurs="1" />
<field name="lastName" minOccurs="1" />
<field name="suffixName" minOccurs="1" />
<field name="gender" minOccurs="1" />
<field name="race" minOccurs="1" />
<field name="ethnicity" minOccurs="1" />
<field name="DOB" minOccurs="1" />
<field name="caseNumber" minOccurs="1" />
</bean>
</record>
</stream>
</code></pre>
<p>Need to add <B><code>clientCode="German" recordCount="1"</code></B> to the MyRootNode. </p>
<p>Appreciate your help!</p>
<p>Thanks & Regards,
Rajiv</p>
| 3 | 1,558 |
Need help sharing a Javascript variable locally between files
|
<p>I've been developing a speed test typing game for some time now, and I've been stuck on how to take the time you finish from one HTML page (the game itself) to an alternate one (the score page). I've been trying to use import{} export{}, but I'm not 100% sure how they function and so they haven't exactly worked. I'll attach both the game HTML and Javascript code and the score HTML and Javascript code.</p>
<pre><code><!-- THIS IS THE HTML PAGE FOR THE GAME -->
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Typeboss || Speed Typing Web Game</title>
<link rel="stylesheet" href="../css/gamestyle.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Cabin:wght@500&display=swap');
</style>
<script src="../js/gamescript.js" defer></script>
<script src="../../main/js/mainscript.js" type="module" defer></script>
<script src="./scorescript.js" type="module" defer></script>
</head>
<body>
<div id="all">
<div id="stats">
<h1 id="bossHealth" class="stat">BOSS HEALTH:</h1>
<h1 id="time" class="stat"><span id="minutes">0</span>:<span id="seconds">00</span></h1>
</div>
<div id="boss">
<img src="../imgs/boss.png" width="400px" height="400px" id="bossSprite">
</div>
<div id="input">
<h3 id="outcome"></h3>
<center><p id="prompt"></p></center>
<textarea id="userInput" name="TypeBox" rows="4" cols="100" autofocus></textarea>
</div>
</div>
</body>
</html>
</code></pre>
<pre><code>// THIS IS THE JAVASCRIPT CODE
let scoreTime;
var seconds = 0;
var minutes = 0;
let score = 0;
const userInput = document.getElementById("userInput");
const promptBox = document.getElementById("prompt");
const outcomeText = document.getElementById("outcome");
const bossHealthtText = document.getElementById("bossHealth");
const timer = document.getElementById("time");
const bossSprite = document.getElementById("bossSprite");
const secondsText = document.getElementById("seconds");
const minutesText = document.getElementById("minutes");
let gameActive = true;
document.addEventListener('keypress', function(event){
if (event.key === 'Enter'){
checkInput();
}
});
let bossHealth = 100;
let multiplier = 10;
let mistakes = 0;
//
const prompts = ["How much wood could a woodchuck chuck if a woodchuck could chuck wood?", "I will not lose another pilot.", "I can't find my keys!", "Live as if you were to die tomorrow.", "Toto, I've got a feeling we're not in Kansas anymore...", "May the force be with you.", "If our lives are already written, it would take a courageous man to change the script.", "An apple a day keeps the doctor away.", "Frankly, my dear, I don't give a damn.", "Hello, world!", "My favorite sport is basketball!", "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.", "You only live once, but if you do it right, once is enough.", "I'm the fastest typer in the wild west!", "Frosty the snowman!", "I'm not a big fan of ice cream.", "If birds can fly, then we should too.", "I don't like trucks, they look weird.", "I love typing!", "I'm a rocket man, burning on a fuse out there alone.", "The water was blue and the skies the same, it was summer."];
//GAME INIT
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
function getNewPrompt() {
promptChoice = Math.floor(Math.random() * prompts.length);
let previousPrompt = prompts[promptChoice];
if (previousPrompt === prompts[promptChoice]){
promptChoice = Math.floor(Math.random() * prompts.length);
console.log("COPY OFF");
}
promptBox.innerHTML = prompts[promptChoice];
}
function checkInput(){
if (userInput.value.trim() === promptBox.innerHTML.trim()){
outcome.innerHTML = "Correct";
bossHealth -= 10;
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
let hitSprite = Math.floor(Math.random() *2);
if(hitSprite === 0){
bossSprite.src = "../imgs/bosshit/bosshit1.png";
}
if(hitSprite === 1){
bossSprite.src = "../imgs/bosshit/bosshit2.png";
}
setTimeout(function(){
bossSprite.src = "../imgs/boss.png";
}, 1000);
if (bossHealth <= 0){
console.log("WORKING");
window.location.href = "./score.html";
createScore();
}
getNewPrompt();
userInput.value = null;
}
else{
outcome.innerHTML = "Try again...";
userInput.value = null;
multiplier --;
mistakes ++;
return;
}
}
function gameTimer(){
console.log("working");
setTimeout(function(){
setInterval(function(){
seconds++;
if(seconds === 60){
minutes ++;
seconds = 0;
}
if (seconds < 9){
secondsText.innerHTML = "0" + seconds;
}
if (seconds > 9){
secondsText.innerHTML = seconds;
}
if(minutes < 9){
minutesText.innerHTML = minutes;
}
if(minutes > 9){
minutesText.innerHTML = minutes;
}
if (seconds < 9){
scoreTime = minutes + ":" + "0" + seconds;
}
if (seconds > 9){
scoreTime = minutes + ":" + seconds;
}
timePoints = minutes + seconds * 2;
return scoreTime;
return timePoints;
}, 1000)
}, 1000);
}
function game(){
gameTimer();
getNewPrompt();
createHeart();
}
function createScore(){
let bonus = Math.floor(Math.random() * 500);
score = timePoints * multiplier + bonus;
export { score };
}
game();
</code></pre>
<pre><code><!-- THIS IS THE SCORE HTML PAGE -->
<!DOCTYPE html>
<!DOCTYPE html>
<html onclick="celebrate()">
<head>
<meta charset="utf-8">
<title>Typeboss || Your Score!</title>
<link rel="stylesheet" href="../css/scorestyle.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Cabin:wght@500&display=swap');
</style>
</head>
<body>
<center><h1 style="color: whitesmoke;" id="header">YOU BEAT THE BOSS!</h1></center>
<center><p>(CLICK FOR VICTORY MUSIC)</p></center>
<h3 id="time">TIME:</h3>
<p id="playertime"></p>
<h3 id="score">SCORE:</h3>
<p id="playertime"></p>
<h3 id="mistakes">MISTAKES:</h3>
<p id="playertime"></p>
<h2 id="highscore"></h2>
<a href="../../main/html/main.html"><button id="redirect">BACK TO HOME</button></a>
</body>
<script type="module" src="../js/gamescript.js" defer></script>
</html>
</code></pre>
<pre><code>// AND HERE IS THE SCORE'S CODE
winMusic = new Audio();
winMusic.src = "./winmusic.mp3";
function celebrate(){
winMusic.play();
winMusic.loop = tru
}
import { score } from "./gamescript.js";
const scoreText = document.getElementById("score");
scoreText.innerHTML = score + " points!"
</code></pre>
<p>I hope I can get this issue resolved, and I hope this post was clear enough to understand. This is my first post on stack so please do let me know if I formatted it wrong, and any feedback that could make it easier to understand in the future. Thank you in advance and have a good day.</p>
| 3 | 4,388 |
Flutter Integration test: I can't target some of my widgets - Getter not found
|
<p>I am learning about integration testing in flutter and I'm running into a problem.</p>
<p>My app contains a sign-in button widget and my test starts with pumping it.</p>
<p>However, I can't seem to target it.</p>
<p>Every attempt results in the following error:</p>
<pre><code>integration_test/doctor_integration_test.dart:21:24: Error: Getter not found: 'SignInPage'.
expect(find.byType(SignInPage), findsOneWidget);
^^^^^^^^^^
FAILURE: Build failed with an exception.
</code></pre>
<p>The SignInPage is called within:</p>
<pre><code>MaterialApp _buildMaterialApp(BuildContext context) {
return MaterialApp(
title: 'Skinopathy: Doctor',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
routes: {
'/': (context) {
return BlocListener<AppBloc, AppState>(
listener: (context, state) {
if (state is AppAuthenticated) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => WelcomePage(),
),
);
} else if (state is AppUnauthenticated) {
Navigator.pushReplacementNamed(context, '/sign_in');
} else if (state is AppOutdated) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => OutdatedVersionPage(),
),
);
}
},
child: Center(
child: SplashPage(),
),
);
},
'/sign_in': (context) {
return SignInPage();
},
</code></pre>
<p>My presumption is that the integration takes place before the SignInPage is loaded.</p>
<p>_buildMaterialApp is also a child of Widget _buildRootLevelWidgets(BuildContext context)</p>
<p>How do I properly target SignInPage for testing?</p>
<p>Is there anything else I'm doing wrong?</p>
<p>Please note: I did NOT build this app; I'm just here to test it.</p>
<p>Thanks in advance!</p>
| 3 | 1,156 |
Issues connecting to server with sslv3 disabled in legacy perl
|
<p>As the title says, I'm attempting to POST some JSON to a REST API using a pretty old version of perl, specifically 5.10.1. I'm working in a pretty old legacy codebase on RHEL 6. The handshake fails with error 500 because the server has sslv3 disabled. However I'm using versions of LWP and IO::Socket::SSL that I believe nominally support at least TLSv1, which the server supports so I'm unsure why the connection fails as it should just use an acceptable cipher. The server appears to be behind a cloudfront reverse proxy which may be relevant. I don't know enough about SSL to say for certain, but it appears that the issue is in the way the server I care about is set up and how the version of perl and libraries in use implement the cipher. Using an online <a href="https://www.ssllabs.com/ssltest/analyze.html?d=dev.superquoteapi.fis.rcuh.com&s=99.84.224.116&latest" rel="nofollow noreferrer">tool</a> I noticed that the handshake fails on several browsers that do not support SNI. The version of openssl available should support this, but neither of the perl SSL implementations appear to. Is there a way around this? </p>
<p><a href="https://stackoverflow.com/questions/49166769/using-perl-5-8-8-with-openssl-1-0-1-to-connect-with-tlsv1-2">this</a> question seems to be dealing with a similar issue, but they solve it by installing a newer version of perl, which I'm not sure I can do given that this would likely break large portions of the codebase.</p>
<p><a href="https://bugzilla.redhat.com/show_bug.cgi?id=1355802" rel="nofollow noreferrer">This</a> unresolved bug seems to accidentally document this behavior
my problem is identical to the one listed, but I can also connect to the openssl host. I'm not sure that it's the same problem but I am on the same version of redhat with the same software and the same inconsistent behavior so it seems valuable. If it helps my software versions are as follows</p>
<pre><code>openssl-1.0.1e-58.el6_10.i686
perl-Crypt-SSLeay-0.57-17.el6.x86_64
perl-IO-Socket-SSL-1.31-3.el6_8.2.noarch
perl-Net-SSLeay-1.35-10.el6_8.1.x86_64
</code></pre>
<p>If I run </p>
<p><code>printf 'HTTP/1.0 200 Ok\r\n\r\n' | openssl s_server -accept 2000 -cert certificate.pem -key key.pem -no_ssl2 -no_ssl3 -no_tls1</code></p>
<p>the following script (test.pl) is able to connect using the same libraries </p>
<pre><code>my $ua = LWP::UserAgent->new(timeout => 600);
my $req = HTTP::Request->new(POST => $ARGV[0]);
$req->content_type('application/json');
$req->content_encoding('gzip');
$req->content('');
my $res = $ua->request($req);
print $res->status_line, "\n";
</code></pre>
<pre><code>>perl5.10.1 test.pl https://localhost:2000/
200 Ok
</code></pre>
<p>However, when I run an only slightly more complicated program using the same libraries and perl version I get errors relating to the sslv3 handshake</p>
<pre><code>500 Can't connect to dev.superquoteapi.fis.rcuh.com:443 (SSL connect attempt failed with unknown errorerror:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure)
</code></pre>
<p>I've even tried to force the program to use only TLSv1, but to no avail, the following line seems to have no impact</p>
<pre><code>my $ua = LWP::UserAgent->new(ssl_opts => {verify_hostname => 0}, SSL_version => '!TLSv12:TLSv1:!SSLv2:!SSLv3', allowed_protocols => ['https']);
</code></pre>
<p>The program I am actually working with is listed below</p>
<pre><code>use LWP;
use IO::Socket::SSL;
my $ua = LWP::UserAgent->new(ssl_opts => {verify_hostname => 0}, SSL_version => '!TLSv12:TLSv1:!SSLv2:!SSLv3', allowed_protocols => ['https']);
my $req = HTTP::Request->new('POST', 'https://dev.superquoteapi.fis.rcuh.com:443/api/quote');
$req->header('Content-Type' => 'application/json');
$req->header('Accept' => 'application/json');
#an api key is required and set in a header, but I won't list that here
open(my $fd, '<', 'data,json')
or die "Unable to open file, $!";
my @json=<$fd>;
close($fd)
or warn "Unable to close the file handle: $!";
$req->content(@json);
my $resp = $ua->request($req);
print $resp->as_string;
</code></pre>
<p>I have tried removing <code>IO::Socket::SSL</code> and replacing it with <code>Net::SSL</code> as is referenced in this question <a href="https://stackoverflow.com/questions/8026524/how-do-i-force-lwp-to-use-cryptssleay-for-https-requests">How do I force LWP to use Crypt::SSLeay for HTTPS requests?</a> but this does not seem to help. The code I used was </p>
<pre><code>use Net::SSL ();
BEGIN {
$Net::HTTPS::SSL_SOCKET_CLASS = "Net::SSL"; # Force use of Net::SSL
}
</code></pre>
<p>The two programs are more or less identical. The issue seems to be in the way the specific server <code>https://dev.superquoteapi.fis.rcuh.com</code> handles ssl requests. However I do not know enough about SSL/TLS to verify this meaningfully, so I have included both for completeness.</p>
<p>I apologize if this question is a bit rambling, but I really need help, and I just want to provide as much information as I can. If I can provide further information, or remove unhelpful information please let me know, I am absolutely at my wits end.</p>
| 3 | 1,793 |
Android Camera in Background
|
<p>I am trying to create an android application that can capture image in the background once the service is started . I am able to capture it and save on sdcard but the image captured is bit dark and i am not able to trace the problem.
What could be the possibilities?</p>
<p>Captured Image: <a href="http://imgur.com/8onjW60" rel="nofollow">http://imgur.com/8onjW60</a></p>
<pre><code>public class MyService extends Service {
Camera mCamera;
public String imageEncodeString,imageName;
public Bitmap bitmap;
public File file;
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if (bitmap != null) {
imageName = String.valueOf(System.currentTimeMillis() + ".jpg");
File basedir = new File(Environment.getExternalStorageDirectory() + "/dirr");
file = new File(Environment.getExternalStorageDirectory() + "/dirr" + File.separator + imageName);
if (!basedir.isDirectory()) {
basedir.mkdirs();
}
try {
file.createNewFile();
FileOutputStream otstream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,otstream);
byte[] img =new byte[0];
otstream.write(img);
otstream.flush();
otstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
mCamera.startPreview();
}
}
};
public MyService() {
}
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(MyService.this, "Starting Service...", Toast.LENGTH_SHORT).show();
Log.d("TAG", "======= service in onStartCommand");
if (checkCameraHardware(this)) {
mCamera = getCameraInstance();
if (mCamera != null) {
SurfaceView sv = new SurfaceView(this);
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(1, 1,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSPARENT);
params.alpha = 0;
SurfaceHolder sh = sv.getHolder();
sv.setZOrderOnTop(true);
sh.setFormat(PixelFormat.TRANSPARENT);
sh.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
parameters.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
mCamera.setParameters(parameters);
Camera.Parameters p = mCamera.getParameters();
List<Camera.Size> listSize;
listSize = p.getSupportedPreviewSizes();
Camera.Size mPreviewSize = listSize.get(2);
Log.v("TAG", "preview width = " + mPreviewSize.width
+ " preview height = " + mPreviewSize.height);
p.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
listSize = p.getSupportedPictureSizes();
Camera.Size mPictureSize = listSize.get(2);
Log.v("TAG", "capture width = " + mPictureSize.width
+ " capture height = " + mPictureSize.height);
p.setPictureSize(mPictureSize.width, mPictureSize.height);
mCamera.setParameters(p);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException e) {
e.printStackTrace();
}
// mCamera.startPreview();
// mCamera.takePicture(null, null, mPictureCallback); // used to takePicture.
// Log.d("TAG", "========= Capturing Started");
// mCamera.stopPreview();
// mCamera.release();
// Log.d("TAG", "========== Capturing finished.");
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
});
wm.addView(sv, params);
} else {
Log.d("TAG", "==== get Camera from service failed");
}
}else {
Log.d("TAG", "==== There is no camera hardware on device.");
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.d("TAG", "========= Capturing Started");
mCamera.startPreview();
mCamera.takePicture(null, null, mPictureCallback);
Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
Log.d("TAG", "========== Capturing finished.");
}
}, 5000);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
Toast.makeText(MyService.this, "Service Stopped...", Toast.LENGTH_SHORT).show();
}
public static boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
Log.d("TAG", "Open camera failed: " + e);
}
return c;
}
}
</code></pre>
| 3 | 3,122 |
Angular2: Unit-test router with cached template
|
<p>I'm dealing with some problems doing test on different environments:</p>
<ul>
<li><strong>SRC</strong>: unminified components, using both .js and .html/.css template files</li>
<li><strong>DIST</strong>: minified components (only .js, no templates)</li>
</ul>
<p>I made two different karma-conf and karma-test-shim, one for SRC and one for DIST.
In the SRC's one, since i mostly execute tests on components in fakeAsync contexts, i'm caching all my templates and .css at karma's startup, as shown in the following karma-test-shim, to avoid XHR errors.</p>
<p><strong>karma-test-shim.src.js</strong></p>
<pre><code>// Turn on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
var karmaFiles = Object.keys(window.__karma__.files); // All files served by Karma.
window.$templateCache = {}; // deckaring Window template cache for caching .html template and .css
// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function () { };
// Just a special configuration for Karma and coverage
System.config({
packages: {
"@angular/core/testing": { main: "../../../../../../node_modules/@angular/core/bundles/core-testing.umd.js" },
"@angular/compiler/testing": { main: "../../../../base/node_modules/@angular/compiler/bundles/compiler-testing.umd.js" },
"@angular/common/testing": { main: "../../../../base/node_modules/@angular/common/bundles/common-testing.umd.js" },
"@angular/http/testing": { main: "../../../../base/node_modules/@angular/http/bundles/http-testing.umd.js" },
"@angular/router/testing": { main: "../../../../../../node_modules/@angular/router/bundles/router-testing.umd.js" },
"@angular/platform-browser/testing": { main: "../../../../base/node_modules/@angular/platform-browser/bundles/platform-browser-testing.umd.js" },
"@angular/platform-browser-dynamic/testing": { main: "../../../../base/node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js" }
},
meta: {
"src/*": { format: "register" }, // Where covered files located
"packages/*": { format: "register" } // Where covered files located
}
});
Promise.all([
System.import('@angular/core/testing'),
System.import('@angular/platform-browser-dynamic/testing'),
System.import('@angular/platform-browser-dynamic') // Contains RESOURCE_CACHE_PROVIDER
]).then(function (providers) {
var testing = providers[0];
var testingBrowserDynamic = providers[1];
var browserDynamic = providers[2];
testing.TestBed.initTestEnvironment(
testingBrowserDynamic.BrowserDynamicTestingModule,
testingBrowserDynamic.platformBrowserDynamicTesting()
);
testing.TestBed.configureCompiler({
providers: [
browserDynamic.RESOURCE_CACHE_PROVIDER
]
})
// Import main module
}).then(function () {
return Promise.all(
karmaFiles
.filter(onlySpecFiles)
.map(file2moduleName)
.map(function (path) {
return System.import(path).then(function (module) {
if (module.hasOwnProperty('main')) {
module.main();
} else {
throw new Error('Module ' + path + ' does not implement main() method.');
}
});
}));
})
// Caching all component's templates files (.html/.css)
.then(function () {
return Promise.all(
karmaFiles
.filter(function (filename) {
var template = filename.endsWith('.html');
var css = filename.endsWith('.css');
return template || css;
})
.map(function (filename) {
return new Promise(function(resolve, reject) {
$.ajax({
type: 'GET',
url: filename,
dataType: 'text',
success: function (contents) {
filename = filename.replace("/base", "..");
window.$templateCache[filename] = contents;
resolve();
}
})
})
})
)
})
.then(function () {
__karma__.start();
}, function (error) {
console.error(error.stack || error);
__karma__.start();
});
// Filter spec files
function onlySpecFiles(path) {
return /\.spec\.js$/.test(path);
}
// Normalize paths to module names.
function file2moduleName(filePath) {
return filePath.replace(/\\/g, '/')
.replace(/^\/base\//, '');
}
</code></pre>
<p>So far so good but i started getting problems on the following spec:</p>
<p><strong>loginPage.spec.js</strong></p>
<pre><code>[...]
import { LoginPageComponent } from "loginPage";
import { RESOURCE_CACHE_PROVIDER } from "@angular/platform-browser-dynamic";
@Component({
selector: "loginpage-host",
template: "<loginPage></loginPage>"
})
export class LoginPageHostComponent {
@ViewChild(LoginPageComponent)
public loginPageComponent;
}
export function main() {
describe('LoginPageComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([]),CommonModule, HttpModule, CoreModule, ComponentsModule, GlobalizationModule],
declarations: [LoginPageHostComponent, LoginPageComponent],
providers: [
MockBackend,
BaseRequestOptions,
{
provide: AuthHttp,
useFactory: (backend: ConnectionBackend, options: BaseRequestOptions) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
},
{
provide: Http,
useFactory: (backend: ConnectionBackend, options: BaseRequestOptions) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
},
{
provide: Configuration,
useFactory: () => new Configuration()
}
]
})
// TestBed.configureCompiler({
// providers: [RESOURCE_CACHE_PROVIDER]
// });
});
it('should work',
fakeAsync(() => {
TestBed
.compileComponents()
.then(() => {
let fixture = TestBed.createComponent(LoginPageHostComponent);
let logPageHostComponentInstance = fixture.debugElement.componentInstance;
expect(logPageHostComponentInstance).toEqual(jasmine.any(LoginPageHostComponent));
expect(logPageHostComponentInstance.loginPageComponent).toEqual(jasmine.any(LoginPageComponent));
fixture.destroy();
discardPeriodicTasks();
});
}));
});
}
</code></pre>
<p>On SRC i get this error: </p>
<blockquote>
<p>Chrome 56.0.2924 (Windows 10 0.0.0) LoginPageComponent should work
FAILED Error: Cannot make XHRs from within a fake async test.</p>
</blockquote>
<p>If i manually provide the RESOURCE_CACHED_PROVIDER to the spec it works:</p>
<pre><code>TestBed.configureCompiler({
providers: [RESOURCE_CACHE_PROVIDER]
});
</code></pre>
<p>but it fails on DIST due to the fact that there's no cached template to load for loginPage.</p>
| 3 | 3,561 |
How to disable d3plus timeline time formating?
|
<p>I have created a bar chart using d3plus. In the code I have created timeline using the following lines: <br></p>
<pre><code> .time({
"value": "__TIME__"
)
.timeline({
"align":"center",
"value":true})
</code></pre>
<p><br>
This is showing a timeline in my chart like below:<a href="https://i.stack.imgur.com/FQkDb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FQkDb.png" alt="enter image description here"></a></p>
<p>In my data, the <strong>__TIME__</strong> variable contains only numbers(1,2,3,4..). But the timeline converted it into months. I just want plain numbers (1,2,3,4....) instead of auto formatting of the time.
<br>
Is it possible to disable the auto formatting for the timeline?<br>
Here is the sample jsfiddle: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [{
"day": 0,
"name": "alpha",
"value": 15
}, {
"day": 1,
"name": "alpha",
"value": 34
}, {
"day": 0,
"name": "alpha2",
"value": 17
}, {
"day": 1,
"name": "alpha2",
"value": 65
}, {
"day": 1,
"name": "beta",
"value": 10
}, {
"day": 1,
"name": "beta",
"value": 10
}, {
"day": 0,
"name": "beta2",
"value": 40
}, {
"day": 1,
"name": "beta2",
"value": 38
}, {
"day": 0,
"name": "gamma",
"value": 5
}, {
"day": 1,
"name": "gamma",
"value": 10
}, {
"day": 0,
"name": "gamma2",
"value": 20
}, {
"day": 1,
"name": "gamma2",
"value": 34
}, {
"day": 0,
"name": "delta",
"value": 50
}, {
"day": 2,
"name": "delta",
"value": 43
}, {
"day": 2,
"name": "delta2",
"value": 17
}, {
"day": 2,
"name": "delta2",
"value": 35
}]
var visualization = d3plus.viz()
.container("#chartContainer")
.data(data)
.type({
"value": "box",
"mode": "extent" // changes box/whisker from tukey to extent mode
})
.id("name")
.x("day")
.y("value")
.time("day")
.timeline({
"align":"center",
"value":true})
//.format() // I couldn't find any format for plain data without converting it into time
.draw()</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//d3plus.org/js/d3.js"></script>
<script src="//d3plus.org/js/d3plus.js"></script>
<div id="chartContainer">
</div></code></pre>
</div>
</div>
</p>
| 3 | 1,062 |
Does Android TextView support state_pressed state?
|
<p>The real quest is to have a custom ButtonBar(as below) in Android with TextViews acts as buttons and each should reflect their state, pressed/selected.</p>
<p><a href="https://i.stack.imgur.com/nC620.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nC620.png" alt="enter image description here" /></a></p>
<p>The TextView is set with the following background for different states to reflect. What all states supported by Android TextView? Say e.g., if it supports states like pressed/selected, how to update the TextView from XML/Code?</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#ffffff">
<shape android:shape="rectangle">
<corners android:radius="16.5dp" />
<size android:width="168dp" android:height="34dp" />
<solid android:color="#000000" />
</shape>
</item>
<item android:color="#000000" >
<shape android:shape="rectangle" >
<corners android:radius="16.5dp" />
<size android:width="168dp" android:height="34dp" />
<solid android:color="#FFFFFF" />
</shape>
</item>
</selector>
</code></pre>
<p>TextView code snippet below for reference</p>
<pre class="lang-xml prettyprint-override"><code> <TextView
android:id="@+id/tv1"
android:layout_width="0dp"
android:layout_height="40dp"
android:background="@drawable/tv_background"
android:gravity="center"
android:maxLines="1"
android:onClick="@{() -> viewModel.onTvClicked()}"
android:text="@string/TVTEXT"
android:textSize="16sp"
app:layout_constraintBaseline_toBaselineOf="@+id/something"
app:layout_constraintEnd_toStartOf="@+id/otherthing"
app:layout_constraintStart_toStartOf="parent" />
</code></pre>
<p>Thanks for your time :)</p>
| 3 | 1,129 |
Reverse for 'blogpost' with arguments '('',)' not found
|
<p>Reverse for 'blogpost' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P[0-9]+)\Z']</p>
<p>I face this problem in every project. So please any devloper solve this problem</p>
<p><strong>my urls.py</strong></p>
<pre><code>from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name='Blog_home'),
path('<int:pk>', views.blogpost, name='blogpost'),
]
</code></pre>
<p><strong>my views.py</strong></p>
<pre><code>from django.shortcuts import render
from blog.models import Post
# Create your views here.
def index(request):
post = Post.objects.all()
context = {'post':post}
return render(request, 'blog/bloghome.html', context)
def blogpost(request, pk):
blog_post = Post.objects.get(id=pk)
context = {'blog_post':blog_post}
return render(request, 'blog/blogpost.html', context)
</code></pre>
<p><strong>my models.py</strong></p>
<pre><code>from django.db import models
# Create your models here.
class Post(models.Model):
post_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
content = models.TextField()
author = models.CharField(max_length=50)
date_and_time = models.DateTimeField(blank=True)
def __str__(self):
return self.title
</code></pre>
<p><strong>Template: bloghome.html</strong></p>
<pre><code>{% extends 'basic.html' %}
{% block title %} Blog {% endblock title %}
{% block blogactive %} active {% endblock blogactive %}
{% block style %}
.overlay-image{
position: absolute;
height: auto;
width: 100%;
background-position: center;
background-size: cover;
opacity: 0.5;
}
{% endblock style %}
{% block body %}
<div class="container">
{% for post in post %}
<div class="row">
<div class="col-md-7 py-4">
<div class="row g-0 border rounded overflow-hidden flex-md-row shadow-sm h-md-250 position-relative">
<!-- <div class="col-auto m-auto img-fluid">
<img src="#">
</div> -->
<div class="col p-4 blog d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-primary">Code</strong>
<h3 class="mb-0">{{post.title}}</h3>
<div class="mb-1 text-muted">{{post.date_and_time}}</div>
<p class="card-text mb-auto">{{post.content | truncatechars:150}}</p>
<div class="my-2">
<a href="{% url 'blogpost' blog_post.id %}" class="btn btn-primary">Continue reading</a>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock body %}
</code></pre>
<p><strong>Template: blogpost.html</strong></p>
<pre><code>{% extends 'basic.html' %}
{% block title %} Blog {% endblock title %}
{% block body %}
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>{{post.title}}</h2>
</div>
</div>
</div>
{% endblock body %}
</code></pre>
<p><strong>Error</strong></p>
<pre><code>NoReverseMatch at /blog/
Reverse for 'blogpost' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<pk>[0-9]+)\\Z']
</code></pre>
<p>Error at Template: bloghome.html</p>
<pre><code><a href="{% url 'blogpost' blog_post.id %}" class="btn btn-primary">Continue reading</a>
</code></pre>
| 3 | 1,750 |
Send a custom email with additional account fields values on save in Woocommerce 3
|
<p>On the basis of the plugin “Advanced Custom Fields” additional fields were created for the personal account of WooCommerce users. Using the second "ACF for WooCommerce" plugin, I placed these fields on the edit-account page.</p>
<p>If the user has filled in the fields or edited them, the administrator will receive an email with the values of these fields. The following code is responsible for notifications:</p>
<pre><code>if (!class_exists('WooCommerceNotifyChanges')) {
class WooCommerceNotifyChanges {
function __construct() {
add_action('woocommerce_save_account_details', array($this, 'woocommerce_send_notification'), 15, 1);
}
function woocommerce_send_notification($user_id) {
$body = '';
$to = 'info@domain.com';
$subject = 'Edit profile data';
update_meta_cache('user', $user_id); // delete cache
$user = new WP_User($user_id);
$user_name = $user->user_login;
$body .= '<table>';
$body .= '<tr><td>'.__("Profile"). '</td></tr>';
$body .= '<tr><td>Login: </td><td>'.$user_name. '</td></tr>';
$body .= '<tr><td>First Name: </td><td>'.$user->billing_first_name. '</td></tr>';
$body .= '<tr><td>Last Name: </td><td>'.$user->billing_last_name. '</td></tr>';
$body .= '<tr><td>Phone: </td><td>'.get_user_meta($user_id, 'field_5b4640119354c', $single=true). '</td></tr>'; //text field
$body .= '<tr><td>Age: </td><td>'.get_user_meta($user_id, 'field_5b462d304b101', $single=true). '</td></tr>'; //text field
$body .= '<tr><td>Family: </td><td>'.get_user_meta($user_id, 'field_5b4bd7d9f0031', $single=true). '</td></tr>'; // selector
$body .= '<tr><td>What style do you prefer? </td><td>'.get_user_meta($user_id, 'field_5b47917a378ed', $single=true). '</td></tr>'; // checkbox
$body .= '</table>';
//set content type as HTML
$headers = array('Content-Type: text/html; charset=UTF-8;');
//send email
if (wp_mail($to, $subject, $body, $headers)) {
//echo 'email sent';
} else {
//echo 'email NOT sent';
}
//exit();
}
}
new WooCommerceNotifyChanges();
}
</code></pre>
<h3>Here two errors occur:</h3>
<ol>
<li><p>When a user edits these fields, old, apparently cached data is sent to the administrator email. When you re-send without editing, you will receive the correct field data.<br>
<br>
I put a line of code:</p>
<pre><code>update_meta_cache('user', $user_id);
</code></pre>
<p>But it does not work, the old data is still coming. Apparently, I did something wrong.</p></li>
<li><p>The data of all fields are correctly stored in the database and also correctly displayed in an email to the administrator. The problem with checkboxes.<br>
<br>
In this case, the "What style do you prefer?" three checkboxes "Classic", "Casual" and "Sport" are displayed. The user selected the "Casual" checkbox. The value of this field is correctly stored in the database.<br>
<br>
But in the email to the administrator, instead of this value, only the word “Array” comes.</p></li>
</ol>
<p>Tell me how to fix it?</p>
<p>Any help is appreciated.</p>
| 3 | 1,722 |
CS50 pset3 i want to resize this image, code is working for some and not for others? Can anyone tell me whats the problem?
|
<p>i want to resize it by "n", it is working for some but not for others , i don't know why, it has no image specific code as per i know, it should work for every image</p>
<pre><code>// Get multiplier
int n = atoi(argv[1]);
// read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf,bfR;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
bfR = bf;
// read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi,biR;
fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
biR = bi;
// ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
bi.biBitCount != 24 || bi.biCompression != 0)
{
fclose(outptr);
fclose(inptr);
fprintf(stderr, "Unsupported file format.\n");
return 4;
}
// modify bitmapinfoheader for height an width
biR.biWidth = bi.biWidth*n;
biR.biHeight = bi.biHeight*n;
// determine padding for scanlines
int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
int outpadding = (4 - (biR.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
// modify bisizeimage
biR.biSizeImage = (((biR.biWidth*(sizeof(RGBTRIPLE)))+outpadding)*abs(biR.biHeight));
// write outfile's BITMAPFILEHEADER
fwrite(&bfR, sizeof(BITMAPFILEHEADER), 1, outptr);
// modify bfsize before writing it
bfR.bfSize = (sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + sizeof(biR.biSizeImage));
// write outfile's BITMAPINFOHEADER
fwrite(&biR, sizeof(BITMAPINFOHEADER), 1, outptr);
// iterate over infile's scanlines
for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
{
for(int m = 0; m < n; m++)
{
// iterate over pixels in scanline
for (int j = 0; j < bi.biWidth; j++)
{
// temporary storage
RGBTRIPLE triple;
// read RGB triple from infile
fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
// write RGB triple to outfile
for (int k = 0; k < n; k++)
{
fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
}
}
// skip over padding, if any
fseek(inptr, padding, SEEK_CUR);
//go back to reprint the same line
if(m != n-1)
{
fseek(inptr, -bi.biWidth * sizeof(RGBTRIPLE),SEEK_CUR);
}
// then add it back (to demonstrate how)
for (int k = 0; k < padding; k++)
{
fputc(0x00, outptr);
}
</code></pre>
<p>Can anyone provide me with identifying the problem?I tried to look online but couldn't find any solution.website says "It looks like your post is mostly code; please add some more details", what i'm supposed to write more......</p>
| 3 | 1,168 |
Data table dcast column headings
|
<p>I have a data table of the form</p>
<pre><code>ID REGION INCOME_BAND RESIDENCY_YEARS
1 SW Under 5,000 10-15
2 Wales Over 70,000 1-5
3 Center 15,000-19,999 6-9
4 SE 15,000-19,999 15-19
5 North 15,000-19,999 10-15
6 North 15,000-19,999 6-9
</code></pre>
<p>created by</p>
<pre><code>exp = data.table(
ID = c(1,2,3,4,5,6),
REGION=c("SW", "Wales", "Center", "SE", "North", "North"),
INCOME_BAND = c("Under ?5,000", "Over ?70,000", "?15,000-?19,999", "?15,000-?19,999", "?15,000-?19,999","?15,000-?19,999"),
RESIDENCY_YEARS = c("10-15","1-5","6-9","15-19","10-15", "6-9"))
</code></pre>
<p>I would like to transform this to </p>
<p><img src="https://i.stack.imgur.com/mXEsw.jpg" alt="Example of the result of any data table manipulation"></p>
<p>I've managed to perform the majority of the work with dcast:</p>
<pre><code>exp.dcast = dcast(exp,ID~REGION+INCOME_BAND+RESIDENCY_YEARS, fun=length,
value.var=c('REGION', 'INCOME_BAND', 'RESIDENCY_YEARS'))
</code></pre>
<p>However I need some help creating sensible column headings.
Currently I have</p>
<blockquote>
<p>["ID"<br>
"REGION.1_Center_?15,000-?19,999_6-9"<br>
"REGION.1_North_?15,000-?19,999_10-15"<br>
"REGION.1_North_?15,000-?19,999_6-9"<br>
"REGION.1_SE_?15,000-?19,999_15-19" "REGION.1_SW_Under
?5,000_10-15" "REGION.1_Wales_Over ?70,000_1-5"<br>
"INCOME_BAND.1_Center_?15,000-?19,999_6-9"<br>
"INCOME_BAND.1_North_?15,000-?19,999_10-15"<br>
"INCOME_BAND.1_North_?15,000-?19,999_6-9"<br>
"INCOME_BAND.1_SE_?15,000-?19,999_15-19"<br>
"INCOME_BAND.1_SW_Under ?5,000_10-15"<br>
"INCOME_BAND.1_Wales_Over ?70,000_1-5"<br>
"RESIDENCY_YEARS.1_Center_?15,000-?19,999_6-9"
"RESIDENCY_YEARS.1_North_?15,000-?19,999_10-15"
"RESIDENCY_YEARS.1_North_?15,000-?19,999_6-9"<br>
"RESIDENCY_YEARS.1_SE_?15,000-?19,999_15-19"<br>
"RESIDENCY_YEARS.1_SW_Under ?5,000_10-15"<br>
"RESIDENCY_YEARS.1_Wales_Over ?70,000_1-5"</p>
</blockquote>
<p>And I would like the column headings to be</p>
<pre><code>ID SW Wales Center SE North Under 5,000 Over 70,000 15,000-19,999 1-5 6-9 10-15 15-19
</code></pre>
<p>Could anybody advise?</p>
| 3 | 1,147 |
Perl, XML::Twig, how to reading field with the same tag
|
<p>I'm working on processing a XML file I receive from a partner. I do not have any influence on changing the makeup of this xml file. An extract of the XML is:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<objects>
<object>
<id>VW-XJC9</id>
<name>Name</name>
<type>House</type>
<description>
<![CDATA[<p>some descrioption of the house</p>]]> </description>
<localcosts>
<localcost>
<type>mandatory</type>
<name>What kind of cost</name>
<description>
<![CDATA[Some text again, different than the first tag]]>
</description>
</localcost>
</localcosts>
</object>
</objects>
</code></pre>
<p>The reason I use Twig is that this XML is about 11GB big, about 100000 different objects) . The problem is when I reach the localcosts part, the 3 fields (type, name and description) are skipped, probably because these names are already used before.</p>
<p>The code I use to go through the xml file is as follows:</p>
<pre><code>my $twig= new XML::Twig( twig_handlers => {
id => \&get_ID,
name => \&get_Name,
type => \&get_Type,
description => \&get_Description,
localcosts => \&get_Localcosts
});
$lokaal="c:\\temp\\data3.xml";
getstore($xml, $lokaal);
$twig->parsefile("$lokaal");
sub get_ID { my( $twig, $data)= @_; $field[0]=$data->text; $twig->purge; }
sub get_Name { my( $twig, $data)= @_; $field[1]=$data->text; $twig->purge; }
sub get_Type { my( $twig, $data)= @_; $field[3]=$data->text; $twig->purge; }
sub get_Description { my( $twig, $data)= @_; $field[8]=$data->text; $twig->purge; }
sub get_Localcosts{
my ($t, $item) = @_;
my @localcosts = $item->children;
for my $localcost ( @localcosts ) {
print "$field[0]: $localcost->text\n";
my @costs = $localcost->children;
for my $cost (@costs) {
$Type =$cost->text if $cost->name eq q{type};
$Name =$cost->text if $cost->name eq q{name};
$Description=$cost->text if $cost->name eq q{description};
print "Fields: $Type, $Name, $Description\n";
}
}
$t->purge;
}
</code></pre>
<p>when I run this code, the main fields are read without issues, but when the code arrives at the 'localcosts' part, the second for-next loop is not executed. When I change the field names in the xml to unique ones, this code works perfectly.</p>
<p>Can someone help me out?</p>
<p>Thanks</p>
| 3 | 1,384 |
Random <divs> onclick
|
<p>I'm trying to make a simple game where</p>
<ul>
<li><p>you start with 9 circles</p></li>
<li><p>when you click on a circle with a thicker border it's going to increment a score and cause new circles to be drawn randomly.</p></li>
</ul>
<p>I've already worked on counting stuff but I have a problem, because wherever you click (I mean whatever div) it sums up points. I don't have an idea about how to deactivate div's which do not have a thicker border. </p>
<p>Please tell if this is a good programming approach.</p>
<p><a href="https://i.stack.imgur.com/owRRg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/owRRg.png" alt="photo of game"></a></p>
<p>HTML</p>
<pre><code><body>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<h1> Wyniki </h1>
<p> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. </p>
</div>
<div class="col-md-8">
<h1> Gra </h1>
<div class="wynik">
<h2> Rezultat </h2>
<p id="zliczenie"> </p>
</div>
<div class="points"> </div>
</div>
<div class="col-md-2">
<h1> Profil </h1>
<p> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. </p>
</div>
</div>
</div>
</body>
</code></pre>
<p>CSS</p>
<pre><code>body {
background-color: #ecf0f1;
margin : 2% 2%;
}
.wynik{
border : solid 1px blue;
}
.point {
width : 100px;
height : 100px;
border : solid 1px #000;
border-radius : 100%;
text-align : center;
cursor : pointer;
float : left;
margin : 20px;
}
.point:hover {
color : red;
border-radius : 0%;
}
.points{
width : calc(140px * 3);
margin : 5px auto;
}
</code></pre>
<p>JS</p>
<pre><code>window.onload = start;
function start()
{
var div_value = "";
for (i = 0; i < 9; i++)
{
var element = "div_number" + i;
div_value = div_value + '<div class="point" id="'+element+'" onclick="c('+i+')"> Klik </div>';
if((i+1)%3 == 0)
{
div_value = div_value + '<div style="clear:both;"> </div>';
}
}
document.getElementsByClassName("points")[0].innerHTML = div_value;
esthetic();
random_show();
}
// IT SHOWS 1 RANDOM DIV TO START THE GAME
function random_show() {
var a = Math.floor((Math.random() * 8));
var x = document.getElementById("div_number" + a).style.border="10px dotted";
}
var liczby = [];
// IT DROWN LOTS AND COUNT THE SCORE
function c(i)
{
var a = Math.floor((Math.random() * 8));
this.i = a;
var z = document.getElementById("div_number" + i);
var y = document.getElementById("div_number" + a);
if(y.style.border = "10px dotted") {
z.style.border ="5px dotted";
liczby.push(i);
} else {
y.style.border="8px solid";
}
var x = document.getElementById("zliczenie").innerHTML = liczby.length;
}
// IT GIVES EVERY DIV INITIAL style.border
function esthetic()
{
var x = document.getElementsByClassName("point");
for (i = 0; i < 9; i++)
{
x[i].style.border = "5px dotted";
}
}
</code></pre>
<p>Thanks a lot for any hints one more time!</p>
| 3 | 1,973 |
Using Typo3 eID for nusoap call
|
<p>i'm using the following code for my soap call. </p>
<p>If i add the wsdl and make my client call i just get the response without the whole soap wrap. </p>
<pre><code>declare(strict_types=1);
namespace Vendor\DocBasics\Controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use Vendor\DocBasics\Domain\Repository\EventsRepository;
use Vendor\CartExtended\Domain\Repository\Order\ItemRepository;
require_once(PATH_site . 'typo3conf/ext/doc_basics/Classes/Libs/nusoap/nusoap.php');
class EventsController
{
protected $action = '';
protected $order;
protected $Vbeln = '';
protected $Zaehl = '';
protected $objectManager;
/**
* @var array
*/
protected $responseArray = [
'hasErrors' => false,
'message' => 'Nothing to declare'
];
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
*/
public function processRequest(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$this->initializeData(file_get_contents('php://input')); //xml datas from soap call
switch (isset($request->getQueryParams()['action']) ? (string)$request->getQueryParams()['action'] : '') {
case 'create':
$this->createAction();
break;
case 'update':
$this->updateAction();
break;
default:
$this->updateAction(); //call it as default, so i can call it as endpoint without action parameter
}
$this->prepareResponse($response,$request->getQueryParams()['action']);
return $response;
}
/**
* action create
*
* @return void
*/
public function createAction()
{
$server = new \soap_server();
$server->configureWSDL("updateorderservice", "https://domain.tld/updateorderservice", "https://domain.tld/index.php?eID=update_order");
$server->register(
"update",
array("Vbeln" => 'xsd:string', "Zaehl" => 'xsd:integer'),
array("return" => 'xsd:string'),
"https://domain.tld/updateorderservice",
"update",
"rpc",
"encoded",
"Update a given order"
);
$this->responseArray['message']= $server->service(file_get_contents('php://input'));
}
public function updateAction()
{
$this->objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$this->itemRepository = $this->objectManager->get(ItemRepository::class);
$order=$this->itemRepository->findOrderByOrder($this->Vbeln);
if($order){
$order->setCancelDate($this->Veindat);
$this->itemRepository->update($order);
$this->persistenceManager->persistAll();
$msg= '<MESSAGE><TYPE>S</TYPE><MSGTXT>Auftrag '.$this->Vbeln.' aktualisiert!</MSGTXT></MESSAGE>';
}
else $msg= '<MESSAGE><TYPE>E</TYPE><MSGTXT>Auftrag '.$this->Vbeln.' konnte nicht aktualisiert!</MSGTXT></MESSAGE>';
$this->responseArray['message'] = $msg; //receive the message but don't know how to wrap it
}
/**
* @param ResponseInterface $response
* @param String $action
* @return void
*/
protected function prepareResponse(ResponseInterface &$response, $action)
{
if($action=='create'){
$response = $response->withHeader('Content-Type', 'text/html; charset=utf-8');
$response->getBody()->write($this->responseArray['message']);
}
else{
$response = $response->withHeader('Content-Type', 'text/xml; charset=utf-8');
$response->getBody()->write($this->responseArray['message']);
}
}
/**
* @param $request
* @return void
*/
protected function initializeData($request)
{
$resp= $this->parseResult($request);
if($resp->Vbeln[0]) $this->Vbeln = (string)($resp->Vbeln[0]);
if($resp->Zaehl[0]) $this->Zaehl = intval($resp->Zaehl[0]);
}
public function parseResult($result){
$result = str_ireplace(['soapenv:','soap:','upd:'], '', $result);
$result = simplexml_load_string($result);
$notification = $result->Body->Update;
return $notification;
}
}
</code></pre>
<p>My response is just the small xml i'm writing as return to the updateAction(). My response should be wrapped between and so on
May be i'm missing something or the way i'm using the eID concept is wrong.</p>
| 3 | 1,872 |
Text in .write gets cut off
|
<p>I am trying to make a program that will create a LaTex file (.tex) with a preamble in it, and sooner some sections. I have defined my function <em>thepreamble(title,subject)</em> such that the inputs will be created in the string, which is seen below in my code.</p>
<pre><code># -*- coding: utf-8 -*-
import io
def thepreamble(title, subject):
global preamble
preamble = r'''\documentclass[a4paper, 12pt]{extarticle}
\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}
\usepackage[english, danish]{babel}
\usepackage{fancyhdr}
\usepackage[dvipsnames]{xcolor}
\usepackage{mathtools}
\usepackage{graphicx}
\usepackage{amssymb}
\usepackage{titlesec}
\usepackage[left=0.5in, right=0.5in, top=0.8in, bottom=0.8in]{geometry}
\usepackage{lipsum}
\usepackage[breaklinks, colorlinks=true,linkcolor=NavyBlue, citecolor=blue, urlcolor=Blue, linktoc=all]{hyperref}
\usepackage[utf8x]{inputenc}
\usepackage{titlesec}
\usepackage{fix-cm}
\usepackage{titletoc}
\usepackage{tocloft}
\usepackage{setspace}
\usepackage[all]{hypcap}
\usepackage{tikz, pgfplots}
\usetikzlibrary{calc}
\usepackage{tkz-euclide}
\usetkzobj{all}
\usetikzlibrary{positioning}
\usepackage{tikzrput}
\usetikzlibrary{arrows.meta}
\usepackage[labelfont=bf]{caption}
\usepackage[hang, flushmargin]{footmisc}
\usepackage{footnotebackref}
\pagestyle{fancy}
\fancyhf{}
\fancyfoot[R]{\textbf \thepage}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{2pt}
\renewcommand{\footrule}{\hbox to\headwidth{\color{NavyBlue}\leaders\hrule height \footrulewidth\hfill}}
\newcommand{\dl}[1]{\underline{\underline{#1}}}
\setcounter{tocdepth}{2}
\setcounter{secnumdepth}{0}
\begin{document}
\begin{titlepage}
\begin{center}
\vspace*{30ex}
{\fontsize{38}{0}\selectfont \bfseries \fontfamily{put}\selectfont \color{NavyBlue} '''+ str(title)+'''} \\
[3ex]
{\fontsize{18}{0}\selectfont \bfseries \fontfamily{put}\selectfont \color{NavyBlue} ('''+str(subject)+ ''')}\\
[14ex]
{ \fontsize{15}{0}\selectfont Casper Juul Lorentzen} \\
[3ex]
{\large \scshape 1.z} \\
[2ex]
{\large \scshape 2018}\\
\vspace{\fill}
\includegraphics[scale=0.45]{C:/LaTeX/Next.png} \\
[4mm]
\small{\bfseries Albertslund Gymnasium \& HF} \\
\end{center}
\end{titlepage}
\renewcommand\contentsname{Indhold \vspace{3ex}}
\tableofcontents
\thispagestyle{empty}
\newpage
\setcounter{page}{1}
'''
return preamble
def sections(numsec, numsubsec):
numbers = []
numbers.extend(numsubsec)
global tasks
tasks = []
print("")
#Brug præfikset 'r' foran unicodes
print("")
for n,i in zip(range(1, numsec+1),range(0,numsec)):
print("")
opgaver = "\section{Opgave "+str(n)+"}"
print(opgaver)
print("")
tasks.append(opgaver)
for x in range(int(numsubsec[i])):
print("\subsection{}")
print("")
return tasks
def runprogram():
encoding ='utf8'
titlefile = input("Title (file): ")
title = input("Title of document: ")
subject = input("Subject: ")
numsec = int(input("How many sections? "))
filename = "C:\\Users\\Casper\\Documents\\LaTeX\\fire.tex"
while True:
numsubsec = input("How many subsections?")
while len(numsubsec) !=numsec:
print("")
numsubsec =input("Error; input must be of "+ str(numsec) + " digits ")
try:
with io.open(filename.replace('fire.tex',titlefile+".tex"), 'w', encoding=encoding) as f:
f.write(unicode_thepreamble(title, subject))
f.close()
#sections(numsec, numsubsec)
break
except:
print("Error")
runprogram()
</code></pre>
<p>Whenever I run the program, it creates a new .tex file with the name of </p>
<pre><code>titlefile = input("Title (file): ")
</code></pre>
<p>As you can see, i have defined <em>preamble</em> as a text with unicode characters in it. And when I run the program, it writes almost everything of the preamble string in the tex document, but it cuts some of it off and creates weird symbol, like this:
<a href="https://i.stack.imgur.com/VlrLg.png" rel="nofollow noreferrer">tex document created</a></p>
<p>I named the title 'stackoverflow' and the subject 'python problem', and that works fine. But what ought to be '\renewcommand' is in the document ' enewcommand'. I do not know how to fix this. I just want precisely what my preamble strings says.</p>
| 3 | 1,822 |
how to change css3 animation state
|
<p>what i am trying to do is <strong>play and pause</strong> css3 animation<br>
from this link:
<a href="https://stackoverflow.com/questions/5804444/how-to-pause-and-resume-css3-animation-using-javascript">How to pause and resume CSS3 animation using JavaScript?</a> i learned how to pause animation<br>
i also achieved it but when i pauses animation it goes back to the initial state
how do i pause or resume from last state(pause or play) and not going back to initial state ?<br>
Here is my code::</p>
<pre><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Teleprompter</title>
<style>
.demo{
width: 500px;
height: 500px;
}
.demo1
{
-webkit-animation-name: example; /* Chrome, Safari, Opera */
-webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
animation-name: example;
animation-duration: 4s;
}
.demo1:hover
{
-webkit-animation-play-state: paused; /* Chrome, Safari, Opera */
animation-play-state: paused;
}
.PauseAnimation{
-webkit-animation-play-state: paused; /* Chrome, Safari, Opera */
animation-play-state: paused;
}
.RunningAnimation{
-webkit-animation-play-state: running; /* Chrome, Safari, Opera */
animation-play-state: running;
}
@-webkit-keyframes example {
from {transform:translateY(0px);}
to {transform:translateY(-100px);}
}
@keyframes example {
from {transform:translateY(0px);}
to {transform:translateY(-100px);}
}
</style>
<script>
function f1()
{
var flag=0;
var s = document.getElementById('btn1').innerHTML;
if(s=="Play"){
document.getElementById('btn1').innerHTML='Pause';
if(flag==0){
document.getElementById('p1').className='demo1';
flag=flag+1;
return;
}
document.getElementById('p1').className='RunningAnimation';
return;
}
else if(s=='Pause'){
document.getElementById('btn1').innerHTML='Play';
document.getElementById('p1').className='PauseAnimation';
return;
}
else return;
}
function f2(){
document.getElementById('div1').contentEditable=true;
}
</script>
</head>
<body >
<div class="demo" id="div1">
<div id="p1">
<br><br><br><br><br>
<p>
Hello!!!
<br>
Hello world!!!
<br>
Hello html!!!
<br>
Hello javascript!!!
<br>
Hello css!!!
<br>
Hello animation!!!
</p>
<br id="br1"><br><br>
</div>
</div>
<button onClick="f1()" id="btn1">Play</button>
<button onClick="">Stop</button>
<button onClick="f2()">Edit text</button>
</body>
</html>
</code></pre>
<p>is there any bug in my code ?</p>
| 3 | 1,269 |
batch file change bracket speciff my.ini
|
<p>I need to locate a [mysqld] bracket inside a file (my.ini), after it finds 2 variables "lower_case_table_names = 1" and "max_allowed_packet = 512M", if they exist make the necessary change in their values, if there is no write With past values.</p>
<p>I am using this batch file, for this verification however, after the file everything goes wrong, and the variables are written in the first line.</p>
<p>batch file teste.bat</p>
<pre><code>>my.ini.new (
echo lower_case_table_names=1
echo max_allowed_packet=512M
for /f "skip=71 delims=" %%A in (my.ini) do echo %%A
)
move /y my.ini.new my.ini >nul
</code></pre>
<p>file my.ini</p>
<pre><code># MySQL Server Instance Configuration File
# ----------------------------------------------------------------------
# Generated by the MySQL Server Instance Configuration Wizard
#
#
# Installation Instructions
# ----------------------------------------------------------------------
#
# On Linux you can copy this file to /etc/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options
# (@localstatedir@ for this installation) or to
# ~/.my.cnf to set user-specific options.
#
# On Windows you should keep this file in the installation directory
# of your server (e.g. C:\Program Files\MySQL\MySQL Server X.Y). To
# make sure the server reads the config file use the startup option
# "--defaults-file".
#
# To run run the server from the command line, execute this in a
# command line shell, e.g.
# mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini"
#
# To install the server as a Windows service manually, execute this in a
# command line shell, e.g.
# mysqld --install MySQLXY --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini"
#
# And then execute this in a command line shell to start the server, e.g.
# net start MySQLXY
#
#
# Guildlines for editing this file
# ----------------------------------------------------------------------
#
# In this file, you can use all long options that the program supports.
# If you want to know the options a program supports, start the program
# with the "--help" option.
#
# More detailed information about the individual options can also be
# found in the manual.
#
#
# CLIENT SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
#
[client]
port=3306
[mysql]
default-character-set=latin1
# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.
#
[mysqld]
# The TCP/IP Port the MySQL Server will listen on
port=3306
#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files (x86)/MySQL/MySQL Server 5.1/"
#Path to the database root
datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"
# The default character set that will be used when a new schema or table is
# created and no character set is defined
character-set-server=latin1
# The default storage engine that will be used when create new tables when
default-storage-engine=INNODB
# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
# The maximum amount of concurrent sessions the MySQL server will
# allow. One of these connections will be reserved for a user with
# SUPER privileges to allow the administrator to login even if the
# connection limit has been reached.
max_connections=160
# Query cache is used to cache SELECT results and later return them
# without actual executing the same query once again. Having the query
# cache enabled may result in significant speed improvements, if your
# have a lot of identical queries and rarely changing tables. See the
# "Qcache_lowmem_prunes" status variable to check if the current value
# is high enough for your load.
# Note: In case your tables change very often or if your queries are
# textually different every time, the query cache may result in a
# slowdown instead of a performance improvement.
query_cache_size=99M
# The number of open tables for all threads. Increasing this value
# increases the number of file descriptors that mysqld requires.
# Therefore you have to make sure to set the amount of open files
# allowed to at least 4096 in the variable "open-files-limit" in
# section [mysqld_safe]
table_cache=320
# Maximum size for internal (in-memory) temporary tables. If a table
# grows larger than this value, it is automatically converted to disk
# based table This limitation is for a single table. There can be many
# of them.
tmp_table_size=103M
# How many threads we should keep in a cache for reuse. When a client
# disconnects, the client's threads are put in the cache if there aren't
# more than thread_cache_size threads from before. This greatly reduces
# the amount of thread creations needed if you have a lot of new
# connections. (Normally this doesn't give a notable performance
# improvement if you have a good thread implementation.)
thread_cache_size=8
#*** MyISAM Specific options
# The maximum size of the temporary file MySQL is allowed to use while
# recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE.
# If the file-size would be bigger than this, the index will be created
# through the key cache (which is slower).
myisam_max_sort_file_size=100G
# If the temporary file used for fast index creation would be bigger
# than using the key cache by the amount specified here, then prefer the
# key cache method. This is mainly used to force long character keys in
# large tables to use the slower key cache method to create the index.
myisam_sort_buffer_size=167M
# Size of the Key Buffer, used to cache index blocks for MyISAM tables.
# Do not set it larger than 30% of your available memory, as some memory
# is also required by the OS to cache rows. Even if you're not using
# MyISAM tables, you should still set it to 8-64M as it will also be
# used for internal temporary disk tables.
key_buffer_size=16M
# Size of the buffer used for doing full table scans of MyISAM tables.
# Allocated per thread, if a full scan is needed.
read_buffer_size=64K
read_rnd_buffer_size=256K
# This buffer is allocated when MySQL needs to rebuild the index in
# REPAIR, OPTIMZE, ALTER table statements as well as in LOAD DATA INFILE
# into an empty table. It is allocated per thread so be careful with
# large settings.
sort_buffer_size=256K
#*** INNODB Specific options ***
# Use this option if you have a MySQL server with InnoDB support enabled
# but you do not plan to use it. This will save memory and disk space
# and speed up some things.
#skip-innodb
# Additional memory pool that is used by InnoDB to store metadata
# information. If InnoDB requires more memory for this purpose it will
# start to allocate it from the OS. As this is fast enough on most
# recent operating systems, you normally do not need to change this
# value. SHOW INNODB STATUS will display the current amount used.
innodb_additional_mem_pool_size=12M
# If set to 1, InnoDB will flush (fsync) the transaction logs to the
# disk at each commit, which offers full ACID behavior. If you are
# willing to compromise this safety, and you are running small
# transactions, you may set this to 0 or 2 to reduce disk I/O to the
# logs. Value 0 means that the log is only written to the log file and
# the log file flushed to disk approximately once per second. Value 2
# means the log is written to the log file at each commit, but the log
# file is only flushed to disk approximately once per second.
innodb_flush_log_at_trx_commit=1
# The size of the buffer InnoDB uses for buffering log data. As soon as
# it is full, InnoDB will have to flush it to disk. As it is flushed
# once per second anyway, it does not make sense to have it very large
# (even with long transactions).
innodb_log_buffer_size=6M
# InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and
# row data. The bigger you set this the less disk I/O is needed to
# access data in tables. On a dedicated database server you may set this
# parameter up to 80% of the machine physical memory size. Do not set it
# too large, though, because competition of the physical memory may
# cause paging in the operating system. Note that on 32bit systems you
# might be limited to 2-3.5G of user level memory per process, so do not
# set it too high.
innodb_buffer_pool_size=570M
# Size of each log file in a log group. You should set the combined size
# of log files to about 25%-100% of your buffer pool size to avoid
# unneeded buffer pool flush activity on log file overwrite. However,
# note that a larger logfile size will increase the time needed for the
# recovery process.
innodb_log_file_size=114M
# Number of threads allowed inside the InnoDB kernel. The optimal value
# depends highly on the application, hardware as well as the OS
# scheduler properties. A too high value may lead to thread thrashing.
innodb_thread_concurrency=10
</code></pre>
| 3 | 2,511 |
Implementing FCFS CPU Scheduler (Wait time function)
|
<p>Process Data:<br>
process goes {CPU burst, I/O time, CPU burst, I/O time, CPU burst, I/O time,…….., last CPU burst}</p>
<p>I split the data into two arrays. cpu burst and io_burst</p>
<p>P1 {4,24,5,73,3,31,5,27,4,33,6,43,4,64,5,19,2}</p>
<p>P2 {18,31,19,35,11,42,18,43,19,47,18,43,17,51,19,32,10}</p>
<p>P3 {6,18,4,21,7,19,4,16,5,29,7,21,8,22,6,24,5}</p>
<p>P4 {17,42,19,55,20,54,17,52,15,67,12,72,15,66,14}</p>
<p>P5 {5,81,4,82,5,71,3,61,5,62,4,51,3,77,4,61,3,42,5}</p>
<p>P6 {10,35,12,41,14,33,11,32,15,41,13,29,11}</p>
<p>P7 {21,51,23,53,24,61,22,31,21,43,20}</p>
<p>P8 {11,52,14,42,15,31,17,21,16,43,12,31,13,32,15}</p>
<p>I'm mostly having a hard time calculating the wait time for this. I made a class process which is here</p>
<pre><code>class Process
{
//public Process(string name, int arrival, int cpuburst,int ioburst, int priority)
//{
// this.name = name;
// this.arrival = arrival;
// this.cpuburst = cpuburst;
// this.ioburst = ioburst;
// this.priority = priority;
//}
public Process()
{
}
public string name;
public int arrival;
public int[] cpuburst;
public int []ioburst;
public int priority;
public int totburst;
public int wait;
public int end;
public int start;
public int contextswitch;
public int response;
public int turnAround;
//public int contextswitch;
public double cpu_utilization;
public double avwaitingtime;
public double avturnaroundtime;
public double avresponse;
}
</code></pre>
<p>}</p>
<p>heres how I'm initializing, I made cpuburst and io_burst the same size by adding some zeroes to the end of the array </p>
<pre><code>void initialize_process()
{
List<Process> processes = new List<Process>();
Process p1 = new Process();
p1.arrival = 0;
p1.end = 0;
p1.name = "P1";
p1.cpuburst = new int[] { 4, 5, 3, 5, 4, 6, 4, 5, 2 ,0};
p1.ioburst = new int[] { 24, 73, 31, 27, 33, 43, 64, 19, 0, 0 };
p1.totburst = 38;
processes.Add(p1);
Process p2 = new Process();
p2.arrival = 0;
p2.name = "P2";
p2.end = 0;
p2.cpuburst = new int[] { 18, 19, 11, 18, 19, 18, 17, 19, 10, 0 };
p2.ioburst = new int[] { 31, 35, 42, 43, 47, 43, 51, 32, 0, 0 };
p2.totburst = 149;
processes.Add(p2);
Process p3 = new Process();
p3.arrival = 0;
p3.end = 0;
p3.name = "P3";
p3.cpuburst = new int[]{ 6, 4, 7, 4, 5, 7, 8, 6, 5 ,0};
p3.ioburst = new int[] { 18, 21, 19, 16, 29, 21, 22, 24, 0, 0 };
p3.totburst = 52;
processes.Add(p3);
Process p4 = new Process();
p4.arrival = 0;
p4.end = 0;
p4.name = "P4";
p4.cpuburst = new int[] { 17, 19, 20, 17, 15, 12, 15, 14,0,0 };
p4.ioburst = new int[] { 42, 55, 54, 52, 67, 72, 66, 0, 0, 0 };
p4.totburst = 129;
processes.Add(p4);
Process p5 = new Process();
p5.arrival = 0;
p5.end = 0;
p5.name = "P5";
p5.cpuburst = new int[]{ 5, 4, 5, 3, 5, 4, 3, 4, 3, 5 };
p5.ioburst = new int[] { 81, 82, 71, 61, 62, 51, 77, 61, 42, 0 };
p5.totburst = 41;
processes.Add(p5);
Process p6 = new Process();
p6.arrival = 0;
p6.end = 0;
p6.name = "P6";
p6.cpuburst = new int[] { 10, 12, 14, 11, 15, 13, 11,0,0,0 };
p6.ioburst = new int[] { 35, 41, 33, 32, 41, 29, 0, 0, 0, 0 };
p6.totburst = 86;
processes.Add(p6);
Process p7 = new Process();
p7.arrival = 0;
p7.end = 0;
p7.name = "P7";
p7.cpuburst = new int[]{ 21, 23, 24, 22, 21, 20,0,0,0,0 };
p7.ioburst = new int[] { 51, 53, 61, 31, 43, 0, 0, 0, 0, 0 };
p7.totburst = 131;
processes.Add(p7);
Process p8 = new Process();
p8.arrival = 0;
p8.end = 0;
p8.name = "P8";
p8.cpuburst = new int[] { 11, 14, 15, 17, 16, 12, 13, 15, 0, 0 };
p8.ioburst = new int[] { 52, 42, 31, 21, 43, 31, 32, 0, 0, 0 };
p8.totburst = 113;
processes.Add(p8);
FCFS(processes);
SJF(processes);
}
</code></pre>
<p>In my FCFS function I call other functions to perform the calculations</p>
<pre><code>void FCFS(List<Process> p)
{
output.Items.Add("After FCFS");
output.Items.Add("-------------------------------------------------------");
wait(p);
turnaroundtime(p);
responsetime(p);
completeoutputlist(p);
}
</code></pre>
<p>my attempts at wait time have failed and I really don't know how to best approach this. I want to get these values calculated here so then I can call them in my other functions.
I'm mostly stuck on how to take I/o time into account when calculating the clock</p>
<p>the processes are doing I/O at the same time one other process is running. So, I/O should be decremented as timer is incremented for every process doing I/O.
multiple processes can be doing i/o at the same time. So you would need a list of processes that are doing i/o.
really just need some guidance in this part.</p>
<pre><code>void wait(List<Process> p)
{
/* Goal keep track of context switches. - p.contextswitch
* Keep track of the first time it enters to get response time - p.start
* Keep track of when the process ends - so later we can calc turnaround time p.end
* then tweak some functions so it works again
*
*/
}
</code></pre>
<p>Before I was doing something like this</p>
<pre><code>void wait(List<Process> p)
{
/* Goal keep track of context switches. - p.contextswitch
* Keep track of the first time it enters to get response time - p.start
* Keep track of when the process ends - so later we can calc turnaround time p.end
* then tweak some functions so it works again
*
*/
int k = 0;
int i = 0;
int clock = 0;
int contextswitch = 0;
int cpuready = 0;
int ioready = 0;
double avwaitingtime = 0;
for (k = 0; k < 10; k++)
{
for (i = 0; i < p.Count; i++)
{
//cpuready = p[i].cpuburst[k];
//ioready = p[i].ioburst[k];
clock += p[i].cpuburst[k];
//sets arrival time P1
if (i == 0 && k == 0)
{
p[0].arrival = 0;
}
//sets arrival time P2
if (i == 1 && k == 0)
{
p[1].arrival = clock;
}
//sets arrival time P3
if (i == 2 && k == 0)
{
p[2].arrival = clock;
}
//sets arrival time P4
if (i == 3 && k == 0)
{
p[3].arrival = clock;
}
//sets arrival time P5
if (i == 4 && k == 0)
{
p[4].arrival = clock;
}
//sets arrival time P6
if (i == 5 && k == 0)
{
p[5].arrival = clock;
}
//sets arrival time P7
if (i == 6 && k == 0)
{
p[6].arrival = clock;
}
//sets arrival time P8
if (i == 7 && k == 0)
{
p[7].arrival = clock;
}
//ADDS TO THE CONTEXT SWITCH CONTER
contextswitch += 1;
//Checks the first row and the last column
if (i == 0 && k == 8)
{
p[0].end = clock;
}
//Checks the 2nd row and the last column
if (i == 1 && k == 8)
{
p[1].end = clock;
}
//Checks the 3rd row and the last column
if (i == 2 && k == 8)
{
p[2].end = clock;
}
//Checks the 4th row and the last column
if (i == 3 && k == 7)
{
p[3].end = clock;
}
//Checks the 5th row and the last column
if (i == 4 && k == 9)
{
p[4].end = clock;
}
//Checks the 6th row and the last column
if (i == 5 && k == 6)
{
p[5].end = clock;
}
//Checks the 7th row and the last column
if (i == 6 && k == 5)
{
p[6].end = clock;
}
//Checks the 8th row and the last column
if (i == 7 && k == 7)
{
p[7].end = clock;
}
}
}
output.Items.Add(clock);
double waitsum = 0;
for (i = 0; i < 8; i++)
{
//CALCS THE WAIT TIME
p[i].wait = (p[i].end- p[i].totburst);
// output.Items.Add(p[i].wait);
//CALCS THE WAITSUM
waitsum += p[i].wait;
}
//calcs avg wait time
avwaitingtime = (waitsum / 8.0);
//output.Items.Add(avg);
output.Items.Add(contextswitch);
cpu_utilization(p, contextswitch,clock);
for (i = 0; i < 8; i++)
{
p[i].avwaitingtime = avwaitingtime;
}
}
</code></pre>
<p>any sort of ideas on how to approach this would be tons of help, thanks!</p>
| 3 | 5,922 |
Why Bitdefender prevent flush data (PHP)?
|
<p>This code print result after each loop to browser.Works on my host and localhost.<br> but after install <code>bitdefender total security 2015</code> on my pc not works(print all text after 10 seconds at once)
i disable antivirus and firewall in bitdefender but not solved.<br>
How to solve this?
Demo: <a href="http://s2.uploadcloud.net/2.php" rel="nofollow">http://s2.uploadcloud.net/2.php</a></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
var es;
function startTask() {
es = new EventSource('progress.php');
//a message is received
es.addEventListener('message', function(e) {
var result = JSON.parse( e.data );
addLog(result.message);
if(e.lastEventId == 'CLOSE') {
addLog('Received CLOSE closing');
es.close();
var pBar = document.getElementById('progressor');
pBar.value = pBar.max; //max out the progress bar
}
else {
var pBar = document.getElementById('progressor');
pBar.value = result.progress;
var perc = document.getElementById('percentage');
perc.innerHTML = result.progress + "%";
perc.style.width = (Math.floor(pBar.clientWidth * (result.progress/100)) + 15) + 'px';
}
});
es.addEventListener('error', function(e) {
addLog('Error occurred');
es.close();
});
}
function stopTask() {
es.close();
addLog('Interrupted');
}
function addLog(message) {
var r = document.getElementById('results');
r.innerHTML += message + '<br>';
r.scrollTop = r.scrollHeight;
}
</script>
</head>
<body>
<br />
<input type="button" onclick="startTask();" value="Start Long Task" />
<input type="button" onclick="stopTask();" value="Stop Task" />
<br />
<br />
<p>Results</p>
<br />
<div id="results" style="border:1px solid #000; padding:10px; width:300px; height:250px; overflow:auto; background:#eee;"></div>
<br />
<progress id='progressor' value="0" max='100' style=""></progress>
<span id="percentage" style="text-align:right; display:block; margin-top:5px;">0</span>
</body>
</html>
</code></pre>
<p>progress.php</p>
<pre><code><?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function send_message($id, $message, $progress) {
$d = array('message' => $message , 'progress' => $progress);
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode($d) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
//LONG RUNNING TASK
for($i = 1; $i <= 10; $i++) {
send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
sleep(1);
}
send_message('CLOSE', 'Process complete');
</code></pre>
| 3 | 1,564 |
Database insertion is taking zero seconds to insert
|
<p>I am trying to measure the performance of <code>Database Insert</code>. So for that I have written a <code>StopWatch</code> class which will reset the counter before <code>executeUpdate</code> method and calculate the time after <code>executeUpdate</code> method is done.</p>
<p>And I am trying to see how much time each thread is taking, so I am keeping those numbers in a <code>ConcurrentHashMap</code>. </p>
<p>Below is my main class-</p>
<pre><code>public static void main(String[] args) {
final int noOfThreads = 4;
final int noOfTasks = 100;
final AtomicInteger id = new AtomicInteger(1);
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
for (int i = 0; i < noOfTasks * noOfThreads; i++) {
service.submit(new Task(id));
}
while (!service.isTerminated()) {
}
//printing the histogram
System.out.println(Task.histogram);
}
</code></pre>
<p>Below is the class that implements Runnable in which I am trying to measure each thread performance in inserting to database meaning how much time each thread is taking to insert to database-</p>
<pre><code>class Task implements Runnable {
private final AtomicInteger id;
private StopWatch totalExecTimer = new StopWatch(Task.class.getSimpleName() + ".totalExec");
public static ConcurrentHashMap<Long, AtomicLong> histogram = new ConcurrentHashMap<Long, AtomicLong>();
public Task(AtomicInteger id) {
this.id = id;
}
@Override
public void run() {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(Constants.INSERT_ORACLE_SQL);
//other preparedStatement
totalExecTimer.resetLap();
preparedStatement.executeUpdate();
totalExecTimer.accumulateLap();
final AtomicLong before = histogram.putIfAbsent(totalExecTimer.getCumulativeTime() / 1000, new AtomicLong(1L));
if (before != null) {
before.incrementAndGet();
}
}
}
</code></pre>
<p>Below is the <code>StopWatch class</code></p>
<pre><code>/**
* A simple stop watch.
*/
protected static class StopWatch {
private final String name;
private long lapStart;
private long cumulativeTime;
public StopWatch(String _name) {
name = _name;
}
/**
* Resets lap start time.
*/
public void resetLap() {
lapStart = System.currentTimeMillis();
}
/**
* Accumulates the lap time and return the current lap time.
*
* @return the current lap time.
*/
public long accumulateLap() {
long lapTime = System.currentTimeMillis() - lapStart;
cumulativeTime += lapTime;
return lapTime;
}
/**
* Gets the current cumulative lap time.
*
* @return
*/
public long getCumulativeTime() {
return cumulativeTime;
}
public String getName() {
return name;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append("=");
sb.append((cumulativeTime / 1000));
sb.append("s");
return sb.toString();
}
}
</code></pre>
<p>After running the above program, I can see 400 rows got inserted. And when it is printing the histogram, I am only seeing like this-</p>
<pre><code>{0=400}
</code></pre>
<p>which means 400 calls came back in 0 seconds? It's not possible for sure.</p>
<p><strong>I am just trying to see how much time each thread is taking to insert the record and then store those numbers in a <code>Map</code> and print that map from the main thread.</strong> </p>
<p>I think the problem I am assuming it's happening because of thread safety here and that is the reason whenever it is doing <code>resetlap</code> zero is getting set to Map I guess.</p>
<p>If yes how can I avoid this problem? And also it is required to pass <code>histogram map</code> from the main thread to constructor of Task? As I need to print that Map after all the threads are finished to see what numbers are there.</p>
<p><strong>Update:-</strong>
If I remove <code>divide by 1000</code> thing to store the number as milliseconds then I am able to see some numbers apart from <code>zero</code>. So that looks good. </p>
<p>But One thing more I found out is that numbers are not consistent, If I sum up each threads time, I will get some number for that. And I also I am printing how much time in which whole program is finishing as well. SO I compare these two numbers they are different by big margin</p>
| 3 | 1,613 |
Showing up highchart after submitting form in other file
|
<p>Kindly need help...
I want to show Highchart in file_1, when highchart script is on file_2..
i'm using PHP, Jquery and AJAX...
here is the script</p>
<p>SCR_test02.php </p>
<pre><code><?php
require "function.inc.php";
//require "showscr.php";
include "conn.php";
include "q_table.php";
?>
<form name="scr_form">
<table border="1" align="center" width="80%">
<tr>
<td align="center">
<input type="button" onClick="SCRajaxFunction()" value="Submit" id="sub">
</td>
<td>
<input type="reset">
</td>
</tr>
<tr>
<td colspan="6">&nbsp;
<div id="scr"></div>
</td>
</tr>
</table>
</form>
<script src="../Highcharts-3.0.5/js/highcharts.js"></script>
</html>
</code></pre>
<p>function.inc</p>
<pre><code>var htmlobjek;
$(document).ready(function()
{
$("#region").change(function()
{
var region = $("#region").val();
$.ajax(
{
url: "GetMSC.php",
data: "region="+region,
cache: false,
success: function(msg)
{
$("#msc").val(msg);
}
});
});
});
//Ketika form di submit
function SCRajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
var ajaxDisplay = document.getElementById('scr');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var period = document.getElementById('period').value;
var datefrom = document.getElementById('datefrom').value;
var dateto = document.getElementById('dateto').value;
var region = document.getElementById('region').value;
var msc = document.getElementById('msc').value;
//var rows = document.getElementById('rows').value;
var dataString = "?datefrom=" + datefrom + "&dateto=" + dateto + "&region=" + region + "&msc=" + msc + "&period=" + period;// + "&rows=" + rows;
ajaxRequest.open("GET", "ShowSCR.php" + dataString, true);
ajaxRequest.send(null);
}
</code></pre>
<p> </p>
<p>ShowSCR</p>
<pre><code><html>
<?
require "function.inc.php";
//require "highchart_tes.php";
include "conn.php";
$period = $_GET['period'];
$datefrom = $_GET['datefrom'];
$dateto = $_GET['dateto'];
$region = $_GET['region'];
$msc = $_GET['msc'];
$drop=array();
$drop2=array();
$traffic=array();
$data1=array();
$data2=array();
$sql = "SELECT distinct Date_id, hour_id
FROM scrkpi_h
WHERE Date_id >= '2012-12-01'
AND Date_id <= '2012-12-03'
AND MSC like 'MSBDL%'
ORDER BY Date_id ASC ";
$qry = mysql_query($sql,$koneksi) or die ("Gagal Query - ".mysql_error());
while ($data=mysql_fetch_array($qry))
{
$a = date('Y-m-d ', strtotime($data['Date_id']));
$data1[] = $a. $data[1];
}
?>
<script type="text/javascript" src="../Highcharts-3.0.5/js/type/jquery-1.7.1.min.js"></script>
<script src="../Highcharts-3.0.5/js/highcharts.js"></script>
<script type="text/javascript">
var chart1;
$(document).ready(function()
{
chart1 = new Highcharts.Chart(
{
chart: {
renderTo: 'scr_core'
},
title: {
text: 'SCR Core ',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis:
{
categories: ['<?php echo join($data1, "','") ?>'],
//['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
labels:
{
rotation: -90
}
},
yAxis: {
title: {
text: '%'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y +' % (percentage)';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series:
[
<?php //query tiap msc lbih dulu, baru tiap msc diambil datanya, dijadikan data berjajar berdasar koma
$sql = "SELECT distinct msc_id, MSC
FROM `scrkpi_h`
WHERE MSC like 'MSBDL%'"; //buat data di legend
$query = mysql_query( $sql );
while( $ret = mysql_fetch_array( $query ) ){
$nId = $ret[0]; //query dari scrkpi_h, msc_id = array 0
$nodes = $ret[1];
$sql_ = "SELECT * FROM `scrkpi_h`
WHERE `msc_id`='$nId'
AND Date_id >= '2012-12-01'
AND Date_id <= '2012-12-03'
AND MSC like 'MSBDL%'
ORDER BY Date_id ASC ";
$query_ = mysql_query( $sql_ );
$data = "";
while( $ret_ = mysql_fetch_array( $query_ ) ){
$kel = $ret_['scrCombine'];
$data = $data . "," . $kel;
}
$data = substr( $data , 1 , strlen( $data ) );
?>
{
name: '<?php echo $nodes; ?>',
data: [<?php echo $data; ?>]
},
<?php
}
?>
]
});
});
</script>
<div id='scr_core' style='min-width: 10px; height: 10px; margin: 0'></div>
</html>
</code></pre>
<p>The chart already show on file ShowSCR.php
But i want to show it on file SCR_test02.php at div="scr" when i click "submit" button
how to work it out, i have try many times but not working, really need help</p>
| 3 | 4,194 |
MongoDB aggregation graphlookup child's parent
|
<p>I've got some documents representing folders. I'd like to match every folder's parent if it has one.</p>
<pre><code>{"_id":{"$oid":"5f8c406fc8c88110e0d927f2"},"name":"A"}
{"_id":{"$oid":"5f8c406fc8c88110e0d927f3"},"parentFolderId":"5f8c406fc8c88110e0d927f2","name":"B"}
</code></pre>
<p>Even if the parent-child relationships are deeper, for <strong>A</strong> I need an <strong>empty parent folder</strong>, and for <strong>B</strong> <strong>parent folder A</strong>. I tried to use GraphLookup for this but it's not working (every <code>parentFolder</code> is empty), and I don't know what I'm missing:</p>
<pre><code>db.folders.aggregate([
{
$addFields: {
convertedId: { $toString: "$_id" }
}
},
{
$graphLookup: {
from: "folders",
startWith: "$parentFolderId",
connectFromField: "parentFolderId",
connectToField: "convertedId",
as: "parentFolder",
maxDepth: 0,
}
}
])
</code></pre>
<p>If I flip the <code>startWith</code>, <code>connectFromField</code>, <code>connectToFields</code> respectively, I get the <em>reverse</em> of what I need, A has an array which is containing B, B has nothing.</p>
<p>Edit:</p>
<p>With the non-working lookup, I get the following result:</p>
<pre><code>{ "_id" : ObjectId("5f8c406fc8c88110e0d927f2"), "name" : "A", "convertedId" : "5f8c406fc8c88110e0d927f2", "parentFolder" : [ ] }
{ "_id" : ObjectId("5f8c406fc8c88110e0d927f3"), "parentFolderId" : "5f8c406fc8c88110e0d927f2", "name" : "B", "convertedId" : "5f8c406fc8c88110e0d927f3", "parentFolder" : [ ] }
</code></pre>
<p>What I'd need is something like:</p>
<pre><code>{ "_id" : ObjectId("5f8c406fc8c88110e0d927f2"), "name" : "A", "convertedId" : "5f8c406fc8c88110e0d927f2", "parentFolder" : [ ] }
{ "_id" : ObjectId("5f8c406fc8c88110e0d927f3"), "parentFolderId" : "5f8c406fc8c88110e0d927f2", "name" : "B", "convertedId" : "5f8c406fc8c88110e0d927f3", "parentFolder" : [ { "_id" : ObjectId("5f8c406fc8c88110e0d927f2"), "name" : "A", "convertedId" : "5f8c406fc8c88110e0d927f2" } ] }
</code></pre>
<p>The only difference I see from the official "reportsTo" example that I'm using the ID field to match the documents, but that shouldn't be a problem, since I'm not using the ObjectID: <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/" rel="nofollow noreferrer">https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/</a></p>
| 3 | 1,465 |
When i click on login button then i want to go homepage with the help of react-router but it is not working in my code if anyone can help me in this
|
<p><strong>App.js</strong>
this is App.js file where I'm connecting one to another</p>
<pre><code>import LoginForm from "./components/login/LoginForm";
import Homepage from "./components/pages/HomePage";
import { Route, Switch, Redirect } from "react-router-dom";
import { useContext } from "react";
import HooteContext from "./store/hoote-context";
import Layout from "./components/Layout/Layout";
function App() {
const hooteCtx = useContext(HooteContext);
const isLoggedIn = hooteCtx.isLoggedIn;
return (
<>
<Layout>
<Switch>
<Route path="/" exact>
<LoginForm />
</Route>
{console.log(isLoggedIn)}
<Route path="/home">{isLoggedIn && <Homepage />}
{/* {!isLoggedIn && <Redirect to='/'></Redirect>} */}
</Route>
{/* <Route path="/login">{!isLoggedIn && <LoginForm />}</Route> */}
<Route path="*">
<Redirect to="/"></Redirect>
</Route>
</Switch>
</Layout>
</>
);
}
export default App;
</code></pre>
<p><strong>StartingPage.js</strong>
this is my startingpage component (homepage). I want go on this page when I click on login button</p>
<pre><code>import "./StartingPage.css";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import HooteContext from "../../store/hoote-context";
import { useContext } from "react";
import { Link } from "react-router-dom";
const StartingPage = () => {
const hooteCtx = useContext(HooteContext);
const isLoggedIn = hooteCtx.isLoggedIn;
// const logoutHandler = () => {
// hooteCtx.logout;
// };
return (
<> <Link to="/home">
<Box sx={{ flexGrow: 1 }}>
{isLoggedIn && <AppBar position="static">
<Toolbar>
<IconButton
size="large"
edge="start"
color="inherit"
aria-label="menu"
sx={{ mr: 2 }}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
News
</Typography>
<Button color="inherit" >
Logout
</Button>
</Toolbar>
</AppBar>}
</Box>
</Link>
{isLoggedIn && <div className="main">
<img className="img_logo" src="./image.png" alt="img" />
<h1 className="content">Content Management System</h1>
</div>}
</>
);
};
export default StartingPage;
</code></pre>
<p><strong>HomePage</strong></p>
<pre><code> import StartingPage from "../StartingPage/StartingPage";
const Homepage = () => {
return <div>
<StartingPage/>
</div>;
};
export default Homepage;
</code></pre>
<p><strong>LoginForm.js</strong>
This is my loginform component where I fetch login Api and signup Api from firebase and I also use material ui for styling</p>
<pre><code> import React, { useState, useRef, useContext } from "react";
// import * as React from 'react';
import Avatar from "@mui/material/Avatar";
import Button from "@mui/material/Button";
// import CssBaseline from '@mui/material/CssBaseline';
import TextField from "@mui/material/TextField";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/material/Checkbox";
import Link from "@mui/material/Link";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import Typography from "@mui/material/Typography";
import { useHistory } from "react-router";
import HooteContext from "../../store/hoote-context";
// import Container from '@mui/material/Container';
// import { createTheme, ThemeProvider } from '@mui/material/styles';
function Copyright(props) {
return (
<Typography
variant="body2"
color="text.secondary"
align="center"
{...props}
>
{"Copyright © "}
<Link color="inherit" href="https://d3gguh60q65ov3.cloudfront.net/#/">
Your Website
</Link>{" "}
{new Date().getFullYear()}
{"."}
</Typography>
);
}
// const theme = createTheme();
const LoginForm = () => {
const hooteCtx=useContext(HooteContext)
const history=useHistory()
const emailInputRef = useRef();
const passwordInputRef = useRef();
const [isLogin, setIsLogin] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const switchAuthModeHandler = () => {
setIsLogin((prevState) => !prevState);
};
const handleSubmit = (event) => {
event.preventDefault();
// const data = new FormData(event.currentTarget);
const enteredEmail = emailInputRef.current.value;
const enteredPassword = passwordInputRef.current.value;
// const formData = {
// email: enteredEmail,
// password: enteredPassword,
// };
// console.log({
// email: data.get('email'),
// password: data.get('password'),
// });
// console.log(formData);
setIsLoading(true);
let url;
if (isLogin) {
url =
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?
key=AIzaSyA7UUC0bXrduiMDaD5Gx-P7JJppWn3yy2g";
} else {
url =
"https://identitytoolkit.googleapis.com/v1/accounts:signUp?
key=AIzaSyA7UUC0bXrduiMDaD5Gx-P7JJppWn3yy2g";
}
fetch(url, {
method: "POST",
body: JSON.stringify({
email: enteredEmail,
password: enteredPassword,
returnSecureToken: true,
}),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
setIsLoading(false);
if (res.ok) {
return res.json();
} else {
return res.json().then((data) => {
console.log(data)
let errorMessage = "Authentication Failed";
throw new Error(errorMessage);
});
}
})
.then((data) => {
hooteCtx.login(data.idToken )
history.replace('/home')
})
.catch((err) => {
alert(err.message);
});
};
return (
<>
{/* <ThemeProvider theme={theme}>
<Container component="main" maxWidth="xs">
<CssBaseline /> */}
<Grid container justifyContent="center" alignItems="center">
<Box
sx={{
marginTop: 8,
display: "flex",
flexDirection: "column",
alignItems: "center",
width: 400,
}}
>
<Avatar sx={{ m: 1, bgcolor: "secondary.main" }}>
<LockOutlinedIcon />
</Avatar>
{isLogin ? (
<Typography component="h1" variant="h5">
Sign In
</Typography>
) : (
<Typography component="h1" variant="h5">
Sign Up
</Typography>
)}
<Box
component="form"
onSubmit={handleSubmit}
noValidate
sx={{ mt: 1 }}
>
<TextField
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
// autoComplete="email"
autoFocus
inputRef={emailInputRef}
/>
<TextField
margin="normal"
required
fullWidth
name="password"
minLength="6"
label="Password"
type="password"
id="password"
// autoComplete="current-password"
inputRef={passwordInputRef}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
{isLogin ? (
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Login
</Button>
) : (
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Create Account
</Button>
)}
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
{isLoading && <p>Sending request...</p>}
{isLogin ? (
<Link
href="#"
variant="body2"
onClick={switchAuthModeHandler}
>
Don't have an account? Sign Up
</Link>
) : (
<Link
href="#"
variant="body2"
onClick={switchAuthModeHandler}
>
Login with existing account
</Link>
)}
</Grid>
</Grid>
</Box>
</Box>
</Grid>
<Copyright sx={{ mt: 8, mb: 4 }} />
{/* </Container>
</ ThemeProvider> */}
</>
);
};
export default LoginForm;
</code></pre>
<p><strong>Layout.js</strong></p>
<pre><code> import StartingPage from "../StartingPage/StartingPage";
const Layout =(props)=>{
return (
<>
<StartingPage/>
<main>{props.children}</main>
</>
);
}
export default Layout
</code></pre>
<p><strong>hoote-context.js</strong></p>
<pre><code> import React, { useState } from "react";
const HooteContext = React.createContext({
token: "",
isLoggedIn: false,
login: (token) => {},
logout: () => {},
});
export const HooteContextProvider = (props) => {
// let initialToken;
// if (tokenData) {
// initialToken = tokenData.token;
// }
const [token, setToken] = useState(null);
const userIsLoggedIn = !!token;
const loginHandler = () => {
setToken(token);
};
const logoutHandler = () => {
setToken(null);
};
const contextValue = {
token: token,
isLoggedIn: userIsLoggedIn,
login: loginHandler,
logout: logoutHandler,
};
return (
<HooteContext.Provider value={contextValue}>
{props.children}
</HooteContext.Provider>
);
};
export default HooteContext;
</code></pre>
| 3 | 6,708 |
android how to have a fixed layout but it will also adjust itself on different screensize
|
<p>I am developing some calculation app. This app will display the results on a table. For now i use "wrap_content" on height and width plus weight of my layout which will make it adjusting the border itself. However this make the table looks poorly designed . The example::</p>
<p>What i want it look like: the value inside it will not change the borders.</p>
<pre><code> ____________________________________________________
| Prepaid |
|____________________________________________________|
| Years | First Payment | Permonth Payment |
|_________|_______________________|__________________|
| Year1 | 1231234345345 | 123123123 |
|_________|_______________________|__________________|
| Year2 | 78978978978999 | 12312312312 |
|_________|_______________________|__________________|
| Year3 | 5675675675677 | 6789679677 |
|_________|_______________________|__________________|
| Year4 | 6786786786786 | 456456456 |
|_________|_______________________|__________________|
| Year5 | 45645645645666 | 345345 |
|_________|_______________________|__________________|
</code></pre>
<p>But what's happening :</p>
<pre><code> ____________________________________________________
| Prepaid |
|____________________________________________________|
| Years | First Payment | Permonth Payment |
|_________|_______________________|__________________|
|Year1| 1231234345345 | 123123123 |
|____ |____________________|_________________________|
|Year2| 78978978978999 | 2312312 |
|_____|___________________________|__________________|
|Year3| 5675675675677 | 6789679677 |
|_____|_______________________|______________________|
|Year4| 6786786786786 | 456456456 |
|_____|_______________________|______________________|
|Year5| 45645645645666 | 345345 |
|_____|_________________________|____________________|
</code></pre>
<p>my xml code for tables:</p>
<pre><code> <TableLayout
android:id="@+id/table1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="8dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="80dp"
android:orientation="vertical" >
<TextView
android:id="@+id/idAADM"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape1"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/AADM"
android:textColor="#000000"
android:textSize="8sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<TextView
android:id="@+id/idtenor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="11"
android:background="@drawable/cell_shape1"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/tenor"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/tppm"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="69"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/angm"
android:textColor="#000000"
android:textSize="8sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<TextView
android:id="@+id/id1thn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/thn1"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbalaa1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbal1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<TextView
android:id="@+id/id2thn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/thn2"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbalaa2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbal2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<TextView
android:id="@+id/id3thn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/thn3"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbalaa3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbal3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<TextView
android:id="@+id/id4thn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/thn4"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbalaa4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbal4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/id5thn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:text="@string/thn5"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbalaa5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
<TextView
android:id="@+id/tumbal5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="48"
android:background="@drawable/cell_shape"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:paddingTop="3dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="8sp" />
</LinearLayout>
</LinearLayout>
</TableLayout>
</code></pre>
<p>my custom drawable cell_shape and cell_shape1 (same code both)</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#ffffff"/>
<stroke
android:width="1dp"
android:color="#000" />
</shape>
</code></pre>
<p>How to have a fixed table that will not change whenever the value gets longer or shorter. And this layout will also not change the size if the screen is different(not changing in different screensize)</p>
| 3 | 9,252 |
Nullpointer returned by function implemented in Locally bounded service in android
|
<p>I am writing a locally bound service in android.My application has two classes
viz. Activity and a Service</p>
<p>In my activity I have one TextView and one button.
I am starting and binding the service in onCreate() method of the activity.
When the button is getting clicked I want my TextView to be upadated with a String value returned from a fucntion written in the Service class</p>
<p>But I am getting null as return value always.What may be the problem?</p>
<p>I am giving my entire code here</p>
<p>This is activity class</p>
<pre><code> package com.tcs.cto.healthcare;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.tcs.cto.healthcare.GlucoseDataService.LocalUSBSerialBinder;
public class HealthcareCTOActivity extends Activity {
Button getDataButton;
TextView dataView;
String TAG="HealthCareCTO";
String glucoseData;
GlucoseDataService myService;
boolean isBound = false;
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
LocalUSBSerialBinder binder = (LocalUSBSerialBinder) service;
myService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_healthcare_cto);
getDataButton=(Button)findViewById(R.id.button1);
dataView=(TextView)findViewById(R.id.glucoseDataView);
Intent intent = new Intent(this, GlucoseDataService.class);
startService(intent);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
Log.i(TAG,"Glucose Service Started");
//getDataButton=(Button)findViewById(R.id.button1);
//dataView=(TextView)findViewById(R.id.glucoseDataView);
getDataButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
Log.i(TAG,"Button clicked");
try{
//glucoseData = myService.getGlucoseValueOverSerialPort();
String currentTime="XXX";
currentTime = myService.getCurrentTime();
//glucoseData = myService.getGlucoseValueOverSerialPort();
//Log.i(TAG,"glucoseData --> "+glucoseData);
Log.i(TAG,"currentTume --> "+currentTime);
dataView.setText(currentTime);
}catch(Exception ex){
Log.i(TAG,"Button click exception");
ex.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_healthcare_cto, menu);
return true;
}
</code></pre>
<p>}</p>
<p>And my service class is as follows</p>
<pre><code>package com.tcs.cto.healthcare;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class GlucoseDataService extends Service {
private final IBinder myBinder = new LocalUSBSerialBinder();
String glucoseData="0000";
String TAG="GlucoseService";
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public String getGlucoseValueOverSerialPort(){
int glucoseValue=120;
glucoseData=String.valueOf(glucoseValue);
return glucoseData;
}
public String getCurrentTime() {
Log.i(TAG,"getCurrentTime");
SimpleDateFormat dateformat =
new SimpleDateFormat("HH:mm:ss MM/dd/yyyy", Locale.US);
return (dateformat.format(new Date()));
}
public class LocalUSBSerialBinder extends Binder {
GlucoseDataService getService() {
return GlucoseDataService.this;
}
</code></pre>
<p>};
}</p>
| 3 | 1,660 |
How do I stop my sql query from displaying the results twice?
|
<p>How do I stop the results from getting displayed twice on the web page? What have I done wrong? Yes this is for a game but it helps me learn SQL and PHP. Please be genital it's my first time.
There is one database with two tables. The database is game_tittle the two tables are player_data and the second is character_data.</p>
<pre><code><?php
include('db_conn.php');
#for connecting to SQL
$sqlget = "SELECT player_data.PlayerName, Character_data.Duration, character_data.KillsZ, character_data.KillsB, character_data.KillsH, character_data.HeadshotsZ, character_data.Humanity, character_data.Generation, character_data.InstanceID FROM player_data, character_data";
$sqldata = mysqli_query($dbcon, $sqlget) or die('error getting data');
echo "<center><table>";
echo "<tr> <th>Player Name</th><th>play time</th><th>Total Kills</th><th>Bandit kills</th><th>Hero Kills</th><th>Head shots</th><th>Humanity</th><th>Alive count</th><th>Instance ID</tr>";
while ($row = mysqli_fetch_array($sqldata)) {
echo "<tr><td>";
echo $row['PlayerName'];
echo "</td><td>";
echo $row['Duration'];
echo "</td><td>";
echo $row['KillsZ'];
echo "</td><td>";
echo $row['KillsB'];
echo "</td><td>";
echo $row['KillsH'];
echo "</td><td>";
echo $row['HeadshotsZ'];
echo "</td><td>";
echo $row['Humanity'];
echo "</td><td>";
echo $row['Generation'];
echo "</td><td>";
echo $row['InstanceID'];
echo "</td></tr>";
echo "</center>";
}
echo "</table>";
#end of table
?>
</code></pre>
<p>Got it to work this way.</p>
<pre><code><?php
include('db_conn.php');
$sqlget = "SELECT player_data.PlayerUID, character_data.PlayerUID, player_data.PlayerName, character_data.HeadshotsZ, character_data.KillsZ, character_data.KillsH, character_data.KillsB, character_data.Alive, character_data.Generation, character_data.Humanity, character_data.InstanceID FROM player_data INNER JOIN character_data ON player_data.PlayerUID = character_data.PlayerUID";
$sqldata = mysqli_query($dbcon, $sqlget) or die('error getting data');
echo "<center><table>";
echo "<tr> <th>Player Name</th><th>Head shots</th><th>Total Kills</th><th>Hero kills</th><th>Bandit Kills</th><th>Live or dead</th><th>Lifes</th><th>Humanity</th><th>Instance ID</tr>";
while ($row = mysqli_fetch_assoc($sqldata)) {
echo "<tr><td>";
echo $row['PlayerName'];
echo "</td><td>";
echo $row['HeadshotsZ'];
echo "</td><td>";
echo $row['KillsZ'];
echo "</td><td>";
echo $row['KillsH'];
echo "</td><td>";
echo $row['KillsB'];
echo "</td><td>";
echo $row['Alive'];
echo "</td><td>";
echo $row['Generation'];
echo "</td><td>";
echo $row['Humanity'];
echo "</td><td>";
echo $row['InstanceID'];
echo "</td></tr>";
echo "</center>";
}
echo "</table>";
#end of table
?>
</code></pre>
| 3 | 1,591 |
ArrayAdapter error when more than one item is in the array
|
<p>I have a error when I get an array which has more than one value in it the ListView... it crashes... </p>
<p>str_amparticipant_firstname is an array of string values.
str_pmparticipant_firstname is also an array of string values. </p>
<pre><code> adapteram = new ArrayAdapter<String>(Attend.this, android.R.layout.simple_list_item_1, str_amparticipant_firstname);
adapterpm = new ArrayAdapter<String>(Attend.this, android.R.layout.simple_list_item_1, str_pmparticipant_firstname);
amattendees.setAdapter(adapteram);
pmattendees.setAdapter(adapterpm);
</code></pre>
<p>The class is called Attend. the ListViews show the values in the array when there is one value in the array. If there is more than one value the app crashes. I have checked that the array is being filled correctly and it is. Hopefully the error log has the answer. The error log I am getting is below:</p>
<pre><code>04-16 19:28:57.664: E/AndroidRuntime(5807): FATAL EXCEPTION: main
04-16 19:28:57.664: E/AndroidRuntime(5807): java.lang.NullPointerException
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.AbsListView.obtainView(AbsListView.java:1430)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.ListView.measureHeightOfChildren(ListView.java:1307)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.ListView.onMeasure(ListView.java:1127)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.View.measure(View.java:8510)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3202)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:701)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.LinearLayout.onMeasure(LinearLayout.java:311)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.View.measure(View.java:8510)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3202)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.View.measure(View.java:8510)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3202)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.View.measure(View.java:8510)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.View.measure(View.java:8510)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3202)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.View.measure(View.java:8510)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.ViewRoot.performTraversals(ViewRoot.java:871)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.view.ViewRoot.handleMessage(ViewRoot.java:1921)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.os.Looper.loop(Looper.java:143)
04-16 19:28:57.664: E/AndroidRuntime(5807): at android.app.ActivityThread.main(ActivityThread.java:4196)
04-16 19:28:57.664: E/AndroidRuntime(5807): at java.lang.reflect.Method.invokeNative(Native Method)
04-16 19:28:57.664: E/AndroidRuntime(5807): at java.lang.reflect.Method.invoke(Method.java:507)
04-16 19:28:57.664: E/AndroidRuntime(5807): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-16 19:28:57.664: E/AndroidRuntime(5807): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-16 19:28:57.664: E/AndroidRuntime(5807): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>again the error only appears when there is more than one value in the array. I have tried to find an answer to this problem but I couldnt find any info on the error. please help! thankyou!</p>
<p>UPDATE: this is how the array is filled and created:</p>
<pre><code>for(int i = 0; i < json_array_amparticipants.length(); i++){
//store all the amparticipants
str_amparticipant_email = new String[json_array_amparticipants.length()];
str_amparticipant_firstname = new String[json_array_amparticipants.length()];
str_amparticipant_lastname = new String[json_array_amparticipants.length()];
str_amparticipant_attendingam = new String[json_array_amparticipants.length()];
str_amparticipant_attendingpm = new String[json_array_amparticipants.length()];
//full_name_am = new String[json_array_amparticipants.length()];
str_amparticipant_email[i] = json_array_amparticipants.getJSONObject(i).getString("email");
str_amparticipant_firstname[i] = json_array_amparticipants.getJSONObject(i).getString("first_name");
str_amparticipant_lastname[i] = json_array_amparticipants.getJSONObject(i).getString("last_name");
str_amparticipant_attendingam[i] = json_array_amparticipants.getJSONObject(i).getString("attending_am");
str_amparticipant_attendingpm[i] = json_array_amparticipants.getJSONObject(i).getString("attending_pm");
//full_name_am[i] = str_amparticipant_firstname[i] + str_amparticipant_lastname[i];
}
</code></pre>
<p>FIXED: I am creating new arrays every time so it still stores the value but it causes the crash... heres the updated fix. Cheers guys:</p>
<pre><code> //store all the amparticipants
str_amparticipant_email = new String[json_array_amparticipants.length()];
str_amparticipant_firstname = new String[json_array_amparticipants.length()];
str_amparticipant_lastname = new String[json_array_amparticipants.length()];
str_amparticipant_attendingam = new String[json_array_amparticipants.length()];
str_amparticipant_attendingpm = new String[json_array_amparticipants.length()];
for(int i = 0; i < json_array_amparticipants.length(); i++){
//full_name_am = new String[json_array_amparticipants.length()];
str_amparticipant_email[i] = json_array_amparticipants.getJSONObject(i).getString("email");
str_amparticipant_firstname[i] = json_array_amparticipants.getJSONObject(i).getString("first_name");
str_amparticipant_lastname[i] = json_array_amparticipants.getJSONObject(i).getString("last_name");
str_amparticipant_attendingam[i] = json_array_amparticipants.getJSONObject(i).getString("attending_am");
str_amparticipant_attendingpm[i] = json_array_amparticipants.getJSONObject(i).getString("attending_pm");
//full_name_am[i] = str_amparticipant_firstname[i] + str_amparticipant_lastname[i];
}
</code></pre>
| 3 | 3,513 |
How to loop data imported from SQLite database
|
<p>I am building an <strong>Express</strong> app ,and i am using <strong>SQLite</strong> database, I managed to fetch the data from the database, but I want to display it in the interface ,So i did this :</p>
<p><strong>index.js</strong></p>
<pre class="lang-js prettyprint-override"><code>/* GET THE LIST OF HOMES*/
router.get('/:homes-list', (req,res) => {
db.all( "SELECT * FROM home WHERE owner_id = ?",[
req.user.id
],
function(err, rows) {
if (err) { return next(err); }
const home = rows.map(function(row) {
return {
location: row.location,
for: row.for,
}
});
res.locals.homes = home;
console.log(res.locals.homes)
res.redirect("/:homes-list", {home: res.locals.homes})
});
});
</code></pre>
<p>Then I tried to display it for the user interface using <strong>EJS:</strong></p>
<p><strong>index.ejs</strong></p>
<pre class="lang-html prettyprint-override"><code>
<form action="/:homes-list" method="get">
<table>
<tbody>
<% home.forEach(function(homes) { %>
<tr>
<td><%= homes.location %></td>
<td><%= homes.for %></td>
</tr>
<% }); %>
</tbody>
</table>
</form>
</code></pre>
<p>After i did all that i had an <strong>error:</strong></p>
<p><strong>Error</strong></p>
<pre><code>/media/onour/Desing/Des/test/roshan/views/index.ejs:45 43| <table> 44| <tbody> >> 45| <% home.forEach(function(homes) { %> 46| <tr> 47| <td><%= homes.location %></td> 48| <td><%= homes.for %></td> home is not defined
ReferenceError: /media/onour/Desing/Des/test/roshan/views/index.ejs:45
43| <table>
44| <tbody>
>> 45| <% home.forEach(function(homes) { %>
46| <tr>
47| <td><%= homes.location %></td>
48| <td><%= homes.for %></td>
home is not defined
at eval (eval at compile (/media/onour/Desing/Des/test/roshan/node_modules/ejs/lib/ejs.js:633:12), <anonymous>:11:8)
at returnedFn (/media/onour/Desing/Des/test/roshan/node_modules/ejs/lib/ejs.js:668:17)
at tryHandleCache (/media/onour/Desing/Des/test/roshan/node_modules/ejs/lib/ejs.js:254:36)
at View.exports.renderFile [as engine] (/media/onour/Desing/Des/test/roshan/node_modules/ejs/lib/ejs.js:485:10)
at View.render (/media/onour/Desing/Des/test/roshan/node_modules/express/lib/view.js:135:8)
at tryRender (/media/onour/Desing/Des/test/roshan/node_modules/express/lib/application.js:640:10)
at Function.render (/media/onour/Desing/Des/test/roshan/node_modules/express/lib/application.js:592:3)
at ServerResponse.render (/media/onour/Desing/Des/test/roshan/node_modules/express/lib/response.js:1008:7)
at /media/onour/Desing/Des/test/roshan/routes/index.js:22:7
at Layer.handle [as handle_request] (/media/onour/Desing/Des/test/roshan/node_modules/express/lib/router/layer.js:95:5)
</code></pre>
<p>and i didn't understand the error, so i didn't know what to do.</p>
| 3 | 1,875 |
jQuery Toggle button not clickable after first click
|
<p>The menu expands and contracts when I click on a button.
The button toggles the "active" class when I click it as expected with only the code required for that action.
However, when I add the code to make the the menu contract when clicking elsewhere on the page, it only contracts when clicking everything EXCEPT for the button.
The button is no longer clickable and the menu remains expanded until I click on a link or on the body of the page.</p>
<p>EDIT: As I was typing this out on a jsfiddle, I got an error on that console that I don't see in my dev tools:
<strong>Uncaught ReferenceError: jQuery is not defined</strong>
The reason why I am not using the "$"symbol that I see everyone using, and I am writting out "jQuery" in front of everything is because that's the only way I could make DIVI (the wordpress builder) compile the code</p>
<pre><code>jQuery(document).ready(function(){
jQuery('.nav__button').click(function(){
jQuery(this).toggleClass('button--active');
jQuery('.nav__row').toggleClass('nav__row--active');
});
});
jQuery(document).mouseup(e => {
if (!jQuery('nav__container').is(e.target)
&& jQuery('nav__container').has(e.target).length === 0) {
jQuery('.nav__row').removeClass('nav__row--active');
jQuery('.nav__button').removeClass('button--active');
}
});
</code></pre>
<p>And If I add this line of code, I break the code all together.</p>
<pre><code>jQuery('.nav__button').is(e.target) ||
</code></pre>
<p>This line is added to the second function, to say that "If I click on the button OR elsewhere" [contract the menu]</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery(document).ready(function(){
jQuery('.nav__button').click(function(){
jQuery(this).toggleClass('button--active');
jQuery('.nav__row').toggleClass('nav__row--active');
});
});
jQuery(document).mouseup(e => {
if (!jQuery('nav__container').is(e.target)
&& jQuery('nav__container').has(e.target).length === 0) {
jQuery('.nav__row').removeClass('nav__row--active');
jQuery('.nav__button').removeClass('button--active');
}
});
</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav__row {
transition: .3s;
overflow: visible !important;
}
.nav__container {
display: flex;
justify-content: space-around;
height: 30px;
}
.nav__container img {
height: 14px;
margin-top: auto;
}
.nav__link-panel {
position: absolute;
width: 175px;
height: 220px;
top: 0;
left: 0;
text-align: right;
transform: translatex(-100%);
background-color: #dcf5ee;
padding-top: 75px !important;
padding-right: 25px !important;
display: flex;
flex-direction: column;
justify-content: space-around;
}
.nav__row.nav__row--active {
transition: .3s;
transform: translatex(70%);
}
/*Hamburger animation*/
.nav__button {
width: 24px;
height: 6px;
position: relative;
background: transparent;
transform: rotate(0deg);
transition: .5s ease-in-out;
cursor: pointer;
border: none;
}
.nav__button span {
display: block;
position: absolute;
height: 2px;
width: 100%;
background: red;
opacity: 1;
left: 0;
transform: rotate(0deg);
transition: .25s ease-in-out;
}
.nav__button span:nth-child(1) {
top: 0px;
transform-origin: left center;
}
.nav__button span:nth-child(2) {
top: 8px;
width: 80%;
transform-origin: left center;
}
.nav__button span:nth-child(3) {
top: 16px;
transform-origin: left center;
}
.nav__button.button--active span:nth-child(1) {
transform: rotate(45deg);
top: 0px;
left: 8px;
}
.nav__button.button--active span:nth-child(2) {
width: 0%;
opacity: 0;
}
.nav__button.button--active span:nth-child(3) {
transform: rotate(-45deg);
top: 17px;
left: 8px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav__container">
<div class="nav__menu">
<button class="nav__button">
<span></span>
<span></span>
<span></span>
</button>
<ul class="nav__link-panel" >
<li><a> Contact </a></li>
</ul>
</div>
</div></code></pre>
</div>
</div>
</p>
| 3 | 1,799 |
Instantaneous change in velocity using a velocity verlet integrator
|
<pre><code> var nx = x + velX * dt + accX * (dt * dt * 0.5);
var ny = y + velY * dt + accY * (dt * dt * 0.5);
var na = a + velA * dt + accA * (dt * dt * 0.5);
var nAccX = 0; var nAccY = 0;
var nAccA = 0;
var i = -1; repeat( ds_list_size(physics_forces) ) { i++;
var force = physics_forces[| i]; //r3_scale( physics_forces[| i], 1 / dt, physics_forces[| i] );
nAccX += clamp(force[0], -physics_maxImpulse, physics_maxImpulse);
nAccY += clamp(force[1], -physics_maxImpulse, physics_maxImpulse);
nAccA += clamp(force[2], -physics_maxImpulseAngular, physics_maxImpulseAngular);
}
ds_list_clear(physics_forces);
nAccX = clamp(nAccX, -physics_maxForce, physics_maxForce);
nAccY = clamp(nAccY, -physics_maxForce, physics_maxForce);
nAccA = clamp(nAccA, -physics_maxForceAngular, physics_maxForceAngular);
var nVelX = velX + (accX + nAccX) * (dt * 0.5);
var nVelY = velY + (accY + nAccY) * (dt * 0.5);
var nVelA = velA + (accA + nAccA) * (dt * 0.5);
x = nx;
y = ny;
a = na;
velX = nVelX;
velY = nVelY;
velA = nVelA;
accX = nAccX;
accY = nAccY;
accA = nAccA;
</code></pre>
<p>I have a relatively simple Velocity-Verlet Integrator set up, as seen here (per <a href="https://en.wikipedia.org/wiki/Verlet_integration#Velocity_Verlet" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Verlet_integration#Velocity_Verlet</a>)</p>
<pre><code>player_move = function(speedChannel, index = 1, magnitude = 1, direction = a) {
if (!is_undefined(speedChannel)) {
var _target = animcurve_channel_evaluate(speedChannel, index);
var _dirX = lengthdir_x(magnitude, direction);
var _dirY = lengthdir_y(magnitude, direction);
physics_applyForce( _target * _dirX - velX, _target * _dirY - velY );
}
}
physics_applyForce = function(fx, fy, _mode = FORCEMODE.IMPULSE) {
switch _mode {
case FORCEMODE.IMPULSE:
ds_list_add(physics_forces, [ fx, fy, 0 ])
break;
case FORCEMODE.CHANGE:
velX = fx;
velY = fy;
break;
}
}
</code></pre>
<p>I want to make my player's velocity follow the shape of a curve hence the acceleration applied is the difference between target speed scaled by movement direction and the velocity.
The issue with this is that, since the Integrator scales values by dt the <em>actual</em> acceleration is far lower than it needs to be.
I'm sure this is a simple fix but I really cannot quite figure out the math here.</p>
| 3 | 1,127 |
spatial domain convolution not equal to frequency domain multiplication using pytorch
|
<p>I want to verify if 2D convolution in spatial domain is really a multiplication in frequency domain, so I used pytorch to implement convolution of an image with a 3×3 kernel (both real). Then I transformed both the image and the kernel into frequency domain, multiplied them, transformed the result back to spatial domain. Here's the result:<br>
When the kernal is even or odd (i.e. pure real or pure imaginary in frequency domain), results of the two transforms seem to match well. I use min and max of both results to evaluate because I'm not sure if some margin alignment problems may affect direct difference. Here are three runs of either even and odd kernel:</p>
<pre><code># Even Kernel
min max with s-domain conv: -0.03659552335739136 4.378755569458008
min max with f-domain mul: -0.0365956649184227 4.378755569458008
min max with s-domain conv: -1.2673343420028687 2.397951126098633
min max with f-domain mul: -1.2673344612121582 2.397951126098633
min max with s-domain conv: -8.185677528381348 0.22980886697769165
min max with f-domain mul: -8.185677528381348 0.22980868816375732
# Odd Kernel
min max with s-domain conv: -1.6630988121032715 1.6592578887939453
min max with f-domain mul: -1.663098692893982 1.6592577695846558
min max with s-domain conv: -3.483165979385376 3.4751217365264893
min max with f-domain mul: -3.483165979385376 3.475121259689331
min max with s-domain conv: -1.7972984313964844 1.7931475639343262
min max with f-domain mul: -1.7972984313964844 1.7931475639343262
</code></pre>
<p>But if I use neither even or odd kernel, the difference is just at another level:</p>
<pre><code>min max with s-domain conv: -2.3028392791748047 1.675748348236084
min max with f-domain mul: -2.5289478302001953 1.4919483661651611
min max with s-domain conv: -1.1227827072143555 3.0336122512817383
min max with f-domain mul: -1.1954418420791626 2.9853036403656006
min max with s-domain conv: -1.6867876052856445 5.575590133666992
min max with f-domain mul: -1.6832940578460693 5.688591957092285
</code></pre>
<p>I was wondering if this arises from precision in floating point. But I tried torch's complex128, it wasn't any better. Is there something wrong with my implementation? Or it is inevitable due to calculation with complex numbers?</p>
<p>Here's a simplified version of my code that could produce this result.</p>
<pre><code>import torch.nn.functional as F
import torch.fft as fft
import torch, cv2
img = cv2.imread('test.png', 0)
x = torch.as_tensor(img).unsqueeze(0)/255
k = torch.randn(1, 1, 3, 3)
for i in range(k.size(0)):
for j in range(k.size(1)):
# For even k
# for p in range(k.size(2)):
# for q in range(k.size(3)):
# k[i, j, p, q] = k[i, j, 2-p, 2-q]
# For odd k
# for p in range(k.size(2)):
# k[i, j, p, 0] = -k[i, j, p, 2]
# k[i, j, p, 1] = 0
# for q in range(k.size(3)):
# k[i, j, 0, q] = -k[i, j, 2, q]
# k[i, j, 1, q] = 0
pass
### Spatial domain convolution
padx = F.pad(x, [1,1,1,1])
sdc = F.conv2d(padx.unsqueeze(0), k)
### Frequency domain convolution
# Transform input
fdx = fft.rfft2(x)
sdfdx = fft.irfft2(fdx)
# Transform kernel
size_diff = x.size(-1)-k.size(-1)
padk = torch.roll(F.pad(k, [0,size_diff,0,size_diff]), (-1,-1), (-1, -2))
fdk = fft.rfft2(padk)
# Frequency domain multiplication
fdc = fdk * fdx
fdc = fdc.squeeze(0)
# Back to spatial domain
sdfdc = fft.irfft2(fdc)
### Compare
print("min max with s-domain conv:", sdc.min().item(), sdc.max().item())
print("min max with f-domain mul:", sdfdc.min().item(), sdfdc.max().item())
</code></pre>
| 3 | 1,481 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.