title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Scala java.nio.charset.UnmappableCharacterException: Input length = 1 | <p>I've found several questions with similar titles, but couldn't seem to use any to resolve my issue. I Can't seem to load my .csv file:</p>
<pre><code>val source = io.Source.fromFile("C:/mon_usatotaldat.csv")
</code></pre>
<p>Returns:</p>
<blockquote>
<p>java.nio.charset.UnmappableCharacterException: Input length = 1</p>
</blockquote>
<p>So I tried:</p>
<pre><code>val source = io.Source.fromFile("UTF-8", "C:/mon_usatotaldat.csv")
</code></pre>
<p>and got:</p>
<blockquote>
<p>java.nio.charset.IllegalCharsetNameException: C:/mon_usatotaldat.csv</p>
</blockquote>
<p>I guess UTF-8 wouldn't work, if the file isn't in UTF-8 format, so that makes sense, but I don't know what to do next.</p>
<p>I've managed to discover the encoding is windows-1252 using:</p>
<pre><code>val source = io.Source.fromFile("C:/mon_usatotaldat.csv").codec.decodingReplaceWith("UTF-8")
</code></pre>
<p>But this didn't do what I had expected, which was convert the file to UTF-8. I have no Idea how to work with it.</p>
<p>Another thing I've tried was:</p>
<pre><code>val source = io.Source.fromFile("windows-1252","C:/mon_usatotaldat.csv")
</code></pre>
<p>But that returned:</p>
<blockquote>
<p>java.nio.charset.IllegalCharsetNameException: C:/mon_usatotaldat.csv</p>
</blockquote>
<p>Please help. Thanks in advance.</p> | 1 |
Drawing on a panel by clicking a button in WinForms | <p>I'm trying to make a program to draw on the a <code>Panel</code> (a square, circle, etc...) by clicking on a button.</p>
<p>I have not done much so far, just tried the code drawing directly to the panel but don't know how to move it to the button. Here is the code I have so far.</p>
<p>If you know a better method to draw than the one I'm using please let me know.</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void mainPanel_Paint(object sender, PaintEventArgs e)
{
Graphics g;
g = CreateGraphics();
Pen pen = new Pen(Color.Black);
Rectangle r = new Rectangle(10, 10, 100, 100);
g.DrawRectangle(pen, r);
}
private void circleButton_Click(object sender, EventArgs e)
{
}
private void drawButton_Click(object sender, EventArgs e)
{
}
}
</code></pre>
<p>}</p> | 1 |
How to extract a Google link's href from search results with Selenium? | <p>Ultimately I am just trying to get the href of the first link to google's search result</p>
<p>The information I need also exists in an 'a' element, but it is stored in a 'data-href' attribute, which I could not figure how to extract the data from (<code>get_attribute('data-href')</code> returns <code>None</code>).</p>
<p>I am using Phantomjs, but have also tried with Firefox web driver</p>
<hr>
<p>The href is displayed in a <code>cite</code> tag in a google search (which can be found by inspecting the small green link text under each link in google search results). </p>
<p>The cite element is apparently found with Selenium, but the text returned (<code>element.text</code>, or <code>get_attribute('innerHTML')</code>, or (<code>text</code>)) is not what is shown in the html.</p>
<p>For instance, there is a cite tag <code><cite class="_Rm">www.fcv.org.br/</cite></code>, but <code>element.text</code> shows “wikimapia.org/.../Fundação-Cristiano-Varella-Hospital...”</p>
<p>I have tried to retrieve the cite element with <code>by_css_selector</code>, <code>tag_name</code>, <code>class_name</code>, and xpath with the same results.</p>
<pre><code>links = driver.find_elements_by_css_selector('div.g') # div[class="g"]
link = links[0] # I am looking for the first link in the main links section
next = link.find_element_by_css_selector('div[class="s"]') # location of cite tag
nextB = next.find_element_by_tag_name('cite')
</code></pre>
<p>div containing cite tag (there is only one in the div)</p>
<pre><code> <div class="s">
<div>
<div class="f kv _SWb" style="white-space:nowrap">
<cite class="_Rm">www.fcv.org.br/</cite>
</code></pre> | 1 |
How is it possible to get "ActiveRecord::DuplicateMigrationNameError" with only 1 migration file? | <p>Here is the setup. Have a Ruby off Rails API application setup. </p>
<p>It pulls in a "database creation application" independently via git submodule. There is a "db/migrate" folder with one migration file and a "db/structure.sql" file. The database creation project is essentially a slimmed down Rails project - we used Rails because we needed rake tasks to let us easily migrate.</p>
<p>The structure.sql file essentially recreates our old database schema (we decided to keep the database code in a separate repo due to having multiple apps that need to access the database and a desire to keep the database consistent as possible).</p>
<p>If I do <code>rake db:create</code> I get told that <code>app_development</code> and <code>app_test</code> exist. I've manually deleted the schema_migrations and schema_info tables from both. In fact app_test, is empty and contains no tables.</p>
<p>If I run rake db:migrate, I get told:</p>
<pre><code>ActiveRecord::DuplicateMigrationNameError:
Multiple migrations have the name YourMigrationToTableBlahBlah
</code></pre>
<p>How is this possible and how do I work around this error so I can migrate?</p>
<p>At one point I did do a git commit that renamed the columns in the 1 migration file in db/migration, but I deleted the tables in app_development and app_test as well as the schema_migrations table so the Rails rake task should not be complaining about this.</p>
<p>EDIT:</p>
<p>One thing I noticed is that during the running of <code>bundle exec rake db:migrate</code> is that the same migrations folder path (e.g., "db/migrate") is being added to <code>ActiveRecord::Tasks::DatabaseTasks.migrations_paths</code> but I don't know why </p> | 1 |
OpenOffice / LibreOffice Base SQL Group By | <p>I have a small LibreOffice database with customer data and invoices. Each invoice consists of n items.</p>
<p>Customers:</p>
<pre><code>**********************
* ID * Name * Adress *
**********************
* 0 * N1 * A1 *
* 1 * N2 * A2 *
**********************
</code></pre>
<p>Invoices:</p>
<pre><code>********************************
* ID * CustomerID * Date *
********************************
* 0 * 0 * 01/01/1970 *
* 1 * 0 * 08/02/1971 *
********************************
</code></pre>
<p>Items:</p>
<pre><code>***********************************
* ID * InvoiceID * Amount * Price *
***********************************
* 1 * 0 * 12 * 12.95 *
* 2 * 0 * 9 * 8.75 *
* 3 * 1 * 29 * 8.75 *
***********************************
</code></pre>
<p>I want to create a query with the value of an invoice:</p>
<pre><code>SELECT "invoices"."ID", SUM( "items"."Amount" * "items"."Price" )
FROM "invoices", "items"
WHERE "invoices"."ID" = "items"."InvoiceID"
GROUP BY "invoice"."ID"
</code></pre>
<p>So far everything works. But if I want to include some more information to the query, e.g. </p>
<pre><code>SELECT "invoices"."ID", "invoices"."Date", SUM( "items"."Amount" * "items"."Price" )
FROM "invoices", "items"
WHERE "invoices"."ID" = "items"."InvoiceID"
GROUP BY "invoice"."ID"
</code></pre>
<p>I get the error message <code>Not in aggregate function or group by clause</code>. I tried it in phpmyadmin and it worked, so I think, that the SQL Syntax should be ok. What is the problem with my SQL statement?</p> | 1 |
Listview Checkbox - vb.net | <p>Ok, i have a listview with checkboxes and a button, how it works is that i have to check the items i want to change the values, then press the button to change the value of those checked item, here's my code on the button.</p>
<pre><code> Try
Dim I As Integer
If lv_id.CheckedItems.Count = 0 Then
For I = 0 To lv_id.Items.Count - 1
lv_id.Items(I).SubItems(1).Text = "Pending"
Next
Else
For I = 0 To lv_id.CheckedItems.Count - 1
lv_id.CheckedItems(I).SubItems(1).Text = "Submitted"
Next
End If
Proc_Items.BackColor = Color.Green
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
</code></pre>
<p>Now, what i want to do is, to remove the button and then when i'll check the item i want to the code above will do the process without pressing the button, i tried "ItemCheck, ItemChecked" event, but with no luck.</p> | 1 |
Sweet Alerts is display UTF-8 Chars wrong | <p>I don't know what is wrong, I have this JavaScript function:</p>
<pre><code><script charset="utf-8" type="text/javascript">
$(document).ready(function(){
//initialize the javascript
App.init();
@if(Session::has('message'))
var msg = '{{ Session::get('message') }}';
console.log(msg);
swal({
title: "",
text: 'compa&ntilde;ia',
type: "warning",
confirmButtonText: "Ok!",
closeOnConfirm: false
});
$(window).bind("load", function() {
$.gritter.add({
title: 'Atencion',
text: 'compa&ntilde;ia',
image: '{{ asset('images/clipboard_icon.png') }}',
class_name: 'danger',
time: ''
});
return false;
});
@endif
});
</script>
</code></pre>
<p>The problem is that sweet alerts doesn't display: <code>'compañia'</code> it displays <code>'compa&ntilde;ia'</code> but the gritter message is correctly displaying the word. (See picture)
<a href="https://i.stack.imgur.com/7neBA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7neBA.png" alt="enter image description here"></a></p>
<p>As you can see the red gritter correctly displays the word, but the sweet alert doesn't,</p>
<p>The file is UTF-8 encoded, so is the meta and the script also just in case, and before you ask why I put <code>'compa&ntilde;ia'</code> its part of a larger message that is send by Laravel on the session and retrieved by the view in that format.</p>
<p>Anyway my real question is why does the gritted display the word fine and how can I fix it so it works also on sweet alert.</p> | 1 |
How do I query RealmObject that have RealmList that contains specified value | <p>I have a <code>RealmObject</code> (let's say <code>Owner</code>) and it has <code>RealmList<Cat></code>. <code>Cat</code> has a property <code>name</code>. How do I query for all the <code>Owner</code>s who have cat with specified name ?</p>
<p>I tried:</p>
<pre><code>RealmResult<Owner> owners = realm.query(Owner.class)
.contains("cats", "Garfield")
.findAll();
</code></pre>
<p>But it does not work.</p>
<p>PS most probably duplicate but cant find.</p> | 1 |
"Required module not found" for module that exists in node_modules | <p>Some modules just seem to be invisible to Flow. For example I have <a href="https://www.npmjs.com/package/react-native-overlay" rel="nofollow">react-native-overlay</a> installed via npm into my node_modules directory but I get a whole bunch of errors like this from Flow:</p>
<pre><code>[js/components/DatePickerOverlay.js:18
18: let Overlay = require('react-native-overlay');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ react-native-overlay. Required module not found
</code></pre>
<p>This module doesn't have types so it would be fine if I could just get Flow to ignore it entirely.</p>
<p>Here's my .flowconfig (based on React Native's one):</p>
<p><a href="https://gist.github.com/almost/20c6caf6d18d0e5c689f" rel="nofollow">https://gist.github.com/almost/20c6caf6d18d0e5c689f</a></p>
<p>As you can see I'm on flow 0.20.1 and I have module.system=haste (as required by React Native)</p>
<p>I tried adding a //$FlowIgnore comment to the import lines but then Flow complains about an unneeded ignore comment! I also tried creating a react-native-flow.js.flow file with a dummy export which seemed to work at first but then after a flow restart stopped working.</p>
<p>Any ideas for how to either help Flow find this module or make it ignore the import line completely?</p> | 1 |
Laravel 5 missing required parameters on destroy route | <p>I recently upgraded from laravel 5.1 to 5.2 and now I'm getting an error of <code>Missing required parameters for [Route: example.destroy] [URI: example/{args}]</code>.</p>
<p>The error occurs here:
<code><form class="form-horizontal" action="<?php echo route('example.destroy'); ?>" method="post"></code> on the action attribute of the form.</p>
<p>Here's how the route was registered on the <code>route.php</code></p>
<pre><code>Route::resource('example', 'ExampleController');
</code></pre>
<p>When I was in 5.1, there was no error with this line. Just went I upgrade to 5.2, it now occurs.</p>
<p>The functionality of this is that it will allow user to delete multiple entries by checking the checkboxes that they wish to be deleted. Then upon submit, it will redirect to the destroy method on the controller.</p> | 1 |
Logstash input Filebeat | <p>First of all I apologize for my English.</p>
<p>I'm an intern in a company and I put up a solution ELK with Filebeat to send the logs.</p>
<p>The problem is that once recover syslog_pri always displays Notice and severity_code 5</p>
<p>Here is my configuration :</p>
<p>Logstash input : </p>
<pre><code>input {
beats {
port => 5044
type => "logs"
#ssl => true
#ssl_certificate => "/etc/pki/tls/certs/logstash-forwarder.crt"
#ssl_key => "/etc/pki/tls/private/logstash-forwarder.key"
}
}
</code></pre>
<p>My Filter :</p>
<pre><code>filter {
if [type] == "syslog" {
grok {
match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" }
add_field => [ "received_at", "%{@timestamp}" ]
add_field => [ "received_from", "%{host}" ]
}
syslog_pri {
syslog_pri_field_name => "syslog_pri"
}
geoip {
source => "ip"
}
date {
match => [ "syslog_timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss" ]
}
}
}
</code></pre>
<p>and I receive the logs like this : </p>
<pre><code>{
"_index": "logstash-2016.01.27",
"_type": "log",
"_id": "AVKDkbeIo9FUMGLWSx1L",
"_score": null,
"_source": {
"message": "2016-01-27T15:52:20.979+0100 WARN [HeartbeatService RUNNING] collector.heartbeat.HeartbeatService - Unable to send heartbeat to Graylog server: ConnectException: Connection refused",
"@version": "1",
"@timestamp": "2016-01-27T14:52:21.896Z",
"beat": {
"hostname": "LABSRVITT003",
"name": "LABSRVITT003"
},
"count": 1,
"fields": null,
"input_type": "log",
"offset": 28494893,
"source": "/var/log/graylog-collector/collector.log",
"type": "log",
"host": "LABSRVITT003",
"tags": [
"gpf_relp"
],
"syslog_severity_code": 5,
"syslog_facility_code": 1,
"syslog_facility": "user-level",
"syslog_severity": "notice"
},
"fields": {
"@timestamp": [
1453906341896
]
},
"sort": [
1453906341896
]
}
</code></pre>
<p>I'm posting this because I am really short of ideas I toured the documentation but I find nothing .</p>
<p>This link :</p>
<p>[<a href="https://serverfault.com/questions/735230/why-cant-the-logstash-syslog-pri-filter-see-the-priority-in-syslog-messages]">https://serverfault.com/questions/735230/why-cant-the-logstash-syslog-pri-filter-see-the-priority-in-syslog-messages]</a>
This person have the same problem and he succeeded.</p>
<p>So if somebody have an idea share it.</p>
<p>Thanks</p> | 1 |
Subquery in Yii2 order by and group by | <p>In mysql the query command I am using is this:</p>
<pre><code>SELECT * FROM (SELECT * FROM `storefirmware_updates` ORDER BY
`old_version` DESC) AS tmp_table GROUP BY store_id
</code></pre>
<p>I can't find a way how to do this in Yii2 and pass it inside the activeprovider. </p>
<p>I tried something like this:</p>
<pre><code> $subquery = new Query;
$subquery->select(["*"]);
$subquery->from('storelist_update_view')->orderBy('old_version DESC');
$query = new Query;
$query->select(["*"]);
$query->from('storelist_update_view')->groupBy(['store_id' => $subquery]);
</code></pre>
<p>but I think this is wrong.</p> | 1 |
Can I expose Swift default parameter values to Objective-C? | <p>Say I have some Swift class with methods I'd like to expose to Objective-C:</p>
<pre><code>@objc(Worker) class Worker : NSObject {
func performWork(label: String = "Regular Work") {
// Perform work
}
}
</code></pre>
<p>I can call this in two ways:</p>
<pre><code>Worker().performWork()
Worker().performWork("Swift Development")
</code></pre>
<p>However, when called from Objective-C, I do not get the "default" version of this method - I <em>must</em> supply a label:</p>
<pre><code>[[[Worker alloc] init] performWork:@"Obj-C Development"];
</code></pre>
<p>See the definition from my <code>AppName-Swift.h</code> header below:</p>
<pre><code>SWIFT_CLASS_NAMED("Worker")
@interface Worker : NSObject
- (void)performWork:(NSString * __nonnull)label;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end
</code></pre>
<p>I would <em>expect</em> to see a method with this signature:</p>
<pre><code>- (void)performWork;
</code></pre>
<p>I realise ObjC doesn't support default parameter values, but my assumption was that the Swift default values simply generate additional Swift functions with trivial implementations calling the "real" function (i.e. they're syntactic sugar hiding the <a href="https://stackoverflow.com/a/561207/1217087">typical implementation</a> we'd use in Obj-C).</p>
<p>Is there any way to expose this default value to Objective-C? If not, can anyone point me to any documentation on why this isn't available?</p> | 1 |
Verilog - Calling a module inside a case statement | <p>I'm not that familiar in Verilog but can you call another module when it's inside a case statement?</p> | 1 |
Eclipse comment auto-generation | <p>For a programming course, I'm required to put comments within each class and method describing the following five things: <strong>Methods</strong>, <strong>fields</strong>, <strong>methods on fields</strong>, <strong>parameters</strong>, and <strong>methods on parameters</strong>. The first three are to be put directly under the class heading, and the last two are specific to each method. </p>
<p>Below is an example of what these comments should look like.</p>
<pre><code>class ConsLoString implements ILoString {
/*
* Methods:
* - String convertToString();
* - String formatString();
* Fields:
* - String first;
* - ILoString rest
* Methods on fields:
* - All String methods
* - All ILoString methods
*/
String first;
ILoString rest;
...
</code></pre>
<p>Naturally, it is tedious and redundant to type all these out for every single class and method in a large file. Is there a way to generate these automatically, in Eclipse or otherwise?</p>
<p>I've looked into Eclipse's <a href="http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Fconcepts%2Fconcept-template-variables.htm" rel="nofollow">Java Editor Template Variables</a> but there doesn't seem to be a way to iterate over every method/field in a class within Eclipse's template editor.</p>
<p>Any help is much appreciated!</p> | 1 |
Why python numpy.delete does not raise indexError when out-of-bounds index is in np array | <p>When using np.delete an indexError is raise when an out-of-bounds index is used. When an out-of-bounds index is in a np.array used and the array is used as the argument in np.delete, why doesnt this then raise an indexError?</p>
<pre><code>np.delete(np.array([0, 2, 4, 5, 6, 7, 8, 9]), 9)
</code></pre>
<p>this gives an index-error, as it should (index 9 is out of bounds)</p>
<p>while </p>
<pre><code>np.delete(np.arange(0,5), np.array([9]))
</code></pre>
<p>and </p>
<pre><code>np.delete(np.arange(0,5), (9,))
</code></pre>
<p>give:</p>
<pre><code>array([0, 1, 2, 3, 4])
</code></pre> | 1 |
How to aggregate multiple XMLELEMENT using XMLAGG | <p>I want to aggregate multiple XMLELEMENT for table following columns and return an xml file.</p>
<p>Here is the table data:
<a href="https://i.stack.imgur.com/eO4f1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eO4f1.png" alt="enter image description here"></a></p>
<p>I want return xml with following format:</p>
<pre><code><employee>
<id>FMCSC00015</id>
<year>2016</year>
<month>1</month>
<head_name>BASIC PAY</head_name>
<amount>35600</amount>
<head_name>BANK LOAN-4</head_name>
<amount>23490</amount>
<head_name>RESEARCH ALLOWANCE</head_name>
<amount>1500</amount>
<head_name>MOTOR GARAGE</head_name>
<amount>500.5</amount>
<head_name>CLUB</head_name>
<amount>207</amount>
.........so on
<employee>
</code></pre>
<p>But i am facing difficulty on aggregating 2 columns [head_name and amount].
here is my oracle code:</p>
<pre><code> select xmlElement( "employee",
xmlelement("id", e.PAYMSTR_EMPID),
xmlelement("year", e.PAYMSTR_SALYR),
xmlelement("month", e.PAYMSTR_SALMT),
XMLAGG(
XMLELEMENT(" ",
XMLELEMENT("head_name", e.PAYMSTR_SALHDNM ),
XMLELEMENT("amount", e.PAYMSTR_AMOUNT ) )
)
) as result
from TBL_PAYROLL_MASTER_FILE e
where e.PAYMSTR_EMPID = 'FMCSC00015'
group by e.PAYMSTR_EMPID,e.PAYMSTR_SALYR, e.PAYMSTR_SALMT;
</code></pre>
<p>As you can see because i used white space inside the first XMLELEMENT of XMLAGG, it still creates <strong>empty tags</strong> with following output xml:</p>
<pre><code><employee>
<id>FMCSC00015</id>
<year>2016</year>
<month>1</month>
<>
<head_name>BASIC PAY</head_name>
<amount>35600</amount>
</>
<>
<head_name>BANK LOAN-4</head_name>
<amount>23490</amount>
</>
<>
<head_name>RESEARCH ALLOWANCE</head_name>
<amount>1500</amount>
</>
<>
<head_name>MOTOR GARAGE</head_name>
<amount>500.5</amount>
</>
<>
<head_name>CLUB</head_name>
<amount>207</amount>
.........so on
<employee>
</code></pre>
<p>How can i avoid this extra empty tags and get my appropriate xml format.Thanks</p> | 1 |
matplotlib plot X Y Z data from csv as pcolormesh | <p>I have data in a csv of this form:</p>
<pre><code>X,Y,Z
0,0,0.0
0,1,0.0
1,0,1.0
1,1,0.55
2,0,4.0
2,1,3.216
</code></pre>
<p>I am not sure how to feed this data to <code>pcolormesh</code>. I think I have to use <code>np.meshgrid</code> but I'm not sure how to in this case.</p>
<pre><code>dat = pd.read_csv('my_dat.csv')
plt.pcolormesh(dat['X'], dat['Y'], dat['Z'])
plt.show()
</code></pre>
<p>Results in <code>Value error: need more than one value to unpack</code></p>
<p>I don't understand - why doesn't this just work? </p> | 1 |
Java if condition check for empty and null values | <p>How can I write a condition in java for a webservice request, In my webservice request I am passing an element that has <code>SpeedInfo</code>. In <code>SpeedInfo</code> element there is two sub elements <code>Bandwidth</code> and <code>AccessSpeed</code>.</p>
<p>This is my Request In SoapUI:</p>
<pre><code> <sch:SpeedInfo>
<ns:Bandwidth xmlns:ns="http://lpp.att.com/logical/classofservice/schema/v1">4000000</ns:Bandwidth>
<ns:AccessSpeed xmlns:ns="http://lpp.att.com/logical/classofservice/schema/v1">4000000</ns:AccessSpeed>
</sch:SpeedInfo>
</code></pre>
<p>My Java condition:</p>
<pre><code>if (request.getSpeedInfo() == null || (request.getSpeedInfo() == null && request.getSpeedInfo().getBandwidth() == null)){
throw new Exception(" SpeedInfo Bandwidth must be passed in the request ");
}
</code></pre>
<p>I need my condition to check for 3 scenarios:</p>
<pre><code> 1. if <speedInfo> itself is not present
2. <sch:SpeedInfo> is present, but bandwidth not present:
<sch:SpeedInfo>
<ns:AccessSpeed xmlns:ns="http://lpp.att.com/logical/classofservice/schema/v1">40000000</ns:AccessSpeed>
</sch:SpeedInfo>
3. Bandwidth is present but no value
<sch:SpeedInfo>
<ns:Bandwidth xmlns:ns="http://lpp.att.com/logical/classofservice/schema/v1"></ns:Bandwidth>
<ns:AccessSpeed xmlns:ns="http://lpp.att.com/logical/classofservice/schema/v1">40000000</ns:AccessSpeed>
</sch:SpeedInfo>
</code></pre>
<p>error I am getting:</p>
<pre><code>2016-02-02 09:45:48,349 WARN http-bio-8080-exec-3--[c0a8381152a2a943f51] c0a8381152a2a943f51 fw.ws.MessageInInterceptor:49 - Content input stream is NOT null, nothing to log in handleFault()?
2016-02-02 09:45:48,351 WARN http-bio-8080-exec-3--[c0a8381152a2a943f51] c0a8381152a2a943f51 cxf.phase.PhaseInterceptorChain:452 - Interceptor for {http://lpp.att.com/logical/v1}LogicalService#{http://lpp.att.com/logical/v1}classOfServiceAllocation has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Unmarshalling Error: cvc-datatype-valid.1.2.1: '' is not a valid value for 'integer'.
at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:908)
at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:712)
</code></pre> | 1 |
How to create a range slider without plugins and Jquery UI? | <p>I try to study javascript and stuck. I want to understand how make a range slider by myself. But everyone uses plugins and libs like jquery UI. or tries stylize input type="range", although this does not supported in IE9. It's good and simple but i want improve my skills. I can't find tutorial about this subject.
May be somebody knows something about this?</p> | 1 |
Execute http request in parallel with Retrofit 2 | <p>I want to implement multiple parallel request in Retrofit 2.
I have the following structure to make 3 request :</p>
<pre><code>HistoricalRApi.IStockChart service=HistoricalRApi.getMyApiService();
//^BVSP,^DJI,^IXIC
Call<HistoricalDataResponseTimestamp> call1= service.get1DHistoricalDataByStock("^IXIC");
Call<HistoricalDataResponseTimestamp> call2= service.get1DHistoricalDataByStock("^DJI");
Call<HistoricalDataResponseTimestamp> call3= service.get1DHistoricalDataByStock("^GSPC");
call1.enqueue(retrofitCallbackAmerica());
call2.enqueue(retrofitCallbackAmerica());
call3.enqueue(retrofitCallbackAmerica());
}
</code></pre>
<p>I have read that in Retrofit1, when defining the rest adapter one can define parallel request with .setExecutor like here: </p>
<pre><code>RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(END_POINT)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setExecutors(Executors.newFixedThreadPool(3), null)
.build();
</code></pre>
<p>My question is how can i achieve the same in Retrofit 2? Thanks in advance</p> | 1 |
AttributeError: 'str' object has no attribute <CLASS NAME> | <p>I'm trying to access a class from another class but I'm running into this issue.</p>
<p>This is the class I'm trying to access.</p>
<pre><code>import tweepy
ckey= '**********************'
csecret= '**********************'
atoken= '**********************'
asecret= '**********************'
class TwtPrinter:
def printTweet(self, user, text):
auth = tweepy.OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
api = tweepy.API(auth)
for status in tweepy.Cursor(api.user_timeline).items():
try:
api.destroy_status(status.id)
except:
pass
</code></pre>
<p>And this is a scaled down version of the class where I'm having the error.</p>
<pre><code>import sqlite3
import random
from app.models.monDAO import monDAO
from app.models.charDAO import CharDAO
from app.models.dunDAO import DunDAO
from app.controllers.twt_print import TwtPrinter
class GameManager:
def testDB(self):
print("hello world")
conn = sqlite3.connect('DunSuciRun.sqlite')
c = conn.cursor()
this = """SELECT * FROM CHARACTERS"""
c.execute(this)
getStuff = c.fetchall()
charTuple = getStuff[0]
cha = CharDAO(charTuple[0], charTuple[1],charTuple[2],charTuple[3],charTuple[4])
print(cha.name.split(' ')[0])
def test(self):
self.twt_print = TwtPrinter
testing = "testing"
print testing
# self.twt_print = TwtPrinter
self.twt_print.printTweet("1""2")
</code></pre>
<p>The error in question is this: </p>
<pre><code>C:\Python27\python.exe C:/Users/Jensi/PycharmProjects/DSR.02/app/controllers/game_manager.py
Traceback (most recent call last):
File "C:/Users/Jensi/PycharmProjects/DSR.02/app/controllers/game_manager.py", line 14, in <module>
class GameManager:
File "C:/Users/Jensi/PycharmProjects/DSR.02/app/controllers/game_manager.py", line 241, in GameManager
test("")
File "C:/Users/Jensi/PycharmProjects/DSR.02/app/controllers/game_manager.py", line 32, in test
self.twt_print = TwtPrinter
AttributeError: 'str' object has no attribute 'twt_print'
Process finished with exit code 1
</code></pre> | 1 |
mosaic plot with percentage and count values as labels in pandas DF | <p>I have pandas dataframe like this:</p>
<pre><code> LEVEL_1 LEVEL_2 Freq Percentage
0 HIGH HIGH 8842 17.684
1 AVERAGE LOW 2802 5.604
2 LOW LOW 22198 44.396
3 AVERAGE AVERAGE 6804 13.608
4 LOW AVERAGE 2030 4.060
5 HIGH AVERAGE 3666 7.332
6 AVERAGE HIGH 2887 5.774
7 LOW HIGH 771 1.542
</code></pre>
<p>I can get tiles of LEVEL_1 and LEVEL_2:</p>
<pre><code> from statsmodels.graphics.mosaicplot import mosaic
mosaic(df, ['LEVEL_1','LEVEL_2'])
</code></pre>
<p><a href="http://i.stack.imgur.com/1J9Qi.png" rel="nofollow">enter image description here</a><br>
I just want to put Freq and Percentage at the center of each tile of mosaic plot.
How can I do this?</p> | 1 |
Binding an event to a method, why does it work in UWP? | <p><code>UWP</code> came with a new way of <code>DataBinding</code>, <code>Compiled Binding</code>, using the <code>{x:Bind}</code> markup extension, when I was discovering this new feature, I found out that we can actually bind an event to a method !</p>
<p><strong>Example :</strong></p>
<p><strong>Xaml :</strong></p>
<pre><code><Grid>
<Button Click="{x:Bind Run}" Content="{x:Bind ButtonText}"></Button>
</Grid>
</code></pre>
<p><strong>Code Behind :</strong></p>
<pre><code>private string _buttonText;
public string ButtonText
{
get { return _buttonText; }
set
{
_buttonText = value;
OnPropertyChanged();
}
}
public MainPage()
{
this.InitializeComponent();
ButtonText = "Click !";
}
public async void Run()
{
await new MessageDialog("Yeah the binding worked !!").ShowAsync();
}
</code></pre>
<p><strong>The result :</strong></p>
<p><a href="https://i.stack.imgur.com/6v3UQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6v3UQ.png" alt="enter image description here"></a></p>
<p>And since {x:Bind} bindings are evaluated at runtime and the compiler generates some files that represent that binding, so I went there to investigate what's going on, so in the MainPage.g.cs file (MainPage is the xaml file in question) I found this :</p>
<pre><code> // IComponentConnector
public void Connect(int connectionId, global::System.Object target)
{
switch(connectionId)
{
case 2:
this.obj2 = (global::Windows.UI.Xaml.Controls.Button)target;
((global::Windows.UI.Xaml.Controls.Button)target).Click += (global::System.Object param0, global::Windows.UI.Xaml.RoutedEventArgs param1) =>
{
this.dataRoot.Run();
};
break;
default:
break;
}
}
</code></pre>
<p>The compiler seems to know that it's a valid binding, moreover it creates the corresponding event handler, and it calls the concerned method inside.</p>
<p>That is great ! but why ?? A binding target should be a dependency property, not an event. <a href="https://msdn.microsoft.com/en-us/library/windows/apps/mt204783.aspx" rel="noreferrer">The official documentation for {x:Bind}</a> does mention this new feature, but doesn't explain why and how can a non dependency property be a target of binding, anyone who has a deep explanation for this ?</p> | 1 |
how to solve Google Charts loader.js can only be loaded once | <pre><code><script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var completed=parseInt(document.getElementById('completed1').value);
var notcompleted=parseInt(document.getElementById('notcompleted1').value);
alert(completed);
alert(notcompleted);
var data = google.visualization.arrayToDataTable([
['Task', 'Student'],
['Students Completed', completed],
['Students Not Completed', notcompleted],
]);
var options = {
title: ''
};
var chart = new google.visualization.PieChart(document.getElementById('piechart1'));
chart.draw(data, options);
}
</script>
</code></pre>
<p>this script is on my one page i am calling this page multiple times so in console it shows "Google Charts loader.js can only be loaded once."</p> | 1 |
how to install c++ library libuv on OS X? | <p>i want to install libuv on OS X,but when i</p>
<pre><code>brew install libuv
</code></pre>
<p>then i write a simple demo :</p>
<pre><code>#include <stdio.h>
#include <uv.h>
int main() {
uv_loop_t *loop = uv_loop_new();
printf(“Now quitting.\n”);
uv_run(loop, UV_RUN_DEFAULT);
return 0;
}
</code></pre>
<p>always error:</p>
<pre><code>main.cc:2:10: fatal error: 'uv.h' file not found
#include <uv.h>
^
1 error generated.
</code></pre> | 1 |
MySQL Error 1055 information_schema.PROFILING.SEQ on every query | <p>I'm using a recent install of mysql from the mysql repository, installed on Ubuntu 14.04. Every query I run results in the error below and I have been unable to find anything that discusses this via google or here.</p>
<p>For example, this (obviously for demonstration purposes only) query returns the following:</p>
<hr>
<p>[SQL]SELECT *
FROM
tabcLocations</p>
<p>Affected rows: 0
Time: 0.705s</p>
<h2>[Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'information_schema.PROFILING.SEQ' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by</h2>
<p>It returns the results of the query just fine, but throws an error on every query, which will obviously affect error handling in my applications. Any suggestions on how to resolve this? It's fairly maddening at the moment.</p> | 1 |
Binary operator '===' cannot be applied to two 'String' operands | <p>Why can't the === be used with String's in Swift? I am unable to compile the following:</p>
<pre><code>let string1 = "Bob"
let string2 = "Fred"
if string1 === string2 {
...
}
</code></pre>
<p>and get the following error (on the if line):</p>
<blockquote>
<p>Binary operator '===' cannot be applied to two 'String' operands</p>
</blockquote>
<hr>
<p>What I want to be able to do in my unit tests is, having performed a copyWithZone:, verify that two objects are indeed a different object with different pointers even if their values are the same. The following code doesn't work...</p>
<blockquote>
<p>XCTAssertFalse(object1.someString === object2.someString)</p>
</blockquote>
<p>If anyone knows of an alternative way please advise.</p> | 1 |
Decision tree in r | <p>my dataset is :</p>
<pre><code>x=data.frame(v1=c(97 , 97 , 85 , 84 , 90 , 80 , 81 , 90 , 80, 70, 90 , 90, 90 ,95 , 88 , 99),
+ v2=c(99 , 91 , 91 ,83 , 99 , 95 , 74 , 88 , 82 , 80 , 96 , 87 , 92 , 96 , 88, 95),
+ v3=c( 89 ,93 , 87 , 80 , 96 , 96 , 75 , 90 , 78, 86 , 92 ,88 , 80, 88 , 98 ,98),
+ v4=c( 89 , 97 ,91 , 86 , 95 , 95 , 89 , 88 , 75, 82 , 99, 92 , 95, 92 , 90, 98),
+ v5=c( 99 ,90 , 93 ,91 , 90 , 90 , 77 , 92 , 85, 76 , 90, 96 , 90, 90 , 90, 92))
> x
v1 v2 v3 v4 v5
1 97 99 89 89 99
2 97 91 93 97 90
3 85 91 87 91 93
4 84 83 80 86 91
5 90 99 96 95 90
6 80 95 96 95 90
7 81 74 75 89 77
8 90 88 90 88 92
9 80 82 78 75 85
10 70 80 86 82 76
11 90 96 92 99 90
12 90 87 88 92 96
13 90 92 80 95 90
14 95 96 88 92 90
15 88 88 98 90 90
16 99 95 98 98 92
</code></pre>
<p>I used <code>rpart</code> package to apply decision tree as follows :</p>
<pre><code># Classification Tree with rpart
library(rpart)
fit <- rpart(v5 ~ v1+v2+v3+v4,
method="class", data=x)
printcp(fit) # display the results
Classification tree:
rpart(formula = v5 ~ v1 + v2 + v3 + v4, data = x, method = "class")
Variables actually used in tree construction:
character(0)
Root node error: 9/16 = 0.5625
n= 16
CP nsplit rel error xerror xstd
1 0.01 0 1 0 0
> summary(fit) # detailed summary of splits
Call:
rpart(formula = v5 ~ v1 + v2 + v3 + v4, data = x, method = "class")
n= 16
CP nsplit rel error xerror xstd
1 0.01 0 1 0 0
Node number 1: 16 observations
predicted class=90 expected loss=0.5625 P(node) =1
class counts: 1 1 1 7 1 2 1 1 1
probabilities: 0.062 0.062 0.062 0.438 0.062 0.125 0.062 0.062 0.062
</code></pre>
<p><strong>plot tree</strong></p>
<pre><code> # plot tree
plot(fit, uniform=TRUE,
+ main="Classification Tree ")
Error in plot.rpart(fit, uniform = TRUE, main = "Classification Tree ") :
fit is not a tree, just a root
text(fit, use.n=TRUE, all=TRUE, cex=.8)
Error in text.rpart(fit, use.n = TRUE, all = TRUE, cex = 0.8) :
fit is not a tree, just a root
</code></pre>
<p>what is my wrong while I applied <code>rpart</code> ? why it give me error with tree plot? how to fix this error Error :</p>
<p>fit is not a tree, just a root</p> | 1 |
groupingBy & Java 8 - after groupingBy convert map to a list of objects | <p>Is there a way I could simplify this and directly convert the map I got from groupingBy to a list of elements that have key and values as attributes? And not to have 2 times conversions to stream. </p>
<p>What I am doing here is that I fetch RiskItems and then map them to DTO, after it I need them grouped by an attribute from RiskItemDTO - the RiskDTO and then all these into a List of elements that have RiskDTO and coressponding RiskItemDTOs as elements..</p>
<pre><code> riskItemRepositoryCustom.findRiskItemsByRiskTypeName(riskTypeName)
.stream()
.map(mapper::mapToDTO)
.collect(groupingBy(RiskItemDTO::getRisk))
.entrySet()
.stream()
.map( entry -> new RiskWithRiskItemsDTO(entry.getKey(),entry.getValue()))
.collect(Collectors.toList());
</code></pre> | 1 |
Allow only one file of directory in robots.txt? | <p>I want to allow only one file of directory <code>/minsc</code>, but I would like to disallow the rest of the directory. </p>
<p>Now in the robots.txt is this:</p>
<pre><code>User-agent: *
Crawl-delay: 10
# Directories
Disallow: /minsc/
</code></pre>
<p>The file that I want to allow is <code>/minsc/menu-leaf.png</code></p>
<p>I'm afraid to do damage, so I dont'know if I must to use:</p>
<p><strong>A)</strong> </p>
<pre><code>User-agent: *
Crawl-delay: 10
# Directories
Disallow: /minsc/
Allow: /minsc/menu-leaf.png
</code></pre>
<p>or </p>
<p><strong>B)</strong></p>
<pre><code>User-agent: *
Crawl-delay: 10
# Directories
Disallow: /minsc/* //added "*" -------------------------------
Allow: /minsc/menu-leaf.png
</code></pre>
<p>?</p>
<p>Thanks and sorry for my English.</p> | 1 |
detect if string is a valid URL and is not empty | <p>I would like to check if one of the input fields is empty and if the #urlink is a the format of a URL before I perform this function in the js: </p>
<pre><code>$scope.favUrls.$add
</code></pre>
<p>not sure how to go about it.</p>
<p><strong>html</strong></p>
<pre><code><input type="text" id="urlName" class="form-control" placeholder="" ng-model="mvName" />
<input type="text" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" />
</code></pre>
<p><strong>app.js</strong></p>
<pre><code>$scope.saveToList = function(event) {
var mvName = $scope.mvName.trim();
var mvUrl = $scope.mvUrl.trim();
if (mvName.length > 0) {
$scope.favUrls.$add({
name: mvName,
title: mvUrl
});
urlName.value = ''; //urlName is the ID of input box - Angular rocks!
urlLink.value = ''; //urlName is the ID of input box - Angular rocks!
}
}
</code></pre> | 1 |
Fitting a plane to a 2D array | <p>I have a topological image that I am attempting to perform a plane subtraction on using Python. The image is a 256x256 2-D array of float32 values between 0 and 1.</p>
<p>What I wish to do is to use linear regression to fit a plane to this data and subsequently subtract this plane from the original values.</p>
<p>I am unsure how to go about achieving this.</p>
<p>I am new to the Python language and appreciate any help.</p> | 1 |
Android Studio setmylocationenabled(true) throws SecurityException | <p>I've encountered a problem. My program throes SecurityException, even if I declraed all the Permissions.
Here is MapsActivity class:</p>
<pre><code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);}
public void onMapReady(GoogleMap googleMap) {
try{
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
// set map type
}
</code></pre>
<p>Here is the Manifest:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mazebug.danuleoshaleosha">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Interface" />
<activity android:name=".Main2Activity" />
<activity android:name=".Main22Activity" />
<activity android:name=".SFR_Table" />
<activity android:name=".sfrtable2" />
<activity android:name=".sfrtable3" />
<activity android:name=".sfrtable4" />
<activity android:name=".sfrtable5" />
<activity android:name=".sfrtable6" />
<activity android:name=".sfrtable7" />
<activity android:name=".mySfrs" />
<activity android:name=".Search_bySiteName" />
<activity android:name=".Search_byDate" />
<activity android:name=".Search_byLocation" />
<activity android:name=".Found_1" />
<activity android:name=".Found_2" />
<activity android:name=".Found_3" />
<activity android:name=".Edit_first" />
<activity android:name=".Edit_1_2" />
<activity android:name=".Edit_1_3" />
<activity android:name=".Edit_1_4" />
<activity android:name=".Edit_1_5" />
<activity android:name=".Edit_1_6" />
<activity android:name=".Edit_1_7" />
<activity android:name=".testing" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity android:name=".Main23Activity" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyA-z6nM3WoXwP7dBzIdz1_dssl8X81xttg" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps"></activity>
</application>
</code></pre>
<p></p>
<p>Here is the thrown Exception</p>
<pre><code>FATAL EXCEPTION: main Process: mazebug.danuleoshaleosha, PID: 13162
java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
at com.google.maps.api.android.lib6.e.ev.c(Unknown Source)
at com.google.android.gms.maps.internal.j.onTransact(SourceFile:274)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.setMyLocationEnabled(Unknown Source)
at com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(Unknown Source)
at mazebug.danuleoshaleosha.MapsActivity.onMapReady(MapsActivity.java:51)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.maps.internal.be.a(SourceFile:82)
at com.google.maps.api.android.lib6.e.fb.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code></pre>
<p>I'm pretty confused, 'cause it seems like I granted the required permissions.
Please give me a piece of advice. Thanks!</p> | 1 |
How to navigate to the corresponding java class from XML layout for fragments in Android Studio? | <p>Suppose that I am in a layout file named "main.xml" and its corresponding fragment java class is "MainFragment.java".</p>
<p>Is there any shortcut to go to "MainFragment.java" from the "main.xml" or any other way?</p>
<p>It will be helpful to navigate around xml and java classes quickly when there are a lot of java classes and xml files in the project.</p>
<p><strong>Note:</strong> For activity, there is a “C” symbol found in the top-left corner of the layout XML file. When we click that "C" symbol it will take us to corresponding java class in which the xml file is used. But for fragments, there is nothing available.</p> | 1 |
How to work on multiple Modules in android studio | <p>Can anyone tell me that how we will utilize the external_projects into our current project in android studio?</p>
<p>Basically I have a small android project for "signIn/SignUp" purposes in the running state and I want to add up that project in one of my other project. I have imported it successfully by placing it in libs folder and also have added the dependencies. So now I am confused, how i will be able to merge them. how signIn/SignUp project will run in first and then the other.</p> | 1 |
Access js and css files from API gateway and lambda | <p>I have an API Gateway in AWS that calls a a lambda function that returns some html. That html is then properly rendered on the screen but without any styles or js files included. How do I get those to the client as well? Is there a better method than creating /js and /css GET endpoints on the API Gateway to go get those files? I was hoping I could just store them in S3 and they'd get autoloaded from there.</p> | 1 |
Application crash with error - EGLFS: OpenGL windows cannot be mixed with others | <p>I've created a very basic project in Qt Creator.</p>
<pre><code>File -> New Project -> Application -> Qt QuickControls Application
</code></pre>
<p>Without adding / modifying anything, compiled the project and deployed on the target system which is a Olimex board with Qt (compiled with eglfs), using tslib. The application is started with</p>
<pre><code>testApp -plugin tslib
</code></pre>
<p>Application starts and clicking on the File menu is killing it. "EGLFS: OpenGL windows cannot be mixed with others" error appears in the terminal.</p>
<p>This is the <code>main.qml</code> file. </p>
<p>import QtQuick 2.5
import QtQuick.Controls 1.4</p>
<pre><code>ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
menuBar: MenuBar {
Menu {
title: qsTr("File")
MenuItem {
text: qsTr("&Open")
onTriggered: console.log("Open action triggered");
}
MenuItem {
text: qsTr("Exit")
onTriggered: Qt.quit();
}
}
}
Label {
text: qsTr("Hello World")
anchors.centerIn: parent
}
}
</code></pre>
<p>I'm aware of the fact that there can only be one top OpenGL window and I'm not adding anything. Any help is greatly appreciated.</p> | 1 |
Trying to get JSON response with JavaEE JAX-B, Jasper and Glassfish 4.1.1, but I get error 500 | <p>I am learning WebServices with JAX-B and Jasper. I can easily generate XML response, but I want to get JSON response, but I get error 500.</p>
<p>Here is exception:</p>
<pre><code>javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException
root cause
org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException
root cause
java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException
root cause
java.lang.ClassNotFoundException: javax.xml.parsers.ParserConfigurationException not found by org.eclipse.persistence.moxy [228]
</code></pre>
<p>Full server log: <a href="http://pastebin.com/Eq2KbyKJ" rel="nofollow">http://pastebin.com/Eq2KbyKJ</a></p>
<p>Okey, I tried with Tomcat, and it works, it seems that is Glassfish related problem, but I want to use Glassfish as server, since I use EJB in my projects.</p> | 1 |
E0277 "Sized is not implemented for the type [u8]", but my type does not have a [u8] | <p>I'm making a <code>Node</code> tree. Here is the code:</p>
<pre><code>use std::option::Option;
use std::path;
#[derive(Debug)]
enum NodeType {
Binding((String, String)),
Header,
Include(path::Path),
Raw(String),
}
#[derive(Debug)]
pub struct Node {
node_type: NodeType,
}
impl Node {
fn new() -> Node {
Node { node_type: NodeType::Header }
}
}
</code></pre>
<p>When I compile this, I get the following error:</p>
<pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied in `std::path::Path`
--> src/main.rs:8:13
|
8 | Include(path::Path),
| ^^^^^^^^^^^ within `std::path::Path`, the trait `std::marker::Sized` is not implemented for `[u8]`
|
= note: `[u8]` does not have a constant size known at compile-time
= note: required because it appears within the type `std::path::Path`
= note: only the last field of a struct may have a dynamically sized type
</code></pre>
<p>I searched for this error, but it seems to refer to an type where <code>Sized</code> is not implemented. Oddly, the error output says that <code>[u8]</code> does not implement <code>Sized</code>, but there's not even one <code>u8</code> in my code. What could it be?</p> | 1 |
IPython (Jupyter) notebook producing ghost line in all equations | <p>I installed IPython / Jupyter using pip on a new machine (Macbook Air with El Capitan). In a fairly simple notebook of mine (created with the same version of the whole stack) all equations, inline or not, suddenly have a vertical line on the right hand side; same height as the embedded image. </p>
<p>This is the case even for a single inline symbol such as <code>$x$</code>. I have no complicated macros or any weird LaTeX hacking going on.</p>
<p>Does anybody know this?</p>
<p>Here's a picture.</p>
<p><a href="https://i.stack.imgur.com/22T7u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/22T7u.png" alt="enter image description here"></a></p> | 1 |
ProcessQueueMessage function in WebJob console app | <p>I'm creating a new console app that I will run as a WebJob on Azure. When I created the new app in Visual Studio, it already created a Function.cs class that contains the following method which automatically picks up the message from my queue and processes it.</p>
<pre><code>public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log)
{
log.WriteLine(message);
}
</code></pre>
<p>My question is how do I have a bit more control over handling the queue message. For example, I 'd like to make sure the message is processed and deleted. This method seems to do all of that for me but how do I know if the message is processed correctly? What if it fails, how do I tell it not to delete the message?</p> | 1 |
My Output has some weird symbols displaying | <p>I had to a coding for my class. The coding is about asking the user to type their Name, age and id. An then the program should for a passcode based on the first 6 letter in their name, their age and the first two letter in their student id. The problem is the a unidentified symbol (╠╠╠╠╠╠╠╠╠╠╠╠╠╠ )in the output. Can anyone tell me why it is there>? Then it should calculate and display the lenght of the passcode. Here is the code:</p>
<pre><code>#include <stdio.h>
#include <string.h>
void main(void)
{
char name[20], id[9], age[3], passcode[10];
int x;
puts("Enter your name:\n");
gets(name);
puts("\nEnter your student id:\n");
gets(id);
puts("\nEnter your age:\n");
gets(age);
x = strlen(passcode);
strncpy(passcode, name, 6);
strncat(passcode, id, 2);
printf("The passcode is:%s \n",passcode);
printf("The passcode has %d characters..\n",x);
}
</code></pre>
<p>And it look like:</p>
<pre><code>Enter your name:
johnny
Enter your student id:
dc87671
Enter your age:
20
The passcode is:johnny╠╠╠╠╠╠╠╠╠╠╠╠╠╠20dc
The passcode has 22 characters..
Press any key to continue . . .
</code></pre> | 1 |
convert python script to exe and run as windows service | <p>I just created an python script that solve me a problem i need but i want to convert this script to exe file to run it in any windows machine without need of install python on it
I have search of how could i convert the py to exe and run it and i have found that i could use script called py2exe the problem here that i want to convert my file to exe and run it as a windows service continuously on the my PC.</p>
<p>Here is the my script:</p>
<pre><code>import socket, sys, serial
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
# try:
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
# print('Connected with {}:{}'.format(addr[0], addr[1]))
str = conn.recv(100)
n_str = str[8:]
last_c = n_str.find('%')
last_str = n_str[:last_c]
final_str = last_str.replace('+',' ')[:-3]
print(final_str)
try:
pole = serial.Serial('COM4')
pole.write(' \r\n')
pole.write(final_str+'\r\n')
pole.close()
except:
print(Exception.message)
s.close()
</code></pre>
<p>Could i have some help here</p> | 1 |
Error Parsing 'Gemfile' | <p>I am working on a learning rails project on</p>
<p><a href="http://railsapps.github.io/installrubyonrails-mac.html" rel="noreferrer">http://railsapps.github.io/installrubyonrails-mac.html</a></p>
<p>I am on the Rails Example Applications section, but when I run </p>
<pre><code>bundle install --without production
</code></pre>
<p>I receive this error:</p>
<pre><code> [!] There was an error parsing `Gemfile`: no .<digit> floating literal anymore; put 0 before dot - ruby ‘2.3.0’
^
/Users/eric.park/workspace/learn-rails/Gemfile:2: syntax error, unexpected tFLOAT, expecting '('
ruby ‘2.3.0’
^. Bundler cannot continue.
# from /Users/eric.park/workspace/learn-rails/Gemfile:2
# -------------------------------------------
# source 'https://rubygems.org'
> ruby ‘2.3.0’
# gem 'rails', '4.2.5'
# -------------------------------------------
</code></pre>
<p>I am new to rails, so if anyone can explain what this error generally means, and how I can address it if it shows up again that would be really helpful. </p> | 1 |
get all element and value of html in android | <p>i have some html like this one:</p>
<pre><code><p>text1 &nbsp;</p>
<p><img src="http://theSite.com/apple.png" alt="apple-touch-icon-144x144-precomposed" /></p>
<p><img src="http://theSite.com/sony.gif" alt="cool" /></p>
<p style="text-align: center;">Second Text&nbsp;</p>
<p><img src="http://theSite.com/img.jpg" alt="2" /></p>
<p>&nbsp;</p>
<p style="text-align: left;">TextAgain&nbsp;</p>
</code></pre>
<p>i need to get element name and some properties of that in a list or array.
just name of tag (like p) and text of between tag and for img tag src property. </p>
<p>like this:</p>
<pre><code> String[] elements = {
"p",
"p",
"img",
"p",
"img"
}
String[] values = {
"text1 &nbsp;",
"<img src=...",
"http://thesite.com/apple.png",
"<img src=...",
"http://thesite.com/sony.gif"
}
</code></pre>
<p>is there any library like Jsoup or any method to doing that? </p> | 1 |
How to resolve “No Dialect mapping for JDBC type: -1” error in java | <p>i'm getting <strong>No Dialect mapping for JDBC type: -1</strong> error.
Previously i asked same question but i'm not catch correct solution.So again i'm asking.</p>
<p>How to resolve this error i.e,</p>
<pre><code>org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
at org.hibernate.dialect.TypeNames.get(TypeNames.java:56)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:81)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:393)
</code></pre>
<p>my code here:</p>
<pre><code>Session session = null;
session = getHibernateTemplate().getSessionFactory().openSession();
Query qu = session.createSQLQuery("select xml from details " +
"where start_date between (select * from(select eventdate from emplyoeevent " +
"where event='logout' and event_id in (select session_id from session " +
"where session_emplyoee='"+Id+"') order by eventdate asc) " +
"where rownum=1) and TO_DATE(SYSDATE, 'DD-MON-YYYY HH:MI:SS PM')");
List li = qu.list();
</code></pre>
<p>I'm getting error in List li = qu.list(); line. What is the meaning of this error.</p>
<p>Any suggestion would be appreciated</p> | 1 |
Server stored fonts vs Google fonts? | <p>What is better in speed and reliability, to store the font in my project (say in <strong>Styles</strong> folder) or to link to a font from Google?</p>
<p>ie</p>
<pre><code>@font-face {
font-family: 'myfont';
src: url(gothic.ttf);
}
body {
font-family: myfont;
}
</code></pre>
<p>or</p>
<pre><code> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine:bold,bolditalic|Inconsolata:italic|Droid+Sans">
body {
font-family: 'Tangerine', 'Inconsolata', 'Droid Sans', serif;
}
</code></pre> | 1 |
How can I let a div fill 100% width if no other elements are beside it? | <p>I have simple markup like this (a tab menu):</p>
<pre class="lang-html prettyprint-override"><code><div class="container">
<div class="tab1"></div>
<div class="tab2"></div>
<div class="tab3"></div>
</div>
</code></pre>
<p>That is the case when all elements have an equal width of 33% to fill 100% of the container.</p>
<p>Is it possible to apply a general CSS rule for all containers that automatically detects if, for example, there are only 1 other container or none? And then adjusts the width of the tabs? ("Strech-To-Fit")</p>
<p>Perhaps something with <code>min-width</code> or <code>max-width</code>? </p> | 1 |
Using awk to get the maximum value of a column, for each unique value of another column | <p>So I have a file such as:</p>
<pre><code>10 1 abc
10 2 def
10 3 ghi
20 4 elm
20 5 nop
20 6 qrs
30 3 tuv
</code></pre>
<p>I would like to get the maximum value of the second column for each value of the first column, i.e.:</p>
<pre><code>10 3 ghi
20 6 qrs
30 3 tuv
</code></pre>
<p>How can I do using <code>awk</code> or similar unix commands?</p> | 1 |
Gradle dependency caching mechanism | <p>Under my user-home/.gradle/caches I am seeing multiple artifacts directories e.g. artifacts-14,artifacts-24, modules-2.
all these folders are storing duplicate artifacts. so my questions is, why and in what conditions gradle has to create multiple artifacts folders? can gradle also be configured to lookup and store artifacts in on directory. doing so I can save disk space from storing duplicate artifacts.</p> | 1 |
how to find all employees under each manager | <p>I need to get a query to display the subordinates all the way down starting from one specific manager. Let's say I have this structure and I need to get all employees starting from ManagerId = 1 </p>
<pre><code>EmployeeId ManagerId
2 1
3 1
4 3
5 3
6 4
</code></pre>
<p><a href="https://i.stack.imgur.com/P2XQ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P2XQ7.png" alt="Here I have the visualization"></a></p>
<p>I need to get as result of the query the ManagerId and direct report employees under him, along with their subordinates.</p>
<p>For example, using SQL Server 2014:</p>
<pre><code>CREATE TABLE #Pepe (EmployeeId INT, ManagerId int)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (2, 1)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (3, 1)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (4, 3)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (5, 3)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (6, 4)
</code></pre>
<p>Now I get the CTE</p>
<pre><code>;WITH relation AS
(
SELECT 1 as EmployeeId, 0 AS LEVEL
UNION ALL
SELECT r.EmployeeId, LEVEL + 1 AS LEVEL
FROM (SELECT EmployeeId, ManagerId FROM #Pepe) r
INNER JOIN relation T
ON r.ManagerId = T.EmployeeId
WHERE r.ManagerId <> r.EmployeeId
)
SELECT DISTINCT EmployeeId, LEVEL FROM relation
</code></pre>
<p>The result of my CTE is this:</p>
<pre><code>EmployeeId LEVEL
1 0
2 1
3 1
4 2
5 2
6 3
</code></pre>
<p>This result start from one specific employee which is 1 (is hardcoded on the CTE), now I need only the direct report, Level = 1 and also Level 0 too which are employee id 1, 2 and 3. </p>
<p>This is fine, now what I need is for each employee id (level 0 and 1), I need to get this result:</p>
<pre><code>EmployeeId ManagerId
1 1
2 1
3 1
4 1
5 1
6 1
2 2
3 3
4 3
5 3
6 3
</code></pre>
<p>As you can see the Manager Id contains the employees with level 0 and 1, and for each one I basically call the CTE to get all employees down, like for example ManagerId = 2 doesn't have subordinates but I need to count it anyway. Is there an efficient way to do this? I was using cross apply putting the CTE in an inline function but I was having troubles with performance.</p> | 1 |
Selecting User Control for Data Template based on an Enum | <p>I am working on a WPF app and currently I have an <code>ItemsControl</code> bound up to my View Model <code>ObservableCollection</code> and I have a <code>DataTemplate</code> that uses a <code>UserControl</code> to render the items on <code>canvas</code>. Can you use multiple User Controls and then switch which one is used based on an <code>Enum</code>? Another way to look it is to either create a <code>Button</code> or a <code>TextBox</code> for the item in the <code>ObservableCollection</code> based on an <code>Enum</code>. </p> | 1 |
Why does click for toggle checkbox become a double click? | <p>I am currently making a <code>checkbox</code> with a <code>label</code> attached to it. I use the <code>for</code> attribute to link the click for the checkbox.</p>
<p>I also have a jQuery function which <code>onclick</code> for the checkbox and labels container does a slide toggle for a text input field.</p>
<p>When I click the checkbox, only one click is detected and the text field slides down nicely. However, when I click the label it seems that a double click is happening so the text field slides down and then immediately back up.</p>
<p>I have an ID of <code>toggle-checkbox</code> on my checkbox and a <code>for="toggle-checkbox"</code> on my label and I suspect that somehow triggers an extra click.</p>
<p>HTML:</p>
<pre><code><div class="cart-summary__coupon-code">
<div class="form-group js-coupon-code">
<input class="cart-summary__coupon-code__checkbox" type="checkbox" id="toggle-checkbox">
<label class="cart-summary__coupon-code__label form-group__label--block" for="toggle-checkbox">click me</label>
</div>
</div>
<div class="coupon-code">
<input type="text" />
</div>
</code></pre>
<p>JavaScript:</p>
<pre><code>jQuery('.js-coupon-code').click(function() {
$( ".coupon-code" ).slideToggle( "slow", function() {
});
});
</code></pre>
<p>CSS:</p>
<pre><code>.coupon-code {
display: none;
}
</code></pre>
<p>I have <a href="http://codepen.io/anon/pen/QyBqXa" rel="nofollow">created a codepen</a> where the issue can be reproduced.</p> | 1 |
Convert string to int and get sum of numbers | <p>When I test this code it always returns 0 and I'm not sure why.</p>
<pre><code>public class test {
public int sumOfDigits(String s) {
int sum = 0;
for (int i=0; i<s.length(); i++) {
char cur = s.charAt(i);
if (cur >= 0 && cur <= 9) {
sum += cur - '0';
}
}
return sum;
}
}
</code></pre> | 1 |
Active and not active marker on click using google maps | <p>How would I achieve having a custom active state on click and when not active it defaults back to the original custom marker. I've tried various attempts but this is the closest I've gotten it. Has anyone solved this before?</p>
<pre><code>jQuery(function($) {
var is_internetExplorer11 = navigator.userAgent.toLowerCase().indexOf('trident') > -1;
var marker_url = (is_internetExplorer11) ? 'map_marker_highlight.png' : 'map_marker_highlight.png';
var activeIcon = {
url: 'map_marker.png',
// This marker is 20 pixels wide by 32 pixels tall.
//size: new google.maps.Size(32, 32),
// The origin for this image is 0,0.
//origin: new google.maps.Point(130.3065885, -193.6986437),
// The anchor for this image is the base of the flagpole at 0,32.
anchor: new google.maps.Point(16, 40)
};
var locations = [
['<b>Name</b><br>Address<br>state<br>', 34.845244, -80.371634, 4],
['<b>Name</b><br>Address<br>state<br>', 34.845244, -80.371634, 4],
];
var mapOptions = {
center: new google.maps.LatLng(138.3065885, -193.6986437),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
zoomControl: true,
scrollwheel: false,
styles: styles
};
map = new google.maps.Map(document.getElementById("mack-map"), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: marker_url,
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
//console.log(activeIcon);
infowindow.setContent(locations[i][0]);
if (infowindow) {
this.setIcon(activeIcon)
} else {
this.setIcon(marker_url)
}
infowindow.open(map, marker);
}
})(marker, i));
}
});
</code></pre> | 1 |
Remove title tooltip on hover but not in HTML | <p>On the following site:</p>
<p><a href="http://gregorydanelian.comule.com/ken/" rel="nofollow">Link to site with issues</a></p>
<p>I have three buttons at the bottom of each thumbnail (hover to see them). The three buttons open up a prettyphoto box that uses the title attribute under the image (hidden as white currently next to the gallery nav buttons).</p>
<p>I need the HMTL title attribute to remain within the HTML. I just do not need the ugly tooltip when you hover over the buttons.</p>
<p>Does anyone know how to remove hover title tooltip on links?</p> | 1 |
Angular thumbnail from local video file | <p>I am trying to generate thumbnails using angular-thumbnails (<a href="https://github.com/aztech-digital/angular-thumbnails" rel="nofollow">https://github.com/aztech-digital/angular-thumbnails</a>) from local video files instead of video urls, this is what I have so far, it only works with some videos: <a href="https://plnkr.co/edit/j7LR7FU0itRmPmLJWgwT?p=preview" rel="nofollow">https://plnkr.co/edit/j7LR7FU0itRmPmLJWgwT?p=preview</a></p>
<pre><code>var app = angular.module('plunker', ['angular-thumbnails']);
app.controller('MainCtrl', function($scope) {
$scope.$watch('myFile', function(newVal, oldVal) {
var reader = new FileReader();
reader.addEventListener('load', function() {
$scope.myVideoData = reader.result;
console.log('myVideoData', $scope.myVideoData);
}, false);
if (newVal) {
reader.readAsDataURL(newVal);
}
});
});
app.directive('fileModel', function() {
return {
restrict: 'A',
scope: {
fileModel: '='
},
link: function(scope, element, attrs) {
element.bind('change', function(e) {
scope.$apply(function() {
scope.fileModel = e.target.files[0];
});
});
}
};
});
</code></pre> | 1 |
Javascript Slideshow with play pause and Next Prev button | <p>I'm making a slideshow in Javascript with a Play / Pause and Next / Prev. I have manage to slideshow working with play/pause button, but now i wanted to add Next and Prev button to it. Can some one please help me how can i do that.</p>
<p>Here's my HTML:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Simple HTML Slideshow</title>
<style type="text/css">
#slideshow {
margin: 50px auto;
position: relative;
width: 900px;
height: 450px;
padding: 10px;
}
#slideshow > div {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
}
#slideshow > div > img {
width: 100%;
}
#button { text-align: center; }
</style>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</head>
<body>
<div id="slideshow">
<div>
<img name="slide" id="imgSlideshow" src="http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg">
</div>
</div>
<div id="button">
<a href="#" id="prevBtn" onclick="showPrev()">Prev</a>
<a href="#" id="startCycle" onclick="setTimer()">Play/Pause</a>
<a href="#" id="nextBtn" onclick="showNext()">Next</a>
</div>
</body>
</html>
</code></pre>
<p>Here is JavaScript:</p>
<pre><code><script language="javascript" type="text/javascript">
var i = 0;
var path = new Array();
//var timer = setInterval("slide()",2000);
var timer;
// LIST OF IMAGES
path[0] = "http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg";
path[1] = "http://themarklee.com/wp-content/uploads/2013/12/starlight.jpg";
path[2] = "http://themarklee.com/wp-content/uploads/2013/12/snowstorm.jpg";
path[3] = "http://themarklee.com/wp-content/uploads/2013/12/misty-winter-afternoon.jpg";
function slide() {
document.getElementById("imgSlideshow").src = path[i];
i = (i + 1)%path.length;
//console.log(i);
}
function setTimer(){
if (timer) {
// stop
clearInterval( timer );
timer=null;
}
else {
timer = setInterval("slide()",2000);
}
}
var imgNumber = 1;
var numberOfImg = path.length;
function previousImage() {
if(imgNumber > 1) {
imgNumber--;
}
else {
imgNumber = numberOfImg;
}
document.getElementById("imgSlideshow").src = path[imgNumber-1];
changeCounter(imgNumber, numberOfImg);
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.getElementById("imgSlideshow").src = path[imgNumber-1];
changeCounter(imgNumber, numberOfImg);
}
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
document.getElementById("counter").innerHTML = 1 + "/" + path.length;
</script>
</code></pre>
<p>Any Help is appreciated and thanks in advance.</p> | 1 |
Run Atom editor as root in FileZilla for view/edit files | <p>I know how to open/edit files from the server in FileZilla. I set up this:</p>
<pre><code>/usr/bin/atom
</code></pre>
<p>in <code>edit -> settings -> file editing</code> </p>
<p>But the problem is that it opens the file in non-root Atom mode.</p>
<p>How to open file in Atom editor as root?</p> | 1 |
How to get a program to repeat itself using a while loop and if statement? | <p>I'm really new to Python and I'm finding it really hard to understand certain aspects of the language. I've been asked to create a program for an assignment and after hours of trying to use this website, I've come to no avail.</p>
<p>The question is:
Write a program which uses a loop to take in the first name, last name and
telephone number from an undefined number of users. The program
should allow the user the option to quit, after each iteration of the loop. <strong>The program should also write the information entered by the user to a text file called names.tx</strong></p>
<p>I have no problem with the part of the question in bold but I really can't wrap my head around the first bit. Here's what I have so far:</p>
<pre><code>def main():
infoList = []
count = 0
while True:
firstname = input('Please enter your first name: ')
lastname = input('Please enter your last name: ')
telephoneno = input('Please enter your telephone number: ')
contiinue = input('Continue (y = yes): ')
if contiinue == y:
count = count + 1
main()
</code></pre>
<p>When the program is iterating itself again, I want the user to be able to give different details to the questions. I know people hate when people ask questions and it seems like they're just trying to get people to do homework for them, but this will genuinely bug me for a while if I am unable to find a resolution.</p> | 1 |
Reading JSON file in Python and detecting specific keywords in field | <p>I just started this week to learn Python and I have the following question. I have a JSON file (Aberdeen2015.json) that contains 60 lines (each line containing a newspaper article). Moreover, each line contains a list with the <code>date</code>, <code>title</code> and <code>body</code> of the article (see picture below, title cannot be seen since it's towards the end of the line). </p>
<p><a href="https://i.stack.imgur.com/q0p2x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q0p2x.png" alt="enter image description here"></a></p>
<p>I want to do the following: if certain keywords are in the <code>body</code> of an article, print a list with the <code>date</code> of those articles. So far I have tried to do the following:</p>
<pre><code>with open("Aberdeen2015.json") as f:
for i in line():
if (' tax ' in body[i]
or ' Tax ' in body[i]
or ' policy ' in body[i]
or ' Policy ' in body[i]
or ' regulation ' in body[i]
or ' Regulation ' in body[i]
or ' spending ' in body[i]
or ' Spending ' in body[i]
or ' budget ' in body[i]
or ' Budget ' in body[i]
or ' central bank ' in body[i]
or ' Central Bank ' in body[i]
or ' Central bank ' in body[i]):
print("date")
</code></pre>
<p>I am aware that the code might have many failures, any help is more than welcome.</p> | 1 |
What are good alternatives to the Cassandra Lucene Index? | <p>Since I constantly have this problem described below I would like to change but lack of a better alternative.</p>
<p>I have 2 queries which should return the same result. But the 2nd query returns a lot less results or sometimes no results. These are the 2 queries:</p>
<pre><code>SELECT * FROM statistics WHERE source = 'toutiao' AND timespan = '3';
SELECT * FROM statistics WHERE source = 'toutiao' AND timespan = '3' AND text = '{ sort: {fields: [{field: "speed", reverse: true}]}}';.
</code></pre>
<p>I use this custom cassandra index <a href="https://github.com/Stratio/cassandra-lucene-index" rel="nofollow">https://github.com/Stratio/cassandra-lucene-index</a>.</p>
<p>EDIT:</p>
<p>I use Cassandra 2.2.4.1 cassandra-lucene-index 2.2.4</p>
<p>'text' is the table column over which I have built the index.</p>
<p>My Index creation query is:</p>
<pre><code>CREATE CUSTOM INDEX statistics_text_idx ON toutiao.statistics (text) USING 'com.stratio.cassandra.lucene.Index' WITH OPTIONS = {'schema': '{
fields : {
title: {
type : "text", analyzer : "english"},
category : {type:"string"},
genre : {type:"string"},
speed : {type : "integer",sorted : true}
}
}', '
refresh_seconds': '1'};
</code></pre>
<p>Table creation query:</p>
<pre><code>DROP TABLE IF EXISTS statistics;
CREATE TABLE statistics (
source text,
timespan text,
id text,
title text,
thumbnail text,
url text,
text text,
created_at timestamp,
category text,
category2 text,
genre text,
author text,
reads int,
likes int,
comments int,
shares int,
speed int,
PRIMARY KEY (source, timespan, id)
)WITH CLUSTERING ORDER BY (timespan DESC) AND caching = '{"keys":"ALL", "rows_per_partition":"ALL"}';
</code></pre>
<p>This is my data insert program:</p>
<pre><code>cluster = Cluster(['localhost'])
session_statis = cluster.connect(keyspace)
session_statis.execute('INSERT INTO tablename(col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,col12,col13,col14,col15) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', (value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15))
</code></pre>
<p>Thank you for the help!</p> | 1 |
Getting child input from div jquery | <p>I have a repeater that has a UserControl inside it that shows me 3 security questions like this: </p>
<pre><code><asp:Repeater runat="server" ID="rptSecurityQuestions">
<ItemTemplate>
<it:TextBoxControl_v2
ID="txtQuestion"
runat="server"
ShowLabel="true"
MinLength="1"
MaxLength="64"
Label='<%# DataBinder.Eval (Container.DataItem, "question") %>'
RegexExpression=""
TextMode="SingleLine"
CssClass="field field-padding-r metro col-centered securityQuestions"
IsRequired="true" />
</ItemTemplate>
</asp:Repeater>
</code></pre>
<p>And it displays like this 3 times: </p>
<pre><code> <div class="securityQuestions">
<span>Question 1</span>
<input></input>
</div>
</code></pre>
<p>all i want is to get the inputs that are child of my div.</p>
<p>I tried something like this but it didn't work out.</p>
<pre><code>$(this).children('securityQuestions').addClass('hover_triangle');
</code></pre> | 1 |
Cannot convert a viewController object to viewController type in Swift | <p>I want to pass data from one view controller to another. And I am using the following code in the <code>prepareForSegue</code> to do so...</p>
<pre><code>let detailVC: DetailVC = segue.destinationViewController as! DetailVC
detailVC.alertDict = sender as! NSDictionary
</code></pre>
<p>In the first line as you can see there is a <code>!</code> after the as. Thats because I have to use it to <strong>force downcast</strong>, and if I do not include the <code>!</code> then I get an error: <code>UIViewController</code> is not convertable to <code>DetailVC</code>. But <code>DetailVC</code> is a inheritance of <code>UIViewController</code> class, so why can it not convert? Here is the code for the class..</p>
<pre><code>class DetailVC: UIViewController, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {/*code*/}
</code></pre> | 1 |
Krajee Bootstrap fileinput how can i change the uploadExtraData dynamically | <p>Hi Am using Krajee Bootstrap fileinput , i need to change the <code>uploadExtraData</code> dynamically on submitting the form. So i made it as a call back function. But it doesn't work for me. As i think <code>uploadExtraData</code> callback function work at on initialization only.</p>
<p>here is my code</p>
<pre><code>$(".file-loading").fileinput({
uploadUrl: document.location.origin + "/discussions/add",
uploadAsync: false,
uploadExtraData:getFormData(),
});
function getFormData(){
var project_id = $("#DiscussionProjectId").val();
var discussion_title = $("#DiscussionDiscussionTitle").val();
var comment = $('#discussionComment').attr('value');
var data = {
project_id:project_id,
discussion_title:discussion_title,
comment:comment
};
return data;
}
</code></pre>
<p>Am doing to save the input files and data on form submit only.</p> | 1 |
Change Connection String at Runtime in EF 6 | <p>I mostly use my dbcontext with using statements like this:</p>
<pre><code>using (var context = new MyContext())
{
}
</code></pre>
<p>But I later had to add a project with a function to change the database. I found out that I could change my dbcontext constructor to this:</p>
<pre><code>public MyContext(string connectionstring)
: base(connectionstring)
{
}
</code></pre>
<p>I made a class with a property for the connectionstring:</p>
<pre><code>public static class DbAccessor
{
public static string ConnectionStringForContext { get; set; }
}
</code></pre>
<p>I set this property in the beginning and my using statements look like this:</p>
<pre><code>using (var context = new MyContext(DbAccessor.ConnectionStringForContext)
{}
</code></pre>
<p>It works, but my connection string is now everywhere and I feel like I should not do that with connection strings. Is there a better way of doing this? What would be the best way to handle my Connection Strings if I want to change them? Should I stop using these using statements?</p>
<p>I've seen this question: <a href="https://stackoverflow.com/questions/20216147/entity-framework-change-connection-at-runtime">Entity Framework change connection at runtime</a></p>
<p>But the difference is, that I have a functioning solution, but I don't want to have my connection string everywhere. If I used that extension method inside every using statement. It would almost be like my solution just one line more in every using statement...</p> | 1 |
React setState only if thing exists? | <p>So I am setting up a parent with several state attributes to pass to children. This is being done via AJAX. The trouble is that for some of these variables, the response may return <code>null</code> or <code>undefined</code>.</p>
<pre><code>$.post(this.props.source, function(data) {
// Parse the response
var response = JSON.parse(data);
if (this.isMounted()) {
this.setState({
// Set initial state vars
minPrice: response.resultDetails.minPrice,
maxPrice: response.resultDetails.maxPrice,
language: response.params.language,
filters: response.params.filters
});
}
}.bind(this));
</code></pre>
<p>How can I say something like <code>if response.params.language, set language</code>? I cannot figure out the React syntax to do such a thing.</p> | 1 |
Ipython Notebook shows Import Error for Seaborn even when package is installed in Conda environment | <p>So I am trying to use Ipython notebook with Anaconda (Windows10). I got into anaconda cmd and create a new environment TryThis. I install Seaborn in this environment. And then I run Ipython command in the conda cmd.</p>
<pre><code> conda create --name TryThis python=2
activate TryThis
conda install seaborn
ipython
</code></pre>
<p>When I run </p>
<pre><code> import seaborn as sns
</code></pre>
<p>in this it executes allright.</p>
<p>However if I exit this and then run</p>
<pre><code> ipython notebook
</code></pre>
<p>in the conda cmd and go on to do the import in an ipython notebook in browser, it throws error</p>
<pre><code>---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-ed9806ce3570> in <module>()
----> 1 import seaborn as sns
ImportError: No module named seaborn
</code></pre>
<p>I do not understand what is going wrong. If Seaborn is in this anaconda environment and I initiated Ipython notebook in this environment and Ipython in console can recognize it, why doesn't the notebook ?</p>
<p>What I might be doing is something blatantly incorrect, but I just started out with using anaconda !</p> | 1 |
Avoiding "An INSERT EXEC statement cannot be nested" | <p>I know that this is not possible to nest <code>insert ... exec</code> statements, but still I'm interested - is there a way to check if I already have active <code>insert ... exec</code> to avoid actual error?</p>
<p>So I want to have something like this:</p>
<pre><code>....
if <check if I have outer insert into exec> = 0
insert into <#some temporary table>
exec <stored procedure>
</code></pre>
<p>In other words - <code>insert ... exec</code> is optional, it's nice to have it, but I want to skip it if somebody tries to call my procedure with outer <code>insert ... exec</code></p> | 1 |
What is the use of Hashable and Equatable in Swift? When to use which? | <p>I know that Hashable is inherited from Equatable, but can you give me an example that requires Hashable, not just Equatable. Thanks!</p> | 1 |
How to write http interceptor for AngularJS 2? | <p>I want to check all my http responses from one place. For example authentication status. If response says user not authenticated any more I wanna redirect or something else. Is there any way to do that.</p> | 1 |
HTML5 form button onsubmit not working | <p>I have a simple form with two HTML5 buttons. Each button submits the form to a different php page. This is working well, but the 'onsubmit' function is never triggered. I want to show a dialog box before the delete.php page is called.</p>
<pre><code><form method="post">
<input type="text" name="fname">
<!-- HTML5 FORMACTION -->
<button type="submit" name="update" formaction="update.php">Update</button>
<button type="submit" name="delete" onsubmit="return confirm('Do you really want to delete?');" formaction="delete.php">Delete</button>
</form>
</code></pre>
<p>I have tried different variations, but the javascript code is never triggered. Why?</p> | 1 |
Repeat set of mocha tests for two different inputs | <p>I have a feeling I might be thinking about this wrong, but is there any way I can run a set of mocha tests for two different inputs? In my use case, I am parsing data from a pdf and want to run the tests for when the pdf is only one page, and when it is multiple pages.</p>
<p>Right now I am using beforeEach to call my parsePdf function:</p>
<pre><code>describe('When parsing a single page pdf', function () {
beforeEach(function (done) {
invoiceParser.parsePdf('./test/samples/invoice_singlepage.pdf', function (invoice) {
this.invoice = invoice;
done();
}.bind(this));
});
...
// tests fields of this.invoice w/ chai.js
...
});
</code></pre>
<p>What I was thinking is I can just parse two invoices before each and check the values of each? Then I have to repeat a lot of code though. Any way to to do this without repeating each test?</p> | 1 |
Set rows to repeat at top when printing - PHPExcel | <p>I need to put table head row to each printed page while printing a long data sheet(<a href="https://support.office.com/en-us/article/Repeat-specific-rows-or-columns-on-every-printed-page-0d6dac43-7ee7-4f34-8b08-ffcc8b022409" rel="nofollow">like this</a>), but I failed to find any related setup in PHPExcel, could anyone faced the same problem help me out?</p> | 1 |
Connecting from psycopg2 on local machine to PostgreSQL db on Docker | <p>I have used the following commands to create a Docker image with Postgres running on it: </p>
<p><code>docker pull postgres
docker run --name test-db -e POSTGRES_PASSWORD=my_secret_password -d postgres</code></p>
<p>I then created a table called test and inserted some random data into a couple of rows.
I am now trying to make a connection to this database table through psycopg2 in Python on my local machine.
I used the command <code>docker-machine ip default</code> to find out the IP address of the machine as 192.168.99.100 and am using the following to try and connect:</p>
<pre><code>conn = psycopg2.connect("dbname='test-db' user='postgres' host='192.168.99.100' password='my_secret_password' port='5432'")
</code></pre>
<p>This is not working with the error message of "OperationalError: could not connect to server: Connection refused (0x0000274D/10061)"</p>
<p>.
.</p>
<p>Everything seems to be in order so I can't think why this would be refused.
According to the documentation for this postgres image, (at <a href="https://hub.docker.com/_/postgres/" rel="nofollow">https://hub.docker.com/_/postgres/</a>) this image includes EXPOSE 5432 (the postgres port) and the default username is postgres.</p>
<p>I also tried to get the IP address of the image itself with <code>docker inspect test-db | grep IPAddress | awk 'print{$2}' | tr -d '",'</code> that I found on SA to a slightly related article, but that IP address didn't work either.</p> | 1 |
Unable to detect adb version, adb output Unable to obtain debug bridge | <p>I am new to coding and have recently installed the latest version of Android Studio and the SDK package on my Mac OSX. I am receiving the error in the title when trying to run the basic "HelloWorld!" app. I know many have commented on this error, and I have tried putting earlier versions of the ADB file into my platform-tools folder but it did not fix the issue. I think it is because I am running it on OSX. As it is now, I have the adb execute file in my platform-tools folder in the right location, so I'm not sure why I am still having issues. Thanks so much.</p> | 1 |
Git reset - branch is behind master | <p>I made several commits (let's say with IDs: 1, 2, 3, 4) and then realized that I made a mistake in commit 3 and want to go back to the version of code at commit 2.</p>
<p>I did:</p>
<pre><code>git reset --hard 2
</code></pre>
<p>Now git says: </p>
<pre><code>On branch master.
Your branch is behind origin/master by 11 commits and can be fast forwarded.
</code></pre>
<p>I am wondering how I can "push" my code so that everyone has this version. </p> | 1 |
Change Item Height of ComboBox | <p>How to set combobox item height? My combobox.size=new size(320,40) and I had set combobox.itemheight=18 but it didn't work. I want my itemheight or text height to be 18, and fixed size for the combobox which is 320x40. I used also drawmode property but nothing is happening.</p> | 1 |
size() function not working in Processing 3.0 | <p>I am trying to set size of the window in <a href="http://processing.org/" rel="nofollow">Processing 3.0</a> by passing the parameters from the image width and height. However, Processing is throwing an error and asking to check the Reference section which isn't helpful. Code is below. </p>
<pre class="lang-java prettyprint-override"><code>PImage img;
...
void setup(){
img = loadImage("XYZ.JPG");
float w = img.width;
float h = img.height;
size(int(w), int(h));
image(img, 0, 0);
}
</code></pre>
<p>and error below:</p>
<pre class="lang-java prettyprint-override"><code>size() function cannot be used here
</code></pre> | 1 |
jquery ajax how should it format dates? | <p>I use jquery to communicate with a REST API. (ASP.net Web API).</p>
<p>I create a simple object and then use jquery to 'PUT' it on the server:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = {
name: 'just a name',
createDate: new Date()
}
$.ajax({
url: 'https://myServer/api/person/1',
dataType: 'json',
method: 'put',
data: myObject
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
<p>Looking at the network traffic in Firebug I can see that my createDate propery gets sent over the line as:</p>
<pre><code>Tue Feb 02 2016 14:40:26 GMT+0100 (W. Europe Standard Time)
</code></pre>
<p>This would be the default rendering of a <code>new Date().toString()</code></p>
<p>Not remarkably my API does not like this, it accepts dates in several formats and really handles the normal JSON version very well:</p>
<pre><code>new Date().toJSON()
results to: "2016-02-02T13:45:37.069Z"
</code></pre>
<p>How to deal with this? I would prefer not to have to post my object by 'manually' converting every date to JSON, this takes the whole ease of working with complex objects out of it.</p>
<p>What I could to (warning really dirty trick coming up), override the default toString method of the date object:</p>
<pre><code>Date.prototype.toString = new Date().toJSON
</code></pre>
<p>This works... but... YUCK!</p>
<p>Any thoughts? </p> | 1 |
What is monkey patching regarding TypeScript ? | <p>Can someone give me an example of monkey patching regarding TypeScript & Angular2 and also an explanation ? </p> | 1 |
How to pass single instance of WebDriver between TestNg classes | <p>I couldnt find a difinitive answer to this anywhere on the net.</p>
<p>I have multiple TestNg classes to run tests, BrowserFunctions, Login, Search, Filter (testing Amazon uk for practice). I also have a BrowserLauncher class that returns the appropriate webdriver based on browser name, and a testng.xml file.</p>
<p>BrowserFunctions.java</p>
<pre><code>public class BrowserFunctions {
BrowserLauncher bl = new BrowserLauncher();
WebDriver driver;
StringBuilder sb = new StringBuilder();
@BeforeSuite
public void initialioseBrowser() {
driver = bl.launchBrowser("Firefox");
}
@Parameters({ "URL" })
@BeforeSuite
public void invokeURL(String URL) {
driver.get(URL);
}
@AfterSuite
public void closeBrowser() {
driver.close();
}
</code></pre>
<p>Login.java</p>
<pre><code>public class Login {
BrowserLauncher bl = new BrowserLauncher();
WebDriver driver;
StringBuilder sb = new StringBuilder();
@Parameters({ "email", "password" })
@Test
public void logInTest(String email, String passowrd) {
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKsignInCTA), "Sign in CTA visible");
CommonFunctions.clickButton(driver, PageElements.amzUKsignInCTA);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKEmailField), "Email field visible");
CommonFunctions.inputToField(driver, PageElements.amzUKEmailField, email);
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKPasswordField),
"Password field visible");
CommonFunctions.inputToField(driver, PageElements.amzUKPasswordField, passowrd);
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKSignInButton),
"Sign in button visible");
CommonFunctions.clickButton(driver, PageElements.amzUKSignInButton);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Assert.assertEquals(driver.getCurrentUrl(), "https://www.amazon.co.uk/?ref_=nav_ya_signin&");
}
</code></pre>
<p>Search.java</p>
<pre><code>public class Search {
BrowserLauncher bl = new BrowserLauncher();
WebDriver driver;
StringBuilder sb = new StringBuilder();
@Parameters({ "searchTerm" })
@Test
public void searchTest(String searchTerm) {
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKSearchField),
"Search field visible");
CommonFunctions.inputToField(driver, PageElements.amzUKSearchField, searchTerm);
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKSearchButton),
"Search button visible");
CommonFunctions.clickButton(driver, PageElements.amzUKSearchButton);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKResultContainer),
"Results container visible");
if (driver.findElements(PageElements.amzUKResultContainer).size() > 0) {
List<WebElement> resultContainerList = driver.findElements(PageElements.amzUKResultContainer);
for (WebElement w : resultContainerList) {
if (w.findElements(PageElements.amzUKResultTitle).size() > 0) {
if (w.findElement(PageElements.amzUKResultTitle).getText().contains(searchTerm)) {
} else {
sb.append(w.findElement(PageElements.amzUKResultTitle).getText() + " does not contain"
+ searchTerm + "\n");
}
}
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKResultImage),
"Result image visible");
if (w.findElements(PageElements.amzUKResultImage).size() > 0) {
} else {
sb.append(w.findElement(PageElements.amzUKResultTitle).getText()
+ " does not contain an image\n");
}
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKResultPrice),
"Result price visible");
if (w.findElements(PageElements.amzUKResultPrice).size() > 0) {
if (w.findElement(PageElements.amzUKResultPrice).getText().contains("£")) {
} else {
sb.append(w.findElement(PageElements.amzUKResultTitle).getText()
+ " does not contain a price\n");
}
}
}
}
System.out.println("searchTest(" + searchTerm + ") Failures:\n" + sb.toString());
}
</code></pre>
<p>Filter.java
public class Filter {</p>
<pre><code>BrowserLauncher bl = new BrowserLauncher();
WebDriver driver;
StringBuilder sb = new StringBuilder();
@Test
public void filterTest() {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<String> filterOptionsList = new ArrayList<String>();
sb.append(CommonFunctions.clickButton(driver, PageElements.amzUKFilterSeeMore));
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKFilterOptions),
"Filter options visible");
for (int i = 0; i < driver.findElements(PageElements.amzUKFilterOptions).size(); i++) {
filterOptionsList.add(driver.findElements(PageElements.amzUKFilterOptions).get(i).getText());
}
for (String s : filterOptionsList) {
Assert.assertTrue(CommonFunctions.checkVisibility(driver, By.partialLinkText(s)), ""
+ s + " link visible");
if (driver.findElements(By.partialLinkText(s)).size() > 0) {
driver.findElement(By.partialLinkText(s)).click();
}else {
sb.append("Link " + s + " not visible");
continue;
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKFilterAnyCategory),
"\"Any Category\" button visible");
CommonFunctions.clickButton(driver, PageElements.amzUKFilterAnyCategory);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
sb.append(CommonFunctions.clickButton(driver, PageElements.amzUKFilterSeeMore));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
System.out.println("filterTest Failures:\n" + sb.toString());
}
</code></pre>
<p>BrowserLauncher.java</p>
<pre><code>public WebDriver launchBrowser(String BrowserName) {
if(BrowserName.equalsIgnoreCase("Firefox")) {
driver = new FirefoxDriver();
driver.manage().window().maximize();
} else if(BrowserName.equalsIgnoreCase("IE")) {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, "");
System.setProperty("webdriver.ie.driver", "C:\\Eclipse EE x86 Workspace\\ResidentAdvisorLabels\\IEDriverServer.exe");
driver = new InternetExplorerDriver(capabilities);
driver.get("javascript:document.getElementById('overridelink').click();");
} else if(BrowserName.equalsIgnoreCase("Chrome")) {
ChromeOptions op = new ChromeOptions();
op.addArguments("--user-data-dir=C:\\Users\\Bernard\\Desktop\\Selenium Data");
op.addArguments("--start-maximized");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
System.setProperty("webdriver.chrome.driver", "C:\\Eclipse EE x86 Workspace\\ResidentAdvisorLabels\\chromedriver.exe");
driver = new ChromeDriver(op);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
} else if(BrowserName.equalsIgnoreCase("PhantomJS")) {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("takesScreenshot", false);
String d = "\\";
capabilities.setCapability("phantomjs.binary.path", "C:"+d+"Eclipse EE x86 Workspace"+d+"phantomjs-2.0.0-windows"+d+"bin"+d+"phantomjs.exe");
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability("load-images", false);
driver = new PhantomJSDriver(capabilities);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
return driver;
}
</code></pre>
<p>testng.xml</p>
<pre><code><suite name="Suite1" verbose="1">
<parameter name="searchTerm" value="Selenium Webdriver" />
<parameter name="URL" value="Http://www.amazon.co.uk" />
<parameter name="email" value="scrubbed" />
<parameter name="password" value="scrubbed" />
<test name="AmazonUKTesting">
<classes>
<class name="tests.amazonUKTests.BrowserFunctions" />
<class name="tests.amazonUKTests.Login" />
<class name="tests.amazonUKTests.Search" />
<class name="tests.amazonUKTests.Filter" />
</classes>
</test>
</code></pre>
<p></p>
<p>My problem is that i cannot seem to be able to pass the WebDriver that is returned to the BrowserFunctions.java class on to the other classes in my test suite without having to create a new instance of WebDriver in each java file. I am looking to open the browser, open the URL, then run the 3 tests one after another in the same browser window, and have the browser close when done.</p> | 1 |
Better way to tokenize string in Ruby? | <p>I have a string of arbitrary characters. I would like to turn it into an array, where each character is in a single array element, EXCEPT of successive word-characters <code>(\w+)</code>, which should end up together in one array element. Example:</p>
<pre><code>ab.:u/87z
</code></pre>
<p>should become</p>
<pre><code>['ab','.',':','u','/','87z']
</code></pre>
<p>My first approach went like this:</p>
<pre><code>mystring.split(/\b/)
</code></pre>
<p>Of course this groups together non-word characters:</p>
<pre><code>['ab','.:','u','/','87','z']
</code></pre>
<p>I can take them apart in a subsequent step, but I'm looking for a more elegant way. Next I tried these:</p>
<pre><code>mystring.split(/(\w+|\W)/)
mystring.split(/(\b|\W)/)
</code></pre>
<p>Both return nearly the desired result, only that they also return array elements containing empty strings, so I have to write something like</p>
<pre><code>mystring.split(/(\b|\W)/).reject(&:empty?)
</code></pre>
<p>Now my question: Is there a simpler way to do this?</p>
<p><strong>UPDATE</strong>: I made a silly mistake when I explained my example. Of course '87' and 'z' should be together, i.e. '87z'. I fixed my example.</p> | 1 |
how to insert and update record through trigger in a custom object in salesforce | <p>Hi I have tried the below code </p>
<pre><code>trigger CreateRecord on Account (before insert,before update) {
List<Account> CreateAcc = new List<Account>();
For(Account acc:trigger.new)
{
acc.Name='abc';
CreateAcc.add(acc);
}
insert CreateAcc;
}
</code></pre>
<p>but the above code is creating the following error :
Review all error messages below to correct your data.
Apex trigger CreateRecord caused an unexpected exception, contact your administrator: CreateRecord: execution of BeforeInsert caused by: System.SObjectException: DML statement cannot operate on trigger.new or trigger.old: Trigger.CreateRecord: line 9, column 1<code>enter code here</code></p>
<p>Please help me through the code as where I am wrong.</p> | 1 |
Converting hex values in buffer to integer | <p><strong>Background:</strong> I'm using node.js to get the volume setting from a device via serial connection. I need to obtain this data as an integer value.</p>
<p>I have the data in a buffer ('buf'), and am using readInt16BE() to convert to an int, as follows:</p>
<pre><code>console.log( buf )
console.log( buf.readInt16BE(0) )
</code></pre>
<p>Which gives me the following output as I adjust the external device:</p>
<pre><code><Buffer 00 7e>
126
<Buffer 00 7f>
127
<Buffer 01 00>
256
<Buffer 01 01>
257
<Buffer 01 02>
258
</code></pre>
<p><strong>Problem:</strong> All looks well until we reach 127, then we take a jump to 256. Maybe it's something to do with signed and unsigned integers - I don't know!</p>
<p>Unfortunately I have very limited documentation about the external device, I'm having to reverse engineer it! Is it possible it only sends a 7-bit value? Hopefully there is a way around this?</p>
<p>Regarding a solution - I must also be able to convert back from int to this format!</p>
<p><strong>Question:</strong> How can I create a sequential range of integers when 7F seems to be the largest value my device sends, which causes a big jump in my integer scale?</p>
<p>Thanks :)</p> | 1 |
CakePHP 3 - Catch Error | <pre><code>use Cake\Core\Exception\Exception;
for($i=1; $i<count($values); $i++) {
$entity = $table->newEntity();
// irrelevant code
try {
$table->save($entity);
} catch (Exception $e) {
$errors[$i-1] = $values[$i];
} finally {
if(count($errors) == 0)
$this->Flash->success('All rows are successfully imported. ');
else {
$this->Flash->error('Not all rows are successfully imported. ');
debug($errors);
}
}
}
</code></pre>
<p>What I want to do is catch the conflicted entities and show these to the user. </p>
<p>What I get is an PDO exception. The ones that don't conflict are still inserted, what I want. </p>
<p>So I only want to catch the PDO exception, but how?</p> | 1 |
Appium : UiAutomator quit before it successfully launched | <blockquote>
<p>Launching Appium server with command: C:\Program Files (x86)\Appium\node.exe lib\server\main.js --address 127.0.0.1 --port 4723 --platform-name Android --platform-version 23 --automation-name Appium --log-no-color
info: Welcome to Appium v1.4.16 (REV ae6877eff263066b26328d457bd285c0cc62430d)
info: Appium REST http interface listener started on 127.0.0.1:4723
info: [debug] Non-default server args: {"address":"127.0.0.1","logNoColors":true,"platformName":"Android","platformVersion":"23","automationName":"Appium"}
info: Console LogLevel: debug
info: --> POST /wd/hub/session {"desiredCapabilities":{"appPackage":"com.Honkampkrueger.hk","appActivity":".MainActivity","app":"C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk","browserName":"","platformName":"Android","deviceName":"Android Emulator","version":"4.4.2"}}
info: Client User-Agent string: Apache-HttpClient/4.5.1 (Java/1.8.0_71)
info: [debug] The following desired capabilities were provided, but not recognized by appium. They will be passed on to any other services running on this server. : version
info: [debug] Using local app from desired caps: C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk
info: [debug] Creating new appium session f2eb01fe-7b8c-4e7c-89c6-5d776471a569
info: Starting android appium
info: [debug] Getting Java version
info: Java version is: 1.8.0_71
info: [debug] Checking whether adb is present
info: [debug] Using adb from C:\Program Files\SDK\platform-tools\adb.exe
info: [debug] Using fast reset? true
info: [debug] Preparing device for session
info: [debug] Checking whether app is actually present
info: Retrieving device
info: [debug] Trying to find a connected android device
info: [debug] Getting connected devices...
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" devices
info: [debug] 1 device(s) connected
info: Found device emulator-5554
info: [debug] Setting device id to emulator-5554
info: [debug] Waiting for device to be ready and to respond to shell commands (timeout = 5)
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 wait-for-device
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "echo 'ready'"
info: [debug] Starting logcat capture
info: [debug] Getting device API level
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "getprop ro.build.version.sdk"
info: [debug] Device is at API Level 19
info: Device API level is: 19
info: [debug] Extracting strings for language: default
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "getprop persist.sys.language"
info: [debug] Current device persist.sys.language: en
info: [debug] java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\appium_apk_tools.jar" "stringsFromApk" "C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk" "C:\Users\KULDEE~1.SAH\AppData\Local\Temp\com.Honkampkrueger.hk" en
info: [debug] No strings.xml for language 'en', getting default strings.xml
info: [debug] java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\appium_apk_tools.jar" "stringsFromApk" "C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk" "C:\Users\KULDEE~1.SAH\AppData\Local\Temp\com.Honkampkrueger.hk"
info: [debug] Reading strings from converted strings.json
info: [debug] Setting language to default
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 push "C:\Users\KULDEE~1.SAH\AppData\Local\Temp\com.Honkampkrueger.hk\strings.json" /data/local/tmp
info: [debug] Checking whether aapt is present
info: [debug] Using aapt from C:\Program Files\SDK\build-tools\23.0.2\aapt.exe
info: [debug] Retrieving process from manifest.
info: [debug] executing cmd: "C:\Program Files\SDK\build-tools\23.0.2\aapt.exe" dump xmltree C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk AndroidManifest.xml
info: [debug] Set app process to: com.Honkampkrueger.hk
info: [debug] Not uninstalling app since server not started with --full-reset
info: [debug] Checking app cert for C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk.
info: [debug] executing cmd: java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\verify.jar" C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk
info: [debug] App already signed.
info: [debug] Zip-aligning C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk
info: [debug] Checking whether zipalign is present
info: [debug] Using zipalign from C:\Program Files\SDK\build-tools\23.0.2\zipalign.exe
info: [debug] Zip-aligning apk.
info: [debug] executing cmd: "C:\Program Files\SDK\build-tools\23.0.2\zipalign.exe" -f 4 C:\Users\kuldeep.sahu\workspace\AppiumIntro\Src\honkamp.apk C:\Users\KULDEE~1.SAH\AppData\Local\Temp\11615-3480-14zot2k\appium.tmp
info: [debug] MD5 for app is 91f72bc7e64a758cdb9d0b8414bd853c
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "ls /data/local/tmp/91f72bc7e64a758cdb9d0b8414bd853c.apk"
info: [debug] Getting install status for com.Honkampkrueger.hk
info: [debug] Getting device API level
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "getprop ro.build.version.sdk"
info: [debug] Device is at API Level 19
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "pm list packages -3 com.Honkampkrueger.hk"
info: [debug] App is not installed
info: Installing App
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "mkdir -p /data/local/tmp/"
info: [debug] Removing any old apks
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "ls /data/local/tmp/*.apk"
info: [debug] Found an apk we want to keep at /data/local/tmp/91f72bc7e64a758cdb9d0b8414bd853c.apk
info: [debug] Couldn't find any apks to remove
info: [debug] Uninstalling com.Honkampkrueger.hk
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "am force-stop com.Honkampkrueger.hk"
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 uninstall com.Honkampkrueger.hk
info: [debug] App was not uninstalled, maybe it wasn't on device?
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "pm install -r /data/local/tmp/91f72bc7e64a758cdb9d0b8414bd853c.apk"
info: [debug] Forwarding system:4724 to device:4724
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 forward tcp:4724 tcp:4724
info: [debug] Pushing appium bootstrap to device...
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 push "C:\Program Files (x86)\Appium\node_modules\appium\build\android_bootstrap\AppiumBootstrap.jar" /data/local/tmp/
info: [debug] Pushing settings apk to device...
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 install "C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk"
info: [debug] Pushing unlock helper app to device...
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 install "C:\Program Files (x86)\Appium\node_modules\appium\build\unlock_apk\unlock_apk-debug.apk"
info: Starting App
info: [debug] Attempting to kill all 'uiautomator' processes
info: [debug] Getting all processes with 'uiautomator'
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "ps 'uiautomator'"
info: [debug] No matching processes found
info: [debug] Running bootstrap
info: [debug] spawning: C:\Program Files\SDK\platform-tools\adb.exe -s emulator-5554 shell uiautomator runtest AppiumBootstrap.jar -c io.appium.android.bootstrap.Bootstrap -e pkg com.Honkampkrueger.hk -e disableAndroidWatchers false
info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_RESULT: shortMsg=java.lang.NullPointerException
info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_RESULT: longMsg=null
info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_CODE: 0
info: [debug] UiAutomator exited
info: [debug] executing cmd: "C:\Program Files\SDK\platform-tools\adb.exe" -s emulator-5554 shell "echo 'ping'"
info: [debug] Attempting to uninstall app
info: [debug] Not uninstalling app since server not started with --full-reset
info: [debug] Cleaning up android objects
info: [debug] Cleaning up appium session
error: UiAutomator quit before it successfully launched
error: Failed to start an Appium session, err was: Error: UiAutomator quit before it successfully launched
info: [debug] Error: UiAutomator quit before it successfully launched
at [object Object]. (C:\Program Files (x86)\Appium\node_modules\appium\lib\devices\android\android.js:205:23)
at [object Object]. (C:\Program Files (x86)\Appium\node_modules\appium\lib\devices\android\android-hybrid.js:249:5)
at Object.async.eachSeries (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\async\lib\async.js:142:20)
at [object Object].androidHybrid.stopChromedriverProxies (C:\Program Files (x86)\Appium\node_modules\appium\lib\devices\android\android-hybrid.js:233:9)
at [object Object]. (C:\Program Files (x86)\Appium\node_modules\appium\lib\devices\android\android.js:200:10)
at [object Object]. (C:\Program Files (x86)\Appium\node_modules\appium\lib\devices\android\android.js:222:9)
at [object Object].androidCommon.uninstallApp (C:\Program Files (x86)\Appium\node_modules\appium\lib\devices\android\android-common.js:478:5)
at [object Object]. (C:\Program Files (x86)\Appium\node_modules\appium\lib\devices\android\android.js:220:12)
at [object Object]. (C:\Program Files (x86)\Appium\node_modules\appium\lib\devices\android\android.js:229:11)
at C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\lib\adb.js:901:7
at [object Object]. (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\lib\adb.js:180:9)
at ChildProcess.exithandler (child_process.js:742:7)
at ChildProcess.emit (events.js:110:17)
at maybeClose (child_process.js:1016:16)
at Process.ChildProcess._handle.onexit (child_process.js:1088:5)
info: [debug] Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: UiAutomator quit before it successfully launched)","origValue":"UiAutomator quit before it successfully launched"},"sessionId":null}
info: <-- POST /wd/hub/session 500 46111.400 ms - 218 </p>
</blockquote>
<p>Error : Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (Original error: UiAutomator quit before it successfully launched) (WARNING: The server did not provide any stacktrace information).</p>
<p>Anyone have solution of this as My running emulator is very slow to launch.</p> | 1 |
Angular 2 - Post File to Web API | <p>I am attempting to pass a file to Web API from an Angular 2 app, and the actual file data does not get sent. </p>
<p>Here is my angular 2 service code: </p>
<pre><code> var headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
var formData = new FormData();
formData.append("file", file);
return this.http.post('http://myapiurl.com/files/upload', formData, { headers: headers }).map(res => res.json());
</code></pre>
<p>In the angular 2 docs, the POST method signature is as follows: </p>
<pre><code>post(url: string, body: string, options?: RequestOptionsArgs) : Observable<Response>
</code></pre>
<p>There is no option to pass Form Data, or other object. Just a string in the bodys request. The current work around is to use javascript and regular xhr requests. There are obvious downsides to this like not being able to use observables, etc. </p>
<p>Any help on this would be greatly appreciated. </p> | 1 |
Django: dynamic template rendering | <p>I'm working on a site that has some mostly static content that I still want to use Django template tags in. I don't want to have to write a view and add a urlconf entry for each URL, I just want to add templates to a specific folder and have them be rendered and accessible on the web. Is there already a project out there that does this?</p> | 1 |
How to read self closing tag's attribute in xml? | <p>I have this type of xml:</p>
<pre><code><trace>
<string key="id" value="1"/>
<event>
<string key="Hello" value="1"/>
<string key="World" value="2"/>
</event>
<event>
<string key="Stack" value="3"/>
<string key="Overflow" value="4"/>
</event>
</trace>
</code></pre>
<p>I want to read the key attributes here.</p>
<p>I already wrote this code:</p>
<pre><code> try {
File fXmlFile = new File("C:\\sampleXml.xes");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile.toString());
doc.getDocumentElement().normalize();
NodeList nListTrace = doc.getElementsByTagName("trace");
for (int j = 0; j < nListTrace.getLength(); j++) {
Node nNode = nListTrace.item(j);
NodeList nListEvent = doc.getElementsByTagName("event");
for(int i = 0 ; i < nListEvent.getLength(); i++){
Node nNodeEvent = nListEvent.item(i);
Element eElement = (Element) nNodeEvent;
System.out.println("\nCurrent Element :" + nNodeEvent.getNodeName());
}
}
} catch(Exception e){
e.printStackTrace();
}
</code></pre>
<p>How can i get all elements in events? How can i get access to attributes in element which has self closing tag?</p> | 1 |
Unable to std::bind member function | <p>I've written the following class:</p>
<pre><code>class SomeClass {
private:
void test_function(int a, size_t & b, const int & c) {
b = a + reinterpret_cast<size_t>(&c);
}
public:
SomeClass() {
int a = 17;
size_t b = 0;
int c = 42;
auto test = std::bind(&SomeClass::test_function, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
test(a, b, c);
}
}
</code></pre>
<p>On its own, this code looks fine in the IDE (Visual Studio 2015) but when I try to compile it, I get the following errors:</p>
<pre><code>Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)' Basic Server C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits 1441
Error C2672 'std::invoke': no matching overloaded function found Basic Server C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits 1441
</code></pre>
<p>What am I doing wrong?</p>
<p>EDIT: I also wrote this version:</p>
<pre><code>class SomeClass {
private:
void test_function(int a, size_t & b, const int & c) {
b = a + reinterpret_cast<size_t>(&c);
}
public:
SomeClass() {
int a = 17;
size_t b = 0;
int c = 42;
auto test = std::bind(&SomeClass::test_function, a, std::placeholders::_1, std::placeholders::_2);
test(b, c);
}
}
</code></pre>
<p>I get the exact same errors.</p> | 1 |
How to change the background color of pop up header? | <p>I am getting issue in background color on popup header.I am trying to change the background color of pop up header using below code but its not working. The header background color for the popup not taking the below css. Please help me.</p>
<p><strong>HTML</strong></p>
<pre><code> <a href="#openModal">Open Modal</a>
<div id="openModal" class="modalDialog">
<div class="pop-header">
<a href="#close" title="Close" class="close">X</a>
</div>
</div>
</code></pre>
<p><strong>css</strong></p>
<pre><code> .pop-header
{
width: 100%;
background-color: #000;
height: 50px;
padding: 20px;
}
.modalDialog {
position: fixed;
font-family: Arial, Helvetica, sans-serif;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
}
.modalDialog:target {
opacity:1;
pointer-events: auto;
}
.modalDialog > div {
width: 600px;
position: relative;
margin: 2% auto;
padding: 5px 20px 13px 20px;
border-radius: 5px;
background: #fff;
height: 100%;
}
.close
{
float: right;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/mWrjq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mWrjq.png" alt="enter image description here"></a></p> | 1 |
Maven, exclude hamcrest dependency for junit | <p>I excluded hamcrest dependency for junit depdendency in pom.xml.
When I compare logs upon running <code>"mvn package"</code> and <code>"mvn dependency:tree"</code>, I do not see any difference before and after exclduing hamcrest dependency.</p>
<p>Here is the portion for excluding the transitive dependency. Where can I find the difference before and after running the exclusion part? I also looked into .m2 directory</p>
<pre><code><dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
<exclusions>
</exclusion>
<groupId> org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
</exclusion>
</exclusions>
</dependency>
</code></pre>
<p></p> | 1 |
generate CSR & RSA Private key (for SSL Certificate) | <p>I purchased SSL certificate for my domain, but I didn't receive PRIVATE key, and provider told me to generate RSA private key from my domain hosting... But in my dashboard, there is no option for this..
Is there available any php commands for this? </p>
<p>p.s. (<code>shell_exec</code> or similar not allowed on hosting)</p> | 1 |
Nodejs - Re-Calling function on error callback - Is there a non blocking way? | <p>I got a function which makes a request to an API. Sometimes the API got some hiccups and isnt available for a second or two every now and then, resulting in an error on which I'd like to call the function again. Since there are another 70~80 lines of code following this callback, I wouldnt like to split the flow with an <code>if(error) <do the same stuff> else <as here></code></p>
<p>After trying for quite some time I ended up using a do-while(error) loop, which works but blocks. Is there an async way of doing this? </p>
<p>My code (simplified for generalization):</p>
<pre><code>//This is the request part
function bar(j, callback){
j++;
//simulated error
if(j<=10){
return( callback('dont', j) );
}
//simulated success
else{
return( callback(null, j) );
}
}
//This is the main function - part of a bigger piece in my code
function foo(){
var i = 0;
var err = 'yes'; //else we'd get an 'err is not defined'
do{
bar(i, function(error, j){
i = j
err = error;
if(error){
console.log(i);
}
else{
return( console.log('done it!') );
// There's more here in my code
}
});
} while (err);
console.log('I blocked');
}
foo();
</code></pre>
<p>Edit: </p>
<p>For those interested, this is the output: </p>
<pre><code>1
2
3
4
5
6
7
8
9
10
done it!
I blocked
</code></pre> | 1 |
Wicket @SpringBean and Spring @Autowired with injection via constructor | <p>I have a Wicket panel in which I want to inject bean using @SpringBean</p>
<pre><code>public class SomePanel extends Panel {
@SpringBean
private BlogSummaryMailGenerator blogSummaryMailGenerator;
}
</code></pre>
<p>But this BlogSummaryMailGenerator has injection via constructor defined like this:</p>
<pre><code>@Component
public class BlogSummaryMailGenerator {
private BlogRepository blogRepository;
private BlogPostRepository blogPostRepository;
@Autowired
public BlogSummaryMailGenerator(BlogRepository blogRepository,
BlogPostRepository blogPostRepository) {
this.blogRepository = blogRepository;
this.blogPostRepository = blogPostRepository;
}
}
</code></pre>
<p>And when SomePanel is instantiated I am getting an exception</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at net.sf.cglib.proxy.Enhancer.emitConstructors(Enhancer.java:721) ~[cglib-3.1.jar:na]
at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:499) ~[cglib-3.1.jar:na]
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25) ~[cglib-3.1.jar:na]
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216) ~[cglib-3.1.jar:na]
at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377) ~[cglib-3.1.jar:na]
at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:285) ~[cglib-3.1.jar:na]
at org.apache.wicket.proxy.LazyInitProxyFactory.createProxy(LazyInitProxyFactory.java:191) ~[wicket-ioc-7.2.0.jar:7.2.0]
</code></pre>
<p>Adding empty no-args constructor to the BlogSummaryMailGenerator solves this issue but adding such code only to make injection work is wrong and I would like to avoid it.</p>
<p>Any suggestions how to make @SpringBean work with beans using injection via constructor?</p> | 1 |
Docker container with non-root user deployed in Google Container Engine can not write to mounted GCE Persistent disk | <p>I'm playing with kubernetes and google container engine (GKE).</p>
<p>I deployed a container from this image <a href="https://github.com/jupyter/docker-stacks/tree/master/all-spark-notebook" rel="noreferrer">jupyter/all-spark-notebook</a></p>
<p>This is my replication controller :</p>
<pre><code>{
"apiVersion": "v1",
"kind": "ReplicationController",
"metadata": {
"name": "datalab-notebook"
},
"spec": {
"replicas": 1,
"selector": {
"app": "datalab-notebook"
},
"template": {
"metadata": {
"name": "datalab-notebook",
"labels": {
"environment": "TEST",
"app": "datalab-notebook"
}
},
"spec": {
"containers": [{
"name": "datalab-notebook-container",
"image": "jupyter/all-spark-notebook",
"env": [],
"ports": [{
"containerPort": 8888,
"name": "datalab-port"
}],
"volumeMounts": [{
"name": "datalab-notebook-persistent-storage",
"mountPath": "/home/jovyan/work"
}]
}],
"volumes": [{
"name": "datalab-notebook-persistent-storage",
"gcePersistentDisk": {
"pdName": "datalab-notebook-disk",
"fsType": "ext4"
}
}]
}
}
}
}
</code></pre>
<p>As you can see I mounted a Google Compute Engine Persistent Disk. My issue is that the container uses a non-root user and the mounted disk is owned by root. so my container can not write to the disk.</p>
<ul>
<li><strong>Is there a way to mount GCE persistent disks and make them read/write for containers without non-root users?</strong></li>
<li><strong>Another general question : is it safe to run container with root user in Google Container Engine?</strong></li>
</ul>
<p>Thank you in advance for your inputs</p> | 1 |
How to get the size of String java.util.Map.Entry.getKey() in java? | <p>I tried some options but I could not get my required output.</p>
<p>The question is how to get the size of <code>m.getKey()</code></p>
<p>I tried <code>m.getKey().length</code> ,<code>m.getKey().size</code> but I could not find.</p>
<pre><code>System.out.print("\n duplicate words: ");
for(Map.Entry<String, Integer> m: map.entrySet()){
if(m.getValue()>toStringArray.length-1)
);
System.out.print(m.getKey() + " ");
}
</code></pre>
<p>The output is </p>
<blockquote>
<p>( HI THIS IS MY OUTPUT)</p>
</blockquote>
<p>The output which I needed is </p>
<blockquote>
<p>(5) //HI THIS IS MY OUTPUT total count is 5</p>
</blockquote>
<p>Suggestions are Welcomed.</p>
<p>I am a beginner to java </p>
<p>Here is my Full code</p>
<pre><code>import java.io.File;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.apache.commons.io.IOUtils;
public class testduplicatewordnew {
public static void main(String[] args) throws Exception {
/* Reading text content from file */
FileInputStream fisTargetFile = new FileInputStream(new File("E:\\testfolder\\மிரளச் செய்யும் மிலரபாவின் கதை! Isha Tamil Blog 15.txt"));
String targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");
String []toStringArray = targetFileStr.split(" ");
HashMap<String , Integer> map = analyzeWords("Analyzing contents ", toStringArray);
System.out.print("\nduplicate words: ");
for(Map.Entry<String, Integer> m: map.entrySet()){
if(m.getValue()>toStringArray.length-1)
// System.out.print(m.getKey() + "-" + m.getValue()/(toStringArray.length-1) + " ");
System.out.print(m.getKey()+ " ");
// System.out.println(map.keySet().size());
// System.out.println(m.getValue());
}
System.out.println("\n");
}
private static HashMap<String, Integer> analyzeWords(String command, String []toStringArray ){
System.out.println(command);
HashMap<String, Integer> unik = new HashMap<String, Integer>();
int i =0;
while(i<toStringArray.length){ unik.put(toStringArray[i++], 0);}
for(i = 0; i< toStringArray.length; i++){
for(int j = 0; j< toStringArray.length; j++ ){
if( (toStringArray[i] != toStringArray[j]) && (i != j))
unik.put(toStringArray[i],(int)unik.get(toStringArray[i]) +1);
}
}// oef outter for loop
return unik;
}// eof analyzeWords method
/* method to read file content.
* returns the contents of text file as a string */
private static String fileNameReader(String fileName) throws FileNotFoundException{
System.out.println("\nReading " +fileName+ " file");
String generateString = "";
try{
File file = new File(fileName);
Scanner scanner = new Scanner(file);
generateString = scanner.nextLine();
while (scanner.hasNextLine()) {
generateString = generateString + "\n" + scanner.nextLine();
}scanner.close();
System.out.println("\nInitial content");
System.out.println(generateString);
}catch(IOException e){
System.out.println("\nError occured while reading file...");
}
return generateString;
}// eof fileNameReader method
}
</code></pre> | 1 |
How to add URL to PDF document using iText? | <p>I have implemented a generic method to create PDFPCell and it is fine for text fields.
Here I am looking for some code which can help me to add url (hot links).
Thanks in advance.</p>
<pre><code>public PdfPCell createCell(String text, Font font, BaseColor bColor, int rowSpan, int colSpan, int hAlign, int vAlign) {
PdfPCell cell = new PdfPCell(new Phrase(text, font));
cell.setBackgroundColor(bColor);
cell.setRowspan(rowSpan);
cell.setColspan(colSpan);
cell.setHorizontalAlignment(hAlign);
cell.setVerticalAlignment(hAlign);
cell.setMinimumHeight(20);
cell.setNoWrap(true);
return cell;
}
</code></pre> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.