title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
standard_init_linux.go:178: exec user process caused "exec format error"
|
<p>docker started throwing this error:</p>
<blockquote>
<p>standard_init_linux.go:178: exec user process caused "exec format error"</p>
</blockquote>
<p>whenever I run a specific docker container with CMD or ENTRYPOINT, with no regard to any changes to the file other then removing CMD or ENTRYPOINT. here is the docker file I have been working with which worked perfectly until about an hour ago:</p>
<pre><code>FROM buildpack-deps:jessie
ENV PATH /usr/local/bin:$PATH
ENV LANG C.UTF-8
RUN apt-get update && apt-get install -y --no-install-recommends \
tcl \
tk \
&& rm -rf /var/lib/apt/lists/*
ENV GPG_KEY 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D
ENV PYTHON_VERSION 3.6.0
ENV PYTHON_PIP_VERSION 9.0.1
RUN set -ex \
&& buildDeps=' \
tcl-dev \
tk-dev \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
\
&& wget -O python.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \
&& wget -O python.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \
&& export GNUPGHOME="$(mktemp -d)" \
&& gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$GPG_KEY" \
&& gpg --batch --verify python.tar.xz.asc python.tar.xz \
&& rm -r "$GNUPGHOME" python.tar.xz.asc \
&& mkdir -p /usr/src/python \
&& tar -xJC /usr/src/python --strip-components=1 -f python.tar.xz \
&& rm python.tar.xz \
\
&& cd /usr/src/python \
&& ./configure \
--enable-loadable-sqlite-extensions \
--enable-shared \
&& make -j$(nproc) \
&& make install \
&& ldconfig \
\
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \
&& python3 /tmp/get-pip.py "pip==$PYTHON_PIP_VERSION" \
&& rm /tmp/get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall "pip==$PYTHON_PIP_VERSION" \
&& [ "$(pip list |tac|tac| awk -F '[ ()]+' '$1 == "pip" { print $2; exit }')" = "$PYTHON_PIP_VERSION" ] \
\
&& find /usr/local -depth \
\( \
\( -type d -a -name test -o -name tests \) \
-o \
\( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
\) -exec rm -rf '{}' + \
&& apt-get purge -y --auto-remove $buildDeps \
&& rm -rf /usr/src/python ~/.cache
RUN cd /usr/local/bin \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -s idle3 idle \
&& ln -s pydoc3 pydoc \
&& ln -s python3 python \
&& ln -s python3-config python-config
RUN pip install uwsgi
RUN mkdir /config
RUN mkdir /logs
ENV HOME /var/www
WORKDIR /config
ADD conf/requirements.txt /config
RUN pip install -r /config/requirements.txt
ADD conf/wsgi.py /config
ADD conf/wsgi.ini /config
ADD conf/__init__.py /config
ADD start.sh /bin/start.sh
RUN chmod +x /bin/start.sh
EXPOSE 8000
ENTRYPOINT ["start.sh", "uwsgi", "--ini", "wsgi.ini"]
</code></pre>
| 0 | 1,605 |
how to use an android timer
|
<p>having a problem trying to understand how to use a timer in android. I have an activity that sets up a timerTask in my onCreate method. I call the task on a button click and all it is supposed to do is append a textview. The problem is that I am getting a NullPointerException at <code>timer.schedule(task, TIMER_DELAY, 3*TIMER_ONE_SECOND);</code></p>
<p>is there any obvious reason for this that I am missing?</p>
<pre><code>public class UseGps extends Activity
{
Button gps_button;
TextView gps_text;
LocationManager mlocManager;
TimerTask task;
Timer timer;
public final int TIMER_DELAY = 1000;
public final int TIMER_ONE_MINUTE = 60000;
public final int TIMER_ONE_SECOND = 1000;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps_button = (Button) findViewById(R.id.Button);
gps_text = (TextView) findViewById(R.id.Text);
task = new TimerTask() {
@Override
public void run() {
gps_text.append("Time up ");
try {
this.wait(TIMER_DELAY);
}
catch (InterruptedException e){
}
}
};
/* Use the LocationManager class to obtain GPS locations */
double gps[] = getLastKnownGPS();
gps_text.setText("Last known Location = "+gps[0]+" "+gps[1]);
gps_button.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam){
gps_text.append("\n\nSearching for current location. Please hold...");
gps_button.setEnabled(false);
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
timer.schedule(task, TIMER_DELAY, 3*TIMER_ONE_SECOND);
}
});
}
}
</code></pre>
<p>Thanks in advance</p>
<p>Kevin</p>
| 0 | 1,068 |
Testing against Java EE 6 API
|
<p>I write an addition to JAX-RS and included the Java EE 6 API as a Maven dependency. </p>
<pre><code><dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</code></pre>
<p>Then I have a little test case:</p>
<pre><code> @Test
public void testIsWriteable() {
class SpecialViewable extends Viewable {
public SpecialViewable() {
super("test");
}
}
FreeMarkerViewProcessor processor = new FreeMarkerViewProcessor(null);
assertTrue(processor.isWriteable(SpecialViewable.class, null, null,
MediaType.WILDCARD_TYPE));
}
</code></pre>
<p>But I get an error:</p>
<pre><code>java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/ws/rs/core/MediaType
...
</code></pre>
<p>If I include Jersey as a JAX-RS implementation instead of the Java EE API everything is fine.</p>
<p>Thanks to BalusC's hint I know what I had guessed: Java EE 6 is only an API without method bodies:
<a href="http://weblogs.java.net/blog/ludo/archive/2007/01/java_ee_5_apis.html" rel="noreferrer">From the java.net blog</a> </p>
<blockquote>
<p>You can compile you code with this
jar, but of course you cannnot run
your application with it since it
contains only the Java EE 5 APIs and
does not contain any method bodies. If
you try to run, you would get this
exception:</p>
<p>Exception in thread "main"
java.lang.ClassFormatError: Absent
Code attribute in method that is not
native or abstract in class file
javax/mail/Session</p>
<p>In order to execute a Java EE 5
application, you'll still need a Java
EE 5 container, like for example the
GlassFish application server.</p>
</blockquote>
<p>I've tried to add Jersy with <code>test</code> scope but it didn't work.</p>
<pre><code><dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey-version}</version>
<scope>test</scope>
</dependency>
</code></pre>
<p>How can I test software that depends only on the official Java EE API?</p>
<p><strong>Solution</strong></p>
<p>The provider (Jersey) needs to be placed <em>before</em> the API (javeee-api) in the pom.xml.</p>
<pre><code><dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</code></pre>
| 0 | 1,268 |
How is column width determined in browser?
|
<p>How is the actual width of columns in table determined?
The code below looks (in Chrome) like this:</p>
<p><img src="https://i.stack.imgur.com/D8zYg.png" alt="rendered table"></p>
<p>My problem is that adding any more characters to the cell with "ddd..." the free space is not used, but the content of other cells gets wrapped. Sometime the problem is that texts "aaa..." and "ccc..." would not overlap. The total size of the table is fixed, but all the content is dynamic, so a fixed layout is not preferred.<br>
Update: Despite containing less text than any of the actual columns the first row (c1-c4) has quite significant (possitive) effect on the final layout.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body {background:#000; color:#fff; font-family:'Tahoma'; font-weight:600; }
.container {width:670px; }
table {font-family:'Tahoma'; font-weight:600; border-color: #ffffff; border-width:1px; }
.detail table{margin-left:20px; font-size:24px; width:650px;}
.detail table .operational {text-align:right;}
</style>
</head>
<body>
<div class="detail">
<table border="1px" cellpadding="0px" cellspacing="0px" >
<tbody>
<!-- first row and borders only for debuging-->
<tr>
<td >c1</td>
<td >c2</td>
<td >c3</td>
<td >c4</td>
</tr>
<tr >
<td class="caption">Date</td>
<td class="value">17.6.2013</td>
<td class="operational" colspan="2">aaaaaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr >
<td class="caption">bbbbbbbb</td>
<td class="value" colspan="2">ccccccccccccccc ccc</td>
<td class="operational">dddddddddddddd</td>
</tr>
<tr >
<td class="caption">bbbbbb bbb</td>
<td class="value" colspan="3">eeeeeeeeeeeeeeeeeeeeeeeeeeeee</td>
</tr>
<tr >
<td class="caption">bbb bbbbbb</td>
<td class="value" colspan="3">xxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx</td>
</tr>
</tbody>
</table>
</div>
</body></html>
</code></pre>
| 0 | 1,256 |
Jquery Mobile: Forcing refresh of content
|
<p>I have a big problem: I have a <code>listview</code> and each item links to page <code>#concorsi</code>. When I click on a link the URL become <code>#concorsi?numero=1</code> because I'm fetching the form number 1 from a JSON.</p>
<p>When I click the first time it's all OK. Each input is visualized with jQuery Mobile classes but if I come back and after go into the same link the code don't refresh.
The header is well visualized but the content no. How can I force the refresh of the div content?</p>
<p>These are my JavaScript functions:</p>
<pre><code><script type="text/javascript">
$(document).bind( "pagebeforechange", function( e, data ) {
// We only want to handle changePage() calls where the caller is
// asking us to load a page by URL.
if ( typeof data.toPage === "string" ) {
// We are being asked to load a page by URL, but we only
// want to handle URLs that request the data for a specific
var u = $.mobile.path.parseUrl( data.toPage ),
re = /^#concorso/;
if ( u.hash.search(re) !== -1 ) {
// We're being asked to display the items for a specific category.
// Call our internal method that builds the content for the category
// on the fly based on our in-memory category data structure.
showConcorso( u, data.options);
// Make sure to tell changePage() we've handled this call so it doesn't
// have to do anything.
e.preventDefault();
}
}
});
</script>
</code></pre>
<p>And <code>showConcorso()</code>L</p>
<pre><code>function showConcorso( urlObj, options )
{
document.getElementById('conccont').innerHTML="";
var concorsoNum = urlObj.hash.replace( /.*numero=/, "" ),
// Get the object that represents the category we
// are interested in. Note, that at this point we could
// instead fire off an ajax request to fetch the data, but
// for the purposes of this sample, it's already in memory.
concorso = obj.concorsi[ concorsoNum ],
// The pages we use to display our content are already in
// the DOM. The id of the page we are going to write our
// content into is specified in the hash before the '?'.
pageSelector = urlObj.hash.replace( /\?.*$/, "" );
if ( concorso ) {
// Get the page we are going to dump our content into.
var $page = $( pageSelector ),
// Get the header for the page.
$header = $page.children( ":jqmData(role=header)" ),
// Get the content area element for the page.
$content = $page.children( ":jqmData(role=content)" ),
$footer = $page.children( ":jqmData(role=footer)" );
// Find the h1 element in our header and inject the name of
// the category into it.
$header.find( "h1" ).html(concorso['title']);
markup=document.createElement('form');
markup.setAttribute('action','#home');
markup.setAttribute('method','POST');
markup.id="concForm";
markup.onchange="alert (test)";
items=obj.concorsi[concorsoNum].elementi;
for(field in items) {
nest=items[field];
nest=obj.campi[nest];
switch(nest.type){
case "free": markup.appendChild(createFree(nest));
break;
case "text": markup.appendChild(createText(nest));
break;
case "textarea": markup.appendChild(createTextArea(nest));
break;
case "switch": markup.appendChild(createSwitch(nest));
break;
case "switchcust": markup.appendChild(createSwitchCustom(nest));
break;
case "slider": markup.appendChild(createSlider(nest));
break;
case "select": markup.appendChild(createSelect(nest));
break;
case "checkbox": markup.appendChild(createCheckbox(nest));
break;
case "radio": markup.appendChild(createRadio(nest));
break;
case "reset": markup.appendChild(createButton(nest));
break;
case "submit": markup.appendChild(createButton(nest));
break;
}
}
// Inject the category items markup into the content element.
$content.html( markup );
// Pages are lazily enhanced. We call page() on the page
// element to make sure it is always enhanced before we
// attempt to enhance the listview markup we just injected.
// Subsequent calls to page() are ignored since a page/widget
// can only be enhanced once.
$page.page();
// We don't want the data-url of the page we just modified
// to be the url that shows up in the browser's location field,
// so set the dataUrl option to the URL for the category
// we just loaded.
options.dataUrl = urlObj.href;
// Now call changePage() and tell it to switch to
// the page we just modified.
$.mobile.changePage( $page, options );
}
}
</code></pre>
| 0 | 2,300 |
screen capturing using html2canvas
|
<p>I am calling <code>screenView()</code> from another class. I am able to call it but I am not getting <code>strDataURI</code>. What am I doing wrong?</p>
<pre><code> function screenView(){
var image;
var date = new Date();
var message,
timeoutTimer,
timer;
var proxyUrl = "http://html2canvas.appspot.com";
var iframe,d;
$(this).prop('disabled',true);
var url = "http://www.facebook.com/google";
var urlParts = document.createElement('a');
urlParts.href = url;
$.ajax({
data: {
xhr2:false,
url:urlParts.href
},
url: proxyUrl,
dataType: "jsonp",
success: function(html){
iframe = document.createElement('iframe');
$(iframe).css({
'visibility':'hidden'
}).width($(window).width()).height($(window).height());
$('#content').append(iframe);
d = iframe.contentWindow.document;
alert("d-----"+d);
d.open();
$(iframe.contentWindow).unbind('load');
alert("inside>>"+ $(iframe).contents().find('body'));
$(iframe).contents().find('body').html2canvas({
canvasHeight: d.body.scrollHeight,
canvasWidth: d.body.scrollWidth,
logging:true
});
alert("inside before load view");
$(iframe.contentWindow).load(function(){
alert("inside view");
$(iframe).contents().find('body').html2canvas({
canvasHeight: 30,
canvasWidth: 10,
logging:true,
proxyUrl: proxyUrl,
logger:function(msg){
$('#logger').val(function(e,i){
return i+"\n"+msg;
});
},
ready: function(renderer) {
alert("in side ready renderer");
$('button').prop('disabled',false);
$("#content").empty();
var finishTime = new Date();
var strDataURI = renderer.canvas.toDataURL("image/jpeg");
image = strDataURI
alert("last"+strDataURI);
d.close();
}
});
});
}
});
return image;
}
</code></pre>
| 0 | 1,958 |
How do I remove all null and empty string values from an object?
|
<p>Can you please tell me how to remove all null and empty string values from an object? I am getting an error while deleting the key.</p>
<p>This is what I have so far, but it doesn't work properly:</p>
<pre><code>$.each(sjonObj, function(key, value) {
if(value == "" || value == null) {
delete sjonObj.key;
}
});
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var sjonObj= {
"executionMode": "SEQUENTIAL",
"coreTEEVersion": "3.3.1.4_RC8",
"testSuiteId": "yyy",
"testSuiteFormatVersion": "1.0.0.0",
"testStatus": "IDLE",
"reportPath": "",
"startTime": 0,
"durationBetweenTestCases": 20,
"endTime": 0,
"lastExecutedTestCaseId": 0,
"repeatCount": 0,
"retryCount": 0,
"fixedTimeSyncSupported": false,
"totalRepeatCount": 0,
"totalRetryCount": 0,
"summaryReportRequired": "true",
"postConditionExecution": "ON_SUCCESS",
"testCaseList": [
{
"executionMode": "SEQUENTIAL",
"commandList": [
],
"testCaseList": [
],
"testStatus": "IDLE",
"boundTimeDurationForExecution": 0,
"startTime": 0,
"endTime": 0,
"label": null,
"repeatCount": 0,
"retryCount": 0,
"totalRepeatCount": 0,
"totalRetryCount": 0,
"testCaseId": "a",
"summaryReportRequired": "false",
"postConditionExecution": "ON_SUCCESS"
},
{
"executionMode": "SEQUENTIAL",
"commandList": [
],
"testCaseList": [
{
"executionMode": "SEQUENTIAL",
"commandList": [
{
"commandParameters": {
"serverAddress": "www.ggp.com",
"echoRequestCount": "",
"sendPacketSize": "",
"interval": "",
"ttl": "",
"addFullDataInReport": "True",
"maxRTT": "",
"failOnTargetHostUnreachable": "True",
"failOnTargetHostUnreachableCount": "",
"initialDelay": "",
"commandTimeout": "",
"testDuration": ""
},
"commandName": "Ping",
"testStatus": "IDLE",
"label": "",
"reportFileName": "tc_2-tc_1-cmd_1_Ping",
"endTime": 0,
"startTime": 0,
"repeatCount": 0,
"retryCount": 0,
"totalRepeatCount": 0,
"totalRetryCount": 0,
"postConditionExecution": "ON_SUCCESS",
"detailReportRequired": "true",
"summaryReportRequired": "true"
}
],
"testCaseList": [
],
"testStatus": "IDLE",
"boundTimeDurationForExecution": 0,
"startTime": 0,
"endTime": 0,
"label": null,
"repeatCount": 0,
"retryCount": 0,
"totalRepeatCount": 0,
"totalRetryCount": 0,
"testCaseId": "dd",
"summaryReportRequired": "false",
"postConditionExecution": "ON_SUCCESS"
}
],
"testStatus": "IDLE",
"boundTimeDurationForExecution": 0,
"startTime": 0,
"endTime": 0,
"label": null,
"repeatCount": 0,
"retryCount": 0,
"totalRepeatCount": 0,
"totalRetryCount": 0,
"testCaseId": "b",
"summaryReportRequired": "false",
"postConditionExecution": "ON_SUCCESS"
}
]
};
$.each(sjonObj, function(key, value) {
if(value == "" || value == null) {
delete sjonObj.key;
}
});
console.log(sjonObj);</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>
| 0 | 2,023 |
Firestore + cloud functions: How to read from another document
|
<p>I'm trying to write a Google cloud function that reads from another document. (Other document = not the document that triggered the cloud function.)</p>
<p>It's a bit of a treasure hunt to figure out how to do such a simple thing.</p>
<ol>
<li><p>The cloud functions documentation seems to suggest to look at the admin SDK: "You can make Cloud Firestore changes via the DeltaDocumentSnapshot interface or via the Admin SDK."</p>
<p><a href="https://firebase.google.com/docs/functions/firestore-events" rel="noreferrer">https://firebase.google.com/docs/functions/firestore-events</a></p></li>
<li><p>The Admin SDK suggest to write the following line of code to get a client. But oh no, it's not going to explain the client. It's going to send us off to a wild goose chase elsewhere in the documentation.</p>
<p><code>var defaultFirestore = admin.firestore();</code></p>
<p>"The default Firestore client if no app is provided or the Firestore client associated with the provided app."</p>
<p><a href="https://firebase.google.com/docs/reference/admin/node/admin.firestore" rel="noreferrer">https://firebase.google.com/docs/reference/admin/node/admin.firestore</a></p></li>
<li><p>That link resolves to a general overview page with no direct clue on figuring out the next thing.</p>
<p><a href="https://cloud.google.com/nodejs/docs/reference/firestore/0.10.x/" rel="noreferrer">https://cloud.google.com/nodejs/docs/reference/firestore/0.10.x/</a></p></li>
<li><p>Digging a big around, there is a promising class called FireStoreClient. It has a 'getDocument' method that seems promising. The parameter seems complicated. Rather than simply passing the path into the method, it seems to want an entire document/collection something as a parameter.</p>
<p><a href="https://cloud.google.com/nodejs/docs/reference/firestore/0.10.x/FirestoreClient#getDocument" rel="noreferrer">https://cloud.google.com/nodejs/docs/reference/firestore/0.10.x/FirestoreClient#getDocument</a></p>
<p><code>var formattedName = client.anyPathPath("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]");
client.getDocument({name: formattedName}).then(function(responses) {
var response = responses[0];
// doThingsWith(response)
})</code></p></li>
</ol>
<p>So, I'm trying to combine all of this information into a Google cloud function that will read from another document.</p>
<pre><code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateLikeCount4 = functions.firestore
.document('likes/{likeId}').onWrite((event) => {
return admin.firestore()
.getDocument('ruleSets/1234')
.then(function(responses) {
var response = responses[0];
console.log('Here is the other document: ' + response);
})
});
</code></pre>
<p>That approach fails with:</p>
<pre><code>admin.firestore.getDocument is not a function
</code></pre>
<p>I've also tried. admin.firestore.document, admin.firestore.doc, admin.firestore.collection, and many more. None of them seem to be a function.</p>
<p>All I want is to read from another Firestore document in my Google cloud function.</p>
<p>PS: They said the documentation is your friend. This documentation is a nightmare that follows the principle of scatter all the clues into the four directions of the wind!</p>
| 0 | 1,084 |
Hibernate Entity proxy initialization
|
<p>I'm having a problem with a Hibernate entity that does not get initialised.<br/>
It seems that it's still returning a not initialised proxy...</p>
<p>If I take a look at my debug info I would expect my entity to be initialised.<br/>
But it looks like the following:</p>
<pre><code>entity = {SomeEntity_$$_jvst47c_1e@9192}"SomeEntityImpl@1f3d4adb[id=1,version=0]"
handler = {org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer@9196}
interfaces = {java.lang.Class[2]@9197}
constructed = true
persistentClass = {java.lang.Class@3605}"class SomeEntityImpl"
getIdentifierMethod = null
setIdentifierMethod = null
overridesEquals = true
componentIdType = null
replacement = null
entityName = {java.lang.String@9198}"SomeEntityImpl"
id = {java.lang.Long@9199}"1"
target = {SomeEntityImpl@9200}"SomeEntityImpl@1f3d4adb[guid=<null>,id=1,version=0]"
initialized = true
readOnly = true
unwrap = false
session = {org.hibernate.internal.SessionImpl@6878}"SessionImpl(PersistenceContext[entityKeys=[EntityKey[EntityReferenceImpl#2], EntityKey[SomeEntityImpl#1], EntityKey[...
readOnlyBeforeAttachedToSession = null
sessionFactoryUuid = null
allowLoadOutsideTransaction = false
</code></pre>
<p>Notice that my Hibernate POJO still only contains a <code>handler</code>even after doing an explicit initialisation... <br/>
In my debug view, I can see the 'real' property values (not displayed above) when I expand the <code>target</code> node.</p>
<p>What I'm doing:</p>
<pre><code>EntityReferenceImpl entityReference = findEntityReference(session);
SomeEntity entity = null;
if (entityReference != null) {
// initialize association using a left outer join
HibernateUtil.initialize(entityReference.getSomeEntity());
entity = entityReference.getSomeEntity();
}
return entity;
</code></pre>
<p>Notice the <code>HibernateUtil.initialize</code> call! </p>
<p><code>SomeEntity</code> mapping:</p>
<pre><code>public class SomeEntityImpl extends AbstractEntity implements SomeEntity {
@OneToMany(mappedBy = "someEntity", fetch = FetchType.EAGER, targetEntity = EntityReferenceImpl.class, orphanRemoval = true)
@Cascade(CascadeType.ALL)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Set<EntityReference> entityReferences = new HashSet<>();
@Target(EntityName.class)
@Embedded
private Name name;
@Target(EntityAddress.class)
@Embedded
private Address address;
...
}
</code></pre>
<p><code>EntityReferenceImpl</code> mapping:</p>
<pre><code>public class EntityReferenceImpl extends AbstractEntity implements EntityReference {
@ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = SomeEntityImpl.class)
@JoinColumn(name = "entity_id")
private SomeEntity someEntity;
...
}
</code></pre>
<p>So what is the side effect: When the POJO later comes with updated properties I'm still having the same structure (as mentioned above) and I can see the updated properties under the <code>target</code> node.
<br/>
But when I'm trying to update the entity using <code>session.merge()</code> or <code>session.update()</code>or <code>session.saveOrUpdate()</code>, Hibernate does not detect the 'dirty' properties and does not invoke an update query to the database.</p>
<p><br/>
Does anyone have some clues about this weird behavior? I have tried everything what I can but without any results.
<br/>
All help is very welcome!!
<br/></p>
| 0 | 1,219 |
Angular 2 component directive not working
|
<p>I am a beginner in angular 2 and I want to make my first app working. I am using TypeScript.
I have the <strong>app.component.ts</strong> in which I have made a directive to another compoent called <strong>todos.component</strong> but I am getting the following error at compile time:</p>
<pre><code>[0] app/app.component.ts(7,3): error TS2345: Argument of type '{ moduleId: string; selector: string; directives: typeof TodosComponent[]; templateUrl: string; s ...' is not assignable to parameter of type 'Component'.
[0] Object literal may only specify known properties, and 'directives' does not exist in type 'Component'.
</code></pre>
<p>My code is like this:</p>
<p><strong>index.html</strong></p>
<pre><code><html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<app-root>Loading...</app-root>
</body>
</html>
</code></pre>
<p><strong>app.component.ts</strong></p>
<pre><code>import { Component } from '@angular/core';
import {TodosComponent} from './todos/todos.component';
@Component({
moduleId : module.id,
selector: 'app-root',
directives: [TodosComponent],
templateUrl : 'app.component.html',
styleUrls : ['app.component.css']
})
export class AppComponent {
title: string = "Does it work?";
}
</code></pre>
<p><strong>app.component.html:</strong></p>
<pre><code><h1> Angular 2 application</h1>
{{title}}
<app-todos></app-todos>
</code></pre>
<p><strong>todos.component.ts</strong></p>
<pre><code>import { Component, OnInit } from '@angular/core';
@Component({
moduleId : module.id,
selector: 'app-todos',
template: '<h2>Todo List</h2>'
})
export class TodosComponent {
title: string = "You have to do the following today:";
}
</code></pre>
<p>Without the directive, the app works fine.
Any help would be appreciated! </p>
<p>Thanks in advance!</p>
| 0 | 1,085 |
TypeScript 2: custom typings for untyped npm module
|
<p>After trying suggestions posted in <a href="https://stackoverflow.com/questions/37641960/typescript-how-to-define-custom-typings-for-installed-npm-package">other places</a>, I find myself unable to get a typescript project running that uses an untyped NPM module. Below is a minimal example and the steps that I tried.</p>
<p>For this minimal example, we will pretend that <code>lodash</code> does not have existing type definitions. As such, we will ignore the package <code>@types/lodash</code> and try to manually add its typings file <code>lodash.d.ts</code> to our project.</p>
<p>Folder structure</p>
<ul>
<li>node_modules
<ul>
<li>lodash</li>
</ul></li>
<li>src
<ul>
<li>foo.ts</li>
</ul></li>
<li>typings
<ul>
<li>custom
<ul>
<li>lodash.d.ts</li>
</ul></li>
<li>global</li>
<li>index.d.ts</li>
</ul></li>
<li>package.json</li>
<li>tsconfig.json</li>
<li>typings.json</li>
</ul>
<p>Next, the files. </p>
<p>File <code>foo.ts</code></p>
<pre><code>///<reference path="../typings/custom/lodash.d.ts" />
import * as lodash from 'lodash';
console.log('Weeee');
</code></pre>
<p>File <code>lodash.d.ts</code> is copied directly from the original <code>@types/lodash</code> package.</p>
<p>File <code>index.d.ts</code></p>
<pre><code>/// <reference path="custom/lodash.d.ts" />
/// <reference path="globals/lodash/index.d.ts" />
</code></pre>
<p>File <code>package.json</code></p>
<pre><code>{
"name": "ts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"typings": "./typings/index.d.ts",
"dependencies": {
"lodash": "^4.16.4"
},
"author": "",
"license": "ISC"
}
</code></pre>
<p>File <code>tsconfig.json</code></p>
<pre><code>{
"compilerOptions": {
"target": "ES6",
"jsx": "react",
"module": "commonjs",
"sourceMap": true,
"noImplicitAny": true,
"experimentalDecorators": true,
"typeRoots" : ["./typings"],
"types": ["lodash"]
},
"include": [
"typings/**/*",
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
</code></pre>
<p>File <code>typings.json</code></p>
<pre><code>{
"name": "TestName",
"version": false,
"globalDependencies": {
"lodash": "file:typings/custom/lodash.d.ts"
}
}
</code></pre>
<p>As you can see, I have tried many different ways of importing typings:</p>
<ol>
<li>By directly importing it in <code>foo.ts</code></li>
<li>By a <code>typings</code> property in <code>package.json</code></li>
<li>By using <code>typeRoots</code> in <code>tsconfig.json</code> with a file <code>typings/index.d.ts</code></li>
<li>By using an explicit <code>types</code> in <code>tsconfig.json</code></li>
<li>By including the <code>types</code> directory in <code>tsconfig.json</code></li>
<li>By making a custom <code>typings.json</code> file and running <code>typings install</code></li>
</ol>
<p>Yet, when I run Typescript:</p>
<pre><code>E:\temp\ts>tsc
error TS2688: Cannot find type definition file for 'lodash'.
</code></pre>
<p>What am I doing wrong?</p>
| 0 | 1,277 |
JUnit ~ Assert that list contains objects with the same values in any order
|
<p>My use case is that I am writing a document parser (for ReqIF documents) and want to compare that the parsed object contains the expected elements. For this, I want to write a JUnit Test.</p>
<p>Effectively, what I am looking for is an assertion method that compares two lists of objects with values and passes when both lists contain (in any order) objects that have the same values as the reference list.</p>
<p>To abstract that, consider this example:</p>
<pre><code>Apple referenceApple1 = new Apple(color="red");
Apple referenceApple2 = new Apple(color="green");
Apple parsedApple1 = new Apple(color="red");
Apple parsedApple2 = new Apple(color="green");
Apple badApple = new Apple(color="brown");
List<Apple> referenceList = new List<Apple>(referenceApple1, referenceApple2);
List<Apple> correctlyParsedList1 = new List<Apple>(parsedApple1, parsedApple2);
List<Apple> correctlyParsedList2 = new List<Apple>(parsedApple2, parsedApple1);
List<Apple> wronglyParsedList1 = new List<Apple>(parsedApple1, badApple);
List<Apple> wronglyParsedList2 = new List<Apple>(parsedApple1, parsedApple2, parsedApple1);
List<Apple> wronglyParsedList3 = new List<Apple>(parsedApple2, parsedApple2);
</code></pre>
<p>I am looking for an assertion method that passes when comparing any of the above <code>correctlyParsedList*</code> with the <code>referenceList</code>, but fails when comparing any of the above <code>wronglyParsedList*</code> with the <code>referenceList</code>.</p>
<p>Currently, the closest I've gotten to is this:</p>
<pre><code>assertEquals(referenceList.toString(), correctlyParsedList1.toString())
</code></pre>
<p>However, that will fail as soon as the objects are in another order.</p>
<pre><code>//Will fail, but I want a method that will compare these and pass
assertEquals(referenceList.toString(), correctlyParsedList2.toString())
</code></pre>
<p>Notably, the following will also fail since the Apples, while containing the same values, are not instances of the same object:</p>
<pre><code>assertThat(correctlyParsedList1, is(referenceList));
//Throws This error:
java.lang.AssertionError:
Expected: is <[[color="red"], [color="green"]]>
but: was <[[color="red"], [color="green"]]>
</code></pre>
<p>Is there a simple way to make such an assertion in JUnit? I know I could write a custom assertion method for this iterating over the objects, but somehow it feels like this would be a common use case that should have a pre-defined assertion method that throws expressive assertion errors.</p>
<hr>
<p>EDIT ~ CONCRETIZATION</p>
<p>What I am actually trying to do with this abstract example is to parse a complex XML using JDOM2, and I want to assert that the attributes of a tag being parsed equal those that exist in the sample document I give as an input. Since this is XML, the order of the attributes is irrelevant, as long as they have the correct values.</p>
<p>So effectively, what I am comparing in this practical use case is two <code>List<Attribute></code>, with <code>Attribute</code> coming from <code>org.jdom2.Attribute</code>.</p>
<p>The complete makeshift testcase with which I am currently unhappy because it will fail if the order of attributes changes but should not is as follows:</p>
<pre><code> @Test
public void importXML_fromFileShouldCreateXML_objectWithCorrectAttributes() throws JDOMException, IOException {
testInitialization();
List<Attribute> expectedAttributes = rootNode.getAttributes();
XML_data generatedXML_data = xml_importer.importXML_fromFile(inputFile);
List<Attribute> actualAttributes = generatedXML_data.attributes;
assertEquals(expectedAttributes.toString(), actualAttributes.toString());
}
</code></pre>
<p>The concrete error I get when trying to make that assertion with <code>assertThat(expectedAttributes, is(actualAttributes))</code> is:</p>
<pre><code>java.lang.AssertionError:
Expected: is <[[Attribute: xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"], [Attribute: xml:lang="en"]]>
but: was <[[Attribute: xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"], [Attribute: xml:lang="en"]]>
</code></pre>
| 0 | 1,404 |
Aforge.net Camera Capture & Save image to directory
|
<p>everyone. I have been stuck here dealing with this bugs for days, but I still couldn't figure it out.
My guess: I think my code has some problem as I did not dispose the object properly after using it, (I'm not very familiar with these concepts of releasing resources, threading) .
I got these code by taking reference of what people did on youtube, but despite me doing exactly the same thing, my code didn't work out nicely.</p>
<p>SITUATION:
I have two picture boxes, left one can take video of me, right one take the snapshot, if you press button1 , you will start the video, clone_button will copy a image i.e. take a snapshot, and save_image should save it to the path reference, however, i get a generic error occured in GDI+ again and again while I'm trying to save it. Also, my debugger seemed to get crazy (i.e. failed to terminate the vshost.exe ) once I ran this program, I have to restart the computer to get my code running again, which is bleak and frustrating.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
//AForge.Video dll
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
using AForge.Imaging.Filters;
using AForge;
namespace WebCameraCapture
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection CaptureDevice; // list of webcam
private VideoCaptureDevice FinalFrame;
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);//constructor
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0; // default
FinalFrame = new VideoCaptureDevice();
}
private void button1_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);// specified web cam and its filter moniker string
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);// click button event is fired,
FinalFrame.Start();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs) // must be void so that it can be accessed everywhere.
// New Frame Event Args is an constructor of a class
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();// clone the bitmap
}
private void From1_CLosing(object sender, EventArgs e)
{
if (FinalFrame.IsRunning==true) FinalFrame.Stop();
}
private void save_Click(object sender, EventArgs e)
{
if (pictureBox2.Image != null)
{
Bitmap varBmp = new Bitmap(pictureBox2.Image);
Bitmap newBitmap = new Bitmap(varBmp);
varBmp.Dispose();
varBmp = null;
varBmp.Save(@"C:\a.png", ImageFormat.Png);
}
else
{ MessageBox.Show("null exception"); }
}
private void clone_Click(object sender, EventArgs e)
{
pictureBox2.Image = (Bitmap)pictureBox1.Image.Clone();
}
}
}
</code></pre>
<p>Any AForge.net user can just PRESS the LINK below and try it out. Thanks!</p>
<p><a href="https://www.dropbox.com/s/zfdovr1wvs55aw4/WebCameraCapture.rar" rel="noreferrer">SAMPLE</a></p>
| 0 | 1,421 |
How to get table cells evenly spaced?
|
<p>I'm trying to create a page with a number of static html tables on them. </p>
<p>What do I need to do to get them to display each column the same size as each other column in the table?</p>
<p>The HTML is as follows:</p>
<pre><code><span class="Emphasis">Interest rates</span><br />
<table cellpadding="0px" cellspacing="0px" class="PerformanceTable">
<tr><th class="TableHeader"></th><th class="TableHeader">Current rate as at 31 March 2010</th><th class="TableHeader">31 December 2009</th><th class="TableHeader">31 March 2009</th></tr>
<tr class="TableRow"><td>Index1</td><td class="PerformanceCell">1.00%</td><td>1.00%</td><td>1.50%</td></tr>
<tr class="TableRow"><td>index2</td><td class="PerformanceCell">0.50%</td><td>0.50%</td><td>0.50%</td></tr>
<tr class="TableRow"><td>index3</td><td class="PerformanceCell">0.25%</td><td>0.25%</td><td>0.25%</td></tr>
</table>
<span>Source: Bt</span><br /><br />
<span class="Emphasis">Stock markets</span><br />
<table cellpadding="0px" cellspacing="0px" class="PerformanceTable">
<tr><th class="TableHeader"></th><th class="TableHeader">As at 31 March 2010</th><th class="TableHeader">1 month change</th><th class="TableHeader">QTD change</th><th class="TableHeader">12 months change</th></tr>
<tr class="TableRow"><td>index1</td><td class="PerformanceCell">1169.43</td><td class="PerformanceCell">5.88%</td><td class="PerformanceCell">4.87%</td><td class="PerformanceCell">46.57%</td></tr>
<tr class="TableRow"><td>index2</td><td class="PerformanceCell">1958.34</td><td class="PerformanceCell">7.68%</td><td class="PerformanceCell">5.27%</td><td class="PerformanceCell">58.31%</td></tr>
<tr class="TableRow"><td>index3</td><td class="PerformanceCell">5679.64</td><td class="PerformanceCell">6.07%</td><td class="PerformanceCell">4.93%</td><td class="PerformanceCell">44.66%</td></tr>
<tr class="TableRow"><td>index4</td><td class="PerformanceCell">2943.92</td><td class="PerformanceCell">8.30%</td><td class="PerformanceCell">-0.98%</td><td class="PerformanceCell">44.52%</td></tr>
<tr class="TableRow"><td>index5</td><td class="PerformanceCell">978.81</td><td class="PerformanceCell">9.47%</td><td class="PerformanceCell">7.85%</td><td class="PerformanceCell">26.52%</td></tr>
<tr class="TableRow"><td>index6</td><td class="PerformanceCell">3177.77</td><td class="PerformanceCell">10.58%</td><td class="PerformanceCell">6.82%</td><td class="PerformanceCell">44.84%</td></tr>
</table>
<span>Source: B</span><br /><br />
</code></pre>
<p>I'm also open to suggestion on how to tidy this up, if there are any? :-)</p>
<p><strong>edit:</strong> I should add that the cellpadding & cellspacing attributes are require by a 3rd party PDF conversion app that we use</p>
| 0 | 1,738 |
Flutter: How to jump to last page dynamically created on a PageView
|
<p>I have a pageView displaying a list of pages.</p>
<p>Application provides a + button to add a new page at the end of the collection.</p>
<p>I need the pageView to automatically jump to the last page once this new page has been successfully created.</p>
<p>If I try to redisplay the view providing a provider with initialPosition set to last pageView index, it does not work </p>
<pre><code>PageController(initialPage: 0, keepPage: false);
</code></pre>
<p>Any implementation idea ?</p>
<ul>
<li>Using listener (but which listener ?)</li>
</ul>
<p>Complete code:</p>
<pre><code> @override
Widget build(BuildContext context) {
if (_userId == null) {
return Scaffold(body: Center(child: Text("Loading experiences")));
}
print('Rebuilding entire view.');
return Scaffold(
appBar: new AppBar(
title: StreamBuilder<ExperiencesInfo>(
stream: _experiencesInfoStream,
builder: (context, snapshot) {
if (snapshot.hasData) {
_selectedExperience = snapshot.data.currentExperience;
return Text(snapshot.data.currentExperience.name);
} else {
return Center();
}
}),
),
body: new Container(
padding: new EdgeInsets.only(
top: 16.0,
),
decoration: new BoxDecoration(color: Colors.yellow),
child: Column(
children: <Widget>[
Expanded(
child:
StreamBuilder<List<Experience>>(
stream: _userExperiencesStream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return _createExperiencesPagesWidget(snapshot.data);
} else {
return Center();
}
})
),
_buildPageIndicator(),
Padding(
padding: EdgeInsets.only(bottom: 20.0),
)
],
),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
onPressed: () {
_displayAddMenu();
}),
);
}
_createExperiencesPagesWidget(List<Experience> experiences) {
print('Creating ExperiencesPagesWidget ${experiences}');
return PageView.builder(
physics: new AlwaysScrollableScrollPhysics(),
controller: _pageController,
itemCount: experiences.length,
itemBuilder: (BuildContext context, int index) {
return ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: Column(children: <Widget>[
_buildMoodIndicator(experiences[index]),
_buildMoodSelector(),
]));
},
onPageChanged: (index) {
if (_actionType == ActionType.none) {
print('page changed to index: ${index}, updating stream.');
_experiencesViewModel.experienceIndexSink.add(index);
} else {
_actionType = ActionType.none;
}
},
);
</code></pre>
<p>Page controller is defined as a class property</p>
<pre><code>PageController _pageController = PageController(initialPage: 0, keepPage: false);
</code></pre>
| 0 | 1,542 |
how to check whether an element already exists in the array
|
<p>i am sending value from one page to another,i want to store the values which i hav sent,& then want to compare the value which i am sending with the one which i hav already sent,i.e the saved value.while storing the values into an arrayin persistent object,& then comparing the value with another array,i face some prob,can anyone tell me how to check whether a value already exits in the array,i am giving the code,kindly help</p>
<pre><code>package com.firstBooks.series.db;
import java.util.Random;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.util.Arrays;
import net.rim.device.api.util.Persistable;
import com.firstBooks.series.db.parser.XMLParser;
import com.firstBooks.series.ui.managers.TopManager;
import com.firstBooks.series.ui.screens.TestScreen;
public class DBMain implements Persistable{
public static String answer = "";
public static String selectedAnswer = "";
public static Question curQuestion;
public static int currQuesNumber = 1;
public static int correctAnswerCount = -1;
static int curQuesnew;
static int quesCount=-1;
static int xyz;
static int j=0;
public static int totalNumofQuestions = Question.totques;
public static int quesNum[] = new int[XMLParser.questionList.size()];
static PersistentObject qStore;
static PersistentObject curQues;
static PersistentObject pQues;
static PersistentObject curans;
static PersistentObject disques;
static PersistentObject restques;
static int a ;
static int b;
static int[] c ;
static int[] d ;
static int pques;
static int cans;
static int[] dques;
static int[] rques;
static {
qStore = PersistentStore.getPersistentObject(0x33010065d24c7883L);
curQues = PersistentStore.getPersistentObject(0x33010064d24c7883L);
pQues = PersistentStore.getPersistentObject(0xbd7460a5b4f9890aL);
curans = PersistentStore.getPersistentObject(0xc5c065a3ae1bec21L);
disques = PersistentStore.getPersistentObject(0xbf8118045165a07aL);
}
static{
initialize();
}
public static void initialize() {
//int quesNum[] = new int[XMLParser.questionList.size()];
Random rgen = new Random(); // Random number generator
//int a=Integer.parseInt(TopManager.quesNumber);
//System.out.println("The value of AAAAAAA is...."+a);
// --- Initialize the array
for (int i = 0; i < quesNum.length; i++) {
quesNum[i] = i;
}
// --- Shuffle by exchanging each element randomly
for (int i=0; i< quesNum.length; i++) {
int randomPosition = rgen.nextInt(quesNum.length);
int temp = quesNum[i];
quesNum[i] = quesNum[randomPosition];
quesNum[randomPosition] = temp;
}
synchronized (qStore) {
qStore.setContents(quesNum);
qStore.commit();
}
}
public static int getQuestionNumber() {
//int quesCount;
//quesCount++;
//synchronized (curQues) {
//quesCount = Integer.parseInt((String)curQues.getContents());
//}
quesCount++;
synchronized (curans) {
int b=Integer.parseInt(TopManager.corrCount);
curans.setContents(b+"");
curans.commit();
}
//int quesNum[];
synchronized (qStore) {
quesNum=(int[]) qStore.getContents();
System.out.println("The value of question is ...."+quesNum.length);
}
synchronized (pQues) {
int a=Integer.parseInt(TopManager.quesNumber);
pQues.setContents(a+"");
pQues.commit();
}
if (quesNum!=null && quesCount < quesNum.length) {
synchronized (curQues) {
curQuesnew=quesNum[quesCount];
curQues.setContents(curQuesnew+"");
curQues.commit();
}
synchronized (disques) {
c[j]=TestScreen.quesNumber;
System.out.println("Astala vistaaaaaaaaaaaaa"+c);
disques.setContents(c+"");
disques.commit();
}
synchronized (disques) {
dques[j]=Integer.parseInt((String)disques.getContents());
System.out.println("valueee is.........."+dques);
}
for(int k=0;k<dques.length;k++){
if(quesNum[quesCount]!=dques[k]){
System.out.println("ghijyghfhgfhfhgfhgfhgfhgfhgddkjklmn");
xyz=quesNum[quesCount];
}
j++;
}
return xyz;
} else {
initialize();
quesCount = -1;
return getQuestionNumber();
}
}
public static int getpresentQuestionNumber(){
synchronized (pQues) {
pques=Integer.parseInt((String)pQues.getContents());
}
return pques;
}
public static int getCorrectanswerNumber(){
synchronized (curans) {
cans=Integer.parseInt((String)curans.getContents());
}
return cans;
}
public static int getCurrQuestionNumber() {
synchronized (curQues) {
return Integer.parseInt((String)curQues.getContents());
//return curQuesnew;
//curQuesnew=(int[]) curQues.getContents();
//return curQuesnew[quesCount];
}
}
}
</code></pre>
| 0 | 2,478 |
MySQL pivot row into dynamic number of columns
|
<p>Lets say I have three different MySQL tables:</p>
<p><strong>Table <code>products</code>:</strong> </p>
<pre><code>id | name
1 Product A
2 Product B
</code></pre>
<p><strong>Table <code>partners</code>:</strong> </p>
<pre><code>id | name
1 Partner A
2 Partner B
</code></pre>
<p><strong>Table <code>sales</code>:</strong></p>
<pre><code>partners_id | products_id
1 2
2 5
1 5
1 3
1 4
1 5
2 2
2 4
2 3
1 1
</code></pre>
<p>I would like to get a table with partners in the rows and products as columns. So far I was able to get an output like this:</p>
<pre><code>name | name | COUNT( * )
Partner A Product A 1
Partner A Product B 1
Partner A Product C 1
Partner A Product D 1
Partner A Product E 2
Partner B Product B 1
Partner B Product C 1
Partner B Product D 1
Partner B Product E 1
</code></pre>
<p>Using this query:</p>
<pre><code>SELECT partners.name, products.name, COUNT( * )
FROM sales
JOIN products ON sales.products_id = products.id
JOIN partners ON sales.partners_id = partners.id
GROUP BY sales.partners_id, sales.products_id
LIMIT 0 , 30
</code></pre>
<p>but I would like to have instead something like:</p>
<pre><code>partner_name | Product A | Product B | Product C | Product D | Product E
Partner A 1 1 1 1 2
Partner B 0 1 1 1 1
</code></pre>
<p>The problem is that I cannot tell how many products I will have so the column number needs to change dynamically depending on the rows in the products table. </p>
<p>This very good answer does not seem to work with mysql: <a href="https://stackoverflow.com/questions/2922797/t-sql-pivot-possibility-of-creating-table-columns-from-row-values">T-SQL Pivot? Possibility of creating table columns from row values</a></p>
| 0 | 1,026 |
Qt 4.8, Visual Studio 2013 compiling error
|
<p>Am folowing this <a href="http://menatronics.blogspot.fr/2012/12/compiling-qt-for-visual-studio-2012.html" rel="noreferrer">tutorial</a> to compile Qt 4.8 with visual Studio 2013 but after running nmake i get:</p>
<pre><code>C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
JSCallbackConstructor.cpp
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
JSCallbackFunction.cpp
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
JSCallbackObject.cpp
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
JSClassRef.cpp
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
JSContextRef.cpp
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
JSObjectRef.cpp
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
JSStringRef.cpp
JSValueRef.cpp
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
OpaqueJSString.cpp
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(103) : error C2491: 'round' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(110) : error C2491: 'roundf' : definition of dllimport function not allowed
C:\Qt\4.8.5.src\src\3rdparty\javascriptcore\JavaScriptCore\wtf/MathExtras.h(128) : error C2084: function 'bool signbit(double)' already has a body
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(615) : error C2264: 'signbit' : error in function definition or declaration; function not called
c:\qt\4.8.5.src\src\3rdparty\javascriptcore\javascriptcore\runtime\JSValue.h(696) : error C2264: 'signbit' : error in function definition or declaration; function not called
Generating Code...
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\BIN\cl.EXE"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: 'cd' : return code '0x2'
</code></pre>
<p>Thanks for any help</p>
| 0 | 3,213 |
Chromedriver: cannot execute binary file
|
<p>I am getting started with Nighwatch for web testing, and trying to do that with Chrome.</p>
<p>However, when I start the test, it immediately crashes with the following error:</p>
<p><code>17:56:35.218 INFO - Executing: [new session: Capabilities [{acceptSslCerts=true, name=Sandbox, browserName=chrome, javascriptEnabled=true, platform=ANY}]])
17:56:35.219 INFO - Creating a new session for Capabilities [{acceptSslCerts=true, name=Sandbox, browserName=chrome, javascriptEnabled=true, platform=ANY}]
/Users/murdockcrc/repos/nightwatch/bin/chromedriver: /Users/murdockcrc/repos/nightwatch/bin/chromedriver: cannot execute binary file</code></p>
<p>I am running the test with the following command:
<code>./bin/nightwatch --test hdv/tests/sandbox.js --config ./nightwatch.json</code></p>
<p>As far as I am concerned, all paths here are accurate and point to the right files.</p>
<p>Below is my nightwatch configuration file:</p>
<pre><code>{
"src_folders" : ["./hdv/tests"],
"output_folder" : "./hdv/reports",
"custom_commands_path" : "",
"custom_assertions_path" : "",
"globals_path" : "",
"live_output" : true,
"parallel_process_delay" : 10,
"disable_colors": false,
"test_workers" : false,
"selenium" : {
"start_process" : false,
"server_path" : "",
"log_path" : "",
"host" : "127.0.0.1",
"port" : 4444,
"cli_args" : {
"webdriver.chrome.driver" : "./bin/chromedriver",
"webdriver.ie.driver" : "",
"webdriver.firefox.profile" : ""
}
},
"test_settings" : {
"default" : {
"launch_url" : "http://localhost:3000",
"selenium_host" : "127.0.0.1",
"selenium_port" : 4444,
"silent" : true,
"disable_colors": false,
"screenshots" : {
"enabled" : false,
"path" : ""
},
"desiredCapabilities" : {
"browserName" : "chrome",
"javascriptEnabled" : true,
"acceptSslCerts" : true
}
}
}
}
</code></pre>
<p>And finally, here is the test I am trying to run (as you can see, just a placeholder to see if it runs at all):</p>
<pre><code>module.exports = {
'Demo test Google' : function (browser) {
browser
.url('http://www.google.com')
.waitForElementVisible('body', 1000)
.setValue('input[type=text]', 'nightwatch')
.waitForElementVisible('button[name=btnG]', 1000)
.click('button[name=btnG]')
.pause(1000)
.assert.containsText('#main', 'Night Watch')
.end();
}
};
</code></pre>
<p>Running this same test but with firefox (by changing the nightwatch.json file) does work without issues.</p>
<p>I would appreciate any pointers on what's wrong with this configuration and get it running on Chrome.</p>
| 0 | 1,076 |
Is there a way to reset the scale of the viewport dynamically to 1.0
|
<p>Im working on a a mobile online-store And got stuck while implementing the product zoom function</p>
<p>After clicking an Image "user-scalable" is allowed and maximum-scale is set to 10.0
When the user zooms in on the product with a pinch gesture, everything works fine.
But after closing the zoomed Image the scale is not reset to 1.0. </p>
<p>Is there a way to reset the scale value of the viewport dynamically.
The "initial-scale" seems not to work, neither does reseting the "minimum-scale" and "maximum-scale" to 1.0</p>
<p>The problems occurs on iPhone / iPad</p>
<p>There seems to be a solution, but i don't know to which element i should apply the on this post:
<a href="https://stackoverflow.com/questions/5380385/how-to-reset-viewport-scaling-without-full-page-refresh">How to reset viewport scaling without full page refresh?</a></p>
<p>"You need to use -webkit-transform: scale(1.1); webkit transition."</p>
<p>But I don't know to which element the style is applied.</p>
<p>Here is some code to illustrate the Problem.</p>
<p>In the meta Tag for the viewport looks like this:</p>
<pre><code><meta name="viewport" content="user-scalable=no, width=device-width, height=device-height, minimum-scale=1.0, maximum-scale=1.0" />
</code></pre>
<p>the rest of the page Looks like this:</p>
<pre><code><div id="page">
<img src="images/smallProductImage.jpg">
</div>
<div id="zoom">
<div class="jsZoomImageContainer"></div>
</div>
</code></pre>
<p>and this is the javascript::</p>
<pre><code>zoom:{
img: null,
initialScreen:null,
load:function(src){
//load the image and show it when loaded
showLoadingAnimation();
this.img = new Image();
this.img.src = src;
jQuery(this.img).load(function(){
zoom.show();
});
},
show:function(){
var screenWidth, screenHeight, imageWidth, imageHeight, scale, ctx;
hideLoadingAnimation();
jQuery("#page").hide();
jQuery("#zoom").show();
jQuery(".jsZoomImageContainer").empty();
this.initialScreen =[jQuery(window).width(), jQuery(window).height()]
jQuery(".jsZoomImageContainer").append(this.img);
imageWidth = jQuery(this.img).width();
imageHeight = jQuery(this.img).height();
scale = this.initialScreen[0] / imageWidth ;
jQuery(this.img).width(imageWidth * scale)
jQuery(this.img).height(imageHeight * scale)
jQuery(".jsZoomImageContainer").click(function(){
zoom.hide();
});
jQuery('meta[name="viewport"]',"head").attr("content","user-scalable=yes, initial-scale:1.0, minimum-scale=1.0, maximum-scale=10.0")
},
hide:function(){
jQuery(".jsZoomImageContainer").empty();
jQuery('meta[name="viewport"]',"head").attr("content","user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0")
jQuery("#zoom").hide();
jQuery("#page").show();
this.img = null;
this.initialScreen = null;
}
}
jQuery("#page img").click(function(){
zoom.load("images/bigProductImage.jpg");
});
</code></pre>
| 0 | 1,355 |
What is difference between getSupportFragmentManager() and getChildFragmentManager()?
|
<p>My class inherits Fragment and that's why it can't use getSupportFragmentManager().
I am using getChildFragmentManager and it is showing me Error - IllegalArguementException: No view found for id... error.</p>
<p>Any guidance would be appreciated.</p>
<p>Code for calling AttachmentsListFragment is</p>
<pre><code>Bundle b = new Bundle();
b.putSerializable("AttachmentsList", msg.attachments);
AttachmentListFragment listfrag = new AttachmentListFragment(msg.attachments);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.attachmentslistcontainer, listfrag);
transaction.addToBackStack(null);
transaction.commit();
</code></pre>
<p>attachmentslayout.xml is</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/attachmentslistcontainer"
android:orientation="vertical" >
<TextView
android:id="@+id/textViewAttachmentHeader"
style="@style/Normal.Header.Toolbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/list_separator_background"
android:ellipsize="end"
android:gravity="center"
android:maxLines="2"
android:text="@string/attachments_header"
android:textColor="#FFFFFFFF"
android:textSize="22sp"
android:textStyle="bold"
android:visibility="visible" />
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</FrameLayout>
</code></pre>
<p>AttachmentsListFragment.java</p>
<pre><code>public class AttachmentListFragment extends ListFragment implements IAttachmentsData {
ArrayList<Attachments> items = null;
Integer cellLayoutID;
Integer index;
public AttachmentListFragment() {
}
public AttachmentListFragment(ArrayList<Attachments> items) {
this.items = items;
Log.i("Logging", "Items size" + items.size()); //$NON-NLS-1$
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle;
if (savedInstanceState != null) {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
//super.onCreateView(inflater, container, savedInstanceState);
// setContentView(R.layout.attachmentslayout);
View view = inflater.inflate(R.layout.attachmentslayout, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new AttachmentAdapter(
getActivity().getApplicationContext(),
R.layout.attachmentslistcellcontent,
items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
index = position;
Intent intent = new Intent();
Bundle b = new Bundle();
b.putByteArray("Data", items.get(position).getImageData());
intent.putExtras(b);
}
public byte[] getData() {
// TODO Auto-generated method stub
if (items != null && index < items.size()) {
return items.get(index).getImageData();
}
return null;
}
}
</code></pre>
| 0 | 1,487 |
How to reuse threads in .NET 3.5
|
<p>I have a subroutine that processes large blocks of information. In order to make use of the entire CPU, it divides the work up into separate threads. After all threads have completed, it finishes. I read that creating and destroying threads uses lots of overhead, so I tried using the threadpool, but that actually runs slower than creating my own threads. How can I create my own threads when the program runs and then keep reusing them? I've seen some people say it can't be done, but the threadpool does it so it must be possible, right?</p>
<p>Here is part of the code that launches new threads / uses the threadpool:</p>
<pre><code>//initialization for threads
Thread[] AltThread = null;
if (NumThreads > 1)
AltThread = new Thread[pub.NumThreads - 1];
do
{
if (NumThreads > 1)
{ //split the matrix up into NumThreads number of even-sized blocks and execute on separate threads
int ThreadWidth = DataWidth / NumThreads;
if (UseThreadPool) //use threadpool threads
{
for (int i = 0; i < NumThreads - 1; i++)
{
ThreadPool.QueueUserWorkItem(ComputePartialDataOnThread,
new object[] { AltEngine[i], ThreadWidth * (i + 1), ThreadWidth * (i + 2) });
}
//get number of threads available after queue
System.Threading.Thread.Sleep(0);
int StartThreads, empty, EndThreads;
ThreadPool.GetAvailableThreads(out StartThreads, out empty);
ComputePartialData(ThisEngine, 0, ThreadWidth);
//wait for all threads to finish
do
{
ThreadPool.GetAvailableThreads(out EndThreads, out empty);
System.Threading.Thread.Sleep(1);
} while (StartThreads - EndThreads > 0);
}
else //create new threads each time (can we reuse these?)
{
for (int i = 0; i < NumThreads - 1; i++)
{
AltThread[i] = new Thread(ComputePartialDataOnThread);
AltThread[i].Start(new object[] { AltEngine[i], ThreadWidth * (i + 1), ThreadWidth * (i + 2) });
}
ComputePartialData(ThisEngine, 0, ThreadWidth);
//wait for all threads to finish
foreach (Thread t in AltThread)
t.Join(1000);
foreach (Thread t in AltThread)
if (t.IsAlive) t.Abort();
}
}
}
</code></pre>
<p>ComputePartialDataOnThread simply unpackages the information and calls ComputePartialData. The data that will be processed is shared among the threads (they don't try to read/write the same locations). AltEngine[] is a separate computation engine for each thread.</p>
<p>The operation runs about 10-20% using the threadpool.</p>
| 0 | 1,112 |
DataTables hidden row details example - the table header is misplaced (test case attached)
|
<p>I'm trying to create a table where more details can be seen when the plus-image is clicked - similar to the <a href="http://www.datatables.net/release-datatables/examples/api/row_details.html" rel="nofollow noreferrer">DataTables hidden row details example</a></p>
<p>Unfortunately there is a warning being printed as JavaScript alert and also the table header is misplaced - as if there would be too many or not enough table cells in it:</p>
<p><img src="https://i.stack.imgur.com/HYLhz.png" alt="enter image description here"></p>
<p>I have prepared a simple test case, which will work instantly, when you save it to a file and open it in a browser:</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables_themeroller.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script type="text/javascript">
var data = [
{"Total":17,"A":0,"B":0,"Details":{"BSN":"1147387861","ProjectName":"R127","StationName":"D"},"C":0,"D":17,"Test":"GSM_1900_GMSK_TXPOWER_HP_H","Measurement":"MEASUREMENT"},
{"Total":8,"A":0,"B":0,"Details":{"BSN":"1147387861","ProjectName":"R127","StationName":"D"},"C":0,"D":8,"Test":"TX_PWR_64_54","Measurement":"POWER"}
];
$(function() {
function fnFormatDetails(oTable, nTr) {
var aData = oTable.fnGetData(nTr);
var sOut = '<table bgcolor="yellow" cellpadding="8" border="0" style="padding-left:50px;">';
sOut += '<tr><td>BSN:</td><td>' + aData['Details']['BSN'] + '</td></tr>';
sOut += '<tr><td>Station:</td><td>' + aData['Details']['StationName'] + '</td></tr>';
sOut += '<tr><td>Project:</td><td>' + aData['Details']['ProjectName'] + '</td></tr>';
sOut += '</table>';
return sOut;
}
var fails = $('#fails').dataTable({
bJQueryUI: true,
sPaginationType: 'full_numbers',
aaData: data,
aaSorting: [[2, 'desc']],
aoColumns: [
{ mDataProp: 'Test', bSearchable: true, bSortable: true },
{ mDataProp: 'Measurement', bSearchable: true, bSortable: true },
{ mDataProp: 'Total', bSearchable: false, bSortable: true },
{ mDataProp: 'A', bSearchable: false, bSortable: true },
{ mDataProp: 'B', bSearchable: false, bSortable: true },
{ mDataProp: 'C', bSearchable: false, bSortable: true },
{ mDataProp: 'D', bSearchable: false, bSortable: true },
]
});
var th = document.createElement('th');
var td = document.createElement('td');
td.innerHTML = '<img src="http://www.datatables.net/release-datatables/examples/examples_support/details_open.png" class="details">';
$('#fails tbody th').each(function() {
this.insertBefore(th, this.childNodes[0]);
});
$('#fails tbody tr').each(function() {
this.insertBefore(td.cloneNode(true), this.childNodes[0]);
});
$('#fails tbody').on('click', 'td img.details', function() {
var nTr = $(this).parents('tr')[0];
if (fails.fnIsOpen(nTr)) {
this.src = 'http://www.datatables.net/release-datatables/examples/examples_support/details_open.png';
fails.fnClose(nTr);
} else {
this.src = 'http://www.datatables.net/release-datatables/examples/examples_support/details_close.png';
fails.fnOpen(nTr, fnFormatDetails(fails, nTr), 'details');
}
});
});
</script>
</head>
<body>
<table id="fails" cellspacing="0" cellpadding="4" width="100%">
<thead>
<tr>
<th>Test</th>
<th>Measurement</th>
<th>Total</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
</code></pre>
<p>Does anybody please have an idea, how to fix this?</p>
<p>I've tried adding/removing <code><th>Details</th></code> in the HTML body, but it didn't help.</p>
<p>I've also asked this question at the <a href="http://www.datatables.net/forums/discussion/17283/datatables-hidden-row-details-example-the-table-header-is-misplaced-test-case-attached" rel="nofollow noreferrer">DataTables forum</a>.</p>
<p><strong>UPDATE:</strong></p>
<p>I've received helpful comments by DataTables author and have decided to just prepend the plus-image to the contents of the first cell in each row - instead of adding a new cell to each row.</p>
<p>Unfortunately I have a new problem: the plus-image is displayed, but the orinigal text (the Test name) is gone:</p>
<p><img src="https://i.stack.imgur.com/5R5yp.png" alt="enter image description here"></p>
<p>Here is my new code (the plus-image is prepended by <code>propTest</code>):</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables_themeroller.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script type="text/javascript">
var data = [
{"Total":17,"A":0,"B":0,"Details":{"BSN":"1147387861","ProjectName":"R127","StationName":"D"},"C":0,"D":17,"Test":"GSM_1900_GMSK_TXPOWER_HP_H","Measurement":"MEASUREMENT"},
{"Total":8,"A":0,"B":0,"Details":{"BSN":"1147387861","ProjectName":"R127","StationName":"D"},"C":0,"D":8,"Test":"TX_PWR_64_54","Measurement":"POWER"}
];
function propTest(data, type, val) {
if (type === 'set') {
console.log(val); // for some reason prints "null"
data.name = val;
data.display = '<img src="http://www.datatables.net/release-datatables/examples/examples_support/details_open.png" width="20" height="20" class="details"> ' + val;
return;
}
if (type === 'display') {
return data.display;
}
// 'sort', 'type', 'filter' and undefined
return data.name;
}
$(function() {
function fnFormatDetails(oTable, nTr) {
var aData = oTable.fnGetData(nTr);
var sOut = '<table bgcolor="yellow" cellpadding="8" border="0" style="padding-left:50px;">';
sOut += '<tr><td>BSN:</td><td>' + aData['Details']['BSN'] + '</td></tr>';
sOut += '<tr><td>Station:</td><td>' + aData['Details']['StationName'] + '</td></tr>';
sOut += '<tr><td>Project:</td><td>' + aData['Details']['ProjectName'] + '</td></tr>';
sOut += '</table>';
return sOut;
}
var fails = $('#fails').dataTable({
bJQueryUI: true,
sPaginationType: 'full_numbers',
aaData: data,
aaSorting: [[2, 'desc']],
aoColumns: [
{ mData: propTest, bSearchable: true, bSortable: true },
{ mData: 'Measurement', bSearchable: true, bSortable: true },
{ mData: 'Total', bSearchable: false, bSortable: true },
{ mData: 'A', bSearchable: false, bSortable: true },
{ mData: 'B', bSearchable: false, bSortable: true },
{ mData: 'C', bSearchable: false, bSortable: true },
{ mData: 'D', bSearchable: false, bSortable: true }
]
});
$('#fails tbody').on('click', 'td img.details', function() {
var nTr = $(this).parents('tr')[0];
if (fails.fnIsOpen(nTr)) {
this.src = 'http://www.datatables.net/release-datatables/examples/examples_support/details_open.png';
fails.fnClose(nTr);
} else {
this.src = 'http://www.datatables.net/release-datatables/examples/examples_support/details_close.png';
fails.fnOpen(nTr, fnFormatDetails(fails, nTr), 'details');
}
});
});
</script>
</head>
<body>
<table id="fails" cellspacing="0" cellpadding="4" width="100%">
<thead>
<tr>
<th>Test</th>
<th>Measurement</th>
<th>Total</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
</code></pre>
| 0 | 5,342 |
ParseException; must be caught (Try/Catch) (Java)
|
<p>I am writing an appointment program and am getting the following errors:</p>
<pre><code>AppointmentNew.java:68: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date lowDate = sdf.parse(stdin.nextLine());
^
AppointmentNew.java:70: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date highDate = sdf.parse(stdin.nextLine());
^
AppointmentNew.java:77: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date newCurrentDate = sdf.parse(currentDate);
</code></pre>
<p>I am pretty sure I need to do a try/catch, but I am not sure of how to produce that. The part where I am getting the error is where it asks the user to input a BEGINNING and END date, when they do that the program then prints out the appointments they have made between the two dates.</p>
<p>Here is my code I have : </p>
<pre class="lang-java prettyprint-override"><code>import java.util.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AppointmentNew
{
public static void main (String[] args)
{
ArrayList<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
String choice = "";
int choiceNum = 0;
String date = "";
String descrip = "";
int type = 0;
String typeChose = "";
System.out.println("Welcome to Appointment App!\n");
System.out.println("\t============================");
do
{
System.out.print("\n\tMake Choice (1: New, 2: Print Range, 3: Print All, 4: Quit) ");
choice = stdin.nextLine();
choiceNum = Integer.parseInt(choice);
if (choiceNum == 1)
{
System.out.print("\n\n\tEnter New Appointment Date in mm/dd/yyyy format: ");
date = stdin.nextLine();
System.out.print("\n\n\tEnter New Appointment Description: ");
descrip = stdin.nextLine();
System.out.print("\n\n\tEnter Type (1 = Once, 2 = Daily, 3 = Monthly): ");
type = stdin.nextInt();
stdin.nextLine();
if (type == 1)
{
Once once = new Once(date, descrip);
typeChose = "One-Time";
}
else if (type == 2)
{
Daily daily = new Daily(date, descrip);
typeChose = "Daily";
}
else
{
Monthly monthly = new Monthly(date, descrip);
typeChose = "Monthly";
}
String stringToAdd = "";
stringToAdd = (date + " : \"" + descrip + "\", " + typeChose);
list.add(stringToAdd);
System.out.println("\n\n\tNew " + typeChose + " Appointment Added for " + date + "\n");
System.out.println("\t============================\n");
}
if (choiceNum == 2)
{
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date lowDate = sdf.parse(stdin.nextLine());
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
Date highDate = sdf.parse(stdin.nextLine());
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
String currentDate = list.get(i);
currentDate.substring(0, dateSpot);
Date newCurrentDate = sdf.parse(currentDate);
if (newCurrentDate.compareTo(lowDate) >= 0 && newCurrentDate.compareTo(highDate) <= 0)
{
System.out.println("\n\t" + list.get(i));
}
}
}
if (choiceNum == 3)
{
for(int i = 0; i < list.size(); i++)
{
System.out.println("\n\t" + list.get(i));
}
}
}while (choiceNum != 4);
}
}
</code></pre>
| 0 | 1,679 |
PostgreSQL connection limit exceeded for non-superusers
|
<p>I am using a spring application and I am getting following exception as:</p>
<pre><code>Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection.
</code></pre>
<p>When I am manually trying to connect to the database using DBVisualizer I am getting following error</p>
<pre><code>An error occurred while establishing the connection:
Long Message:
FATAL: connection limit exceeded for non-superusers
Details:
Type: org.postgresql.util.PSQLException
Error Code: 0
SQL State: 53300
</code></pre>
<p>Here is my spring-context.xml file</p>
<pre><code><jee:jndi-lookup id="dataSource1" jndi-name="jdbc/PmdDS"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource1" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
</props>
</property>
</bean>
</code></pre>
<p>My question is I am getting this error because that I have not added following line in spring-context.xml</p>
<pre><code> <prop key="hibernate.connection.release_mode">auto</prop>
</code></pre>
<p>Will adding this line will solve my problem. I am fearing that my application is creating connection but not releasing the database connection because I have not added the above line in spring-context.xml..
Note I am not using HibernateTemplate . I am using <code>sessionFactory.getCurrentSession().createQuery("").list()</code> to fire my queries
My Context.xml details</p>
<pre><code><Context>
Specify a JDBC datasource
<Resource name="jdbc/PmdDS"
auth="Container"
type="javax.sql.DataSource"
username="sdfsfsf"
password="sfsdfsdf" maxActive="-1"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://111.11.11.11:5432/test"/>
</Context>
</code></pre>
<p>Please suggest any solution</p>
| 0 | 1,152 |
How to get all extra values from intent
|
<p>Here is my code</p>
<pre><code> Log.i("sdfgsdf", time.toGMTString());
String SENT = "SMS_SENT";
Intent y= new Intent(SENT);
y.putExtra("number", phoneNumber);
y.putExtra("time", time.toString());
String DELIVERED = "SMS_DELIVERED";
int FLAG_UPDATE_CURRENT =(0x08000000) ;
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
y, FLAG_UPDATE_CURRENT);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), FLAG_UPDATE_CURRENT);
//---when the SMS has been sent---
r= new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent"+arg1.getStringExtra("number"),
Toast.LENGTH_SHORT).show();
Constant.DB = Compose.this.openOrCreateDatabase("Indigo",MODE_PRIVATE, null);
Constant.DB.execSQL("UPDATE Message SET IsMsgSent='true' where DateAndTime='" + arg1.getStringExtra("time") + "' and ContactNumber='"+arg1.getStringExtra("number")+"'");
Constant.DB.execSQL("UPDATE Message SET FolderId='5' where DateAndTime='" + arg1.getStringExtra("time") + "' and ContactNumber='"+arg1.getStringExtra("number")+"'");
Constant.DB.close();
// unregisterReceiver(r);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure"+arg1.getStringExtra("number"),
Toast.LENGTH_SHORT).show();
Constant.DB = Compose.this.openOrCreateDatabase("Indigo",MODE_PRIVATE, null);
Constant.DB.execSQL("UPDATE Message SET IsMsgSent='false' where DateAndTime='" + arg1.getStringExtra("time") + "' and ContactNumber='"+arg1.getStringExtra("number")+"'");
Constant.DB.close();
// unregisterReceiver(r);
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service"+arg1.getStringExtra("number"),
Toast.LENGTH_SHORT).show();
Constant.DB = Compose.this.openOrCreateDatabase("Indigo",MODE_PRIVATE, null);
Constant.DB.execSQL("UPDATE Message SET IsMsgSent='false' where DateAndTime='" + arg1.getStringExtra("time") + "' and ContactNumber='"+arg1.getStringExtra("number")+"'");
Constant.DB.close();
// unregisterReceiver(r);
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU"+arg1.getStringExtra("number"),
Toast.LENGTH_SHORT).show();
Constant.DB = Compose.this.openOrCreateDatabase("Indigo",MODE_PRIVATE, null);
Constant.DB.execSQL("UPDATE Message SET IsMsgSent='false' where DateAndTime='" + arg1.getStringExtra("time") + "' and ContactNumber='"+arg1.getStringExtra("number")+"'");
Constant.DB.close();
// unregisterReceiver(r);
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off"+arg1.getStringExtra("number"),
Toast.LENGTH_SHORT).show();
Constant.DB = Compose.this.openOrCreateDatabase("Indigo",MODE_PRIVATE, null);
Constant.DB.execSQL("UPDATE Message SET IsMsgSent='false' where DateAndTime='" + arg1.getStringExtra("time") + "' and ContactNumber='"+arg1.getStringExtra("number")+"'");
Constant.DB.close();
// unregisterReceiver(r);
break;
}
}
};
registerReceiver(r, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
</code></pre>
<p>And when i send multiple sms using a for loop iam getting extras of only last sent sms.how to get all extras..?</p>
| 0 | 2,756 |
Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)
|
<p>I just upgraded my MacMini Server from Lion Server to Mountain Lion using OS X Server. I am having the same problem with PostgreSQL that I did last year when I first installed Lion Server.</p>
<p>When I try to do any kind of PostgreSQL terminal command I get the following notorious error message that many have gotten over the years:</p>
<pre><code>psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
</code></pre>
<p>I was attempting to change the password for _postgres when I got the error. I tried several commands but got the same error. I just rebooted my server but no luck. I logged in as root to look at /var/pgsql_socket and the folder is empty. Folder /var/pgsql_socket_alt is also empty.</p>
<p>I have checked online about this. However just about all of the solutions I have read, including on Stack Overflow, suggest a removal and reinstall of PostgreSQL. I do not know but this does not seem like a plausible option because several options on the Server App use PostgreSQL. I contacted Apple Enterprise Support (no agreement) and I was told that my issue would have to be solved by the developers which would cost $695.</p>
<p>I have a website that is down right now because I cannot rebuild it. I don't know where to turn for help with this at this point. I will continue looking online to see if I can find something. However I hope that someone can give me an answer quick so I can rebuild my database.</p>
<p><strong>Update: 12/13/2012 15:33 GMT-6</strong></p>
<p>Here is my output for ps auwx|grep postg:</p>
<pre><code>_postgres 28123 0.0 0.1 2479696 7724 ?? Ss 3:01PM 0:00.04 /Applications/Server.app/Contents/ServerRoot/usr/bin/postgres_real -D /Library/Server/PostgreSQL For Server Services/Data -c listen_addresses= -c log_connections=on -c log_directory=/Library/Logs/PostgreSQL -c log_filename=PostgreSQL_Server_Services.log -c log_line_prefix=%t -c log_lock_waits=on -c log_statement=ddl -c logging_collector=on -c unix_socket_directory=/Library/Server/PostgreSQL For Server Services/Socket -c unix_socket_group=_postgres -c unix_socket_permissions=0770
server1 28216 0.0 0.0 2432768 620 s000 R+ 3:02PM 0:00.00 grep postg
_postgres 28138 0.0 0.0 2439388 752 ?? Ss 3:01PM 0:00.01 postgres: stats collector process
_postgres 28137 0.0 0.0 2479828 1968 ?? Ss 3:01PM 0:00.00 postgres: autovacuum launcher process
_postgres 28136 0.0 0.0 2479696 544 ?? Ss 3:01PM 0:00.00 postgres: wal writer process
_postgres 28135 0.0 0.0 2479696 732 ?? Ss 3:01PM 0:00.01 postgres: writer process
_postgres 28134 0.0 0.0 2479696 592 ?? Ss 3:01PM 0:00.00 postgres: checkpointer process
_postgres 28131 0.0 0.0 2439388 368 ?? Ss 3:01PM 0:00.00 postgres: logger process
</code></pre>
<p><strong>Update: 12/13/2012 18:10 GMT-6</strong></p>
<p>After intense web searching this video was found. I was able to get PostgreSQL working and remove the error. I am able to connect using pgadmin and phppgadmin. I was about to go back to Lion Server because of sheer frustration. Now I will not have to.</p>
<p><a href="http://www.youtube.com/watch?v=y1c7WFMMkZ4" rel="nofollow noreferrer">http://www.youtube.com/watch?v=y1c7WFMMkZ4</a></p>
| 0 | 1,357 |
Unable to tag SCM when I using maven release plugin
|
<p>when I using maven release plugin,I encountered some questions,the most one is tag scm failed,the error is :
svn: “svn://192.168.5.222/show/test-show/trunk/show” does not in the revision 0 .</p>
<pre><code>at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.jvnet.hudson.maven3.launcher.Maven3Launcher.main(Maven3Launcher.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchStandard(Launcher.java:329)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:239)
at org.jvnet.hudson.maven3.agent.Maven3Main.launch(Maven3Main.java:158)
at hudson.maven.Maven3Builder.call(Maven3Builder.java:98)
at hudson.maven.Maven3Builder.call(Maven3Builder.java:64)
at hudson.remoting.UserRequest.perform(UserRequest.java:118)
at hudson.remoting.UserRequest.perform(UserRequest.java:48)
at hudson.remoting.Request$2.run(Request.java:326)
at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
</code></pre>
<p>Caused by: org.apache.maven.plugin.MojoFailureException: Unable to tag SCM</p>
<p>then I found my log:</p>
<p>[INFO] Executing: /bin/sh -c cd /data/.hudson/jobs/hxbos/workspace && svn --username liulaixi --password '<strong>*</strong>' --no-auth-cache --non-interactive copy --file /tmp/maven-scm-49732292.commit --revision 0 svn://192.168.5.213/hxbos/hxecp-src/trunk/hxbos svn://192.168.5.213/hxbos/hxecp-src/tags/hxbos/hxbos-all-test-1.5.0
[INFO] Working directory: /data/.hudson/jobs/hxbos/workspace</p>
<p>why my --revision is 0?who can help me?thanks!</p>
| 0 | 1,101 |
How to decode a base64 encoded certificate
|
<p>Below is my requirement:</p>
<ol>
<li>Program will have an XML file as input with 3 tags: <code>OrgContent</code>, <code>Signature</code> and <code>Certificate</code>. All these data are Base64 encoded. Note: Program is using BC jars</li>
<li>Program needs to decode them and verify the data for its authenticity using the signature and certificate</li>
<li>Verified data should be Base64 decoded and written into another file</li>
</ol>
<p>Below is my code which tries to decode the certificate:</p>
<pre><code>public void executeTask(InputStream arg0, OutputStream arg1) throws SomeException{
try{
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(arg0));
String orgContent = "", splitData = "", signContent = "", certContent = "";
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(arg0);
doc.getDocumentElement().normalize();
NodeList originalContent = doc.getElementsByTagName("OrgContent");
Element originalElement = (Element)originalContent.item(0);
NodeList textOrgContent = originalElement.getChildNodes();
orgContent = ((Node)textOrgContent.item(0)).getNodeValue().trim();
NodeList signature = doc.getElementsByTagName("Signature");
Element signatureElement = (Element)signature.item(0);
NodeList signatureContent = signatureElement.getChildNodes();
signContent = ((Node)signatureContent.item(0)).getNodeValue().trim();
NodeList certificate = doc.getElementsByTagName("Certificate");
Element certificateElement = (Element)certificate.item(0);
NodeList certificateContent = certificateElement.getChildNodes();
certContent = ((Node)certificateContent.item(0)).getNodeValue().trim();
String decodedCertContent = new String(Base64.decode(certContent),StandardCharsets.UTF_8);
byte[] certByteValue = Base64.decode(certContent);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
System.out.println("certContent:\n" + new String(certByteValue,StandardCharsets.UTF_8));
InputStream inputStream = new ByteArrayInputStream(Base64.decode(certContent));
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(inputStream);
arg1.write(decodedOrgData.getBytes());
arg1.flush();
}
catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (org.xml.sax.SAXException e){
e.printStackTrace();
}
catch (CertificateException e){
e.printStackTrace();
}
}
</code></pre>
<p>When I print the value of new String(certByteValue,StandardCharsets.UTF_8) the program is printing some unrecognizable text. When executing the last line of the code <code>X509Certificate cert = (X509Certificate)certFactory.generateCertificate(inputStream);</code> system is throwing</p>
<blockquote>
<p>java.security.cert.CertificateException: Could not parse certificate: java.io.IOException: Invalid BER/DER data (too huge?).</p>
</blockquote>
<p>Since I am a newbie to these certificates thing, I have hit a deadlock. I am unable to proceed with the requirement. I would like to know how to achieve my above said requirements.</p>
<p>The input stream to the above code will be an XML file. Another program creates that XML file with base64 encoded data with signature and certificate. In that program, for encoding the certificate the below code is used:</p>
<pre><code>KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("Filepath/certificate.p12"), "password".toCharArray());
PrivateKey privateKey = (PrivateKey)keyStore.getKey(alias, "password".toCharArray());
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) factory.generateCertificate(new FileInputStream("D:/Sujai/Implementation Team/PI/Axis Treds/Certificates/PI_7.5_Cert/Arteria_Certificate-cert.cert"));
byte[] encodedCert = certificate.getEncoded();
String encodedStringCert = new String(Base64.encode(new String(encodedCert).getBytes(StandardCharsets.UTF_8)));
</code></pre>
<p>The variable <code>encodedStringCert</code> is passed as the certificate value inside a tag. In the program shared at the top of this question, I need to decode this certificate value.</p>
<p>Sample certificate content:</p>
<pre class="lang-none prettyprint-override"><code>-----BEGIN CERTIFICATE-----
MIIDBjCCAe6....IM1g==
-----END CERTIFICATE-----
</code></pre>
| 0 | 1,691 |
Android studio getSlotFromBufferLocked: unknown buffer error
|
<p>I want to make a simple login and register app, so the user can create an account. (name, username, password)
I use WAMP and a MYSQL database where I store the accounts.</p>
<p>When I fill in the user info on the registration form and click register I get the following error:</p>
<pre><code>09-14 09:30:39.864 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7115e0
09-14 09:30:48.632 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7125a0
09-14 09:30:51.940 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7125a0
</code></pre>
<p>When I go check the database it didn't store the account.</p>
<p>MainActivity.java</p>
<pre><code>import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void userReg(View v)
{
startActivity(new Intent(this, Register.class));
}
public void userLogin(View view)
{
}
}
</code></pre>
<p>Register.java</p>
<pre><code>import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class Register extends Activity {
EditText ET_NAME,ET_USER_NAME,ET_USER_PASS;
String name,user_name,user_pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
ET_NAME = (EditText) findViewById(R.id.name);
ET_USER_NAME = (EditText) findViewById(R.id.new_user_name);
ET_USER_PASS = (EditText) findViewById(R.id.new_user_pass);
}
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(Register.this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
}
</code></pre>
<p>Backgroundtask.java</p>
<pre><code>import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String, Void, String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx) {
this.ctx = ctx;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2.2/webapp/register.php";
String login_url = "http://10.0.2.2.2/webapp/login.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p>register.php</p>
<pre><code><?php
require "init.php";
$name = $_POST["user"];
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$sql_query = "insert into user_info values('$name','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query))
{
//echo"<h3> Data insertion success...</h3>";
}
else{
//echo "Data insertion error..".mysqli_error($con);
}
?>
</code></pre>
<p>init.php</p>
<pre><code><?php
$db_name="myDBname";
$mysql_user = "root";
$mysql_pass = "root";
$server_name="localhost";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
if(!$con)
{
//echo"Connection Error".mysqli_connect_error();
}
else
{
//echo"<h3> Database connection success.....</h3>";
}
?>
</code></pre>
| 0 | 2,532 |
Error C2593: 'operator =' is ambiguous For string template
|
<p>I keep getting this error for part of my template, for this is working fine. I would love to handle this error myself but I don't even know what this means. Maybe my operator overload syntax is incorrect? But even without my operator loading method I still get the same error</p>
<pre><code>node.h(12): error C2593: 'operator =' is ambiguous
c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring(992): could be 'std::basic_string<_Elem,_Traits,_Alloc> &std::basic_string<_Elem,_Traits,_Alloc>::operator =(_Elem)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Alloc=std::allocator<char>
1> ]
1> c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring(987): or 'std::basic_string<_Elem,_Traits,_Alloc> &std::basic_string<_Elem,_Traits,_Alloc>::operator =(const _Elem *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Alloc=std::allocator<char>
1> ]
c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring(987): or 'std::basic_string<_Elem,_Traits,_Alloc> &std::basic_string<_Elem,_Traits,_Alloc>::operator =(const _Elem *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Alloc=std::allocator<char>
1> ]
1> while trying to match the argument list '(std::string, int)'
1> c:\users\aaron\documents\visual studio 2012\projects\redblacktreefinal\redblacktreefinal\node.h(10) : while compiling class template member function 'Node<T>::Node(void)'
1> with
1> [
1> T=std::string
1> ]
1> c:\users\aaron\documents\visual studio 2012\projects\redblacktreefinal\redblacktreefinal\redblacktree.cpp(145) : see reference to function template instantiation 'Node<T>::Node(void)' being compiled
1> with
1> [
1> T=std::string
1> ]
1> c:\users\aaron\documents\visual studio 2012\projects\redblacktreefinal\redblacktreefinal\redblacktree.cpp(203) : see reference to class template instantiation 'Node<T>' being compiled
1> with
1> [
1> T=std::string
1> ]
1> c:\users\aaron\documents\visual studio 2012\projects\redblacktreefinal\redblacktreefinal\redblacktree.cpp(197) : while compiling class template member function 'bool RedBlackTree<T>::remove(T)'
1> with
1> [
1> T=std::string
1> ]
1> c:\users\aaron\documents\visual studio 2012\projects\redblacktreefinal\redblacktreefinal\redblacktreefinal.cpp(240) : see reference to function template instantiation 'bool RedBlackTree<T>::remove(T)' being compiled
1> with
1> [
1> T=std::string
1> ]
1> c:\users\aaron\documents\visual studio 2012\projects\redblacktreefinal\redblacktreefinal\redblacktreefinal.cpp(213) : see reference to class template instantiation 'RedBlackTree<T>' being compiled
1> with
1> [
1> T=std::string
1> ]
</code></pre>
<p>My node.h file</p>
<pre><code>#include <cstdlib>
#include <cstring>
template <class T>
class Node {
public :
Node<T>(void) {
parent = NULL;
left = NULL;
right = NULL;
data = NULL;
isBlack = false;
}
Node<T>(T x){
parent = NULL;
left = NULL;
right = NULL;
data = x;
isBlack = false;
}
Node<T>(const Node<T>* & nd){
parent = nd->parent;
left = nd->left;
right = nd->right;
data = nd->data;
isBlack = nd->isBlack;
}
Node<T> & Node<T>::operator = (const Node<T>* & nd){
parent = nd->parent;
left = nd->left;
right = nd->right;
data = nd->data;
isBlack = nd->isBlack;
return* this;
}
Node<T>* parent;
Node<T>* left;
Node<T>* right;
T data;
bool isBlack;
private :
};
</code></pre>
<p>How it's being used</p>
<pre><code>void part2()
{
cout << endl << endl << "REDBLACKTREE<STRING>";
cout << endl << "insert file and print contents (load, dump)" << endl;
RedBlackTree<string> rb;
string fname = "part2.txt"; //should contain strings
int n = 0;
// read file and load contents into tree
string* arr = readFile<string>(fname, n);
rb.load(arr, n);
// read contents from tree into array
int out_n = 0;
string* out = rb.dump(out_n);
// print dumped contents
int count = 0;
for(int i=0; i < out_n; i++){
if(count % 5 == 0){
cout << endl;
}
cout << left << setw(13) << out[i];
count ++;
}
cout << endl;
statsPrint(rb, 174, 5, 9, true);
// remove all items from tree
cout << endl << endl << "empty tree one item at a time";
for(int i=0; i < n; i++){
rb.remove(arr[i]);
}
statsPrint(rb, 0, 0, 0, true);
delete[] arr;
delete[] out;
}
</code></pre>
| 0 | 2,916 |
uwsgi python3 plugin doesn't work
|
<p>i compiled uwsgi with make and it's successfully done,and now i decide to run my django1.5 site with python3.3 . i've checked for the doc (<a href="http://projects.unbit.it/uwsgi/wiki/Guide4Packagers" rel="noreferrer">http://projects.unbit.it/uwsgi/wiki/Guide4Packagers</a>) and set up python3.3 development headers through apt-get and then compile the plugin by:</p>
<blockquote>
<p>python3.3 uwsgiconfig.py --plugin plugins/python package python33</p>
</blockquote>
<p>then it says:</p>
<pre><code>using profile: buildconf/package.ini
detected include path: ['/usr/lib/gcc/i686-linux-gnu/4.7/include', '/usr/local/include','/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed', '/usr/include/i386-linux-gnu', '/usr/include']
*** uWSGI building and linking plugin plugins/python ***
[i686-linux-gnu-gcc -pthread] /usr/lib/uwsgi/python33_plugin.so
*** python33 plugin built and available in /usr/lib/uwsgi/python33_plugin.so ***
</code></pre>
<p>it seems all is well done and i do find python33_plugin.so in that dir.
nginx is running and is ok,now my uwsgi ini file is like this:</p>
<pre><code>[uwsgi]
socket=0.0.0.0:8000
listen=20
master=true
pidfile=/usr/local/nginx/uwsgi.pid
processes=2
plugins=python33
module=django_wsgi
pythonpath=
profiler=true
memory-report=true
enable-threads=true
logdate=true
limit-as=6048
</code></pre>
<p>and when i run "sudo ./uwsgi uwsgi.ini",</p>
<pre><code>[uWSGI] getting INI configuration from uwsgi.ini
open("./python33_plugin.so"): No such file or directory [core/utils.c line 3347]
!!! UNABLE to load uWSGI plugin: ./python33_plugin.so: cannot open shared object file: No such file or directory !!!
</code></pre>
<p>it doesn't find the .so file.anyway then i copy the .so file to the uwsgi dir,and run again,</p>
<pre><code>[uWSGI] getting INI configuration from uwsgi.ini
Sun Apr 28 22:54:40 2013 - *** Starting uWSGI 1.9.8 (32bit) on [Sun Apr 28 22:54:40 2013] ***
Sun Apr 28 22:54:40 2013 - compiled with version: 4.7.3 on 28 April 2013 21:25:27
Sun Apr 28 22:54:40 2013 - os: Linux-3.8.0-19-generic #29-Ubuntu SMP Wed Apr 17 18:19:42 UTC 2013
Sun Apr 28 22:54:40 2013 - nodename: bill-Rev-1-0
Sun Apr 28 22:54:40 2013 - machine: i686
Sun Apr 28 22:54:40 2013 - clock source: unix
Sun Apr 28 22:54:40 2013 - pcre jit disabled
Sun Apr 28 22:54:40 2013 - detected number of CPU cores: 4
Sun Apr 28 22:54:40 2013 - current working directory: /media/bill/cloud/cloud/program/kkblog/kkblog
Sun Apr 28 22:54:40 2013 - writing pidfile to /usr/local/nginx/uwsgi.pid
Sun Apr 28 22:54:40 2013 - detected binary path: /usr/sbin/uwsgi
Sun Apr 28 22:54:40 2013 - uWSGI running as root, you can use --uid/--gid/--chroot options
Sun Apr 28 22:54:40 2013 - *** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
Sun Apr 28 22:54:40 2013 - your processes number limit is 31552
Sun Apr 28 22:54:40 2013 - limiting address space of processes...
Sun Apr 28 22:54:40 2013 - your process address space limit is 2046820352 bytes (1952 MB)
Sun Apr 28 22:54:40 2013 - your memory page size is 4096 bytes
Sun Apr 28 22:54:40 2013 - detected max file descriptor number: 1024
Sun Apr 28 22:54:40 2013 - lock engine: pthread robust mutexes
Sun Apr 28 22:54:40 2013 - uwsgi socket 0 bound to TCP address 0.0.0.0:8000 fd 3
Sun Apr 28 22:54:40 2013 - Python version: 2.7.4 (default, Apr 19 2013, 18:35:44) [GCC 4.7.3]
Sun Apr 28 22:54:40 2013 - Python main interpreter initialized at 0x973e2d0
Sun Apr 28 22:54:40 2013 - python threads support enabled
</code></pre>
<p>i'm using ubuntu 13.04 and python2.7 and python3.3 are preinstalled. </p>
<p>I SET THE PYTHON33 PLUGIN BUT UWSGI STILL LAUNCHES PYTHON2.7 ,why?</p>
<p>anybody who ever met this problem? and by the way i don't like to setup uwsgi and plugins through apt-get,because it won't work at any PaaS.</p>
<p>thanks!</p>
| 0 | 1,372 |
Creating Registry Keys with Powershell
|
<p>I am trying to check if a key-structure exists in the registry using powershell. If the structure does not exist, I need to create it and then I need to create the keys in the ending folder. If I run the snippets individually to create the keys, they create just fine. But running the block itself (ensuring manually within the registry that the keys don't exist) it won't create the folder structure. Not sure what the issue is. Any help would be appreciate. The code is as follows:</p>
<pre><code>$Registry_Paths = "hkcu:\Software\Microsoft\Office\14.0", "hkcu:\Software\Microsoft\Office\14.0\Groove", "hkcu:\Software\Microsoft\Office\14.0\Groove\Development"
foreach($Registry_Path in $Registry_Paths)
{
$Test_Path_Result = Test-Path -Path $Registry_Path
if($Test_Path_Result -eq $false)
{
$Registry_Key_Log += "Warning: No registry key path found at " + $Registry_Path +"`n"
$Registry_Key_Log += "Creating key now for " + $Registry_Path + "`n" + "`n"
if($Registry_Path -eq "hkcu:\Software\Microsoft\Office\14.0")
{
try{
New-Item -Path "HKCU:\Software\Microsoft\Office\14.0" -ItemType Key
}
catch
{
$Error_Log += "Warning: There was an error when attempting to create a new registry key, or key property for $Registry_Path"
$Error_Log += $_.exception.message
}
}
if($Registry_Path -eq "hcku:\Software\Microsoft\Office\14.0\Groove")
{
try{
New-Item -Path "HKCU:\Software\Microsoft\Office\14.0\Groove" -ItemType Key
}
catch
{
$Error_Log += "Warning: There was an error when attempting to create a new registry key, or key property for $Registry_Path"
$Error_Log += $_.exception.message
}
}
if($Registry_Path -eq "hcku:\Software\Microsoft\Office\14.0\Groove\Development")
{
try{
New-Item -Path "HKCU:\Software\Microsoft\Office\14.0\Groove\Development" -ItemType Key
New-ItemProperty -Path "hkcu:\Software\Microsoft\Office\14.0\Groove\Development" -Value 00000001 -PropertyType dword -Name "EnableReleaseBuildDebugOutput"
New-ItemProperty -Path "hkcu:\Software\Microsoft\Office\14.0\Groove\Development" -Value 1 -Name "TraceIdentityMessaging"
New-ItemProperty -Path "hkcu:\Software\Microsoft\Office\14.0\Groove\Development" -Value 00000001 -PropertyType dword -Name "TraceTelespaceFetch"
New-ItemProperty -Path "hkcu:\Software\Microsoft\Office\14.0\Groove\Development" -Value 1 -Name "TraceConnectSequence"
}
catch
{
$Error_Log += "Warning: There was an error when attempting to create a new registry key, or key property for $Registry_Path"
$Error_Log += $_.exception.message
}
}
}
}
</code></pre>
| 0 | 1,073 |
using CSS to center FLOATED input elements wrapped in a DIV
|
<p>There's no shortage of questions and answers about centering but I've not been able to get it to work given my specific circumstances, which involve floating.</p>
<p>I want to center a container DIV that contains three floated input elements (split-button, text, checkbox), so that when my page is resized wider, they go from this:</p>
<pre><code> ||.....[ ][v] [ ] [ ] label .....||
</code></pre>
<p>to this</p>
<pre><code> ||......................[ ][v] [ ] [ ] label.......................||
</code></pre>
<p>They float fine, but when the page is made wider, they stay to the left:</p>
<pre><code> ||.....[ ][v] [ ] [ ] label .......................................||
</code></pre>
<p>If I remove the float so that the input elements are stacked rather than side-by-side:</p>
<pre><code> [ ][v]
[ ]
[ ] label
</code></pre>
<p>then they DO center correctly when the page is resized. SO it is the float being applied to the elements of the DIV#hbox inside the container that is messing up the centering. <strong>Is what I want to do impossible because of the way float is designed to work?</strong> </p>
<p>Here is my DOCTYPE, and the markup does validate at w3c:</p>
<pre><code> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
</code></pre>
<p>Here is my markup:</p>
<pre><code> <div id="term1-container">
<div class="hbox">
<div>
<button id="operator1" class="operator-split-button">equals</button>
<button id="operator1drop">show all operators</button>
</div>
<div><input type="text" id="term1"></input></div>
<div><input type="checkbox" id="meta2"></input><label for="meta2" class="tinylabel">meta</label></div>
</div>
</div>
</code></pre>
<p>And here's the (not-working) CSS:</p>
<pre><code> #term1-container {text-align: center}
.hbox {margin: 0 auto;}
.hbox div {float:left; }
</code></pre>
<p>I have also tried applying <strong>display: inline-block</strong> to the floated button, text-input, and checkbox; and even though I think it applies only to text, I've also tried applying <strong>white-space: nowrap</strong> to the #term1-container DIV, based on posts I've seen here on SO.</p>
<p>And just to be a little more complete, here's the jQuery that creates the split-button:</p>
<pre><code>$(".operator-split-button").button().click( function() {
alert( "foo" );
}).next().button( {
text: false,
icons: {
primary: "ui-icon-triangle-1-s"
}
}).click( function(){positionOperatorsMenu();} )
})
</code></pre>
| 0 | 1,083 |
Sort latitude and longitude coordinates into clockwise ordered quadrilateral
|
<p><strong>Problem</strong></p>
<p>Users can provide up to four latitude and longitude coordinates, in any order. They do so with Google Maps. Using Google's <code>Polygon</code> API (v3), the coordinates they select should highlight the selected area between the four coordinates.</p>
<p><strong>Question</strong></p>
<p>How do you sort an array of latitude and longitude coordinates in (counter-)clockwise order?</p>
<p><strong>Solutions and Searches</strong></p>
<p><em>StackOverflow Questions</em></p>
<ul>
<li><a href="https://stackoverflow.com/questions/2353409/drawing-resizable-not-intersecting-polygons">Drawing resizable (not intersecting) polygons</a></li>
<li><a href="https://stackoverflow.com/questions/2374708/how-to-sort-points-in-a-google-maps-polygon-so-that-lines-do-not-cross">How to sort points in a Google maps polygon so that lines do not cross?</a></li>
<li><a href="https://stackoverflow.com/questions/242404/sort-four-points-in-clockwise-order">Sort Four Points in Clockwise Order</a></li>
</ul>
<p><em>Related Sites</em></p>
<ul>
<li><a href="http://www.daftlogic.com/projects-google-maps-area-calculator-tool.htm" rel="noreferrer">http://www.daftlogic.com/projects-google-maps-area-calculator-tool.htm</a></li>
<li><a href="http://en.literateprograms.org/Quickhull_%28Javascript%29" rel="noreferrer">http://en.literateprograms.org/Quickhull_%28Javascript%29</a></li>
<li><a href="http://www.geocodezip.com/map-markers_ConvexHull_Polygon.asp" rel="noreferrer">http://www.geocodezip.com/map-markers_ConvexHull_Polygon.asp</a></li>
<li><a href="http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm" rel="noreferrer">http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm</a></li>
</ul>
<p><em>Known Algorithms</em></p>
<ul>
<li>Graham's scan (too complicated)</li>
<li>Jarvis March algorithm (handles N points)</li>
<li>Recursive Convex Hull (removes a point)</li>
</ul>
<p><strong>Code</strong></p>
<p>Here is what I have so far:</p>
<pre><code>// Ensures the markers are sorted: NW, NE, SE, SW
function sortMarkers() {
var ns = markers.slice( 0 );
var ew = markers.slice( 0 );
ew.sort( function( a, b ) {
if( a.position.lat() < b.position.lat() ) {
return -1;
}
else if( a.position.lat() > b.position.lat() ) {
return 1;
}
return 0;
});
ns.sort( function( a, b ) {
if( a.position.lng() < b.position.lng() ) {
return -1;
}
else if( a.position.lng() > b.position.lng() ) {
return 1;
}
return 0;
});
var nw;
var ne;
var se;
var sw;
if( ew.indexOf( ns[0] ) > 1 ) {
nw = ns[0];
}
else {
ne = ns[0];
}
if( ew.indexOf( ns[1] ) > 1 ) {
nw = ns[1];
}
else {
ne = ns[1];
}
if( ew.indexOf( ns[2] ) > 1 ) {
sw = ns[2];
}
else {
se = ns[2];
}
if( ew.indexOf( ns[3] ) > 1 ) {
sw = ns[3];
}
else {
se = ns[3];
}
markers[0] = nw;
markers[1] = ne;
markers[2] = se;
markers[3] = sw;
}
</code></pre>
<p>Thank you.</p>
| 0 | 1,278 |
Error TS2440 (TS) Import declaration conflicts with local declaration of 'PluginConfig'
|
<p>I am trying to run my application in Visual studio 2017 and I keep getting the error:</p>
<pre><code> "Error TS2440 (TS) Import declaration conflicts with local declaration of 'PluginConfig'"
</code></pre>
<p>I tried downgrading my typescript, but the error is not going away. Below is my package.json file:</p>
<pre><code>{
"name": "frontend",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^5.2.4",
"@angular/cdk": "^5.2.1",
"@angular/common": "^5.2.0",
"@angular/compiler": "^5.2.0",
"@angular/core": "^5.2.0",
"@angular/flex-layout": "^5.0.0-beta.14",
"@angular/forms": "^5.2.0",
"@angular/http": "^5.2.0",
"@angular/material": "^5.2.1",
"@angular/platform-browser": "^5.2.0",
"@angular/platform-browser-dynamic": "^5.2.0",
"@angular/router": "^5.2.0",
"ajv": "^6.0.0",
"angular2-text-mask": "^9.0.0",
"angular5-time-picker": "^1.0.8",
"bootstrap": "4.3.1",
"core-js": "^2.4.1",
"font-awesome": "^4.7.0",
"jquery": "^1.9.1",
"ngx-mask": "^2.9.6",
"popper.js": "^1.12.9",
"rxjs": "^5.5.6",
"text-mask-addons": "^3.7.2",
"zone.js": "^0.8.19"
},
"devDependencies": {
"@angular/cli": "1.6.7",
"@angular/compiler-cli": "^5.2.0",
"@angular/language-service": "^5.2.0",
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^2.0.4",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "^5.3.2",
"ts-node": "~4.1.0",
"tslint": "~5.9.1",
"typescript": "~2.5.3"
}
}
</code></pre>
<p>Below is the screen shot of angular/cli version:</p>
<p><a href="https://i.stack.imgur.com/kCnos.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kCnos.png" alt="enter image description here"></a></p>
<p>I tried opening the application in both Visual studio 2017 and 2019 and I getting the same error in both versions of Visual studio. I also tried to change the typescript version in Visual studio itself, but that didnt work either. Below is the screen shot from Visual studio Typescript version:</p>
<p><a href="https://i.stack.imgur.com/cb6qW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cb6qW.png" alt="enter image description here"></a></p>
<p>any help in resolving this error will be greatly appreciated.</p>
| 0 | 1,270 |
Nullpointer Exception in webdriver, driver is null
|
<p>I am a newbie in selenium java and trying to run test case by calling methods from another class in a framework. Methods are defined in a different class. The issue is that for first instance, the driver is found (Firefox driver) but when a method from another class is called, the driver is null. </p>
<pre><code>Below is the code snippet:
public class ActionDriver {
WebDriver driver;
public ActionDriver(WebDriver driver){
this.driver = driver;
}
public void type(By loc, String value) {
driver.findElement(loc).sendKeys(value);
}
}
</code></pre>
<p>NPE comes for the above line of code for driver for second instance when method is called from the WebAction class. driver.findElement(loc).sendKeys(value);</p>
<p>Second class is :</p>
<pre><code>public class WebActions {
WebDriver driver;
ActionDriver ad = new ActionDriver(driver);
SizeChartTemplate sct = new SizeChartTemplate();
public void TypeTemplateName(){
ad.type(jsct.Template_Name, "Men's Vest");
}
}
</code></pre>
<p>NPE is for the above line of code at ad.</p>
<p>Test Case:</p>
<pre><code>public class LoginToJcilory extends OpenAndCloseBrowser {
@Test
public void logintojcilory() throws BiffException, IOException, InterruptedException{
WebActions wa = new WebActions();
System.out.println("Entered login to jcilory block");
ActionDriver actdrvr = new ActionDriver(driver);
JciloryLoginPage jclp = new JciloryLoginPage();
JcilorySizeChartTemplate jsct = new JcilorySizeChartTemplate();
String username = actdrvr.readExcel(0, 1);
String password = actdrvr.readExcel(1, 1);
System.out.println(username);
System.out.println(password);
actdrvr.type(jclp.Username, username);
actdrvr.type(jclp.Password, password);
actdrvr.click(jclp.LoginButton);
Thread.sleep(2000);
driver.get("http://qacilory.dewsolutions.in/JCilory/createSizeChartTemplate.jc");
wa.TypeTemplateName();
}
</code></pre>
<p>NPE comes for wa element in the above code.</p>
<p>Below is the error:</p>
<pre><code>FAILED: logintojcilory
java.lang.NullPointerException
at Config.ActionDriver.type(ActionDriver.java:40)
at Config.WebActions.TypeTemplateName(WebActions.java:17)
at Test.LoginToJcilory.logintojcilory(LoginToJcilory.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.access$000(SuiteRunner.java:37)
at org.testng.SuiteRunner$SuiteWorker.run(SuiteRunner.java:368)
at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
===============================================
Test run on FIREFOX
Tests run: 1, Failures: 1, Skips: 0
===============================================
OpenAndCloseBrowser:
public class OpenAndCloseBrowser {
protected WebDriver driver;
@Parameters({"browser","baseURL"})
@BeforeClass
public void openBrowser(String browser,String baseURL){
if(browser.equalsIgnoreCase("firefox")){
driver=new FirefoxDriver();
}
else if(browser.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\driver\\chromedriver.exe");
driver=new ChromeDriver();
}
else if(browser.equalsIgnoreCase("ie")){
System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\driver\\IEDriverServer.exe");
DesiredCapabilities caps=new DesiredCapabilities();
caps.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver=new InternetExplorerDriver(caps);
}
else{
driver=new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get(baseURL);
}
@AfterClass
public void closeBrowser(){
//driver.quit();
}
}
</code></pre>
<p>I guess there is an issue with the way i am defining the driver in these classes. Any help is resolving the issue is appreciated.</p>
| 0 | 2,041 |
How to connect the Bluetooth device by click the item of listview in Android?
|
<p>I am developing an application where I have to connect to Bluetooth device on Android 4.3.</p>
<p>I can scan the bluetooth device, but it can not connect the bluetooth device.</p>
<p>I have already add the permission in Manifest of the following:</p>
<pre><code><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
</code></pre>
<p>My Operation is when I push SCAN Button, it will scan the Bluetooth device and show on the ListView.</p>
<p>When I click the bluetooth device on ListView,it will connect the bluetooth device of item.</p>
<p>But when I click the device item, the app will crash, and I don't know why...</p>
<p>This is my java code:</p>
<pre><code> package com.example.preventthelost;
import java.io.IOException;
import java.net.Socket;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class DeviceList extends Activity {
protected static final String tag = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT=1;
private Button btn_cancel;
private Button btn_scan;
private ListView pair_devices_list;
private ListView new_devices_list;
private Set<BluetoothDevice> pairedDevice;
private ArrayAdapter<String> newDevicelistArrayAdapter;
private ArrayAdapter<String> pairDevicelistArrayAdapter;
private final UUID my_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
//private final UUID my_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
btn_scan = (Button)findViewById(R.id.btn_scan);
newDevicelistArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
new_devices_list = (ListView)findViewById(R.id.new_devices_list);
new_devices_list.setAdapter(newDevicelistArrayAdapter);
**//check device support bluetooth or not**
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null) {
Toast.makeText(this, "No support bluetooth", Toast.LENGTH_SHORT).show();
finish();
return;
}else if(!mBluetoothAdapter.isEnabled()){ **//if bluetooth is close, than open it**
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
}
**//click the scan button**
btn_scan.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//**list the bluetooth device**
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
newDevicelistArrayAdapter.clear();
}
});
//new_devices_list click
new_devices_list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mBluetoothAdapter.cancelDiscovery();
final String info = ((TextView) arg1).getText().toString();
//get the device address when click the device item
String address = info.substring(info.length()-19);
//connect the device when item is click
BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(my_UUID);
socket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});//************new_devices_list end
}
public final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice bdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);;
if(bdevice.getBondState() != BluetoothDevice.BOND_BONDED)
newDevicelistArrayAdapter.add("\n" + bdevice.getName() + "\n" + bdevice.getAddress());
newDevicelistArrayAdapter.notifyDataSetChanged();
}
}
};
protected void onDestroy() {
super.onDestroy();
if(mBluetoothAdapter != null)
mBluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.device_list, menu);
return true;
}
}
</code></pre>
<p>when I type the connect code of following into <code>new_devices_list.setOnItemClickListener</code>, it always crash.</p>
<pre><code>//get the device address when click the device item
String address = info.substring(info.length()-19);
//connect the device when item is click
BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(my_UUID);
socket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
</code></pre>
<p>I am not sure, but the problem look like in this line:</p>
<p><code>BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);</code> </p>
<p>The data type of the <code>address</code> is String rather address.</p>
<p>But the type of getRemoteDevice I choose is String address.</p>
<p>SO...I don't know Why the app always crash when I type the connect code in new_devices_list even??</p>
<p>Does it can not be use in Android 4.3 ??</p>
<p>Can someone teach me?? </p>
<p>Thanks!!</p>
| 0 | 3,812 |
Error on execution -version `Qt_5' not found required by
|
<p>On execution of eiskaltdc++ on ubuntu 15.10 ,I get the following error:</p>
<pre><code>eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Multimedia.so.5: version `Qt_5' not found (required by eiskaltdcpp-qt)
eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5: version `Qt_5' not found (required by eiskaltdcpp-qt)
eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Concurrent.so.5: version `Qt_5' not found (required by eiskaltdcpp-qt)
eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Sql.so.5: version `Qt_5' not found (required by eiskaltdcpp-qt)
eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5: version `Qt_5' not found (required by eiskaltdcpp-qt)
eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5: version `Qt_5' not found (required by eiskaltdcpp-qt)
eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5: version `Qt_5.6' not found (required by eiskaltdcpp-qt)
eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5: version `Qt_5' not found (required by eiskaltdcpp-qt)
eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5: version `Qt_5' not found (required by eiskaltdcpp-qt)
</code></pre>
<h1>Qt version</h1>
<pre><code>~$ which qmake
/opt/Qt5.6.0/5.6/gcc_64/bin/qmake
~$ qmake -version
QMake version 3.0
Using Qt version 5.6.0 in /opt/Qt5.6.0/5.6/gcc_64/lib
~$ echo $PATH
/opt/Qt5.6.0/5.6/gcc_64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
</code></pre>
<p>I am able to successfully compile applications with Qt creator.</p>
<h1>Edit</h1>
<p>running ldd gave me this.I am not sure how to interpret this </p>
<pre><code>~$ ldd /usr/local/bin/eiskaltdcpp-qt
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Multimedia.so.5: version `Qt_5' not found (required by /usr/local/bin/eiskaltdcpp-qt)
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5: version `Qt_5' not found (required by /usr/local/bin/eiskaltdcpp-qt)
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Concurrent.so.5: version `Qt_5' not found (required by /usr/local/bin/eiskaltdcpp-qt)
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Sql.so.5: version `Qt_5' not found (required by /usr/local/bin/eiskaltdcpp-qt)
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5: version `Qt_5' not found (required by /usr/local/bin/eiskaltdcpp-qt)
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5: version `Qt_5' not found (required by /usr/local/bin/eiskaltdcpp-qt)
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5: version `Qt_5.6' not found (required by /usr/local/bin/eiskaltdcpp-qt)
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5: version `Qt_5' not found (required by /usr/local/bin/eiskaltdcpp-qt)
/usr/local/bin/eiskaltdcpp-qt: /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5: version `Qt_5' not found (required by /usr/local/bin/eiskaltdcpp-qt)
linux-vdso.so.1 => (0x00007ffd580bf000)
libQt5Widgets.so.5 => /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5 (0x00007fbeffcec000)
libQt5Xml.so.5 => /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5 (0x00007fbeffcb0000)
libQt5Multimedia.so.5 => /usr/lib/x86_64-linux-gnu/libQt5Multimedia.so.5 (0x00007fbeffbcf000)
libQt5Concurrent.so.5 => /usr/lib/x86_64-linux-gnu/libQt5Concurrent.so.5 (0x00007fbeffbc8000)
libQt5DBus.so.5 => /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5 (0x00007fbeffb47000)
libQt5Sql.so.5 => /usr/lib/x86_64-linux-gnu/libQt5Sql.so.5 (0x00007fbeffb04000)
libboost_system.so.1.58.0 => /usr/lib/x86_64-linux-gnu/libboost_system.so.1.58.0 (0x00007fbeff900000)
libeiskaltdcpp.so.2.3 => /usr/local/lib/libeiskaltdcpp.so.2.3 (0x00007fbeff52d000)
libQt5Gui.so.5 => /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5 (0x00007fbefeff2000)
libQt5Core.so.5 => /usr/lib/x86_64-linux-gnu/libQt5Core.so.5 (0x00007fbefeb36000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fbefe918000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbefe54d000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fbefe1cb000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fbefdec3000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fbefdcab000)
libgobject-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgobject-2.0.so.0 (0x00007fbefda58000)
libglib-2.0.so.0 => /lib/x86_64-linux-gnu/libglib-2.0.so.0 (0x00007fbefd749000)
libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007fbefd40e000)
libQt5Network.so.5 => /usr/lib/x86_64-linux-gnu/libQt5Network.so.5 (0x00007fbefd2bb000)
libpulse.so.0 => /usr/lib/x86_64-linux-gnu/libpulse.so.0 (0x00007fbefd06c000)
librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007fbefce63000)
libdbus-1.so.3 => /lib/x86_64-linux-gnu/libdbus-1.so.3 (0x00007fbefcc17000)
libbz2.so.1.0 => /lib/x86_64-linux-gnu/libbz2.so.1.0 (0x00007fbefca06000)
libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007fbefc7ec000)
libssl.so.1.0.0 => /lib/x86_64-linux-gnu/libssl.so.1.0.0 (0x00007fbefc583000)
libcrypto.so.1.0.0 => /lib/x86_64-linux-gnu/libcrypto.so.1.0.0 (0x00007fbefc13e000)
libpcrecpp.so.0 => /usr/lib/x86_64-linux-gnu/libpcrecpp.so.0 (0x00007fbefbf34000)
libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007fbefbd2f000)
libpng12.so.0 => /lib/x86_64-linux-gnu/libpng12.so.0 (0x00007fbefbb08000)
libharfbuzz.so.0 => /usr/lib/x86_64-linux-gnu/libharfbuzz.so.0 (0x00007fbefb8aa000)
libGL.so.1 => /usr/lib/nvidia-352/libGL.so.1 (0x00007fbefb57a000)
libicui18n.so.55 => /usr/lib/x86_64-linux-gnu/libicui18n.so.55 (0x00007fbefb116000)
libicuuc.so.55 => /usr/lib/x86_64-linux-gnu/libicuuc.so.55 (0x00007fbefad82000)
libpcre16.so.3 => /usr/lib/x86_64-linux-gnu/libpcre16.so.3 (0x00007fbefab1f000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fbefa91a000)
/lib64/ld-linux-x86-64.so.2 (0x000055b48dc4b000)
libffi.so.6 => /usr/lib/x86_64-linux-gnu/libffi.so.6 (0x00007fbefa712000)
libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007fbefa4a4000)
libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007fbefa283000)
libjson-c.so.2 => /lib/x86_64-linux-gnu/libjson-c.so.2 (0x00007fbefa077000)
libpulsecommon-6.0.so => /usr/lib/x86_64-linux-gnu/pulseaudio/libpulsecommon-6.0.so (0x00007fbef9dfe000)
libsystemd.so.0 => /lib/x86_64-linux-gnu/libsystemd.so.0 (0x00007fbef9d7d000)
libfreetype.so.6 => /usr/lib/x86_64-linux-gnu/libfreetype.so.6 (0x00007fbef9ad6000)
libgraphite2.so.3 => /usr/lib/x86_64-linux-gnu/libgraphite2.so.3 (0x00007fbef98b1000)
libnvidia-tls.so.352.63 => /usr/lib/nvidia-352/tls/libnvidia-tls.so.352.63 (0x00007fbef96ad000)
libnvidia-glcore.so.352.63 => /usr/lib/nvidia-352/libnvidia-glcore.so.352.63 (0x00007fbef6c1a000)
libXext.so.6 => /usr/lib/x86_64-linux-gnu/libXext.so.6 (0x00007fbef6a08000)
libicudata.so.55 => /usr/lib/x86_64-linux-gnu/libicudata.so.55 (0x00007fbef4f50000)
libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007fbef4d4c000)
libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007fbef4b45000)
libwrap.so.0 => /lib/x86_64-linux-gnu/libwrap.so.0 (0x00007fbef493b000)
libsndfile.so.1 => /usr/lib/x86_64-linux-gnu/libsndfile.so.1 (0x00007fbef46d2000)
libasyncns.so.0 => /usr/lib/x86_64-linux-gnu/libasyncns.so.0 (0x00007fbef44cc000)
liblzma.so.5 => /lib/x86_64-linux-gnu/liblzma.so.5 (0x00007fbef42a9000)
libgcrypt.so.20 => /lib/x86_64-linux-gnu/libgcrypt.so.20 (0x00007fbef3fc7000)
libnsl.so.1 => /lib/x86_64-linux-gnu/libnsl.so.1 (0x00007fbef3dac000)
libFLAC.so.8 => /usr/lib/x86_64-linux-gnu/libFLAC.so.8 (0x00007fbef3b37000)
libvorbisenc.so.2 => /usr/lib/x86_64-linux-gnu/libvorbisenc.so.2 (0x00007fbef3884000)
libresolv.so.2 => /lib/x86_64-linux-gnu/libresolv.so.2 (0x00007fbef3668000)
libgpg-error.so.0 => /lib/x86_64-linux-gnu/libgpg-error.so.0 (0x00007fbef3455000)
libogg.so.0 => /usr/lib/x86_64-linux-gnu/libogg.so.0 (0x00007fbef324c000)
libvorbis.so.0 => /usr/lib/x86_64-linux-gnu/libvorbis.so.0 (0x00007fbef301f000)
</code></pre>
<p>Please suggest a solution.Thanks in advance.</p>
| 0 | 4,419 |
Can't use 'defined(@array)' warning in converting .obj to .h
|
<p>I'm trying to convert my .obj file to a .h header file, but i'm getting "Can't use 'defined(@array)' (Maybe you should just omit the defined()?)" warning and no .h files has created. </p>
<p>I've tried replacing <code>@center</code> to <code>$center</code> or omintting <code>defined()</code> but it creates .exe file!<br>
I've read somewhere that it may be a perl version problem, mine is 5.22 and I couldn't find higher versions to try.</p>
<p><strong>Update1:</strong><br>
I've put the "obj2opengl.pl " and "myobject.obj" in the same folder. and trying to convert it with this code in console(win10):
<code>c:\obj2openglfolder>obj2opengl.pl myobject.obj</code> </p>
<p><strong>Update2:</strong><br>
This is the line154 code that cause the problem:</p>
<pre><code>if(defined(@center)) {
$xcen = $center[0];
$ycen = $center[1];
$zcen = $center[2];
}
</code></pre>
<p><strong>Update3:</strong><br>
this is the whole code:</p>
<pre><code># -----------------------------------------------------------------
# Main Program
# -----------------------------------------------------------------
handleArguments();
# derive center coords and scale factor if neither provided nor disabled
unless(defined($scalefac) && defined($xcen)) {
calcSizeAndCenter();
}
if($verbose) {
printInputAndOptions();
}
# TODO check integrity: Does every referenced vertex, normal and coord
exist?
loadData();
normalizeNormals();
if($verbose) {
printStatistics();
}
writeOutput();
# -----------------------------------------------------------------
# Sub Routines
# -----------------------------------------------------------------
sub handleArguments() {
my $help = 0;
my $man = 0;
my $noscale = 0;
my $nomove = 0;
$verbose = 1;
$errorInOptions = !GetOptions (
"help" => \$help,
"man" => \$man,
"noScale" => \$noscale,
"scale=f" => \$scalefac,
"noMove" => \$nomove,
"center=f{3}" => \@center,
"outputFilename=s" => \$outFilename,
"nameOfObject=s" => \$object,
"verbose!" => \$verbose,
);
if($noscale) {
$scalefac = 1;
}
if($nomove) {
@center = (0, 0, 0);
}
if(@center) {
$xcen = $center[0];
$ycen = $center[1];
$zcen = $center[2];
}
if($#ARGV == 0) {
my ($file, $dir, $ext) = fileparse($ARGV[0], qr/\.[^.]*/);
$inFilename = $dir . $file . $ext;
} else {
$errorInOptions = true;
}
# (optional) derive output filename from input filename
unless($errorInOptions || defined($outFilename)) {
my ($file, $dir, $ext) = fileparse($inFilename, qr/\.[^.]*/);
$outFilename = $dir . $file . ".h";
}
# (optional) define object name from output filename
unless($errorInOptions || defined($object)) {
my ($file, $dir, $ext) = fileparse($outFilename, qr/\.[^.]*/);
$object = $file;
}
($inFilename ne $outFilename) or
die ("Input filename must not be the same as output filename")
unless($errorInOptions);
if($errorInOptions || $man || $help) {
pod2usage(-verbose => 2) if $man;
pod2usage(-verbose => 1) if $help;
pod2usage();
}
# check wheter file exists
open ( INFILE, "<$inFilename" )
|| die "Can't find file '$inFilename' ...exiting \n";
close(INFILE);
}
# Stores center of object in $xcen, $ycen, $zcen
# and calculates scaling factor $scalefac to limit max
# side of object to 1.0 units
sub calcSizeAndCenter() {
open ( INFILE, "<$inFilename" )
|| die "Can't find file $inFilename...exiting \n";
$numVerts = 0;
my (
$xsum, $ysum, $zsum,
$xmin, $ymin, $zmin,
$xmax, $ymax, $zmax,
);
while ( $line = <INFILE> )
{
chop $line;
if ($line =~ /v\s+.*/)
{
$numVerts++;
@tokens = split(' ', $line);
$xsum += $tokens[1];
$ysum += $tokens[2];
$zsum += $tokens[3];
if ( $numVerts == 1 )
{
$xmin = $tokens[1];
$xmax = $tokens[1];
$ymin = $tokens[2];
$ymax = $tokens[2];
$zmin = $tokens[3];
$zmax = $tokens[3];
}
else
{
if ($tokens[1] < $xmin)
{
$xmin = $tokens[1];
}
elsif ($tokens[1] > $xmax)
{
$xmax = $tokens[1];
}
if ($tokens[2] < $ymin)
{
$ymin = $tokens[2];
}
elsif ($tokens[2] > $ymax)
{
$ymax = $tokens[2];
}
if ($tokens[3] < $zmin)
{
$zmin = $tokens[3];
}
elsif ($tokens[3] > $zmax)
{
$zmax = $tokens[3];
}
}
}
}
close INFILE;
# Calculate the center
unless(defined($xcen)) {
$xcen = $xsum / $numVerts;
$ycen = $ysum / $numVerts;
$zcen = $zsum / $numVerts;
}
# Calculate the scale factor
unless(defined($scalefac)) {
my $xdiff = ($xmax - $xmin);
my $ydiff = ($ymax - $ymin);
my $zdiff = ($zmax - $zmin);
if ( ( $xdiff >= $ydiff ) && ( $xdiff >= $zdiff ) )
{
$scalefac = $xdiff;
}
elsif ( ( $ydiff >= $xdiff ) && ( $ydiff >= $zdiff ) )
{
$scalefac = $ydiff;
}
else
{
$scalefac = $zdiff;
}
$scalefac = 1.0 / $scalefac;
}
}
sub printInputAndOptions() {
print "Input file : $inFilename\n";
print "Output file : $outFilename\n";
print "Object name : $object\n";
print "Center : <$xcen, $ycen, $zcen>\n";
print "Scale by : $scalefac\n";
}
sub printStatistics() {
print "----------------\n";
print "Vertices : $numVerts\n";
print "Faces : $numFaces\n";
print "Texture Coords : $numTexture\n";
print "Normals : $numNormals\n";
}
# reads vertices into $xcoords[], $ycoords[], $zcoords[]
# where coordinates are moved and scaled according to
# $xcen, $ycen, $zcen and $scalefac
# reads texture coords into $tx[], $ty[]
# where y coordinate is mirrowed
# reads normals into $nx[], $ny[], $nz[]
# but does not normalize, see normalizeNormals()
# reads faces and establishes lookup data where
# va_idx[], vb_idx[], vc_idx[] for vertices
# ta_idx[], tb_idx[], tc_idx[] for texture coords
# na_idx[], nb_idx[], nc_idx[] for normals
# store indizes for the former arrays respectively
# also, $face_line[] store actual face string
sub loadData {
$numVerts = 0;
$numFaces = 0;
$numTexture = 0;
$numNormals = 0;
open ( INFILE, "<$inFilename" )
|| die "Can't find file $inFilename...exiting \n";
while ($line = <INFILE>)
{
chop $line;
# vertices
if ($line =~ /v\s+.*/)
{
@tokens= split(' ', $line);
$x = ( $tokens[1] - $xcen ) * $scalefac;
$y = ( $tokens[2] - $ycen ) * $scalefac;
$z = ( $tokens[3] - $zcen ) * $scalefac;
$xcoords[$numVerts] = $x;
$ycoords[$numVerts] = $y;
$zcoords[$numVerts] = $z;
$numVerts++;
}
# texture coords
if ($line =~ /vt\s+.*/)
{
@tokens= split(' ', $line);
$x = $tokens[1];
$y = 1 - $tokens[2];
$tx[$numTexture] = $x;
$ty[$numTexture] = $y;
$numTexture++;
}
#normals
if ($line =~ /vn\s+.*/)
{
@tokens= split(' ', $line);
$x = $tokens[1];
$y = $tokens[2];
$z = $tokens[3];
$nx[$numNormals] = $x;
$ny[$numNormals] = $y;
$nz[$numNormals] = $z;
$numNormals++;
}
# faces
if ($line =~ /f\s+([^ ]+)\s+([^ ]+)\s+([^ ]+)(\s+([^ ]+))?/)
{
@a = split('/', $1);
@b = split('/', $2);
@c = split('/', $3);
$va_idx[$numFaces] = $a[0]-1;
$ta_idx[$numFaces] = $a[1]-1;
$na_idx[$numFaces] = $a[2]-1;
$vb_idx[$numFaces] = $b[0]-1;
$tb_idx[$numFaces] = $b[1]-1;
$nb_idx[$numFaces] = $b[2]-1;
$vc_idx[$numFaces] = $c[0]-1;
$tc_idx[$numFaces] = $c[1]-1;
$nc_idx[$numFaces] = $c[2]-1;
$face_line[$numFaces] = $line;
$numFaces++;
# ractangle => second triangle
if($5 != "")
{
@d = split('/', $5);
$va_idx[$numFaces] = $a[0]-1;
$ta_idx[$numFaces] = $a[1]-1;
$na_idx[$numFaces] = $a[2]-1;
$vb_idx[$numFaces] = $d[0]-1;
$tb_idx[$numFaces] = $d[1]-1;
$nb_idx[$numFaces] = $d[2]-1;
$vc_idx[$numFaces] = $c[0]-1;
$tc_idx[$numFaces] = $c[1]-1;
$nc_idx[$numFaces] = $c[2]-1;
$face_line[$numFaces] = $line;
$numFaces++;
}
}
}
close INFILE;
}
sub normalizeNormals {
for ( $j = 0; $j < $numNormals; ++$j)
{
$d = sqrt ( $nx[$j]*$nx[$j] + $ny[$j]*$ny[$j] + $nz[$j]*$nz[$j] );
if ( $d == 0 )
{
$nx[$j] = 1;
$ny[$j] = 0;
$nz[$j] = 0;
}
else
{
$nx[$j] = $nx[$j] / $d;
$ny[$j] = $ny[$j] / $d;
$nz[$j] = $nz[$j] / $d;
}
}
}
sub fixedIndex {
local $idx = $_[0];
local $num = $_[1];
if($idx >= 0)
{
$idx;
} else {
$num + $idx + 1;
}
}
sub writeOutput {
open ( OUTFILE, ">$outFilename" )
|| die "Can't create file $outFilename ... exiting\n";
print OUTFILE "/*\n";
print OUTFILE "created with obj2opengl.pl\n\n";
# some statistics
print OUTFILE "source file : $inFilename\n";
print OUTFILE "vertices : $numVerts\n";
print OUTFILE "faces : $numFaces\n";
print OUTFILE "normals : $numNormals\n";
print OUTFILE "texture coords : $numTexture\n";
print OUTFILE "\n\n";
# example usage
print OUTFILE "// include generated arrays\n";
print OUTFILE "#import \"".$outFilename."\"\n";
print OUTFILE "\n";
print OUTFILE "// set input data to arrays\n";
print OUTFILE "glVertexPointer(3, GL_FLOAT, 0, ".$object."Verts);\n";
print OUTFILE "glNormalPointer(GL_FLOAT, 0, ".$object."Normals);\n"
if $numNormals > 0;
print OUTFILE "glTexCoordPointer(2, GL_FLOAT, 0, ".$object."TexCoords);\n"
if $numTexture > 0;
print OUTFILE "\n";
print OUTFILE "// draw data\n";
print OUTFILE "glDrawArrays(GL_TRIANGLES, 0, ".$object."NumVerts);\n";
print OUTFILE "*/\n\n";
# needed constant for glDrawArrays
print OUTFILE "unsigned int ".$object."NumVerts = ".($numFaces * 3).";\n\n";
# write verts
print OUTFILE "float ".$object."Verts \[\] = {\n";
for( $j = 0; $j < $numFaces; $j++)
{
$ia = fixedIndex($va_idx[$j], $numVerts);
$ib = fixedIndex($vb_idx[$j], $numVerts);
$ic = fixedIndex($vc_idx[$j], $numVerts);
print OUTFILE " // $face_line[$j]\n";
print OUTFILE " $xcoords[$ia], $ycoords[$ia], $zcoords[$ia],\n";
print OUTFILE " $xcoords[$ib], $ycoords[$ib], $zcoords[$ib],\n";
print OUTFILE " $xcoords[$ic], $ycoords[$ic], $zcoords[$ic],\n";
}
print OUTFILE "};\n\n";
# write normals
if($numNormals > 0) {
print OUTFILE "float ".$object."Normals \[\] = {\n";
for( $j = 0; $j < $numFaces; $j++) {
$ia = fixedIndex($na_idx[$j], $numNormals);
$ib = fixedIndex($nb_idx[$j], $numNormals);
$ic = fixedIndex($nc_idx[$j], $numNormals);
print OUTFILE " // $face_line[$j]\n";
print OUTFILE " $nx[$ia], $ny[$ia], $nz[$ia],\n";
print OUTFILE " $nx[$ib], $ny[$ib], $nz[$ib],\n";
print OUTFILE " $nx[$ic], $ny[$ic], $nz[$ic],\n";
}
print OUTFILE "};\n\n";
}
# write texture coords
if($numTexture) {
print OUTFILE "float ".$object."TexCoords \[\] = {\n";
for( $j = 0; $j < $numFaces; $j++) {
$ia = fixedIndex($ta_idx[$j], $numTexture);
$ib = fixedIndex($tb_idx[$j], $numTexture);
$ic = fixedIndex($tc_idx[$j], $numTexture);
print OUTFILE " // $face_line[$j]\n";
print OUTFILE " $tx[$ia], $ty[$ia],\n";
print OUTFILE " $tx[$ib], $ty[$ib],\n";
print OUTFILE " $tx[$ic], $ty[$ic],\n";
}
print OUTFILE "};\n\n";
}
close OUTFILE;
}
</code></pre>
| 0 | 5,548 |
How to correctly check if user is authenticated in Angular4?
|
<p>I am currently developing an Angular 4 application.</p>
<p>The application uses Auth0 for authentication whose syntax is quite similar to those of other authentication services.</p>
<p>The code for authentication looks as follows:</p>
<p>// auth.services.ts</p>
<pre><code>@Injectable()
export class Auth {
public lock = new Auth0Lock(myConfig.clientID, myConfig.domain, myConfig.lock);
public userProfile: any;
public idToken: string;
public signUpIncomplete: boolean;
// Configure Auth0
private auth0 = new Auth0.WebAuth({
domain: myConfig.domain,
clientID: myConfig.clientID,
redirectUri: myConfig.redirectUri,
responseType: myConfig.responseType
});
// Create a stream of logged in status to communicate throughout app
private loggedIn: boolean;
private loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);
constructor(private router: Router, private http: Http) {
// Set userProfile attribute of already saved profile
this.userProfile = JSON.parse(localStorage.getItem('profile'));
}
public isAuthenticated(): boolean {
// Check whether the id_token is expired or not
console.log("isAuthenticated");
return tokenNotExpired('id_token');
}
public login(username?: string, password?: string): Promise<any> {
if (!username && !password) {
return;
}
return this.processLogin(username, password);
}
public logout() {
// Remove tokens and profile and update login status subject
localStorage.removeItem('token');
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
this.idToken = '';
this.userProfile = null;
this.setLoggedIn(false);
// Go back to the home rout
this.router.navigate(['/']);
}
public loginWithWidget(): void {
this.lock.show();
}
// Call this method in app.component
// if using path-based routing <== WE ARE USING PATH BASED ROUTING
public handleAuth(): void {
// When Auth0 hash parsed, get profile
this.auth0.parseHash({}, (err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
// window.location.hash = '';
this._getProfile(authResult);
this.router.navigate(['/']);
} else if (err) {
this.router.navigate(['/']);
console.error(`Error: ${err.error}`);
}
});
}
private setLoggedIn(value: boolean) {
// Update login status subject
this.loggedIn$.next(value);
this.loggedIn = value;
}
private _getProfile(authResult) {
// Use access token to retrieve user's profile and set session
// const lock2 = new Auth0Lock(myConfig.clientID, myConfig.domain, myConfig.lock)
const idToken = authResult.id_token || authResult.idToken;
this.lock.getProfile(idToken, (error, profile) => {
if (error) {
// Handle error
console.error(error.error);
return;
}
// Save session data and update login status subject
this._setSession(authResult, profile);
if (!this.checkUserHasRole(profile)) {
this.router.navigate(['/signup/complete']);
}
});
}
private _setSession(authResult, profile) {
// Save session data and update login status subject
localStorage.setItem('token', authResult.access_token || authResult.accessToken);
localStorage.setItem('id_token', authResult.id_token || authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
this.idToken = authResult.id_token || authResult.idToken;
this.setLoggedIn(true);
this.userProfile = profile;
this.checkUserHasRole(profile);
}
private processLogin(username?: string, password?: string): Promise<any> {
const options = {
client_id: myConfig.clientID,
connection: postConfig.body.connection,
grant_type: 'password',
username,
password,
scope: myConfig.scope
};
const headers = new Headers();
headers.append('content-type', 'application/json');
const reqOpts = new RequestOptions({
method: RequestMethod.Post,
url: postConfig.urlLogin,
headers,
body: options
});
return this.http.post(postConfig.urlLogin, options, reqOpts)
.toPromise()
.then(this.extractData)
.then((data) => { this._getProfile(data); })
.catch(this.handleLoginError);
}
...
}
</code></pre>
<p>The problem I have is that the <code>isAuthenticated</code> method is called more than 1000 times on page load. Additionally, it is called each time I move the mouse in the window object. </p>
<p>Although I followed the tutorial of Auth0 step by step, I suppose that this cannot be the expected behaviour as it will and already does affect the performance of the application.</p>
<p>What could be a reason for the fact that isAuthenticated is called that often? Do I have to implement a timer which does the check periodically after a specified time or do I have to implement an observer? Are there any obvious mistakes in my code?</p>
| 0 | 1,736 |
Mocha + TypeScript: Cannot use import statement outside a module
|
<p>I was watching <a href="https://www.youtube.com/watch?v=I4BZQr-5mBY" rel="noreferrer">this video</a> in order to learn how to add some simple tests to my Express routes but I am getting all kind of errors while executing a test. The error is:</p>
<blockquote>
<p>import * as chai from 'chai';</p>
<p>^^^^^^</p>
<p>SyntaxError: Cannot use import statement outside a module</p>
</blockquote>
<p>I have read some similar Stack Overflow questions and GitHub issues but I didn't find a solution for my own application. Finally I found <a href="https://github.com/mochajs/mocha-examples/tree/master/packages/typescript#es-modules" rel="noreferrer">Mocha documentation</a> on GitHub regarding ES modules but it didn't work:</p>
<p>I created the app using TypeScript and CommonJS module to transpile, so I added <code>"test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha src/test/*.ts"</code> to the <code>package.json</code> scripts but I am getting the same error every time. I am using <code>ts-node</code> as a server.</p>
<p>Anyway, this is my <code>tsconfig.json</code> file:</p>
<pre class="lang-js prettyprint-override"><code>{
"compilerOptions": {
"sourceMap": true,
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src"
},
"exclude": [
"node_modules"
]
}
</code></pre>
<p>And this is the <code>src/test/mi-route.ts</code> file:</p>
<pre class="lang-js prettyprint-override"><code>import * as chai from 'chai';
import * as chaiHttp from 'chai-http';
import server from '../app';
// Assertions
chai.should();
chai.use(chaiHttp);
describe('API Users', () => {
// Test Route GET
describe('GET /api/admin/users', () => {
it('Should return all the users', done => {
chai.request(server)
.get('/api/admin/users')
.end((err, response) => {
response.should.have.status(200);
response.body.should.be.a('object');
done();
});
});
});
});
</code></pre>
<p>An this is my <code>package.json</code> scripts:</p>
<pre><code>"scripts": {
"dev": "ts-node-dev src/app.ts",
"start": "node dist/app.js",
"test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha src/test/*.ts",
"build": "tsc -p"
},
</code></pre>
<p>So... any suggestions? Should I change Common JS Module? Thanks in advance</p>
| 0 | 1,046 |
Stateless component React router
|
<p>I am new to React and Redux, I am actually creating a code of myself but I got stuck with a router kind of thing inside stateless component.</p>
<p>So, Actually I need to route to a component by using this.props.history.push('/somepath'). This is not happening inside a stateless component.</p>
<p>My Stateless component is</p>
<pre><code>import React from "react"; // eslint-disable-line no-unused-vars
import "bootstrap/dist/css/bootstrap.min.css";
import "./header.css";
const Header = () => ({
handleAuthor() {
this.props.history('/somepath')// this is not working
},
render(){
return (
<div className = "header">
<h1 onClick = {this.handleAuthor.bind(this)}>{this.props.headerText}</h1>
</div>
);
}
});
export default Header;
</code></pre>
<p>I am calling this inside another stateless component like mainlayout</p>
<pre><code>import React from "react"; // eslint-disable-line no-unused-vars
import Header from "../header/Header"; // eslint-disable-line no-unused-vars
import Footer from "../footer/Footer"; // eslint-disable-line no-unused-vars
import "./mainLayout.css";
const MainLayout = props => ({
render() {
return (
<div className="App">
<Header headerText = "RK Boilerplate"/>
<div className = "mainLayout">
<main>{props.children}</main>
</div>
<Footer />
</div>
);
}
});
export default MainLayout;
</code></pre>
<p>My main file index.js looks like this</p>
<pre><code>import React from "react"; // eslint-disable-line no-unused-vars
import ReactDOM from "react-dom"; // eslint-disable-line no-unused-vars
import { matchRoutes, renderRoutes } from "react-router-config"; // eslint-disable-line no-unused-vars
import { Router } from "react-router-dom"; // eslint-disable-line no-unused-vars
import { Switch } from "react-router"; // eslint-disable-line no-unused-vars
import { Provider } from "react-redux"; // eslint-disable-line no-unused-vars
import store from "./store"; // eslint-disable-line no-unused-vars
import routes from "./routes"; // eslint-disable-line no-unused-vars
import MainLayout from "./components/mainLayout/MainLayout"; // eslint-disable-line no-unused-vars
import createHistory from "history/createBrowserHistory";
let history = createHistory();
const App = document.getElementById("app");
export default App;
ReactDOM.render(
<Provider store={store}>
<MainLayout>
<Router history= {history}>
<Switch>
{renderRoutes(routes)}
</Switch>
</Router>
</MainLayout>
</Provider>,
App);
</code></pre>
<p>SO what i need is I have to route from the header to another component where this component and path is given in a router file</p>
<p>router.js</p>
<pre><code>import Home from "../containers/Home";
import About from "../containers/About";
import CreateUser from "../containers/CreateUser";
import Layout from "../containers/Layout";
const routes = [
{ path: "/",
exact: true,
component: Layout
},
{ path: "/home",
exact: true,
component: Home
},
{
path:"/About",
exact: true,
component: About
},
{
path:"/createUser",
exact: true,
component: CreateUser
}
];
export default routes;
</code></pre>
<p>I got an error like push of undefined , when i tried to route from header.
Am I missing something is there any change that i should do here.</p>
<p>Thanks in advance.</p>
| 0 | 1,578 |
Extjs scrollbar doesn't appear
|
<p>I have a problem like in this topic: <a href="https://stackoverflow.com/questions/18232448/extjs-how-to-make-the-scrollbar-appear">Extjs how to make the scrollbar appear?</a>, but too many things are confusing for me. </p>
<p>I need to show a scrollbar as soon as the form is wider than the containing container. Why is autoScroll: true not working? </p>
<p>I will give three different examples, combined with this problem. The most needed - the first ex.
1. <a href="https://fiddle.sencha.com/#fiddle/j2c" rel="nofollow noreferrer">https://fiddle.sencha.com/#fiddle/j2c</a></p>
<pre><code>var win = Ext.create("Ext.window.Window", {
renderTo: Ext.getBody(),
title: "Window",
bodyPadding: 5,
layout: 'anchor',
items: [{
itemId: "TPMethodContentProvider",
xtype: "form",
autoScroll: true,
layout: 'anchor',
anchor: "100%",
items: [{
xtype: "container",
padding: 5,
layout: 'anchor',
anchor: "100%",
autoScroll: true,
items: [{
margin: 5,
padding: 5,
width: 850,
xtype: "container",
autoScroll: true,
anchor: "100%",
layout: 'column',
items: [{
columnWidth: 0.7,
items: [{
itemId: "S1",
margin: 5,
xtype: 'textfield',
anchor: "95%",
fieldLabel: "type:",
labelWidth: 140,
tabIndex: 0,
value: "bd",
}],
layout: "anchor"
}, {
columnWidth: 0.3,
items: [{
itemId: "S2",
margin: 5,
xtype: 'textfield',
anchor: "95%",
fieldLabel: "num:",
labelWidth: 140,
}],
layout: "anchor"
}, ] //panel items
}] // some container items
}] // form items
}] }); win.show();
</code></pre>
<p>No scrollbar. </p>
<ol start="2">
<li><p>..fiddle.sencha.com/#fiddle/j2f</p>
<pre><code>Ext.create('Ext.form.Panel', {
renderTo: Ext.getBody(),
title: 'Form Panel',
bodyPadding: '5 5 0',
width: 600,
items: [{
xtype: 'container',
padding: '5',
layout: 'anchor',
fieldDefaults: {
labelAlign: 'top',
msgTarget: 'side'
},
defaults: {
border: false,
xtype: 'panel',
layout: 'anchor'
},
layout: 'hbox',
items: [{
items: [{
xtype:'textfield',
fieldLabel: 'First Name',
anchor: '-5',
name: 'first',
}]
}, {
items: [{
xtype:'textfield',
fieldLabel: 'Last Name',
anchor: '100%',
name: 'last'
}]
}],
}],
}); //Ext.create('Ext.container.Viewport', {});
</code></pre></li>
</ol>
<p>It works, until commented last line Ext.create('Ext.container.Viewport', {});
If I remove the code inside items Viewport observed the same behavior. </p>
<ol start="3">
<li><p>..fiddle.sencha.com/#fiddle/j2g..</p>
<pre><code>Ext.create('Ext.container.Viewport', {
padding: '5',
items: [{
id: 'mainPanelContainer',
autoScroll: true,
xtype: 'container',
padding: '5',
layout: 'anchor',
//width: 600,
items: [{ //outer container
autoScroll: true,
xtype: 'container',
padding: '5',
layout: 'anchor',
width: 600,
items: [{
xtype: 'container',
padding: '5',
layout: 'column',
items: [{
xtype: 'textfield',
fieldLabel: 'text1',
name: 'Name1',
columnWidth: .3
}, {
xtype: 'textfield',
fieldLabel: 'text2',
name: 'Name2',
columnWidth: .7
}], //container items
}], //outer container items
}, ] //form items
}, ]});
</code></pre></li>
</ol>
<p>Scroll works until width: 600 set in that place, but doesn't work in the commented place.</p>
<p>Sorry for outer code in 2, 3 ex. Some unhandy snippets code.</p>
| 0 | 2,210 |
How to generate classes from wsdl using Maven and wsimport?
|
<p>When I attempt to run "mvn generate-sources" this is my output : </p>
<pre><code>SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building gensourcesfromwsdl 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.104s
[INFO] Finished at: Tue Aug 20 15:41:10 BST 2013
[INFO] Final Memory: 2M/15M
[INFO] ------------------------------------------------------------------------
</code></pre>
<p>I do not receive any errors but there are no java classes generated from the wsdl file.</p>
<p>Here is my pom.xml file that I'm running the plugin against : </p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>gensourcesfromwsdl</groupId>
<artifactId>gensourcesfromwsdl</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>1.12</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlLocation>http://mysite/firstwsdl.asmx?wsdl</wsdlLocation>
<packageName>com</packageName>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
</code></pre>
<p>What am I doing wrong ? The package <code>com</code> exists in the project 'gensourcesfromwsdl' and the wsdl location is valid.</p>
<p>When I run <code>wsimport</code> via the command line : ><code>wsimport -keep -verbose http://mysite/firstwsdl.asmx?wsdl</code> the class is generated.</p>
| 0 | 1,404 |
how to send an HTML email with an inline attached image with PHP
|
<p>I have a PHP script which sends an HTML email with an attached image. It works beauifully, however, I can't get the attachment to display in an <code><img></code> tag in the email body. The attached file is called <code>postcard.png</code> and the original filename on the server is <code>4e60348f83f2f.png</code>. I've tried giving the image URL as various things: <code>cid:postcard.png</code>, <code>cid:4e60348f83f2f.png</code>, <code>postcard.png</code>, and <code>4e60348f83f2f.png</code>. Nothing works. </p>
<p>I think the key part that I'm doing wrong is here, because this makes it a separated attachment instead of an inline attachment that I can use:</p>
<pre><code>Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="$fname" // i.e.: "postcard.png"
</code></pre>
<p>I've tried changing it to use a CID but I don't really know how to do that, and this didnt' work at all:</p>
<pre><code>Content-Transfer-Encoding: base64
Content-ID: <$fname> // i.e.: postcard.png
</code></pre>
<p>Here's the full code: (It's based on <a href="http://www.php.net/manual/en/function.mail.php#83491" rel="noreferrer">this code</a> from a comment in the php <code>mail()</code> page.)</p>
<pre><code><?php
$to = "recipient@email.com";
$email = "sender@email.com";
$name = "Namename";
$subject = "An inline image!";
$comment = "Llookout <b>Llary</b> it's <br> the <b>Ll</b>andllord!<br><img src='cid:postcard.png'><br><img src='cid:4e60348f83f2f.png'><img src='postcard.png'><br><img src='4e60348f83f2f.png'>";
$To = strip_tags($to);
$TextMessage =strip_tags(nl2br($comment),"<br>");
$HTMLMessage =nl2br($comment);
$FromName =strip_tags($name);
$FromEmail =strip_tags($email);
$Subject =strip_tags($subject);
$boundary1 =rand(0,9)."-"
.rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
$boundary2 =rand(0,9)."-".rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
$filename1 = "4e60348f83f2f.png"; //name of file on server with script
$handle =fopen($filename1, 'rb');
$f_contents =fread($handle, filesize($filename1));
$attachment=chunk_split(base64_encode($f_contents));
fclose($handle);
$ftype ="image/png";
$fname ="postcard.png"; //what the file will be named
$attachments='';
$Headers =<<<AKAM
From: $FromName <$FromEmail>
Reply-To: $FromEmail
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="$boundary1"
AKAM;
$attachments.=<<<ATTA
--$boundary1
Content-Type: $ftype;
name="$fname"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="$fname"
$attachment
ATTA;
$Body =<<<AKAM
This is a multi-part message in MIME format.
--$boundary1
Content-Type: multipart/alternative;
boundary="$boundary2"
--$boundary2
Content-Type: text/plain;
charset="windows-1256"
Content-Transfer-Encoding: quoted-printable
$TextMessage
--$boundary2
Content-Type: text/html;
charset="windows-1256"
Content-Transfer-Encoding: quoted-printable
$HTMLMessage
--$boundary2--
$attachments
--$boundary1--
AKAM;
// Send email
$ok=mail($To, $Subject, $Body, $Headers);
echo $ok?"<h1> Mail sent!</h1>":"<h1> Mail not sent!</h1>";
?>
</code></pre>
| 0 | 1,425 |
AssertionError in django
|
<p>I've been pulling my hair out on this one and it seems like there is a really simple solution for it but I'm too blind to see it.
I've upgraded from Django 1.4.3 to Django 1.6 and ever since then I get an assertion error while trying to get DateTimeField to work.</p>
<p>Here's my model</p>
<pre><code>class Article(models.Model):
'''Article Model'''
banner = models.ImageField(verbose_name="Banner", null=True, blank=True, upload_to='ajax_uploads/banners', max_length=300)
title = models.CharField(
verbose_name = _(u'Title'),
help_text = _(u' '),
max_length = 255
)
slug = models.SlugField(
verbose_name = _(u'Slug'),
help_text = _(u'Uri identifier.'),
max_length = 255
)
content_markdown = models.TextField(
verbose_name = _(u'Content (Markup)'),
help_text = _(u' '),
)
content_markup = models.TextField(
verbose_name = _(u'Content (Markup)'),
help_text = _(u' '),
)
categories = models.ManyToManyField(
Category,
verbose_name = _(u'Categories'),
help_text = _(u' '),
null = True,
blank = True
)
date_publish = models.DateTimeField(
default=datetime.date.today,
verbose_name = _(u'Publish Date'),
help_text = _(u' ')
)
class Meta:
app_label = _(u'blog')
verbose_name = _(u'Article')
verbose_name_plural = (u'Articles')
ordering = ['-date_publish']
def save(self):
self.content_markup = markdown(self.content_markdown, ['codehilite'])
super(Article, self).save()
def __unicode__(self):
return '%s' % (self.title,)
</code></pre>
<p>views.py:</p>
<pre><code>def index(request):
'''News index'''
archive_dates = Article.objects.dates('date_publish','month', order='DESC')
categories = Category.objects.all()
page = request.GET.get('page')
article_queryset = Article.objects.all()
paginator = Paginator(article_queryset, 5)
try:
articles = paginator.page(page)
except PageNotAnInteger:
#If page requested is not an integer, deliver first page.
articles = paginator.page(1)
except EmptyPage:
#If page requested is out of range, deliver last page of results.
articles = paginator.page(paginator.num_pages)
return render(
request,
'blog/article/index.html',
{
'articles' : articles,
'archive_dates' : archive_dates,
'categories' : categories
}
)
</code></pre>
<p>and template</p>
<pre><code> <div class="8u skel-cell-important">
{% for item in articles %}
<!-- Content -->
<article class="box is-post">
<a href="{% url "blog-article-single" slug=item.slug %}" class="image image-full"><img src="/media/{{ item.banner }}" alt="" /></a>
<header>
<h2><a href="{% url "blog-article-single" slug=item.slug %}">{{ item.title }}</a></h2>
<span class="byline">Published {{ item.date_publish|date:"j, M, Y" }}</span>
</header>
<p>
{{ item.content_markup|safe|slice:":250" }}...
</p>
</article>
{% endfor %}
</div>
</code></pre>
<p>and finally error traceback:</p>
<pre><code>AssertionError at /blog/
'date_publish' is a DateTimeField, not a DateField.
Request Method: GET
Request URL: http://localhost:8000/blog/
Django Version: 1.6.1
Exception Type: AssertionError
Exception Value:
'date_publish' is a DateTimeField, not a DateField.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/sql/subqueries.py in _check_field, line 258
Python Executable: /usr/bin/python2.7
Python Version: 2.7.3
Python Path:
['/home/user/paperpxl',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-control-panel',
'/usr/lib/python2.7/dist-packages/ubuntuone-couch',
'/usr/lib/python2.7/dist-packages/ubuntuone-installer',
'/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
Server time: Thu, 19 Dec 2013 15:28:43 +0000
</code></pre>
<p>Any kind of help would be appreciated!</p>
<p><strong>EDIT</strong> : Thanks for your help guys, I'm going back to the release notes to read through them again! I wish I had an eye for detail like you do.</p>
| 0 | 2,516 |
Warning: file_exists() [function.file-exists]: open_basedir restriction in effect. File(/usr/local/apache/bin/apachectl)
|
<p>First of all, sorry for the long title, I never expected this error, so I don't know how to describe it.</p>
<p>I'm getting this error:</p>
<pre><code>Warning: file_exists() [function.file-exists]: open_basedir restriction in effect. File(/usr/local/apache/bin/apachectl) is not within the allowed path(s): (/home/:/backup/:/tmp/) in /home/xxxxx/public_html/plugins/system/jch_optimize/jchoptimize/helper.php on line 176
</code></pre>
<p>Does it mean that there is something in the tmp directory already being used or something is missing? </p>
<p>I'm lost here, where can I start from?</p>
<p>Here is the helper.php:</p>
<pre><code><?php
use JchOptimize\JSMinRegex;
/**
* JCH Optimize - Joomla! plugin to aggregate and minify external resources for
* optmized downloads
* @author Samuel Marshall <sdmarshall73@gmail.com>
* @copyright Copyright (c) 2010 Samuel Marshall
* @license GNU/GPLv3, See LICENSE file
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* If LICENSE file missing, see <http://www.gnu.org/licenses/>.
*
* This plugin, inspired by CssJsCompress <http://www.joomlatags.org>, was
* created in March 2010 and includes other copyrighted works. See individual
* files for details.
*/
defined('_JEXEC') or die('Restricted access');
/**
* Some helper functions
*
*/
class JchOptimizeHelper
{
/**
* Checks if file (can be external) exists
*
* @param type $sPath
* @return boolean
*/
public static function fileExists($sPath)
{
//global $_PROFILER;
//JCH_DEBUG ? $_PROFILER->mark('beforeFileExists - ' . $sPath . ' plgSystem (JCH Optimize)') : null;
$bExists = (file_exists($sPath) || @fopen($sPath, "r") != FALSE);
//JCH_DEBUG ? $_PROFILER->mark('afterFileExists - ' . $sPath . ' plgSystem (JCH Optimize)') : null;
return $bExists;
}
/**
* Get local path of file from the url if internal
* If external or php file, the url is returned
*
* @param string $sUrl Url of file
* @return string File path
*/
public static function getFilePath($sUrl)
{
// global $_PROFILER;
//JCH_DEBUG ? $_PROFILER->mark('beforeGetFilePath - ' . $sUrl . ' plgSystem (JCH Optimize)') : null;
$sUriBase = str_replace('/administrator/', '', JUri::base());
$sUriPath = str_replace('/administrator', '', JUri::base(TRUE));
$oUri = clone JUri::getInstance($sUriBase);
if (JchOptimizeHelper::isInternal($sUrl) && !preg_match('#\.php#i', $sUrl))
{
$sUrl = preg_replace(
array(
'#^' . preg_quote($sUriBase, '#') . '#',
'#^' . preg_quote($sUriPath, '#') . '/#',
'#\?.*?$#'
), '', $sUrl);
//JCH_DEBUG ? $_PROFILER->mark('afterGetFilePath - ' . $sUrl . ' plgSystem (JCH Optimize)') : null;
return JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $sUrl);
}
else
{
switch (TRUE)
{
case preg_match('#://#', $sUrl):
break;
case (substr($sUrl, 0, 2) == '//'):
$sUrl = $oUri->toString(array('scheme')) . substr($sUrl, 2);
break;
case (substr($sUrl, 0, 1) == '/'):
$sUrl = $oUri->toString(array('scheme', 'host')) . $sUrl;
break;
default:
$sUrl = $sUriBase . $sUrl;
break;
}
//JCH_DEBUG ? $_PROFILER->mark('afterGetFilePath - ' . $sUrl . ' plgSystem (JCH Optimize)') : null;
return html_entity_decode($sUrl);
}
}
/**
* Gets the name of the current Editor
*
* @staticvar string $sEditor
* @return string
*/
public static function getEditorName()
{
static $sEditor;
if (!isset($sEditor))
{
$sEditor = JFactory::getUser()->getParam('editor');
$sEditor = !isset($sEditor) ? JFactory::getConfig()->get('editor') : $sEditor;
}
return $sEditor;
}
/**
* Determines if file is internal
*
* @param string $sUrl Url of file
* @return boolean
*/
public static function isInternal($sUrl)
{
$oUrl = JUri::getInstance($sUrl);
//trying to resolve bug in php with parse_url before 5.4.7
if (preg_match('#^//([^/]+)(/.*)$#i', $oUrl->getPath(), $aMatches))
{
if (!empty($aMatches))
{
$oUrl->setHost($aMatches[1]);
$oUrl->setPath($aMatches[2]);
}
}
$sBase = $oUrl->toString(array('scheme', 'host', 'port', 'path'));
$sHost = $oUrl->toString(array('scheme', 'host', 'port'));
if (stripos($sBase, JUri::base()) !== 0 && !empty($sHost))
{
return FALSE;
}
return TRUE;
}
/**
*
* @staticvar string $sContents
* @return boolean
*/
public static function modRewriteEnabled()
{
if (function_exists('apache_get_modules'))
{
return (in_array('mod_rewrite', apache_get_modules()));
}
elseif (file_exists('/usr/local/apache/bin/apachectl'))
{
return (strpos(shell_exec('/usr/local/apache/bin/apachectl -l'), 'mod_rewrite') !== false);
}
else
{
static $sContents = '';
if ($sContents == '')
{
$oFileRetriever = JchOptimizeFileRetriever::getInstance($GLOBALS['oParams']);
$sJbase = JUri::base(true);
$sBaseFolder = $sJbase == '/' ? $sJbase : $sJbase . '/';
$sUrl = JUri::base() . 'plugins/system/jch_optimize/assets' . $sBaseFolder . 'test_mod_rewrite';
if (!$oFileRetriever->isUrlFOpenAllowed())
{
return FALSE;
}
$sContents = $oFileRetriever->getFileContents($sUrl);
}
if ($sContents == 'TRUE')
{
return TRUE;
}
else
{
return FALSE;
}
}
}
/**
*
* @param type $aArray
* @param type $sString
* @return boolean
*/
public static function findExcludes($aArray, $sString, $bScript=FALSE)
{
foreach ($aArray as $sValue)
{
if($bScript)
{
$sString = JSMinRegex::minify($sString);
}
if ($sValue && strpos($sString, $sValue) !== FALSE)
{
return TRUE;
}
}
return FALSE;
}
}
</code></pre>
| 0 | 5,037 |
Convert JSON to XML using PHP
|
<p>My Task is to convert the JSON data in to XML. Right now, My array_to_xml function converts the data from the array into:</p>
<blockquote>
<p><code><0>Maserati</0><1>BMW</1><2>Mercedes/2><3>Ford</3><4>Chrysler</4><5>Acura</5><6>Honda</6><0>1</0><1>2</1><2>1</2><3>0</3><4>4</4><5>0</5><6>0</6><0>1</0><1>2</1><2>1</2><3>0</3><4>4</4><5>0</5><6>0</6></code></p>
</blockquote>
<p>I would like to have the XML in the following format:</p>
<pre><code> <Maserati> 1 </Maserati>
<BMW> 2 </BMW>
...
</code></pre>
<p>Please take a look at the PHP below and let me know the changes to be made.
Thanks in advance</p>
<pre><code>$inpData = $_POST['data'];
// initializing array
$inp_info = $inpData;
// creating object of SimpleXMLElement
$xml_inp_info = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><demandSignals>\n</demandSignals>\n");
// function call to convert array to xml
array_to_xml($inp_info,$xml_inp_info);
//saving generated xml file
$xml_inp_info->asXML(dirname(__FILE__)."/demand.xml") ;
// function definition to convert array to xml
function array_to_xml($inp_info, &$xml_inp_info) {
foreach($inp_info as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_inp_info->addChild("$key");
if(count($value) >1 && is_array($value)){
$jump = false;
$count = 1;
foreach($value as $k => $v) {
if(is_array($v)){
if($count++ > 1)
$subnode = $xml_inp_info->addChild("$key");
array_to_xml($v, "$subnode");
$jump = true;
}
}
if($jump) {
goto LE;
}
array_to_xml($value, "\n$subnode");
}
else
array_to_xml($value, $subnode);
}
else{
array_to_xml($value, $xml_inp_info);
}
}
else {
$xml_inp_info->addChild("$key","$value");
}
LE: ;
}
}
</code></pre>
| 0 | 1,654 |
Move containing elements up and down with jquery
|
<p>Thanks for any help you can provide! Currently, I use a ui-sortable code to allow users to move items up and down in order. Now, I want to give each of these items a set of "up" and "down" buttons that allow users to move items up and down with a click. I've tried reworking theses posts, but I seem to be missing something obvious...</p>
<p><a href="https://stackoverflow.com/questions/2951941/jquery-sortable-move-up-down-button">jQuery Sortable Move UP/DOWN Button</a>
<a href="https://stackoverflow.com/questions/4260373/move-up-down-in-jquery">move up/down in jquery</a></p>
<p>I think somehow I'm not applying the jquery to the right element. My jsfiddle is here: <a href="http://jsfiddle.net/kevindp78/vexw5/2/" rel="nofollow noreferrer">http://jsfiddle.net/kevindp78/vexw5/2/</a> and code is below.</p>
<p>HTML</p>
<pre><code><div id="box" class="ui-sortable" style="display: block;">
<div class="leg">
<a class="image">IMG1</a>
<div class="details">
<h3><a href="/details">Info</a></h3>
<span class="moreinfo">MoreInfo</span>
</div>
<div class="clear"></div>
<div class="up-down">
<p>Change Order</p>
<div class="up">
<input type="button" value="Up" class="up-button"/>
</div>
<div class="down">
<input type="button" value="down" class="down-button"/>
</div>
</div>
<div class="morestuff">
Stuff1
</div>
</div>
<div class="leg">
<a class="image">IMG2</a>
<div class="details">
<h3><a href="/details">Info</a></h3>
<span class="moreinfo">MoreInfo</span>
</div>
<div class="clear"></div>
<div class="up-down">
<p>Change Order</p>
<div class="up">
<input type="button" value="Up" class="up-button"/>
</div>
<div class="down">
<input type="button" value="down" class="down-button"/>
</div>
</div>
<div class="morestuff">
Stuff2
</div>
</div>
<div class="leg">
<a class="image">IMG3</a>
<div class="details">
<h3><a href="/details">Info</a></h3>
<span class="moreinfo">MoreInfo</span>
</div>
<div class="clear"></div>
<div class="up-down">
<p>Change Order</p>
<div class="up">
<input type="button" value="Up" class="up-button"/>
</div>
<div class="down">
<input type="button" value="down" class="down-button"/>
</div>
</div>
<div class="morestuff">
Stuff3
</div>
</div>
</code></pre>
<p></p>
<p>JS</p>
<pre><code>$('up-button').click(function(){
$(this).parent('.leg').insertBefore.previous('.leg')
});
$('.down-button').click(function(){
$(this).parent('.leg').insertAfter.next('.leg')
});
</code></pre>
| 0 | 1,628 |
Implementing Pipes in a C shell (Unix)
|
<p>Basically I have created a shell using standard POSIX commands, I want to be able to Implement Piping as well. Right now it handles commands correctly, and can do background processing with &. But I need to be able to pipe using | and >> as well.
For example something like this:
cat file1 file2 >> file3
cat file1 file2 | more
more file1 | grep stuff</p>
<p>Here is the code I have currently. I also want to AVOID "SYSTEM" calls. I know U need to use dup2, but the way I did my code is a bit odd, so im hoping if someone can tell me if it is feasible to implement pipes in this code? thanks! I know dup2 is used, but also im def. confused at how to implement >> as WELL as |</p>
<pre><code>#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
void Execute(char* command[],bool BG)
{
//Int Status is Used Purely for the waitpid, fork() is set up like normal.
int status;
pid_t pid = fork();
switch(pid)
{
case 0:
execvp(command[0], command);
if(execvp(command[0], command) == -1)
{
cout << "Command Not Found" << endl;
exit(0);
}
default:
if(BG == 0)
{
waitpid(pid, &status, 0);
//Debug cout << "DEBUG:Child Finished" << endl;
}
}
}
bool ParseArg(char* prompt, char* command[], char Readin[],bool BG)
{
fprintf(stderr, "myshell>");
cin.getline(Readin,50);
prompt = strtok(Readin, " ");
int i = 0;
while(prompt != NULL)
{
command[i] = prompt;
if(strcmp(command[i], "&") == 0){
//Debug cout << "& found";
command[i] = NULL;
return true;
}
//Debug cout << command[i] << " ";
i++;
prompt = strtok(NULL, " ");
}
return false;
}
void Clean(char* command[])
{
//Clean Array
for(int a=0; a < 50; a++)
{
command[a] = NULL;
}
}
int main()
{
char* prompt;
char* command[50];
char Readin[50];
bool BG = false;
while(command[0] != NULL)
{
Clean(command);
BG = ParseArg(prompt, command, Readin, BG);
if(strcmp(command[0], "exit") == 0 || strcmp(command[0], "quit") == 0 )
{
break;
}
else
{
Execute(command,BG);
}
}
return 1;
}
</code></pre>
| 0 | 1,223 |
Using AsyncTask
|
<p>Apologies if this is a simple question but I am very new to this and still learning.</p>
<p>I have an app and when my users click the button to login after entering their details, it is crashing with android.os.NetworkOnMainThreadException
I have discovered this is because I am performing a network operation on the main thread and to resolve I need to use AsyncTask, I am stuck however with the syntax.</p>
<p>Here is my code after the button is clicked, calls a function to connect and then parses json into sqlite db. </p>
<pre><code>// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
</code></pre>
<p>How do I change this to the correct class ? I am not passing URL's etc. I think it needs to be something like this , but I am really struggling to get the syntax right.</p>
<p>Many thanks!!!</p>
<pre><code>class login extends AsyncTask<Void, Void, Void> {
private Exception exception;
protected ??? doInBackground(???) {
try {
</code></pre>
| 0 | 1,291 |
Maven Settings for multiple repositories
|
<p>I have the following in settings.xml</p>
<pre class="lang-xml prettyprint-override"><code><mirrors>
<mirror>
<id>paid-jars</id>
<name>jars with license</name>
<url>http://url:8081/nexus/content/repositories/paidjars/</url>
<mirrorOf>!central</mirrorOf>
</mirror>
<mirror>
<id>Org-central</id>
<name>mirror of central</name>
<url>http://url:8081/nexus/content/repositories/central/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
</code></pre>
<p>In pom.xml I have two jars </p>
<ol>
<li>apache-commons.jar (which I assumes to be downloaded from central)</li>
<li>licensed.jar (which I assume to be downloaded from paid-jars)</li>
</ol>
<p>But when I run <code>maven clean install</code> it tries to download licensed.jar from Org-central.</p>
<p>How can I make it use paid-jars to download? Is it possible first it goes to Org-central and if fails it tries at paid-jars? If so, how? I don't want to put repo entries in pom.xml</p>
<hr>
<p><strong>Settings.xml</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<proxies>
<proxy>
<id>Proxy</id>
<active>true</active>
<protocol>http</protocol>
<username>username</username>
<password>******</password>
<host>host.url</host>
<port>8080</port>
<nonProxyHosts>local.net|internal.com</nonProxyHosts>
</proxy>
</proxies>
<mirrors>
<mirror>
<id>paid-jars</id>
<name>jars with license</name>
<url>http://url:8081/nexus/content/repositories/paidjars/</url>
<mirrorOf>!central</mirrorOf>
</mirror>
<mirror>
<id>Org-central</id>
<name>mirror of central</name>
<url>http://url:8081/nexus/content/repositories/central/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
<profiles>
<profile>
<id>compiler</id>
<properties>
<JAVA_1_7_HOME>C:\Program Files (x86)\Java\jdk1.7.0_51\bin</JAVA_1_7_HOME>
</properties>
</profile>
</profiles>
</settings>
</code></pre>
| 0 | 1,529 |
Partition by date range PostgreSQL scans all partitions
|
<p>I have a table partitioned per month (timestamp column). </p>
<p>when querying the data, explain shows that all partitions are being queried when I'm constructing a date with date functions, whereas when I use hard coded dates only the targeted partitions are being scanned.</p>
<p>So when querying like this:</p>
<pre><code>SELECT * FROM vw_comments
WHERE created >= '2019-4-1'
AND created <= '2019-4-30'
limit 100;
</code></pre>
<p>it only scans 1 partition (1 month, good!)
but then to make it more dynamic I'm passing in something like this (simplified)</p>
<pre><code>SELECT * FROM vw_comments
WHERE created >= (date_trunc('month', now()))::timestamp
AND created <= (date_trunc('month', now() + interval '1 month') - interval '1 day') ::timestamp
limit 100;
</code></pre>
<p>the exact same dates come out of the above date methods as the first query, but EXPLAIN shows all partitions get scanned. </p>
<p>How to make it work?</p>
<p><strong>edit: add table definition and explain</strong></p>
<p>upon request from @a_horse_with_no_name, I added the actual table and explain. Upon doing that I figured out something more: dynamic dates don't work when doing a join. So leaving out the 'users' table in the below query makes dynamic dates work.</p>
<pre><code>CREATE TABLE public.comments
(
comment_id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
comment_id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
from_user_id integer NOT NULL,
fk_topic_id integer NOT NULL,
comment_text text COLLATE pg_catalog."default",
parent_comment_id integer,
created timestamp without time zone NOT NULL,
comment_type integer NOT NULL DEFAULT 0,
CONSTRAINT comments_pkey PRIMARY KEY (comment_id, created)
) PARTITION BY RANGE (created)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.comments
OWNER to soichat;
CREATE INDEX ix_comments_comment_id
ON public.comments USING btree
(comment_id DESC)
TABLESPACE pg_default;
CREATE INDEX ix_comments_created
ON public.comments USING btree
(created DESC)
TABLESPACE pg_default;
CREATE INDEX ix_comments_fk_topic_id
ON public.comments USING btree
(fk_topic_id)
TABLESPACE pg_default;
CREATE INDEX ix_comments_from_user_id
ON public.comments USING btree
(from_user_id)
TABLESPACE pg_default;
CREATE INDEX ix_comments_parent_comment_id
ON public.comments USING btree
(parent_comment_id)
TABLESPACE pg_default;
-- Partitions SQL
CREATE TABLE public.comments_2019_2 PARTITION OF public.ix_comments_parent_comment_id
FOR VALUES FROM ('2019-02-01 00:00:00') TO ('2019-03-01 00:00:00');
CREATE TABLE public.comments_2019_3 PARTITION OF public.ix_comments_parent_comment_id
FOR VALUES FROM ('2019-03-01 00:00:00') TO ('2019-04-01 00:00:00');
CREATE TABLE public.comments_2019_4 PARTITION OF public.ix_comments_parent_comment_id
FOR VALUES FROM ('2019-04-01 00:00:00') TO ('2019-05-01 00:00:00');
CREATE TABLE public.comments_2019_5 PARTITION OF public.ix_comments_parent_comment_id
FOR VALUES FROM ('2019-05-01 00:00:00') TO ('2019-06-01 00:00:00');
</code></pre>
<p>the query:</p>
<pre><code>explain (analyse, buffers)
SELECT comments.comment_id,
comments.from_user_id,
comments.fk_topic_id,
comments.comment_text,
comments.parent_comment_id,
comments.created,
users.user_name,
users.picture_path
FROM comments
LEFT JOIN users ON comments.from_user_id = users.user_id
WHERE comments.created >= (date_trunc('month', now()))::timestamp
AND comments.created <= (date_trunc('month', now() + interval '1 month') - interval '1 day') ::timestamp
limit 100;
</code></pre>
<p><a href="https://explain.depesz.com/s/K6wh" rel="noreferrer">explain (analyze, buffers)</a> </p>
<pre><code>Limit (cost=1.20..11.93 rows=100 width=126) (actual time=1.441..1.865 rows=100 loops=1)
Buffers: shared hit=499
-> Merge Left Join (cost=1.20..753901.07 rows=7028011 width=126) (actual time=1.440..1.778 rows=100 loops=1)
Merge Cond: (comments_2019_2.from_user_id = users.user_id)
Buffers: shared hit=499
-> Merge Append (cost=0.92..665812.08 rows=7028011 width=51) (actual time=0.017..0.259 rows=100 loops=1)
Sort Key: comments_2019_2.from_user_id
Buffers: shared hit=15
-> Index Scan using comments_2019_2_from_user_id_idx on comments_2019_2 (cost=0.15..58.95 rows=5 width=56) (actual time=0.002..0.003 rows=0 loops=1)
Filter: ((created >= (date_trunc('month'::text, now()))::timestamp without time zone) AND (created <= ((date_trunc('month'::text, (now() + '1 mon'::interval)) - '1 day'::interval))::timestamp without time zone))
Buffers: shared hit=1
-> Index Scan using comments_2019_3_from_user_id_idx on comments_2019_3 (cost=0.15..9790.24 rows=1 width=51) (actual time=0.002..0.003 rows=0 loops=1)
Filter: ((created >= (date_trunc('month'::text, now()))::timestamp without time zone) AND (created <= ((date_trunc('month'::text, (now() + '1 mon'::interval)) - '1 day'::interval))::timestamp without time zone))
Buffers: shared hit=1
-> Index Scan using comments_2019_4_from_user_id_idx on comments_2019_4 (cost=0.43..550483.74 rows=7028000 width=51) (actual time=0.010..0.162 rows=100 loops=1)
Filter: ((created >= (date_trunc('month'::text, now()))::timestamp without time zone) AND (created <= ((date_trunc('month'::text, (now() + '1 mon'::interval)) - '1 day'::interval))::timestamp without time zone))
Buffers: shared hit=12
-> Index Scan using comments_2019_5_from_user_id_idx on comments_2019_5 (cost=0.15..58.95 rows=5 width=56) (actual time=0.001..0.002 rows=0 loops=1)
Filter: ((created >= (date_trunc('month'::text, now()))::timestamp without time zone) AND (created <= ((date_trunc('month'::text, (now() + '1 mon'::interval)) - '1 day'::interval))::timestamp without time zone))
Buffers: shared hit=1
-> Index Scan using pk_users on users (cost=0.28..234.83 rows=1606 width=79) (actual time=0.005..0.870 rows=1395 loops=1)
Buffers: shared hit=484
Planning Time: 0.360 ms
Execution Time: 1.942 ms
</code></pre>
| 0 | 2,582 |
Jest - Map through an Array of Items and test their Values
|
<p>I have a simple Utility Function. It takes an Enum, and Transform's it to an Array of Objects shaped as <code>{label: string, value:string}</code>.</p>
<p>Here is the Function as well as the Interface it uses:</p>
<pre><code>export interface ISelectOption {
value: string;
label: string;
selected?: boolean;
}
const transformEnumToISelectArray = (object: object): ISelectOption[] =>
Object.keys(object).map(value => ({
label: value,
value
}));
export default transformEnumToISelectArray;
</code></pre>
<p>I have a repetitive Test. Basically, I check if the output of label/value, is what is expected, if I provide a Enum. Here is the test, that it is currently working:</p>
<pre><code>import transformEnumToISelectArray from '../transformEnumToISelectArray';
import ISelectOption from '../../interfaces/ISelectOption';
describe('transformEnumToISelectArray', () => {
enum mockEnum {
FIELD1 = 'FIELD1',
FIELD2 = 'FIELD2',
FIELD3 = 'FIELD3'
}
let expectedResult: ISelectOption[] = [];
let nonExpectedResult: ISelectOption[] = [];
describe('ExpectedResults', () => {
beforeEach(() => {
expectedResult = [
{
label: 'FIELD1',
value: 'FIELD1'
},
{
label: 'FIELD2',
value: 'FIELD2'
},
{
label: 'FIELD3',
value: 'FIELD3'
}
];
});
it('should return an Array of ISelectOption shaped Object with correct `label` and `value`', () => {
const response = transformEnumToISelectArray(mockEnum);
expect(response[0].label).toEqual(expectedResult[0].label);
expect(response[1].label).toEqual(expectedResult[1].label);
expect(response[2].label).toEqual(expectedResult[2].label);
expect(response[0].value).toEqual(expectedResult[0].value);
expect(response[1].value).toEqual(expectedResult[1].value);
expect(response[2].value).toEqual(expectedResult[2].value);
});
});
});
</code></pre>
<p>Please ignore the <code>beforeEach()</code>, I have more tests, but I ommited them. My problem and this is just an optimization here, is that I want to make it better. So, I though I would <code>map</code> through the Array of <code>response</code> and <code>expectedResult</code> using Enzymes's <code>.map(fn) => Array<Any></code>.</p>
<p>This is what I did:</p>
<pre><code>expect(response.map(index => response[index].lable)).toEqual(
expectedResult.map(index => expectedResult[index].label)
);
</code></pre>
<p>But I get the following:</p>
<pre><code>Type 'ISelectOption' cannot be used as an index type.ts(2538)
</code></pre>
<p>Does anyone understand this. Do I need to spacifiy an index Property on my ISelectOption interface for this to work? Any Ideas?</p>
| 0 | 1,063 |
Symfony2: There is no extension able to load the configuration for
|
<p>I am building an extension to load config files from all installed bundles.</p>
<p>my Extension looks like this:</p>
<pre><code>namespace Acme\MenuBundle\DependencyInjection;
// use ...
use Acme\MenuBundle\DependencyInjection\Configuration;
class AcmeMenuExtension extends Extension {
public function load(array $configs, ContainerBuilder $container) {
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$finder = new \Symfony\Component\Finder\Finder();
$finder
->directories()
->in($container->getParameter('kernel.root_dir') . '/../src/*/*Bundle/Resources')
->path('config');
$possibleLocations = array();
foreach ($finder as $c_dir) {
$possibleLocations[] = $c_dir->getPathName();
}
$loader = new Loader\YamlFileLoader($container, new FileLocator($possibleLocations));
$loader->load('menu.yml');
}
}
</code></pre>
<p>And then there is my (very simple) Configuration class: I will add a more complex tree in the future, but for now I want it to work with this:</p>
<pre><code>namespace Acme\MenuBundle\DependencyInjection;
// use ...
class Configuration implements ConfigurationInterface {
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('mw_menu');
$rootNode
->children()
->scalarNode('mw_menu')->defaultValue('')->end()
->end();
return $treeBuilder;
}
}
</code></pre>
<p>For testing I only placed a "menu.yml" file inside the current MenuBundle\Resources\config with this content:</p>
<pre><code># file: src\Acme\MenuBundle\Resource\config\menu.yml
mw_menu: "some teststring"
</code></pre>
<p>For manual testing I use a testAction in a default Controller, which does actually nothing but render an empty template.</p>
<p>Anyway, I get this error:</p>
<pre><code>InvalidArgumentException: There is no extension able to load the configuration for
"mw_menu" (in {path to symfony}/app/../src/Acme/MenuBundle/Resources\config\menu.yml).
Looked for namespace "mw_menu", found none
</code></pre>
<p><strong>How can I fix that?</strong></p>
<p>From what I currently understand, Symfony notices the key 'mw_menu' in the config file, but is not able to find the matching configuration.</p>
<p>I worked along the cookbook article: <a href="http://symfony.com/doc/master/cookbook/bundles/extension.html" rel="nofollow noreferrer">How to expose a semantic configuration?</a></p>
<p>Please note: I know of Knp Menu Bundle and similar Bundles but I do want to implement a menu myself.</p>
<p>Additionally I found <a href="https://groups.google.com/forum/?fromgroups=#!topic/symfony-users/GX2X_yOOj3g" rel="nofollow noreferrer">this</a> notice. Is he right?</p>
| 0 | 1,121 |
DataTables: search all columns when server-side
|
<p>I'm using <a href="https://github.com/IgnitedDatatables/Ignited-Datatables/wiki" rel="nofollow">IgnitedDatatables</a> (CodeIgniter library) for <a href="http://datatables.net" rel="nofollow">DataTables</a>. The table gets generated without problems but if I search/filter it can only filter one column at a time. If I set "bServerSide" to false it works but then I lose the server-side functionality. </p>
<p>In the examples, this one is working:
<a href="http://datatables.net/release-datatables/examples/ajax/custom_data_property.html" rel="nofollow">http://datatables.net/release-datatables/examples/ajax/custom_data_property.html</a></p>
<p>while this isn't (server-side):
<a href="http://datatables.net/release-datatables/examples/data_sources/server_side.html" rel="nofollow">http://datatables.net/release-datatables/examples/data_sources/server_side.html</a></p>
<p>Is this not possible to achieve when running server-side?</p>
<p>This is my JSON response (shortened and with replaced data):</p>
<pre><code>{"sEcho":0,"iTotalRecords":45438,"iTotalDisplayRecords":45438,"aaData":[["abc","12345","example@example.com","","","2010-01-27 22:31:10","Edit<\/a> Delete<\/a>"],["abc2"," test123","test@test.com","","","2008-06-15 22:09:33","Edit<\/a> Delete<\/a>"]],"sColumns":"fname,lname,email,phone,cellphone,created,edit"}
</code></pre>
<p>JavaScript code:</p>
<pre><code>$("#members").dataTable( {
"bProcessing": true,
"bServerSide": true,
'sAjaxSource': '<?php echo base_url();?>members/listener',
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": 'POST',
"url": sSource,
"data": aoData,
"success": fnCallback
} );
},
"bLengthChange": false,
"aaSorting": [[ 0, "asc" ]],
"iDisplayLength": 15,
"sPaginationType": "full_numbers",
"bAutoWidth": false,
"aoColumnDefs": [
{ "sName": "fname", "aTargets": [ 0 ] },
{ "sName": "lname", "aTargets": [ 1 ] },
{ "sName": "email", "aTargets": [ 2 ] },
{ "sName": "phone", "sWidth": "80px", "aTargets": [ 3 ] },
{ "sName": "cellphone", "sWidth": "100px", "aTargets": [ 4 ] },
{ "sName": "created", "sWidth": "120px", "aTargets": [ 5 ] },
{ "bSortable": false, "sName": "edit", "sWidth": "115px", "aTargets": [ 6 ] }
]
});
</code></pre>
<p>Thank you!</p>
| 0 | 1,048 |
Angular 6: Send click event in child to parent
|
<p><strong>EDIT:
It still don't work and not throw any errors.
I edited the code and added partial code from parent.component.ts</strong></p>
<p>I have parent component of a side nav-bar and child component which is nested in parent component's body and contains iframe.
I want that when there's a click event on the iframe, I'll return to the parent that event has occurred so I can mark this video as watched in the parent's sidebar with a 'V'.</p>
<p><strong>parent component.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// .....
export class CoursePlayComponent implements OnInit {
course: ICourse;
courseId: number;
// current user
public currentUser: IUser;
// variables for current lesson
public current: IVideo;
constructor(private courseService: CourseService,
private route: ActivatedRoute,
private router: Router,
private userService: UserService) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
ngOnInit() {
// save this course id from course-detail and get http request from the service
this.courseId = JSON.parse(localStorage.getItem("courseId"));
this.getCourse(this.courseId);
}
// get course by id from service
getCourse(id:number) {...}
// get current lesson by unit and lesson position in course
getCurrent(unit_position: number, lesson_position: number) { ... }
// check if the lesson already watched
isLessonIncluded(course_id: number, lesson_id: number) {
return this.userService.isLessonIncluded(course_id, lesson_id);
}
// check the value from child lesson and add the new lesson to the completed lessons array
watched(state) {
console.log("parent-video watched: ", state);
// update user data array
this.userService.addToCompletedLessons(this.course.id, this.current.id);
}
}</code></pre>
</div>
</div>
</p>
<p><strong>parent.component.html:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-sidenav-container fullscreen *ngIf="course">
<mat-sidenav #sidenav mode="side" class="app-sidenav">
<mat-toolbar id="sidenav" color="primary">
<button mat-icon-button (click)="sidenav.toggle()" class="mat-icon-button sidenav-toggle-button" [hidden]="!sidenav.opened">
<mat-icon aria-label="Menu" class="material-icons">close</mat-icon>
</button>
</mat-toolbar>
<mat-nav-list *ngFor="let unit of course.units">
<h6 class="course-list-title">Unit {{ unit?.position }}: {{ unit?.name }}</h6>
<a mat-list-item *ngFor="let lesson of unit.videos" class="sidenav-link course-item" [routerLink]="['/courses' , course?.id , 'unit' , unit?.position , 'lesson' , lesson?.position]" (click)="sidenav.toggle()" (click)="getCurrent(unit?.position,lesson?.position)">
<span mat-line class="title">Lesson {{lesson?.id}}: {{lesson?.name}}</span>
<span *ngIf="isLessonIncluded(course.id, lesson.id)" class="fas fa-check" style="color:lightgreen;"></span>
</a>
</mat-nav-list>
</mat-sidenav>
<!-- ... -->
<div class="course-body container-fluid text-center">
<course-lesson *ngIf="showLesson == true" (clicked)="watched($event)" [lessonId]="current?.id" [lessonName]="current?.name" [lessonData]="current?.data" [totalLesoons]="totalLesoons"></course-lesson>
</div>
</mat-sidenav-container></code></pre>
</div>
</div>
</p>
<p><strong>child.component.ts:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// ....
export class CourseLessonComponent implements OnInit {
@Input() lessonId: number;
@Input() lessonName: string;
@Input() lessonData: string;
@Input() totalLesoons: number;
@Output() clicked = new EventEmitter();
clicked: boolean = false;
constructor(private courseService: CourseService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit() { }
watchedVideo() {
console.log("child- video watched");
this.clicked.emit(true);
}
}</code></pre>
</div>
</div>
</p>
<p><strong>child.component.html:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="lesson-title">{{lessonName}}</h1>
<p class="small-text" *ngIf="totalLesoons > 0">lesson {{lessonId}} of {{totalLesoons}}</p>
<hr>
<iframe (click)="clicked = true" frameborder="0" allowfullscreen="true" [src]='lessonData | safe'></iframe></code></pre>
</div>
</div>
</p>
| 0 | 2,032 |
How to close a server port after we are done using it?
|
<p>Note: I found a similar question here:</p>
<p><a href="https://stackoverflow.com/questions/6147481/how-to-close-port-after-using-server-sockets">How to close port after using server sockets</a></p>
<p>But did not find any satisfactory answer there.</p>
<p>Here is my code for the client program:</p>
<pre><code>package hf;
import java.io.*;
import java.net.*;
public class DailyAdviceClient
{
private static final int chatPort = 4242;
public static void main(String[] args)
{
DailyAdviceClient client = new DailyAdviceClient();
client.go();
}
private void go()
{
try
{
Socket socket = new Socket("127.0.0.1",chatPort);
InputStreamReader inputStream = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStream);
String advice = bufferedReader.readLine();
System.out.println("Advice received by the client for today is "+advice);
bufferedReader.close();
}
catch(Exception e)
{
System.out.println("Failed to connect to the server");
}
}
}
</code></pre>
<p>And here is the code for the server program:</p>
<pre><code>package hf;
import java.io.*;
import java.net.*;
public class DailyAdviceServer
{
private String[] adviceList = {"Take smaller bites",
"Go for the tight jeans. No they do NOT make you look fat.",
"One word: inappropriate",
"Just for today, be honest. Tell your boss what you *really* think",
"You might want to rethink that haircut."};
private static final int chatPort = 4242;
public static void main(String[] args)
{
DailyAdviceServer server = new DailyAdviceServer();
server.go();
}
private void go()
{
try
{
ServerSocket serverSocket = new ServerSocket(chatPort);
while(true)
{
Socket socket = serverSocket.accept();
PrintWriter writer = new PrintWriter(socket.getOutputStream());
String advice = getTodaysAdvice();
writer.println(advice);
writer.close();
}
}
catch(Exception e)
{
System.out.println("Error in establishing connection with the client");
}
}
private String getTodaysAdvice()
{
String advice = null;
int randomIndex = (int) (Math.random()*adviceList.length);
advice = adviceList[randomIndex];
return advice;
}
}
</code></pre>
<p>In the application, whenever a client program connects to the server program, it receives a String that contains advice for the day.</p>
<p>When I run </p>
<pre><code>netstat -an
</code></pre>
<p>In the command prompt of my Windows computer as suggested in one of the answers in the aforementioned link, I get a message that the port 4242 is </p>
<pre><code>LISTENING
</code></pre>
<p>How do I close the port and make it available for future re-use?</p>
| 0 | 1,252 |
Error :Could not load file or assembly 'DocumentFormat.OpenXml,
|
<p>I'm getting this error is VS2015</p>
<blockquote>
<p>Additional information: Could not load file or assembly
'DocumentFormat.OpenXml, Version=2.5.5631.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The
located assembly's manifest definition does not match the assembly
reference. (Exception from HRESULT: 0x80131040)</p>
</blockquote>
<p>I am trying to send mail with database table attachment in c#</p>
<p>here my code id</p>
<pre><code>using ClosedXML.Excel;
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.IO;
using System.Net.Mail;
using System.Windows.Forms;
namespace Email
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String MyConString = "SERVER=10.0.30.125;" + "DATABASE=test;" + "UID=root;" + "PASSWORD=asterisk;" + "Convert Zero Datetime = True";
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = GetData();
dt.TableName = "data";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
using (MailMessage Msg = new MailMessage())
{
Msg.From = new MailAddress("my@mail.com");
Msg.To.Add("to@mail.com");
Msg.Subject = "DATA";
Msg.Body = "Excel Attachment";
Msg.Attachments.Add(new Attachment(new MemoryStream(bytes), "DATA.xlsx"));
Msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
credentials.UserName = "my@mail.com";
credentials.Password = "password";
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(Msg);
MessageBox.Show("MAIL SENT SUCCESSFULLY TO " + txtTo.Text);
txtTo.Text = "";
}
}
}
}
private DataTable GetData()
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * from table;", conn))
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = conn;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
}
</code></pre>
<p>I add it in my AddReference</p>
<pre><code>ClosedXml.dll
DocumentFormat.OpenXml.dll
MySql.Data.dll
</code></pre>
<p>Help to solve my problem . why i m getting this error?</p>
| 0 | 1,858 |
TypeError: Assignment to constant variable
|
<p>Please help me solve the error. I have attached my index.js code routes.js code and db.js code and the error description.
I've been trying hard to solve the error.</p>
<blockquote>
<p>index.js</p>
</blockquote>
<pre><code>const express = require('express');
const app = express();
const routes = require('./routes');
const path = require('path');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const session = require('express-session');
const auth = require('./routes/auth');
const {
con,
sessionStore
} = require('./config/db');
const fs = require('fs');
require('dotenv').config({
path: path.join(__dirname, '.env')
});
const port = process.env.PORT || 3000;
// parse application/json
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
//static files
app.use(express.static('public'))
app.use('/css' , express.static(__dirname + 'public/css'))
app.use('/imgs' , express.static(__dirname + 'public/imgs'))
var sess = {
secret: 'keyboard cat',
store: sessionStore,
cookie: {
httpOnly: false,
},
resave: false,
saveUninitialized: false
}
app.use(session(sess));
app.use(fileUpload());
//set views
app.set('view engine' , 'ejs');
app.set('views', path.join(__dirname, 'views'))
//
app.use(require('connect-flash')());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('/', (req,res) =>{
res.render('index22')
})
app.get('/login', (req, res) => {
res.render('login');
});
let s;
const loginRequired = (req, res, next) => {
if (req.session.username) {
s = req.session;
next();
} else {
res.redirect('/auth/login');
}
}
// app.get('/new', (req, res) => {
// res.render('new');
// });
// app.get('/show', (req, res) => {
// res.render('show');
// });
// app.get('/', loginRequired, (req, res) => {
// res.redirect('/new');
// });
// app.get('/', loginRequired, (req, res) => {
// res.redirect('/show');
// });
app.get('/new', loginRequired, routes.new);//call for main index page
app.post('/new', loginRequired, routes.new);//call for signup post
app.get('/show', loginRequired, routes.show);
app.use('/auth', auth);
app.listen(port, () => console.log(`listening on http://${process.env.HOST}:${port}`));
</code></pre>
<blockquote>
<p>routes.js</p>
</blockquote>
<pre><code>const {
con,
sessionStore
} = require('./config/db');
exports.new = function(req, res){
message = '';
if(req.method == "POST"){
const post = req.body;
const username= post.username;
const title= post.title;
const state= post.state;
const category= post.category;
const description= post.description;
if (!req.files)
return res.status(400).send('No files were uploaded.');
const file = req.files.uploads;
const img_name=file.name;
if(file.mimetype == "image/jpeg" ||file.mimetype == "image/png"||file.mimetype == "image/gif" ){
file.mv('public/imgs/uploads/'+file.name, function(err) {
if (err)
return res.status(500).send(err);
const sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `img_name` ,`description`) VALUES ('" + username + "','" + title + "','" + state + "','" + category + "','" + image + "','" + description + "')";
const query = con.query(sql, function(err, result) {
res.redirect('show/'+result.insertUsername);
});
});
} else {
message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
res.render('new.ejs',{message: message});
}
} else {
res.render('new');
}
};
exports.show = function(req, res){
const message = '';
const username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
</code></pre>
<blockquote>
<p>db.js</p>
</blockquote>
<pre><code>const mysql = require('mysql');
const path = require('path');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
require('dotenv').config({ path: path.join(__dirname, '../.env') });
// config for your database
const con = mysql.createConnection({
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
server: process.env.DB_HOST,
database: process.env.DB_NAME,
port: parseInt(process.env.DB_PORT)
});
var sessionStore = new MySQLStore({}/* session store options */, con);
// connect to your database
con.connect((err) => {
if (err) throw err;
console.log("Connected to database");
});
module.exports = { con, sessionStore };
</code></pre>
<blockquote>
<p>Description of the error:</p>
</blockquote>
<pre><code>C:\Users\hp\Desktop\Internship\Nt\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
TypeError: Assignment to constant variable.
at Query.<anonymous> (C:\Users\hp\Desktop\Nt\routes.js:50:12)
at Query.<anonymous> (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\Connection.js:526:10)
at Query._callback (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\Connection.js:488:16)
at Query.Sequence.end (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)
at Query.EofPacket (C:\Users\hp\Desktop\\Nt\node_modules\mysql\lib\protocol\sequences\Query.js:133:8)
at Protocol._parsePacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Protocol.js:38:16)
</code></pre>
<p>I guess mainly the error is in the routes.js file
Any help will be highly appreciated.
Thank you</p>
| 0 | 2,825 |
Is it possible to group a set of html elements so that they move together?
|
<p>When the browser size is changed/on different sized devices, I need a set of html elements that are all semantically related to remain together and move in a block. That is, if one of the elements move to the next "row" due to their not being enough width to contain the whole grouping, ALL of it should move down.</p>
<p>IOW, this is sort of like the "keep together" attribute that some groupings of items in a word processing document have.</p>
<p>To be a little more specific, say that I have collections of the following elements: </p>
<pre><code>1) an anchor tag, filling out a first "column"
2) a collection of tags, to the right of the anchor tag, consisting of:
(a) a div, followed by a <br/>
(b) a cite, followed by a <br/>
(c) another div, followed by a <br/>
(d) two or three anchor tags that are aligned side-by-side at the bottom of the second "column"
</code></pre>
<p>So to sum up, if there is not enough room for the second "column" in a "row," rather than keep the in the first "column" and moving the elements in the second column down to the next "row," the in the first column should adhere to its siblings and always remain on the same "row" with them (I'm putting "row" and "column" in quotes because I'm not using an html table, and those exist only in a virtual sense).</p>
<p>If you're finding this a little hard to visualize (I don't blame you), check out the fiddle: <a href="http://jsfiddle.net/W7CYC/8/" rel="noreferrer">http://jsfiddle.net/W7CYC/8/</a></p>
<p>Note: wrapping the groupings into html5 s did not help.</p>
<p>Here's the code:</p>
<p>HTML:</p>
<pre><code><div class="yearBanner">2013</div>
<section>
<a id="mainImage" class="floatLeft" href="https://rads.stackoverflow.com/amzn/click/com/0299186342" rel="nofollow noreferrer"><img height="240" width="160" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg"></a>
<div id="prizeCategory" class="category">BIOGRAPHY</div>
<br/>
<cite id="prizeTitle" class="title">Son of the Wilderness: The Life of John Muir</cite>
<br/>
<div id="prizeArtist" class="author">Linnie Marsh Wolfe</div>
<br/>
<img class="floatLeft" height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
<img class="floatLeft" height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
<img class="floatLeft" height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
</section>
<section>
<a class="floatLeft" href="https://rads.stackoverflow.com/amzn/click/com/0299186342" rel="nofollow noreferrer"><img height="240" width="160" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg"></a>
<div class="category">BIOGRAPHY</div>
<br/>
<cite class="title">Son of the Wilderness: The Life of John Muir</cite>
<br/>
<div class="author">Linnie Marsh Wolfe</div>
<br/>
<img height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
<img height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
<img height="60" width="40" src="http://ecx.images-amazon.com/images/I/51usxIl4vML._SY346_.jpg">
</section>
</code></pre>
<p>CSS:</p>
<pre><code>body {
background-color: black;
}
.floatLeft {
float: left;
padding-right: 20px;
padding-left: 5px;
}
.yearBanner {
font-size: 3em;
color: white;
font-family: Verdana, Arial, Helvetica, sans-serif;
float: left;
padding-top: 64px;
}
.category {
display: inline-block;
font-family: Consolas, sans-serif;
font-size: 2em;
color: Orange;
width: 160px;
}
.title {
display: inline-block;
font-family: Calibri, Candara, serif;
color: Yellow;
width: 160px;
}
.author {
display: inline-block;
font-family: Courier, sans-serif;
font-size: 0.8em;
color: White;
width: 160px;
}
</code></pre>
<p>jQuery:</p>
<pre><code>$('#prizeCategory').text("Changed Category");
$('#prizeTitle').text("Changed Title that spans two rows");
$('#prizeArtist').text("Changed Author and co-author");
$('#mainImage img').attr("src", "http://ecx.images-amazon.com/images/I/61l0rZz6mdL._SY300_.jpg");
$('#mainImage img').attr("height", "200");
</code></pre>
| 0 | 1,793 |
Jetpack navigation: Title and back/up arrow in the action bar?
|
<p>I have installed the latest canary version of Android Studio, and followed this (<a href="https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing" rel="noreferrer">https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing</a>) instruction to implement a simple two page navigation. Basically page1 has a button, and when it is clicked, the app shows page2.</p>
<p>It works, but there is one problem... It does not seem to do anything with the action bar automatically. Is it supposed to show up/back arrow and the "Label" attribute on the action bar automatically by the navigation library? Or am I supposed to do all the work manually as before? I want to show the back arrow and "Details" on action(tool) bar when page2 is showing.</p>
<p>On button click at page 1.</p>
<pre><code>override fun onViewCreated(view: View, savedInstanceState: Bundle?)
{
button1.setOnClickListener {
val nav = NavHostFragment.findNavController(this);
nav.navigate(R.id.show_page2)
}
}
</code></pre>
<p>Main activity XML. By default it was the default Action Bar, I have replaced it with a ToolBar. There was no difference.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:elevation="4dp"
android:background="?attr/colorPrimary"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:layout_width="match_parent">
</androidx.appcompat.widget.Toolbar>
<fragment
android:id="@+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar"
app:navGraph="@navigation/nav_graph"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>Nav graph XML.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/page1">
<activity
android:id="@+id/mainActivity2"
android:name="com.android.navtest.MainActivity"
android:label="activity_main"
tools:layout="@layout/activity_main"/>
<fragment
android:id="@+id/page1"
android:name="com.android.navtest.BlankFragment2"
android:label="Home page"
tools:layout="@layout/page1">
<action
android:id="@+id/show_page2"
app:destination="@id/page2"
app:enterAnim="@anim/anim1"
app:popExitAnim="@anim/anim2"/>
</fragment>
<fragment
android:id="@+id/page2"
android:name="com.android.navtest.BlankFragment"
android:label="Details"
tools:layout="@layout/page2"/>
</navigation>
</code></pre>
| 0 | 1,635 |
Convert from an infix expression to postfix (C++) using Stacks
|
<p>My lecturer gave me an assignment to create a program to convert and infix expression to postfix using Stacks. I've made the stack classes and some functions to read the infix expression. </p>
<p>But this one function, called <code>convertToPostfix(char * const inFix, char * const postFix)</code> which is responsible to convert the inFix expression in the array inFix to the post fix expression in the array postFix using stacks, is not doing what it suppose to do. Can you guys help me out and tell me what I'm doing wrong?</p>
<p>The following is code where the functions to convert from inFix to postFix is and <code>convertToPostfix(char * const inFix, char * const postFix)</code> is what I need help fixing:</p>
<pre><code> void ArithmeticExpression::inputAndConvertToPostfix()
{
char inputChar; //declaring inputChar
int i = 0; //inizalize i to 0
cout << "Enter the Arithmetic Expression(No Spaces): ";
while( ( inputChar = static_cast<char>( cin.get() ) ) != '\n' )
{
if (i >= MAXSIZE) break; //exits program if i is greater than or equal to 100
if(isdigit(inputChar) || isOperator(inputChar))
{
inFix[i] = inputChar; //copies each char to inFix array
cout << inFix[i] << endl;
}
else
cout << "You entered an invalid Arithmetic Expression\n\n" ;
}
// increment i;
i++;
convertToPostfix(inFix, postFix);
}
bool ArithmeticExpression::isOperator(char currentChar)
{
if(currentChar == '+')
return true;
else if(currentChar == '-')
return true;
else if(currentChar == '*')
return true;
else if(currentChar == '/')
return true;
else if(currentChar == '^')
return true;
else if(currentChar == '%')
return true;
else
return false;
}
bool ArithmeticExpression::precedence(char operator1, char operator2)
{
if ( operator1 == '^' )
return true;
else if ( operator2 == '^' )
return false;
else if ( operator1 == '*' || operator1 == '/' )
return true;
else if ( operator1 == '+' || operator1 == '-' )
if ( operator2 == '*' || operator2 == '/' )
return false;
else
return true;
return false;
}
void ArithmeticExpression::convertToPostfix(char * const inFix, char * const postFix)
{
Stack2<char> stack;
const char lp = '(';
stack.push(lp); //Push a left parenthesis ‘(‘ onto the stack.
strcat(inFix,")");//Appends a right parenthesis ‘)’ to the end of infix.
// int i = 0;
int j = 0;
if(!stack.isEmpty())
{
for(int i = 0;i < 100;){
if(isdigit(inFix[i]))
{
postFix[j] = inFix[i];
cout << "This is Post Fix for the first If: " << postFix[j] << endl;
i++;
j++;
}
if(inFix[i] == '(')
{
stack.push(inFix[i]);
cout << "The InFix was a (" << endl;
i++;
//j++;
}
if(isOperator(inFix[i]))
{
char operator1 = inFix[i];
cout << "CUrrent inFix is a operator" << endl;
if(isOperator(stack.getTopPtr()->getData()))
{
cout << "The stack top ptr is a operator1" << endl;
char operator2 = stack.getTopPtr()->getData();
if(precedence(operator1,operator2))
{
//if(isOperator(stack.getTopPtr()->getData())){
cout << "The stack top ptr is a operato2" << endl;
postFix[j] = stack.pop();
cout << "this is post fix " << postFix[j] << endl;
i++;
j++;
// }
}
}
else
stack.push(inFix[i]);
// cout << "Top Ptr is a: "<< stack.getTopPtr()->getData() << endl;
}
for(int r = 0;r != '\0';r++)
cout << postFix[r] << " ";
if(inFix[i] == ')')
{
while(stack.stackTop()!= '(')
{
postFix[j] = stack.pop();
i++;
j++;
}
stack.pop();
}
}
}
}
</code></pre>
<p>Note the function convertToPostfix was made using this algorithm:</p>
<ul>
<li>Push a left parenthesis ‘(‘ onto the stack.</li>
<li>Append a right parenthesis ‘)’ to the end of infix.</li>
<li><p>While the stack is not empty, read infix from left to right and do the following:</p>
<ul>
<li>If the current character in infix is a digit, copy it to the next element of postfix.</li>
<li>If the current character in infix is a left parenthesis, push it onto the stack.</li>
<li><p>If the current character in infix is an operator,</p>
<ul>
<li>Pop operator(s) (if there are any) at the top of the stack while they have equal or higher precedence than the current operator, and insert the popped operators in postfix.</li>
<li>Push the current character in infix onto the stack.</li>
</ul></li>
<li>If the current character in infix is a right parenthesis
<ul>
<li>Pop operators from the top of the stack and insert them in postfix until a left parenthesis is at the top of the stack.</li>
<li>Pop (and discard) the left parenthesis from the stack.</li>
</ul></li>
</ul></li>
</ul>
| 0 | 3,738 |
error: overloaded 'operator<<' must be a binary operator (has 3 parameters)
|
<p>I know there are plenty of questions like these, but I couldn't find a solution that worked for me. </p>
<p>I am trying to make simple fraction calculator than can add or subtract any number of functions and write the answer as a reduced fraction. </p>
<p><em>Example: input=
3/2 + 4/
8
, output =
2</em></p>
<p>I am trying overload operators in order to accomplish this.</p>
<p>So in the program I am trying to develop, the input consists of an expression made of fractions separated by the operators <code>+</code> or <code>-</code>. </p>
<p>The number of fractions in the expression is arbitrary. </p>
<p>Each of the following 6 lines is an example of a valid input expression:</p>
<pre><code>1/2 + 3/4
1/2 -5/7+3/5
355/113
3 /9-21/ -7
4/7-5/-8
-2/-3+7/5
</code></pre>
<p>***The problem that I am having is that in when I run my program it has an overload operating error: *error: overloaded 'operator<<' must be a binary operator (has 3 parameters)**** </p>
<pre><code> /Users/Spicycurryman/Desktop/ECS40/hw1/fraction.cpp:61:22: error: overloaded 'operator<<' must be a binary operator (has 3 parameters)
ostream& Fraction::operator<<(ostream &os, Fraction& n)
^
/Users/Spicycurryman/Desktop/ECS40/hw1/fraction.cpp:80:22: error: overloaded 'operator>>' must be a binary operator (has 3 parameters)
istream& Fraction::operator>>(istream &os, Fraction& n)
</code></pre>
<p>I don't understand why that is an error. </p>
<p>My following code is below:</p>
<p><strong>CPP FILE</strong></p>
<pre><code>#include "Fraction.h"
Fraction::Fraction(int a, int b)
{
}
int Fraction::find_gcd (int n1, int n2)
{
int gcd, remainder;
remainder = n1 % n2;
while ( remainder != 0 )
{
n1 = n2;
n2 = remainder;
remainder = n1 % n2;
}
gcd = n2;
return (gcd);
}
void Fraction::reduce_fraction(int nump, int denomp)
{
this->nump = nump;
this->denomp = denomp;
int gcd;
gcd = find_gcd(nump, denomp);
nump = nump / gcd;
denomp = denomp / gcd;
if ((denomp<0 && nump < 0 ))
{
denomp*=-1;
nump*=-1;
}
else if (denomp < 0 && nump >0){
denomp*=-1;
}
if ( denomp ==0) {
throw invalid_argument( "Error: zero denominator" );
}
}
Fraction& Fraction::operator+(const Fraction& n) {
denom = denomp * n.denom;
numera = (nump * n.numera) + (n.denom * n.nump);
return (*this);
}
Fraction& Fraction::operator-(const Fraction& n) {
denom = denomp * n.denom;
numera = (nump * n.numera) - (n.denom* n.nump);
return (*this);
}
ostream& Fraction::operator<<(ostream &os, Fraction& n)
{
if (n.numera == 0)
{
cout << 0 << endl;
return os;
}
else if (n.numera == n.denom)
{
cout << 1 << endl;
return os;
}
else
{
cout << n.numera << '/' << n.denom << endl;
return os;
}
}
istream& Fraction::operator>>(istream &os, Fraction& n)
{
char slash = 0;
return os >> n.numera >> slash >> n.denom;
}
</code></pre>
<p><strong>Header File</strong></p>
<pre><code>#ifndef FRACTION_H
#define FRACTION_H
#include <iostream>
#include <stdexcept>
using namespace std;
class Fraction{
public:
Fraction(int a, int b);
int fraction(int a,int b);
int find_gcd(int n1, int n2);
void reduce_fraction(int nump, int denomp);
Fraction& operator+(const Fraction& n);
Fraction& operator-(const Fraction& n);
friend ostream& operator<<(ostream &os, const Fraction& n);
friend istream& operator>>(istream &is, const Fraction& n);
private:
int denom;
int numera;
int denomp;
int nump;
};
#endif
</code></pre>
<p><strong>MAIN CPP FILE</strong></p>
<pre><code>#include "Fraction.h"
#include <iostream>
using namespace std;
int main()
{
Fraction x(2,3);
Fraction y(6,-2);
cout << x << endl;
cout << y << endl;
cin >> y;
cout << y << endl;
Fraction z = x + y;
cout << x << " + " << y << " = " << z << endl;
}
</code></pre>
<p>I know that the operators are member functions and a member function takes an implicit first parameter, meaning my operators now takes three parameters it may be fixed being a non-member function; however, that would not work in this program. How exactly in my case would I fix it so the program would work? </p>
<p>Thank you very much!</p>
| 0 | 2,036 |
How do I set android:layout_columnWeight="1" programmatically to an element in an android support v7 Gridlayout
|
<p>I'm trying to build a GirdLayout programmatically with 2 columns and I want these columns to have equal width set at half the width of the screen. </p>
<p>I figured out you can do this since API 21 or with the support v7 GirdLayout view. I see examples that uses android:layout_columnWeight="1" to do this. But I can not find how to do this programmatically. </p>
<p>Can anyone help me with this matter?</p>
<pre><code>package com.tunify.v3.component;
import java.util.ArrayList;
import android.support.v7.widget.GridLayout;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ViewGroup;
import com.tunify.asme.data.ChangeableSelectionParameterValue;
public class ChangeableSelectionParameters extends GridLayout{
//private ArrayList<ChangeableSelectionParameterView> selectionParameterViews;
private ArrayList<ChangeableSelectionParameterValue> selectionParameterValues;
private static final int ITEM_PADDING_LEFT_DP = 0;
private static final int ITEM_PADDING_RIGHT_DP = 0;
private static final int ITEM_PADDING_TOP_DP = 0;
private static final int ITEM_PADDING_BOTTOM_DP = 0;
//private static final int MUSICCOLLECTION_DISPLAY_TEXT_SIZE_SP = 15;
public ChangeableSelectionParameters(android.content.Context context, ArrayList<ChangeableSelectionParameterValue> selectionParameterValues) {
super(context);
this.selectionParameterValues = selectionParameterValues;
initializeLayoutBasics(context);
initializeComponents();
}
private void initializeLayoutBasics(android.content.Context context) {
setOrientation(VERTICAL);
setColumnCount(2);
setRowCount((int)Math.ceil(selectionParameterValues.size()/2.0));
int width = ViewGroup.LayoutParams.MATCH_PARENT;
int height = ViewGroup.LayoutParams.WRAP_CONTENT;
android.view.ViewGroup.LayoutParams layoutParams = new android.view.ViewGroup.LayoutParams(width, height);
this.setLayoutParams(layoutParams);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int paddingLeftPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ITEM_PADDING_LEFT_DP, metrics);
int paddingRightPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ITEM_PADDING_RIGHT_DP, metrics);
int paddingTopPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ITEM_PADDING_TOP_DP, metrics);
int paddingBottomPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ITEM_PADDING_BOTTOM_DP, metrics);
setPadding(paddingLeftPx, paddingTopPx, paddingRightPx, paddingBottomPx);
}
private void initializeComponents() {
for(ChangeableSelectionParameterValue param : this.selectionParameterValues){
ChangeableSelectionParameterView v = new ChangeableSelectionParameterView(getContext(), param);
//TODO set views layout column weight to 1
this.addView(v);
}
}
}
</code></pre>
<p>SOLUTION:</p>
<pre><code> GridLayout.LayoutParams parem = new LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 1f), GridLayout.spec(GridLayout.UNDEFINED, 1f));
v.setLayoutParams(parem);
</code></pre>
| 0 | 1,056 |
How to hide <span> value under class
|
<p>How can I hide span value under .fa .fa-search class <a href="http://prntscr.com/fr3vvk" rel="nofollow noreferrer">http://prntscr.com/fr3vvk</a></p>
<pre><code><div role="tabpanel" class="tab-pane fade in active" id="stm_all_listing_tab">
<form action="" method="GET">
<button type="submit" class="heading-font"><i class="fa fa-search"></i> <span>76</span> Lorry </button>
<div class="stm-filter-tab-selects filter stm-vc-ajax-filter">
<div class="row"><div class="col-md-3 col-sm-6 col-xs-12 stm-select-col"><div class="stm-ajax-reloadable"><select name="condition" data-class="stm_select_overflowed" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true"><option value="">Choose Condition</option><option value="new-cars">New (10) </option><option value="rebuild">Rebuild (28) </option><option value="used-cars">Second Hand (38) </option></select><span class="select2 select2-container select2-container--default" dir="ltr" style="width: 141px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-condition-w3-container"><span class="select2-selection__rendered" id="select2-condition-w3-container" title="Choose Condition">Choose Condition</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span></div></div><div class="col-md-3 col-sm-6 col-xs-12 stm-select-col"><div class="stm-ajax-reloadable"><select name="body" data-class="stm_select_overflowed" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true"><option value="">Choose Body</option><option value="box">Box (8) </option><option value="cargo">Cargo (23) </option><option value="crane">Crane (4) </option><option value="flatbed">Flatbed (1) </option><option value="no-body">No-body (2) </option><option value="others">Others (2) </option><option value="roll-on-roll-off">Roll-on-Roll-Off (2) </option><option value="skylift">Skylift (2) </option><option value="tipper">Tipper (22) </option><option value="trailer">Trailer (10) </option></select><span class="select2 select2-container select2-container--default" dir="ltr" style="width: 144px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-body-0d-container"><span class="select2-selection__rendered" id="select2-body-0d-container" title="Choose Body">Choose Body</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span></div></div><div class="col-md-3 col-sm-6 col-xs-12 stm-select-col"><div class="stm-ajax-reloadable"><select name="make" data-class="stm_select_overflowed" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true"><option value="">Choose Brand</option><option value="bison">Bison (0) </option><option value="daihatsu">Daihatsu (16) </option><option value="dong-feng">Dong Feng (0) </option><option value="ford">Ford (0) </option><option value="fuso">Fuso (4) </option><option value="hicom">Hicom (4) </option><option value="hino">Hino (6) </option><option value="inokom-truck">Inokom Truck (1) </option><option value="isuzu">Isuzu (11) </option><option value="jac">JAC (0) </option><option value="jbc">JBC (0) </option><option value="mazda">Mazda (3) </option><option value="mercedes-benz">Mercedes-Benz (0) </option><option value="nissan">Nissan (15) </option><option value="renault">Renault (0) </option><option value="scania">Scania (4) </option><option value="shacman">Shacman (8) </option><option value="suzuki">Suzuki (0) </option><option value="tata">Tata (0) </option><option value="toyota">Toyota (1) </option><option value="ud-trucks">UD Trucks (1) </option><option value="volvo">Volvo (2) </option></select><span class="select2 select2-container select2-container--default" dir="ltr" style="width: 145px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-make-5f-container"><span class="select2-selection__rendered" id="select2-make-5f-container" title="Choose Brand">Choose Brand</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span></div></div><div class="col-md-3 col-sm-6 col-xs-12 stm-select-col"><select class="stm-filter-ajax-disabled-field select2-hidden-accessible" name="max_price" data-class="stm_select_overflowed" tabindex="-1" aria-hidden="true"><option value="">Max Price</option><option value="5000">RM 5 ,000</option><option value="10000">RM 10 ,000</option><option value="15000">RM 15 ,000</option><option value="20000">RM 20 ,000</option><option value="30000">RM 30 ,000</option><option value="40000">RM 40 ,000</option><option value="50000">RM 50 ,000</option><option value="70000">RM 70 ,000</option><option value="80000">RM 80 ,000</option><option value="100000">RM 100 ,000</option></select><span class="select2 select2-container select2-container--default" dir="ltr" style="width: 105px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-max_price-sn-container"><span class="select2-selection__rendered" id="select2-max_price-sn-container" title="Max Price">Max Price</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span></div></div> </div>
</form>
</div>
</code></pre>
| 0 | 3,148 |
Mockito cannot create Spy of @Autowired Spring-Data Repository
|
<p>I am trying to overlay my whole test environment with Mockito.spy functionality so whenever I want i can stub a method but all other calls go to default functionality.
This worked very well with the Service layer but I have problems with the Repository layer.</p>
<p>My setup is as follows:</p>
<p>Mockito - 2.15.0
Spring - 5.0.8
SpringBoot - 2.0.4</p>
<p>Repository:</p>
<pre><code>public interface ARepository extends CrudRepository<ADBO, Long> {}
</code></pre>
<p>Service:</p>
<pre><code>@Service
public class AService {
@Autowired
ARepository aRepository;
public ADBO getById(long id) {
return aRepository.findById(id).orElse(null);
}
public Iterable<ADBO> getAll() {
return aRepository.findAll();
}
}
</code></pre>
<p>The configuration for the spy:</p>
<pre><code>@Profile("enableSpy")
@Configuration
public class SpyConfig {
@Bean
@Primary
public ARepository aRepository() {
return Mockito.spy(ARepository.class);
}
}
</code></pre>
<p>And my test class:</p>
<pre><code>@ActiveProfiles("enableSpy")
@RunWith(SpringRunner.class)
@SpringBootTest
public class AServiceTest {
@Autowired
AService aService;
@Autowired
ARepository aRepository;
@Test
public void test() {
ADBO foo = new ADBO();
foo.setTestValue("bar");
aRepository.save(foo);
doReturn(Optional.of(new ADBO())).when(aRepository).findById(1L);
System.out.println("result (1):" + aService.getById(1));
System.out.println("result all:" + aService.getAll());
}
}
</code></pre>
<p>Now there are three possible outcomes to this test:</p>
<ul>
<li>aRepository is neither a mock nor a spy:<br>
<code>org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of corr...</code></li>
<li><p>aRepository is a mock but not a spy (this is the result I get):<br>
<code>result (1):ADBO(id=null, testValue=null)
result all:[]</code></p></li>
<li><p>aRepository is a spy (this is what I want):<br>
<code>result (1):ADBO(id=null, testValue=null)
result all:[ADBO(id=1, testValue=bar)]</code></p></li>
</ul>
<p>I attribute this behavior to the fact that the spring instantiation of the repository is more complex in the background and the repository is not correctly instantiated when calling <code>Mockito.spy(ARepository.class)</code>.</p>
<p>I have also tried autowireing the proper instance into the Configuration and calling <code>Mockito.spy()</code> with the @Autowired object.</p>
<p>This results in:</p>
<pre><code>Cannot mock/spy class com.sun.proxy.$Proxy75
Mockito cannot mock/spy because :
- final class
</code></pre>
<p>According to my research Mockito can mock and spy final classes since v2.0.0.</p>
<p>Calling <code>Mockito.mockingDetails(aRepository).isSpy()</code> returns <code>true</code> which leads me to think the object in the background was not correctly instantiated.</p>
<p><strong>Finally my question:</strong></p>
<p>How do I get a spy instance of a Spring-Data Repository in my UnitTest with @Autowired?</p>
| 0 | 1,147 |
ListView items are not clickable. why?
|
<p>I have a <code>ListView</code> that uses a customized adapter, but I can't click on the ListView Item ..</p>
<p>Activity for list view ..</p>
<pre><code>package com.adhamenaya.projects;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.adhamenaya.classes.Place;
public class PlacesListActivity extends Activity {
private ArrayList<Place> places;
private ArrayList<String> items;
GridviewAdapter mAdapter;
private ListView lvPlaces;
private EfficientAdapter adap;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.places_list);
lvPlaces = (ListView) this.findViewById(R.id.lvPlaces);
new DowanloadPlaces().execute("");
}
private void bindList(ArrayList<Place> places) {
this.places = places;
// Start creating the list view to show articles
items = new ArrayList<String>();
for (int i = 0; i < places.size(); i++) {
items.add(String.valueOf(places.get(i).mName));
}
adap = new EfficientAdapter(this);
adap.notifyDataSetChanged();
lvPlaces.setAdapter(adap);
}
// EfficientAdapter : to make a customized list view item
public class EfficientAdapter extends BaseAdapter implements Filterable {
// The function of inflater to convert objects from XML layout file (i.e. main.xml) to a programmable
LayoutInflater inflater;
Context context;
public EfficientAdapter(Context context) {
inflater = LayoutInflater.from(context);
this.context = context;
}
public int getCount() {
// Get the number of items in the list
return items.size();
}
public Object getItem(int position) {
// To return item from a list in the given position
return items.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int position, View convertView,ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.adaptor_content, null);
holder = new ViewHolder();// Create an object to hold at components in the list view item
holder.textLine = (TextView) convertView.findViewById(R.id.textLine);
holder.buttonLine = (Button) convertView.findViewById(R.id.buttonLine);
holder.buttonLine.setOnClickListener(new OnClickListener() {
private int pos = position;
public void onClick(View v) {
places.remove(pos);
bindList(places);// to bind list items
Toast.makeText(getApplicationContext(),"Deleted successfuly :)", Toast.LENGTH_LONG).show();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.textLine.setText(String.valueOf(places.get(position).mName));
return convertView;
}
public Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
// ViewHolder : class that represents a list view items
static class ViewHolder {
TextView textLine;
Button buttonLine;
}
// DownloadRSSFeedsTask: works in a separate thread
private class DowanloadPlaces extends AsyncTask<String, Void, ArrayList<Place>> {
@Override
protected ArrayList<Place> doInBackground(String... params) {
ArrayList<Place> places = new ArrayList<Place>();
Place p = new Place();
for(int i =0;i<25;i++){
p.mName = "Al Mathaf Hotel";
places.add(p);
}
return places;
}
@Override
protected void onPostExecute(ArrayList<Place> places) {
bindList(places);
}
}
}
</code></pre>
<p>places_list.xml layout</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lvPlaces">
</ListView>
</LinearLayout>
</code></pre>
<p>adaptor_content.xml layout</p>
<p>
</p>
<p></p>
<p></p>
<pre><code><ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textLine"
android:layout_centerVertical="true"
android:src="@drawable/settings" />
</RelativeLayout>
</code></pre>
| 0 | 2,423 |
read/write an object to file
|
<p>here is the code :
my mission is to serialize an my object(Person) , save it in a file in android(privately), read the file later,(i will get a byte array), and deserialize the byta array. </p>
<pre><code> public void setup()
{
byte[] data = SerializationUtils.serialize(f);
WriteByteToFile(data,filename);
}
Person p =null ;
public void draw()
{
File te = new File(filename);
FileInputStream fin = null;
try {
fin=new FileInputStream(te);
byte filecon[]=new byte[(int)te.length()];
fin.read(filecon);
String s = new String(filecon);
System.out.println("File content: " + s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text(p.a,150,150);
}
</code></pre>
<p>and my function : </p>
<pre><code>public void WriteByteToFile(byte[] mybytes, String filename){
try {
FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
FOS.write(mybytes);
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done");
}
</code></pre>
<p>it is returning a filenotfoundexception .</p>
<p>(i am new at this, so please be patient and understanding)</p>
<p>EDIT ::this is how i am (trying to ) read, (for cerntainly) </p>
<pre><code>ObjectInputStream input = null;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Person myPersonObject = (Person) input.readObject();
text(myPersonObject.a,150,150);
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
</code></pre>
<p>and for reading ::: </p>
<pre><code>if(mousePressed)
{
Person myPersonObject = new Person();
myPersonObject.a=432;
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.writeObject(myPersonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
</code></pre>
| 0 | 1,674 |
Copying from asset folder to SD card
|
<p>I am not sure what is wrong with this code? It creates a file in SD card but with 0 byte..
Can one of you look into it and tell me whats wrong with this?</p>
<p>Here i am trying to copy a file from asset folder which is codes.db to sd card.. </p>
<pre><code> AssetManager assetManager = getResources().getAssets();
InputStream in = null;
OutputStream out = null;
BufferedInputStream buf = null;
try {
in = assetManager.open("codes.db");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error jh: " + e.getMessage());
}
if (in != null) {
try {
out = new FileOutputStream("/sdcard/" + "codes.db");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Error Line : " + e.getLocalizedMessage());
}
}
System.out.println("IN VALUE : " + in);
System.out.println("OUT VALUE : " + out);
int chunkBytes = 0;
byte[] outputByte = new byte[1024];
if (in != null && out != null) {
try {
// while ((chunkBytes = in.read(outputByte, 0, 1024)) != -1) {
while ((chunkBytes = in.read()) != -1) {
// write contents to the file
System.out.println("I m here");
// out.write(outputByte, 0, (int) chunkBytes);
out.write(chunkBytes);
// publish the progress of downloading..
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Error here: "
+ e.getLocalizedMessage().toString());
}
}
try {
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error there: " + e.getLocalizedMessage());
}
}
</code></pre>
<p>I am getting this error in all the case.. i am sure i have my permission set... codes.db in sd card is 0 byte... :(</p>
<pre><code>05-24 09:59:34.221: W/System.err(5559): java.io.IOException
05-24 09:59:34.221: W/System.err(5559): at android.content.res.AssetManager.readAsset(Native Method)
05-24 09:59:34.221: W/System.err(5559): at android.content.res.AssetManager.access$700(AssetManager.java:36)
05-24 09:59:34.221: W/System.err(5559): at android.content.res.AssetManager$AssetInputStream.read(AssetManager.java:571)
05-24 09:59:34.221: W/System.err(5559): at com.bewo.copy.TestCopyActivity.copyStream(TestCopyActivity.java:136)
05-24 09:59:34.221: W/System.err(5559): at com.bewo.copy.TestCopyActivity.onCreate(TestCopyActivity.java:19)
05-24 09:59:34.221: W/System.err(5559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-24 09:59:34.221: W/System.err(5559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2635)
05-24 09:59:34.221: W/System.err(5559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2687)
05-24 09:59:34.221: W/System.err(5559): at android.app.ActivityThread.access$2300(ActivityThread.java:127)
05-24 09:59:34.221: W/System.err(5559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2035)
05-24 09:59:34.221: W/System.err(5559): at android.os.Handler.dispatchMessage(Handler.java:99)
05-24 09:59:34.221: W/System.err(5559): at android.os.Looper.loop(Looper.java:123)
05-24 09:59:34.221: W/System.err(5559): at android.app.ActivityThread.main(ActivityThread.java:4635)
05-24 09:59:34.221: W/System.err(5559): at java.lang.reflect.Method.invokeNative(Native Method)
05-24 09:59:34.221: W/System.err(5559): at java.lang.reflect.Method.invoke(Method.java:521)
05-24 09:59:34.221: W/System.err(5559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-24 09:59:34.221: W/System.err(5559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-24 09:59:34.221: W/System.err(5559): at dalvik.system.NativeStart.main(Native
</code></pre>
| 0 | 1,737 |
MYSQL 5.7 Percona XtraDBCluster - Cant start MYSQL - Digital Ocean Box
|
<p>I rebooted a digital ocean box and now I can't start mysql. When I run start command i get : </p>
<pre><code>Redirecting to /bin/systemctl restart mysql.service
Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details.
</code></pre>
<p>Result of systemctl status mysql.service</p>
<pre><code>● mysql.service - Percona XtraDB Cluster
Loaded: loaded (/usr/lib/systemd/system/mysql.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Mon 2017-12-11 17:08:18 UTC; 5s ago
Process: 26300 ExecStopPost=/usr/bin/mysql-systemd stop-post (code=exited, status=0/SUCCESS)
Process: 26270 ExecStop=/usr/bin/mysql-systemd stop (code=exited, status=2)
Process: 25674 ExecStartPost=/usr/bin/mysql-systemd start-post $MAINPID (code=exited, status=1/FAILURE)
Process: 25673 ExecStart=/usr/bin/mysqld_safe --basedir=/usr (code=exited, status=0/SUCCESS)
Process: 25632 ExecStartPre=/usr/bin/mysql-systemd start-pre (code=exited, status=0/SUCCESS)
Main PID: 25673 (code=exited, status=0/SUCCESS)
Dec 11 17:08:18 server-name-hidden mysql-systemd[25674]: ERROR! mysqld_safe with PID 25673 has already exited: FAILURE
Dec 11 17:08:18 server-name-hidden systemd[1]: mysql.service: control process exited, code=exited status=1
Dec 11 17:08:18 server-name-hidden mysql-systemd[26270]: WARNING: mysql pid file /var/run/mysqld/mysqld.pid empty or not readable
Dec 11 17:08:18 server-name-hidden mysql-systemd[26270]: ERROR! mysql already dead
Dec 11 17:08:18 server-name-hidden systemd[1]: mysql.service: control process exited, code=exited status=2
Dec 11 17:08:18 server-name-hidden mysql-systemd[26300]: WARNING: mysql pid file /var/run/mysqld/mysqld.pid empty or not readable
Dec 11 17:08:18 server-name-hidden mysql-systemd[26300]: WARNING: mysql may be already dead
Dec 11 17:08:18 server-name-hidden systemd[1]: Failed to start Percona XtraDB Cluster.
Dec 11 17:08:18 server-name-hidden systemd[1]: Unit mysql.service entered failed state.
Dec 11 17:08:18 server-name-hidden systemd[1]: mysql.service failed.
</code></pre>
<p>/var/run/mysqld/ is owned by mysql user - but it's empty. If i add a mysqld.pid file it gets removed when i run mysql start.</p>
<p>Does anyone know why a reboot would cause this or give me any next steps. I have reviewed the mysqld.log file and can't see anything of use. here are the last 30 lines </p>
<pre><code>017-12-11T15:14:42.473164Z 0 [Note] WSREP: Received shutdown signal. Will sleep for 10 secs before initiating shutdown. pxc_maint_mode switched to SHUTDOWN
2017-12-11T15:14:52.474584Z 0 [Note] WSREP: Stop replication
2017-12-11T15:14:52.474691Z 0 [Note] WSREP: Closing send monitor...
2017-12-11T15:14:52.475160Z 0 [Note] WSREP: Closed send monitor.
2017-12-11T15:14:52.475268Z 0 [Note] WSREP: gcomm: terminating thread
2017-12-11T15:14:52.475305Z 0 [Note] WSREP: gcomm: joining thread
2017-12-11T15:14:52.475886Z 0 [Note] WSREP: gcomm: closing backend
2017-12-11T15:14:52.476079Z 0 [Note] WSREP: Current view of cluster as seen by this node
2017-12-11T15:14:52.476491Z 0 [Note] WSREP: gcomm: closed
2017-12-11T15:14:52.476532Z 0 [Note] WSREP: Received self-leave message.
2017-12-11T15:14:52.476559Z 0 [Note] WSREP: Flow-control interval: [0, 0]
2017-12-11T15:14:52.476595Z 0 [Note] WSREP: Trying to continue unpaused monitor
2017-12-11T15:14:52.476602Z 0 [Note] WSREP: Received SELF-LEAVE. Closing connection.
2017-12-11T15:14:52.476608Z 0 [Note] WSREP: Shifting SYNCED -> CLOSED (TO: 13842228)
2017-12-11T15:14:52.476632Z 0 [Note] WSREP: RECV thread exiting 0: Success
2017-12-11T15:14:52.477098Z 0 [Note] WSREP: recv_thread() joined.
2017-12-11T15:14:52.477110Z 0 [Note] WSREP: Closing replication queue.
2017-12-11T15:14:52.477116Z 0 [Note] WSREP: Closing slave action queue.
2017-12-11T15:14:52.477123Z 0 [Note] Giving 63 client threads a chance to die gracefully
2017-12-11T15:14:52.478905Z 0 [Warning] /usr/sbin/mysqld: Forcing close of thread 21 user: ‘hidden’
2017-12-11T15:14:52.478957Z 0 [Warning] /usr/sbin/mysqld: Forcing close of thread 22 user: 'hidden'
2017-12-11T15:14:52.478994Z 0 [Warning] /usr/sbin/mysqld: Forcing close of thread 6387 user: 'hidden'
2017-12-11T15:14:52.479034Z 0 [Warning] /usr/sbin/mysqld: Forcing close of thread 6367 user: 'hidden'
2017-12-11T15:14:52.479084Z 0 [Warning] /usr/sbin/mysqld: Forcing close of thread 6373 user: 'hidden'
2017-12-11T15:14:52.479130Z 0 [Warning] /usr/sbin/mysqld: Forcing close of thread 6368 user: 'hidden'
2017-12-11T15:14:54.479289Z 0 [Note] WSREP: Waiting for active wsrep applier to exit
</code></pre>
<p>I've also been told to try : systemctl start mysql@bootstrap however this fails with the same error. here is the result from journalctl -xe</p>
<pre><code>Dec 11 17:24:58 dropletname systemd[1]: mysql@bootstrap.service: control process exited, code=exited status=1
Dec 11 17:24:58 dropletname mysql-systemd[28663]: WARNING: mysql pid file /var/run/mysqld/mysqld.pid empty or not readable
Dec 11 17:24:58 dropletname mysql-systemd[28663]: ERROR! mysql already dead
Dec 11 17:24:58 dropletname systemd[1]: mysql@bootstrap.service: control process exited, code=exited status=2
Dec 11 17:24:58 dropletname mysql-systemd[28694]: WARNING: mysql pid file /var/run/mysqld/mysqld.pid empty or not readable
Dec 11 17:24:58 dropletname mysql-systemd[28694]: WARNING: mysql may be already dead
Dec 11 17:24:58 dropletname systemd[1]: Failed to start Percona XtraDB Cluster with config /etc/sysconfig/mysql.bootstrap.
Dec 11 17:24:58 dropletname systemd[1]: Unit mysql@bootstrap.service entered failed state.
Dec 11 17:24:58 dropletname systemd[1]: mysql@bootstrap.service failed.
Dec 11 17:24:58 dropletname polkitd[510]: Unregistered Authentication Agent for unix-process:28009:649814 (system bus name :1.159, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_GB.UTF-8) (disconnected from bus)
Dec 11 17:25:02 dropletname sendmail[27970]: unable to qualify my own domain name (dropletname) -- using short name
Dec 11 17:25:02 dropletname sendmail[27970]: vBBHP2cx027970: from=hidden, size=1655, class=-60, nrcpts=1, msgid=<201712111725.vBBHP2cx027970@dropletname>, relay=hidden@localhost
Dec 11 17:25:02 dropletname sendmail[28728]: vBBHP26v028728: from=<hidden@dropletname>, size=1935, class=-60, nrcpts=1, msgid=<201712111725.vBBHP2cx027970@dropletname>, proto=ESMTP, daemon=MTA, relay=dropletname [127.0.0.1]
Dec 11 17:25:02 dropletname sendmail[27970]: vBBHP2cx027970: to=hidden, ctladdr=hidden (1000/1000), delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=139655, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (vBBHP26v028728 Message accepted for del
Dec 11 17:25:02 dropletname sendmail[28729]: vBBHP26v028728: to=<hidden@dropletname>, ctladdr=<hidden@dropletname> (1000/1000), delay=00:00:00, xdelay=00:00:00, mailer=local, pri=140148, dsn=2.0.0, stat=Sent
Dec 11 17:25:02 dropletname systemd[1]: Removed slice User Slice of hidden
</code></pre>
<p>ps aux|grep mysql </p>
<pre><code>root 11590 0.0 0.0 107924 608 pts/0 T 15:43 0:00 cat /var/log/mysqld.log
root 24666 0.0 0.0 107924 612 pts/0 T 16:52 0:00 cat /var/log/mysqld.log
root 32182 0.0 0.0 112664 972 pts/2 S+ 17:59 0:00 grep --color=auto mysq
</code></pre>
| 0 | 2,780 |
Android: How to run asynctask from different class file?
|
<p>When I use my code in one class file, it runs perfectly:</p>
<pre><code>package com.example.downloadfile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class DownloadFile extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
private static String fileName = "yo.html";
private static String fileURL = "http://example.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("This is download file program with asynctask... ");
tv.append("\nYo, this line is appended!");
startDownload();
}
private void startDownload() {
new DownloadFileAsync().execute(fileURL);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
try {
File root = Environment.getExternalStorageDirectory();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
</code></pre>
<p>I want to run the asyntask I have from a different class file, I have my code:</p>
<p><strong>DownloadFile.java</strong></p>
<pre><code>package com.example.downloadfile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class DownloadFile extends Activity {
private static String fileName = "yo.html";
private static String fileURL = "http://example.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("This is download file program with asynctask... ");
tv.append("\nYo, this line is appended!");
startDownload();
}
private void startDownload() {
new DownloadFileAsync().execute(fileURL);
}
}
</code></pre>
<p><strong>DownloadFileAsync.java</strong></p>
<pre><code>package com.example.downloadfile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
class DownloadFileAsync extends AsyncTask<String, String, String> {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
try {
File root = Environment.getExternalStorageDirectory();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
}
</code></pre>
<p>I'm using eclipse and I'm getting errors in my DownloadFile.java file, there are many red underlined codes.... I'm new to java and android dev.</p>
| 0 | 3,308 |
RecyclerView with Fragments
|
<p>I am trying to use the new <code>RecyclerView</code> widget inside a <code>Fragment</code> but I am getting this error: </p>
<blockquote>
<p>Unable to start activity
ComponentInfo{com.example.myapplication/com.example.myapplication.MyActivity}:
java.lang.NullPointerException: Attempt to invoke interface method
'boolean java.util.List.add(java.lang.Object)' on a null object
reference</p>
</blockquote>
<p>What am I doing wrong?</p>
<p>This is my <code>Fragment</code>:</p>
<pre><code>import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
public class RecyclerviewFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerviewAdapter mRecyclerviewAdapter;
private LinearLayoutManager mLinearLayoutManager;
private List<ViewModel> viewModel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recyclerview, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mRecyclerviewAdapter = new RecyclerviewAdapter(viewModel);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setAdapter(mRecyclerviewAdapter);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
}
</code></pre>
<p>And my Activity:</p>
<pre><code>import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.List;
public class MyActivity extends Activity {
private List<ViewModel> viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
RecyclerviewFragment recyclerviewFragment = new RecyclerviewFragment();
getFragmentManager().beginTransaction().add(android.R.id.content, recyclerviewFragment).commit();
viewModel.add(new ViewModel("View"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>Thanks!</p>
| 0 | 1,198 |
java.lang.OutOfMemoryError BitmapFactory.nativeDecodeAsset()
|
<p>Hi i am creating an app about traffic signs. traffic signs are in .png format. some of them I am showing in horizontalscrollview. But when try to open activities , I get this error from android market error reports. here is my error report:</p>
<pre><code><java.lang.RuntimeException: Unable to start activity ComponentInfo{com.besalti.svenskavagmarken/com.besalti.svenskavagmarken.varningsmarken}: android.view.InflateException: Binary XML file line #645: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #645: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:518)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:227)
at android.app.Activity.setContentView(Activity.java:1657)
at com.besalti.svenskavagmarken.varningsmarken.onCreate(varningsmarken.java:25)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
... 11 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
at android.view.LayoutInflater.createView(LayoutInflater.java:505)
... 26 more
Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:494)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:370)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:715)
at android.content.res.Resources.loadDrawable(Resources.java:1720)
at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
at android.widget.ImageView.<init>(ImageView.java:122)
at android.widget.ImageView.<init>(ImageView.java:112)
... 29 more>
</code></pre>
<p>can anyone help me?</p>
| 0 | 1,161 |
How to fix ambiguous mapping methods
|
<p>I'm doing an experiment with jHipster.</p>
<p>I have created two entities A and B backed by DTO (mapstruct).
There is a many-to-many relationship between them.
They both also have a many-to-one relationship with the user.</p>
<p>Up until creating the last relationship, everything works fine.
After creating the last many-to-one relationship, I get the following error:</p>
<pre><code>[INFO] --- maven-processor-plugin:2.2.4:process (process) @ m2m ---
[ERROR] diagnostic: /Users/andy/jhipster-m2m/src/main/java/com/m2m/web/rest/mapper/AMapper.java:18: error: Ambiguous mapping methods found for mapping property "java.lang.Long userId" to com.m2m.domain.User: com.m2m.domain.User userFromId(java.lang.Long id), com.m2m.domain.User com.m2m.web.rest.mapper.BMapper.userFromId(java.lang.Long id).
A aDTOToA(ADTO aDTO);
^
[ERROR] error on execute: error during compilation
</code></pre>
<p>The definitions are very straightforward:
For A:</p>
<pre><code>{
"relationships": [
{
"relationshipId": 1,
"relationshipName": "b",
"otherEntityName": "b",
"relationshipType": "many-to-many",
"otherEntityField": "id",
"ownerSide": true
},
{
"relationshipId": 2,
"relationshipName": "user",
"otherEntityName": "user",
"relationshipType": "many-to-one",
"otherEntityField": "id"
}
],
"fields": [
{
"fieldId": 1,
"fieldName": "nameA",
"fieldType": "String"
}
],
"changelogDate": "20150909165353",
"dto": "mapstruct",
"pagination": "no"
</code></pre>
<p>}</p>
<p>For B:</p>
<pre><code>{
"relationships": [
{
"relationshipId": 1,
"relationshipName": "a",
"otherEntityName": "a",
"relationshipType": "many-to-many",
"ownerSide": false,
"otherEntityRelationshipName": "b"
},
{
"relationshipId": 2,
"relationshipName": "user",
"otherEntityName": "user",
"relationshipType": "many-to-one",
"otherEntityField": "id"
}
],
"fields": [
{
"fieldId": 1,
"fieldName": "nameB",
"fieldType": "String"
}
],
"changelogDate": "20150909165433",
"dto": "mapstruct",
"pagination": "no"
</code></pre>
<p>}</p>
<p>I'm really stuck on this.
Any help is very much appreciated!!</p>
<p>EDIT: Providing github repo that demonstrates the problem <a href="https://github.com/andyverbunt/jhipster-m2m.git" rel="nofollow">https://github.com/andyverbunt/jhipster-m2m.git</a></p>
| 0 | 1,082 |
Django Rest Framework ImageField
|
<p>I can not save the image in this ImageField.</p>
<p><strong>when sending data back:</strong></p>
<pre><code>{
"image": ["No file was submitted. Check the encoding type on the form."]
}
</code></pre>
<p><strong>model.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class MyPhoto(models.Model):
owner = models.ForeignKey('auth.User', related_name='image')
image = models.ImageField(upload_to='photos', max_length=254)
</code></pre>
<p><strong>serializers.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class PhotoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MyPhoto
fields = ('url', 'id', 'image', 'owner')
owner = serializers.Field(source='owner.username')
</code></pre>
<p><strong>view.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class PhotoList(APIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
def get(self, request, format=None):
photo = MyPhoto.objects.all()
serializer = PhotoSerializer(photo, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
def post(self, request, format=None):
serializer = PhotoSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def pre_save(self, obj):
obj.owner = self.request.user
class PhotoDetail(APIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
def get_object(self, pk):
try:
return MyPhoto.objects.get(pk=pk)
except MyPhoto.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
photo = self.get_object(pk)
serializer = PhotoSerializer(photo)
return Response(serializer.data)
def put(self, request, pk, format=None):
photo = self.get_object(pk)
serializer = PhotoSerializer(photo, data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
photo = self.get_object(pk)
photo.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
def pre_save(self, obj):
obj.owner = self.request.user
</code></pre>
<p><strong>url.py</strong></p>
<pre class="lang-py prettyprint-override"><code>urlpatterns = patterns('',
url(r'^$', 'main.views.main_page'),
url(r'^api/photo/$', views.PhotoList.as_view(), name='myphoto-list'),
url(r'^api/photo/(?P<pk>[0-9]+)/$', views.PhotoDetail.as_view(), name='myphoto-detail'),)
</code></pre>
<p><strong>curl</strong></p>
<pre><code>curl -X POST -S \
-H 'Content-Type: application/json' \
-u "michael:bush_pass" \
--data-binary '{"owner":"/users/1/", \
"image":"/Users/test/Downloads/1383310998_05.jpg"}' \
127.0.0.1:8000/api/photo/
</code></pre>
| 0 | 1,288 |
Angular 2 - Unexpected Module declared by AppModule
|
<p>I am new to angular and trying to separate my modules in Angular2 app having the following directory structure.</p>
<p>I have my module and other components declared in the AppModule, but I am getting an error in browser console that <code>Unexpected HomeModule declared by AppModule</code></p>
<pre><code>app
--authentication
---- htmls, ts, css
--home
----dashboard
--------html, ts, css
----representativs
--------html, ts, css
----home-routing.module.ts
----home.module.ts
--app.routing.ts
--app.module.ts
</code></pre>
<p>app.module.ts</p>
<pre><code>import { routing } from "./app.routing"
import { AppComponent } from './app.component';
import { HomeModule } from "./home/home.module";
@NgModule({
imports: [BrowserModule, routing, HttpModule, ReactiveFormsModule],
declarations: [ AppComponent, HomeModule],
bootstrap: [AppComponent],
providers: [UserAuthenticationService]
})
export class AppModule { }
</code></pre>
<p>home.module.ts</p>
<pre><code>import { NgModule } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { RepresentativesComponent } from './representatives/representatives.component';
import { HomeRoutingModule } from "./home-routing.module";
@NgModule({
imports: [
HomeRoutingModule
],
declarations: [
DashboardComponent,
RepresentativesComponent,
]
})
export class HomeModule { }
</code></pre>
<p>home-routing.ts</p>
<pre><code>const homeRoutes: Routes = [
{
path: 'home',
component: HomeComponent,
children: [
{
path: "representatives",
component: RepresentativesComponent
},
{
path: "dashboard",
component: DashboardComponent
},
{
path: "",
redirectTo: "dashboard",
pathMatch: "full"
}
]
}
]
@NgModule({
imports: [
RouterModule.forChild(homeRoutes)
],
exports: [
RouterModule
]
})
export class HomeRoutingModule { }
</code></pre>
<p>app.routing.ts</p>
<pre><code>import { AuthenticationComponent } from "./authentication/authentication.component";
import { HomeComponent } from "./home/home.component";
const routes: Routes = [
{
path: 'auth/:action',
component: AuthenticationComponent
},
{
path: 'auth',
redirectTo: 'auth/signin',
pathMatch: 'prefix'
},
{
path: '',
redirectTo: 'home',
component: HomeComponent
}
]
export const routing = RouterModule.forRoot(routes);
</code></pre>
| 0 | 1,089 |
Node.js mysql error cannot read property of undefined?
|
<p>I have a program that inserts SMDR data into a database as it comes in.</p>
<p>Here is my code:</p>
<pre><code>var net = require('net'),
mysql = require('mysql'),
PORT = 1752,
HOST = '192.168.10.2',
pool = mysql.createPool({
host: 'localhost',
port: 3307,
user: 'root',
password: 'root',
database: 'mydb'
});
function connectionListener(conn) {
console.log('Listening for incoming calls...');
}
function logCall(phonenumber, operator) {
pool.getConnection(function(err, connection) {
if (!err) { // If no error exists
var opquery = connection.query('SELECT OperatorID FROM tblOperators WHERE Phone_Login = ' + operator, function(err, rows) {
if (err) {
console.error(err);
connection.release();
return;
}
var query = connection.query('INSERT INTO incoming_calls(phone_number, OperatorID) VALUES("' +
phonenumber + '", "' + rows[0].OperatorID + '") ON DUPLICATE KEY UPDATE OperatorID=OperatorID, date_created=NOW()', function(err, rows) {
if (err) {
console.error(err);
}
connection.release();
});
});
} else {
console.error(err);
}
});
}
function processdata(data) {
var phonedata = data.toString().match(/([0-9]?)([0-9]{10})/),
operdata = data.toString().match(/([*])([0-9]{4})/);
if (phonedata !== null && operdata !== null) {
var phonenumber = phonedata[2],
oper = operdata[2];
oper = oper.replace('*', '');
phonenumber = phonenumber.slice(0,3)+"-"+phonenumber.slice(3,6)+"-"+phonenumber.slice(6);
logCall(phonenumber, oper);
}
}
logCall('999-999-9999', '1203');
var conn = net.createConnection(PORT, HOST, connectionListener);
conn.on('data', processdata);
conn.setEncoding('utf8');
</code></pre>
<p>And here is the error that I get, when OperatorID clearly does exist within the table:</p>
<pre><code>c:\xampp\htdocs>node listener
Listening for incoming calls...
c:\xampp\htdocs\node_modules\mysql\lib\protocol\Parser.js:82
throw err;
^
TypeError: Cannot read property 'OperatorID' of undefined
at Query._callback (c:\xampp\htdocs\listener.js:27:48)
at Query.Sequence.end (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Sequence.js:96:24)
at Query._handleFinalResultPacket (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Query.js:143:8)
at Query.EofPacket (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Query.js:127:8)
at Protocol._parsePacket (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Protocol.js:271:23)
at Parser.write (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Parser.js:77:12)
at Protocol.write (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (c:\xampp\htdocs\node_modules\mysql\lib\Connection.js:82:28)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:764:14)
</code></pre>
<p>Does anyone have any ideas as to why this would happen, I have a production database that uses this, has the same exact information and it works?</p>
| 0 | 1,509 |
Making a button do something on Arduino TFT touchscreen
|
<p>so I have an Arduino MEGA2560 and a TFT shield touchscreen. I used one of the examples to make 2 buttons to display on screen, by just using <code>drawRect()</code>. But how do I make these 2 boxes do something when I press them? I know the coordinates for these 2 boxes, so how do I make them "sense" the touch and transist into another screen of display? Maybe a example of code would be great help! thanks.</p>
<p>My current code is below: you could add the necessary parts to it.</p>
<pre><code>#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library
#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0
#define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin
#define BLACK 0x0000
#define BLUE 0x001F
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
void setup(void) {
Serial.begin(9600);
progmemPrintln(PSTR("TFT LCD"));
#ifdef USE_ADAFRUIT_SHIELD_PINOUT
progmemPrintln(PSTR("Using Adafruit 2.8\" TFT Arduino Shield Pinout"));
#else
progmemPrintln(PSTR("Using Adafruit 2.8\" TFT Breakout Board Pinout"));
#endif
tft.reset();
uint16_t identifier = tft.readID();
if(identifier == 0x9325) {
progmemPrintln(PSTR("Found ILI9325 LCD driver"));
} else if(identifier == 0x9328) {
progmemPrintln(PSTR("Found ILI9328 LCD driver"));
} else if(identifier == 0x7575) {
progmemPrintln(PSTR("Found HX8347G LCD driver"));
} else {
progmemPrint(PSTR("Unknown LCD driver chip: "));
Serial.println(identifier, HEX);
progmemPrintln(PSTR("If using the Adafruit 2.8\" TFT Arduino shield, the line:"));
progmemPrintln(PSTR(" #define USE_ADAFRUIT_SHIELD_PINOUT"));
progmemPrintln(PSTR("should appear in the library header (Adafruit_TFT.h)."));
progmemPrintln(PSTR("If using the breakout board, it should NOT be #defined!"));
progmemPrintln(PSTR("Also if using the breakout, double-check that all wiring"));
progmemPrintln(PSTR("matches the tutorial."));
return;
}
tft.begin(identifier);
progmemPrint(PSTR("Text "));
Serial.println(startText());
delay(0);
progmemPrintln(PSTR("Done!"));
}
void loop(void) {
startText();
delay(9999999);
}
unsigned long startText() {
tft.fillScreen(BLACK);
unsigned long start = micros();
tft.setCursor(0, 0);
tft.println();
tft.println();
tft.setTextColor(GREEN); tft.setTextSize(2.8);
tft.println("Welcome ");
tft.println();
tft.setTextColor(WHITE); tft.setTextSize(2.5);
tft.println();
tft.drawRect(5, 150, 110, 110, YELLOW);
tft.drawRect(130, 150, 110, 110, RED);
tft.setCursor(155, 170);
tft.setTextColor(RED);
tft.println("OFF");
tft.fillRect(5, 150, 110, 110, YELLOW);
tft.fillRect(13, 158, 94, 94, BLACK);
tft.setTextColor(GREEN);
tft.setCursor(20, 170);
tft.println("ON");
return micros() - start;
}
// Copy string from flash to serial port
// Source string MUST be inside a PSTR() declaration!
void progmemPrint(const char *str) {
char c;
while(c = pgm_read_byte(str++)) Serial.print(c);
}
// Same as above, with trailing newline
void progmemPrintln(const char *str) {
progmemPrint(str);
Serial.println();
}
</code></pre>
| 0 | 1,333 |
Passing screenProps to a tab navigator
|
<p><strong>Background</strong></p>
<p>I have a root component that controls the views of 2 components. I am conditionally rendering these components. </p>
<p>I am passing <code>screenProps</code> to these 2 components so I can expose a <code>function</code> from the root components. </p>
<p>When component 1 is rendered it takes the <code>screenProps</code> perfectly. But component 2 is actually controlled by a <code>tabNavigator</code>. So when it is loaded, it is the default component in the <code>tabNavigator</code> which ends up being <code>Login</code>.</p>
<p>I want to pass the <code>screenProps</code> down multiple components or in other words give access to a function from root in the <code>Login</code> component, which is a component that is loaded through the <code>TabNavigator</code>. </p>
<p><strong>Example</strong></p>
<pre><code><Secure screenProps={{ login: () => this.setState:({ secure: false }) }} />
<Public screenProps={{ login: () => this.setState:({ secure: true }) }} />
Secure takes the component fine. But the screenProps is called inside of the actual Secure component. The Public component has a TabNavigator. So when I pass screenProps to Public the components loaded via the TabNavigator do not have access to the screen props.
</code></pre>
<p><strong>Question</strong></p>
<p>How do I pass <code>screenProps</code> to the children of <code>Public</code> which are loaded through a <code>TabNavigator</code>?</p>
<p><strong>Code</strong></p>
<p>Component that calls the <code>TabNavigator</code></p>
<pre><code>const Public = props => (
<View style={styles.container}>
{/* <Header
headerStyle={StyleSheet.flatten(styles.headerColor)}
headerTitle="wunO"
/> */}
<BottomTabNav /* screenProps past here! */ />
</View>
);
</code></pre>
<p><code>LoginComponent</code> which is loaded when tab is clicked from the <code>PublicComponent</code>.</p>
<pre><code> async getToken() {
try {
const tokenKey = 'WUNO-TOKEN';
const token = await AsyncStorage.getItem(tokenKey, (err) => {
if (err) {
throw err;
}
this.props.screenProps.login();
});
return token;
} catch (e) {
throw e;
}
</code></pre>
<p>}</p>
<p>So all together,</p>
<p><strong>Main Component</strong></p>
<pre><code><Public screenProps={{ login: () => this.setState({ secure: true }) }} />
</code></pre>
<p><strong>Public Component</strong></p>
<pre><code><BottomTabNav screenProps={props.screenProps.login} />
</code></pre>
<p><strong>Login Component</strong></p>
<pre><code>this.props.screenProps.login();
</code></pre>
<p>This throws the error,</p>
<blockquote>
<p>Cannot read property 'login of undefined</p>
</blockquote>
| 0 | 1,082 |
Add Header and Footer for PDF using iTextsharp
|
<p>How can I add header and footer for each page in the pdf.</p>
<p>Headed will contain just a text
Footer will contain a text and pagination for pdf (Page : 1 of 4)</p>
<p>How is this possible ? I tried to add the below line, but header does not show up in pdf.</p>
<pre><code>document.AddHeader("Header", "Header Text");
</code></pre>
<p>This the code I am using for generation PDF :</p>
<pre><code> protected void GeneratePDF_Click(object sender, EventArgs e)
{
DataTable dt = getData();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Locations.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Document document = new Document();
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.COURIER , 8);
PdfPTable table = new PdfPTable(dt.Columns.Count);
PdfPRow row = null;
float[] widths = new float[] { 6f, 6f, 2f, 4f, 2f };
table.SetWidths(widths);
table.WidthPercentage = 100;
int iCol = 0;
string colname = "";
PdfPCell cell = new PdfPCell(new Phrase("Locations"));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, font5));
}
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), font5));
table.AddCell(new Phrase(r[1].ToString(), font5));
table.AddCell(new Phrase(r[2].ToString(), font5));
table.AddCell(new Phrase(r[3].ToString(), font5));
table.AddCell(new Phrase(r[4].ToString(), font5));
}
}
document.Add(table);
document.Close();
Response.Write(document);
Response.End();
}
}
</code></pre>
| 0 | 1,070 |
How to convert the Long value to String using sql
|
<p>I am doing a long to string conversion using java in following way.</p>
<pre><code>Long longValue = 367L;
String str = Long.toString(longValue, 36).toUpperCase();
</code></pre>
<p>this is returning me as value A7. how can achieve this in doing oracle sql.</p>
<p>UPDATED:</p>
<p>Hi, I have analyzed how java code is working then wanted to implement the same thing in procedure. </p>
<p>First point is Input vaues. LONG and Radix. in my case Radix is 36. so i will have values from 1..9A...Z0 It picks up the values from this set only.
Second point Long value as input. we have to divide this value with radix. if the quotient is more than 36 again we need to divide.</p>
<p>For eaxmple 367 then my converted value is 10(quotient) 7(remainder) that is A7.
3672 converted value is 102 0 i need to do again for 102 that is 2 -6 so my final value will be 2-6 0 that is 2U0(- means reverse the order).</p>
<p>UPDATE 2:</p>
<p>Using oracle built in functions we can do this. this was solved by my friend and gave me a function.I want to thank my friend. this will give me an out put as follows.</p>
<p>367 then my converted value is 10(quotient) 7(remainder) that is *A*7.(I modified this to my requirement).</p>
<pre><code>FUNCTION ENCODE_STRING(BASE_STRING IN VARCHAR2,
FROM_BASE IN NUMBER,
TO_BASE IN NUMBER)
RETURN VARCHAR2
IS
V_ENCODED_STRING VARCHAR(100);
BEGIN
WITH N1 AS (
SELECT SUM((CASE
WHEN C BETWEEN '0' AND '9'
THEN TO_NUMBER(C)
ELSE
ASCII(C) - ASCII('A') + 10
END) * POWER(FROM_BASE, LEN - RN)
) AS THE_NUM
FROM (SELECT SUBSTR(BASE_STRING, ROWNUM, 1) C, LENGTH(BASE_STRING) LEN, ROWNUM RN
FROM DUAL
CONNECT BY ROWNUM <= LENGTH(BASE_STRING))
),
N2 AS (
SELECT (CASE
WHEN N < 10
THEN TO_CHAR(N)
ELSE CHR(ASCII('A') + N - 10)
END) AS DIGI, RN
FROM (SELECT MOD(TRUNC(THE_NUM/POWER(TO_BASE, ROWNUM - 1)), TO_BASE) N, ROWNUM RN
FROM N1
CONNECT BY ROWNUM <= TRUNC(LOG(TO_BASE, THE_NUM)) + 1)
)
SELECT SYS_CONNECT_BY_PATH(DIGI, '*') INTO V_ENCODED_STRING
FROM N2
WHERE RN = 1
START WITH RN = (SELECT MAX(RN) FROM N2)
CONNECT BY RN = PRIOR RN - 1;
RETURN V_ENCODED_STRING;
</code></pre>
| 0 | 1,498 |
JPA 1.0 error: The name is not a recognized entity or identifier. Known entity names: []
|
<p>I am getting following exception while I try to execute simple JPA 1.0 code.
What may be the cause?</p>
<pre><code>5453 DevPQRWDPBSSPersist WARN [P=351601:O=0:CT] openjpa.Enhance - This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: "[class com.XYZ.PQR.bss.client.db.data.markerentry, class com.XYZ.PQR.bss.client.db.data.Serviceproduct, class com.XYZ.PQR.bss.client.db.data.Agreementterms, class com.XYZ.PQR.bss.client.db.data.Offeringattribute, class com.XYZ.PQR.bss.client.db.data.marker, class com.XYZ.PQR.bss.client.db.data.OfferingpriceadjustmentrelPK, class com.XYZ.PQR.bss.client.db.data.Serviceoffering, class com.XYZ.PQR.bss.client.db.data.Offeringassociation, class com.XYZ.PQR.bss.client.db.data.OfferingpriceserviceofferingrelPK, class com.XYZ.PQR.bss.client.db.data.Offer, class com.XYZ.PQR.bss.client.db.data.Offeringpriceadjustmentrel, class com.XYZ.PQR.bss.client.db.data.Offeringfamily, class com.XYZ.PQR.bss.client.db.data.Offeringpriceserviceofferingrel, class com.XYZ.PQR.bss.client.db.data.Serviceproductattribute, class com.XYZ.PQR.bss.client.db.data.Offeringprice, class com.XYZ.PQR.bss.client.db.data.Agreement]".
6563 DevPQRWDPBSSPersist TRACE [P=351601:O=0:CT] openjpa.jdbc.SQL - <t 1183336072, conn 944453707> executing prepstmnt 152307988 SELECT so.* from DB2INST1.SERVICEOFFERING so where so.ISDELETED = 0 and so.id in (select oa.SERVICEOFFERINGID from DB2INST1.OFFERINGATTRIBUTE oa where oa.SERVICEOFFERINGID = so.id AND oa.name = ? and oa.STRINGVALUE = ? and oa.ISDELETED = 0) [params=(String) productbundleid, (String) attrValue]
7281 DevPQRWDPBSSPersist TRACE [P=351601:O=0:CT] openjpa.jdbc.SQL - <t 1183336072, conn 944453707> [718 ms] spent
Exception in thread "P=351601:O=0:CT" <openjpa-1.2.1-SNAPSHOT-r422266:686069 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter "SELECT OBJECT(attr) FROM Offeringattribute attr WHERE attr.serviceofferingid IN (:OfferingIds) AND attr.isdeleted = 0". Error message: The name "Offeringattribute" is not a recognized entity or identifier. Known entity names: []
at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.parseException(AbstractExpressionBuilder.java:118)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getClassMetaData(JPQLExpressionBuilder.java:180)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.resolveClassMetaData(JPQLExpressionBuilder.java:150)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:225)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:195)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateType(JPQLExpressionBuilder.java:188)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.access$600(JPQLExpressionBuilder.java:69)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.populate(JPQLExpressionBuilder.java:1756)
at org.apache.openjpa.kernel.jpql.JPQLParser.populate(JPQLParser.java:56)
at org.apache.openjpa.kernel.ExpressionStoreQuery.populateFromCompilation(ExpressionStoreQuery.java:153)
at org.apache.openjpa.kernel.QueryImpl.newCompilation(QueryImpl.java:658)
at org.apache.openjpa.kernel.QueryImpl.compilationFromCache(QueryImpl.java:639)
at org.apache.openjpa.kernel.QueryImpl.compileForCompilation(QueryImpl.java:605)
at org.apache.openjpa.kernel.QueryImpl.compileForExecutor(QueryImpl.java:667)
at org.apache.openjpa.kernel.QueryImpl.getOperation(QueryImpl.java:1492)
at org.apache.openjpa.kernel.DelegatingQuery.getOperation(DelegatingQuery.java:123)
at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:243)
at org.apache.openjpa.persistence.QueryImpl.getResultList(QueryImpl.java:293)
at com.XYZ.PQR.bss.client.offering.impl.OfferingServiceImpl.getOfferingsByStringAttribute(OfferingServiceImpl.java:661)
at com.XYZ.PQR.bss.marker.impl.testAks.testAPI(testAks.java:38)
at com.XYZ.PQR.bss.marker.impl.testAks.main(testAks.java:24)
<properties>
<property name="openjpa.ConnectionDriverName" value="com.XYZ.db2.jcc.DB2Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:db2://xyz.com:50000/ABC"/>
<property name="openjpa.ConnectionUserName" value="usr"/>
<property name="openjpa.ConnectionPassword" value="pwd"/>
<property name="openjpa.jdbc.Schema" value="sch123"/>
<property name="openjpa.Log" value="SQL=TRACE" />
</properties>
</code></pre>
| 0 | 1,796 |
query with join across multiple databases-syntax error
|
<p>I have 2 databases namely db1,db2. I need a query that fetch the data from these dbs(db1,db2) which have inturn 2 tables(concessions,invoicing) each.</p>
<p>In db1.concessions => concession is primary key.
db1.invoicing => [Concession Number] is primary key</p>
<p>similarly in db2.concessions => concession is primary key.
db2.invoicing => [Concession Number] is primary key</p>
<p><strong>In database1</strong></p>
<p>db1.tbl1 => Concessions table has data</p>
<pre><code> concession
TH-123
TH-456
FP-789
NZ-609
</code></pre>
<p>db1.tbl2 => invoicing table has data</p>
<pre><code> [Concession Number] invoiced_on
TH-322 10.09.10
TH-900 23.10.10
FP-675 04.05.09
NZ-111 19.11.08
</code></pre>
<p>luckily, in a database the value of concession in unique. i.e concessions.[concession] = invoicing.[concession Number] yields no data..</p>
<p><strong>In database2:</strong></p>
<p>db1.tbl1 => Concessions table has data</p>
<pre><code> concession
TH-123
FP-789
NZ-999
TH-900
</code></pre>
<p>db1.tbl2 => invoicing table has data</p>
<pre><code> [Concession Number] invoiced_on(dd.mm.yy)
TH-456 18.01.06
TH-777 23.10.04
FP-675 03.05.09
NZ-149 26.11.08
</code></pre>
<p>HEre in db2 concession is unique, concessions.[concession] = invoicing.[concession Number] yields no data..</p>
<p>Now the query should fetch the records that have common
db1.(concessions.concession OR invoicing.concession number) = db2(concessions.concession OR invoicing.concession number)</p>
<p>In the sample data it should return, TH-123,FP-789,NZ-999, FP-675.</p>
<p><strong>My 2nd</strong> question is there is possibility of extending this query to multiple database. I can't change the count of databases to 1 as they are already <strong>fixed</strong>. Please let me know the best procedure for the same.</p>
<p>I tried something like this, there are syntax errors,</p>
<pre><code>SELECT a.concession as db1_CON_NUMBER FROM db1.dbo.concessions as a UNION
SELECT b.[Concession Number] as db1_CON_NUMBER FROM db1.dbo.invoicing as b
INNER JOIN
SELECT c.concession as db2_CON_NUMBER FROM db2.dbo.concessions as c UNION
SELECT d.[Concession Number] as db2_CON_NUMBER FROM db2.dbo.invoicing as d
ON db1_CON_NUMBER = db2_CON_NUMBER
</code></pre>
<p>Hope you will answer both the questions.
Thanks for your patience in reading such a long mail!</p>
| 0 | 1,149 |
Distance between two locations in javascript
|
<p>Can some one help me what went wrong on this code snippet ? My ultimate aim to find distance two locations using googles javascript API . I have used geocomplete jquery function for address autocomplete. On click of search nothing is happening.Im just a beginner please help </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Distance between Two Places</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles.css" />
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<script type="text/javascript">
var geocoder, location1, location2;
function initialize() {
geocoder = new GClientGeocoder();
}
function showLocation() {
geocoder.getLocations(document.forms[0].address1.value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the first address");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(document.forms[0].address2.value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
calculateDistance();
}
});
}
});
}
function calculateDistance()
{
try
{
var glatlng1 = new GLatLng(location1.lat, location1.lon);
var glatlng2 = new GLatLng(location2.lat, location2.lon);
var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
var kmdistance = (miledistance * 1.609344).toFixed(1);
document.getElementById('results').innerHTML = '<strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
}
catch (error)
{
alert(error);
}
}
</script>
</head>
<body onload="initialize()">
<form action="#" onsubmit="showLocation(); return false;">
<input id="geocomplete" type="text" name="address1" placeholder="Type in an address" size="90" />
<input id="geocomplete1" type="text" name="address2" placeholder="Type in an address" size="90" />
<input type="submit" name="find" value="Search" />
</form>
<p id="results"></p>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="../jquery.geocomplete.js"></script>
<script src="logger.js"></script>
<script>
$(function(){
$("#geocomplete").geocomplete()
.bind("geocode:result", function(event, result){
$.log("Result: " + result.formatted_address);
})
.bind("geocode:error", function(event, status){
$.log("ERROR: " + status);
})
.bind("geocode:multiple", function(event, results){
$.log("Multiple: " + results.length + " results found");
});
$("#geocomplete1").geocomplete()
.bind("geocode:result", function(event, result){
$.log("Result: " + result.formatted_address);
})
.bind("geocode:error", function(event, status){
$.log("ERROR: " + status);
})
.bind("geocode:multiple", function(event, results){
$.log("Multiple: " + results.length + " results found");
});
$("#find").click(function(){
$("#geocomplete").trigger("geocode");
});
$("#examples a").click(function(){
$("#geocomplete").val($(this).text()).trigger("geocode");
return false;
});
});
</script>
</body>
</html>
</code></pre>
| 0 | 2,186 |
Unable to resume activity
|
<p>I am novice and trying to allow my <code>ListView</code> to refresh after my SQLite DB is updated. I am not receiving a compiling error after I revised my <code>onResume()</code> method. I am using a <code>SimpleCursorAdapter</code> to requery but it's not working. The error received was from logcat and is below. Please advise… examples help best.</p>
<p>Logcat:</p>
<pre><code> 02-19 21:31:49.933: E/AndroidRuntime(714): java.lang.RuntimeException: Unable to resume activity {com.loginplus.home/com.loginplus.home.LoginList}: java.lang.NullPointerException
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2444)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2472)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.ActivityThread.access$600(ActivityThread.java:123)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.os.Looper.loop(Looper.java:137)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.ActivityThread.main(ActivityThread.java:4424)
02-19 21:31:49.933: E/AndroidRuntime(714): at java.lang.reflect.Method.invokeNative(Native Method)
02-19 21:31:49.933: E/AndroidRuntime(714): at java.lang.reflect.Method.invoke(Method.java:511)
02-19 21:31:49.933: E/AndroidRuntime(714): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-19 21:31:49.933: E/AndroidRuntime(714): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-19 21:31:49.933: E/AndroidRuntime(714): at dalvik.system.NativeStart.main(Native Method)
02-19 21:31:49.933: E/AndroidRuntime(714): Caused by: java.lang.NullPointerException
02-19 21:31:49.933: E/AndroidRuntime(714): at com.loginplus.home.LoginList.onResume(LoginList.java:101)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1154)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.Activity.performResume(Activity.java:4539)
02-19 21:31:49.933: E/AndroidRuntime(714): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2434)
</code></pre>
<p>Activity:</p>
<pre><code> public class LoginList extends Activity implements OnClickListener, OnItemClickListener {
private ListView loginList;
private Button webLogin;
private ListAdapter loginListAdapter;
private ArrayList<LoginDetails> loginArrayList;
List<String> arrayList = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
arrayList = populateList();
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
setContentView(R.layout.login_listview);
loginList = (ListView)
findViewById(R.id.loginlist);
loginList.setOnItemClickListener(this);
webLogin = (Button)
findViewById(R.id.button3);
webLogin.setOnClickListener(this);
}
@Override
public void onClick (View v) {
Intent webLoginIntent = new Intent (this, LoginPlusActivity.class);
startActivity(webLoginIntent);
}
public List<String> populateList (){
List<String> webNameList = new ArrayList<String>();
dataStore openHelperClass = new dataStore (this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(dataStore.TABLE_NAME_INFOTABLE, null, null, null, null, null, dataStore.COLUMN_NAME_SITE, null);
startManagingCursor(cursor);
while (cursor.moveToNext()){
String sName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_SITE));
String wUrl = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_ADDRESS));
String uName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_USERNAME));
String pWord = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_PASSWORD));
String lNotes = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_NOTES));
LoginDetails lpDetails = new LoginDetails();
lpDetails.setsName(sName);
lpDetails.setwUrl(wUrl);
lpDetails.setuName(uName);
lpDetails.setpWord(pWord);
lpDetails.setlNotes(lNotes);
loginArrayList.add(lpDetails);
webNameList.add(sName);
}
sqliteDatabase.close();
return webNameList;
}
@Override
protected void onResume() {
super.onResume();
loginArrayList.clear();
arrayList.clear();
arrayList = populateList();
dataStore refreshHelper = new dataStore (this);
SQLiteDatabase sqliteDatabase = refreshHelper.getWritableDatabase();
Cursor cursor = sqliteDatabase.query(dataStore.TABLE_NAME_INFOTABLE, null, null, null, null, null, dataStore.COLUMN_NAME_SITE, null);
String[]columns = new String[] { dataStore.COLUMN_NAME_SITE, dataStore.COLUMN_NAME_ADDRESS, dataStore.COLUMN_NAME_USERNAME, dataStore.COLUMN_NAME_PASSWORD, dataStore.COLUMN_NAME_NOTES };
int[] to = new int[]{R.id.rusName, R.id.ruwUrl, R.id.ruuName, R.id.rupWord, R.id.ruNotes};
SimpleCursorAdapter loginListAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, columns, to);
loginListAdapter.notifyDataSetChanged();
}
@Override
public void onItemClick(AdapterView<?> arg0 , View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Selected ID :" + arg2, Toast.LENGTH_SHORT).show();
Intent updateDeleteLoginInfo = new Intent (this, UpdateDeleteLoginList.class);
LoginDetails clickedObject = loginArrayList.get(arg2);
Bundle loginBundle = new Bundle();
loginBundle.putString("clickedWebSite",clickedObject.getsName());
loginBundle.putString("clickedWebAddress",clickedObject.getwUrl());
loginBundle.putString("clickedUserName",clickedObject.getuName());
loginBundle.putString("clickedPassWord",clickedObject.getpWord());
loginBundle.putString("clickedNotes",clickedObject.getlNotes());
updateDeleteLoginInfo.putExtras(loginBundle);
startActivityForResult(updateDeleteLoginInfo, 0);
}
}
</code></pre>
<p>RennoDiniro EditResults:</p>
<p>Logcat:</p>
<pre><code> 02-21 23:40:18.419: E/AndroidRuntime(705): FATAL EXCEPTION: main
02-21 23:40:18.419: E/AndroidRuntime(705): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loginplus.home/com.loginplus.home.LoginList}: java.lang.NullPointerException
02-21 23:40:18.419: E/AndroidRuntime(705): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.app.ActivityThread.access$600(ActivityThread.java:123)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.os.Looper.loop(Looper.java:137)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.app.ActivityThread.main(ActivityThread.java:4424)
02-21 23:40:18.419: E/AndroidRuntime(705): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 23:40:18.419: E/AndroidRuntime(705): at java.lang.reflect.Method.invoke(Method.java:511)
02-21 23:40:18.419: E/AndroidRuntime(705): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-21 23:40:18.419: E/AndroidRuntime(705): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-21 23:40:18.419: E/AndroidRuntime(705): at dalvik.system.NativeStart.main(Native Method)
02-21 23:40:18.419: E/AndroidRuntime(705): Caused by: java.lang.NullPointerException
02-21 23:40:18.419: E/AndroidRuntime(705): at com.loginplus.home.LoginList.populateList(LoginList.java:88)
02-21 23:40:18.419: E/AndroidRuntime(705): at com.loginplus.home.LoginList.onCreate(LoginList.java:37)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.app.Activity.performCreate(Activity.java:4465)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
02-21 23:40:18.419: E/AndroidRuntime(705): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
</code></pre>
<p>Activity Class:</p>
<pre><code> public class LoginList extends Activity implements OnClickListener, OnItemClickListener {
private ListView loginList;
private Button webLogin;
private ListAdapter loginListAdapter;
private ArrayList<LoginDetails> loginArrayList;
List<String> arrayList = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
arrayList = populateList();
setContentView(R.layout.login_listview);
loginList = (ListView)
findViewById(R.id.loginlist);
loginList.setOnItemClickListener(this);
webLogin = (Button)
findViewById(R.id.button3);
webLogin.setOnClickListener(this);
}
@Override
public void onClick (View v) {
Intent webLoginIntent = new Intent (this, LoginPlusActivity.class);
startActivity(webLoginIntent);
}
public List<String> populateList (){
List<String> webNameList = new ArrayList<String>();
dataStore openHelperClass = new dataStore (this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(dataStore.TABLE_NAME_INFOTABLE, null, null, null, null, null, dataStore.COLUMN_NAME_SITE, null);
startManagingCursor(cursor);
while (cursor.moveToNext()){
String sName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_SITE));
String wUrl = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_ADDRESS));
String uName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_USERNAME));
String pWord = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_PASSWORD));
String lNotes = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_NOTES));
LoginDetails lpDetails = new LoginDetails();
lpDetails.setsName(sName);
lpDetails.setwUrl(wUrl);
lpDetails.setuName(uName);
lpDetails.setpWord(pWord);
lpDetails.setlNotes(lNotes);
loginArrayList.add(lpDetails);
webNameList.add(sName);
}
sqliteDatabase.close();
return webNameList;
}
@Override
protected void onResume() {
super.onResume();
try{
loginArrayList = new ArrayList<LoginDetails>();
arrayList = new ArrayList<String>();
loginArrayList.clear();
arrayList.clear();
arrayList = populateList();
dataStore refreshHelper = new dataStore (this);
SQLiteDatabase sqliteDatabase = refreshHelper.getWritableDatabase();
Cursor cursor = sqliteDatabase.query(dataStore.TABLE_NAME_INFOTABLE, null, null, null, null, null, dataStore.COLUMN_NAME_SITE, null);
String[]columns = new String[] { dataStore.COLUMN_NAME_SITE, dataStore.COLUMN_NAME_ADDRESS, dataStore.COLUMN_NAME_USERNAME, dataStore.COLUMN_NAME_PASSWORD, dataStore.COLUMN_NAME_NOTES };
int[] to = new int[]{R.id.rusName, R.id.ruwUrl, R.id.ruuName, R.id.rupWord, R.id.ruNotes};
SimpleCursorAdapter loginListAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, columns, to);
loginListAdapter.notifyDataSetChanged();
}catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public void onItemClick(AdapterView<?> arg0 , View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Selected ID :" + arg2, Toast.LENGTH_SHORT).show();
Intent updateDeleteLoginInfo = new Intent (this, UpdateDeleteLoginList.class);
LoginDetails clickedObject = loginArrayList.get(arg2);
Bundle loginBundle = new Bundle();
loginBundle.putString("clickedWebSite",clickedObject.getsName());
loginBundle.putString("clickedWebAddress",clickedObject.getwUrl());
loginBundle.putString("clickedUserName",clickedObject.getuName());
loginBundle.putString("clickedPassWord",clickedObject.getpWord());
loginBundle.putString("clickedNotes",clickedObject.getlNotes());
updateDeleteLoginInfo.putExtras(loginBundle);
startActivityForResult(updateDeleteLoginInfo, 0);
}
}
</code></pre>
| 0 | 4,962 |
java.io.FileNotFoundException: C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt (Access is denied)
|
<p>I'm trying to test my servlet by running it on Tomcat. However, I get the above error (sometimes this error occurs, but earlier the servlet was running fine). A few facts:</p>
<ol>
<li><p>I've looked thoroughly at the explanations given by <a href="https://stackoverflow.com/questions/10207033/http-status-404-description-the-requested-resource-is-not-available-apache-t">this similar problem</a>, as well as in <a href="https://stackoverflow.com/questions/4728110/the-requested-resource-is-not-available-when-running-tomcat-7-0-after-downl">here</a>, and <a href="https://stackoverflow.com/questions/2280064/tomcat-started-in-eclipse-but-unable-to-connect-to-link-to-http-localhost8085">here</a></p></li>
<li><p>When I attempt to restart Tomcat (from within Eclipse's "Servers" tab), I get some error log from the console:</p></li>
</ol>
<p>"SEVERE: Failed to open access log file [~\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt]" and at the very end of the log output, there's "INFO: SessionListener: sessionDestroyed('E9A6117FDF54752D80A1B9B72F2B83D3') -- see more info at the bottom of this text</p>
<ol start="3">
<li><p>I've looked at my log files at " C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs" and there is not file with contents similar to the ones in item (2) above</p></li>
<li><p>I 'deploy' my application through Eclipse (that is, during development, I depend on Eclipse to start Tomcat), only doing a real deployment when I have a stable version of my project by copying the appropriate java class files into Tomcat's /webapps/WEB-INF/classes folder and restarting Tomcat</p></li>
</ol>
<p>and most importantly,
5. Typing in "<a href="http://localhost:8080" rel="nofollow noreferrer">http://localhost:8080</a>" leads me to the Tomcat homepage (so I'm pretty sure the server is running), whereas "<a href="http://localhost:8080/MyProjectName/MyServlet" rel="nofollow noreferrer">http://localhost:8080/MyProjectName/MyServlet</a>" in the browser leads to the error shown this question's title. </p>
<p>Any ideas/help?
Thank you very much!</p>
<p>See more of the error logs here</p>
<pre><code>>!Jul 12, 2012 6:18:18 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0\jre\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:\Users\Kiptoo\introcs\java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32\wbem;C:\Program Files\MiKTeX 2.8\miktex\bin;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files\Matlab\R2010a\runtime\win32;C:\Program Files\Matlab\R2010a\bin;C:\Program Files\TortoiseSVN\bin;C:\Program Files\QuickTime\QTSystem;C:\Users\Kiptoo\introcs\bin;C:\Users\Kiptoo\introcs\java\bin;C:\Python27;C:\Program Files\Eclipse;;.
Jul 12, 2012 6:18:20 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Jul 12, 2012 6:18:20 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Jul 12, 2012 6:18:20 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2050 ms
Jul 12, 2012 6:18:20 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jul 12, 2012 6:18:20 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.25
Jul 12, 2012 6:18:20 PM org.apache.catalina.valves.AccessLogValve open
SEVERE: Failed to open access log file [C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt]
java.io.FileNotFoundException: C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at org.apache.catalina.valves.AccessLogValve.open(AccessLogValve.java:1115)
at org.apache.catalina.valves.AccessLogValve.startInternal(AccessLogValve.java:1222)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardPipeline.startInternal(StandardPipeline.java:185)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1144)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1568)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1558)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Jul 12, 2012 6:18:20 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\AndroidTest
Jul 12, 2012 6:18:20 PM org.apache.catalina.core.StandardContext postWorkDirectory
WARNING: Failed to create work directory [C:\Program Files\Apache Software Foundation\Tomcat 7.0\work\Catalina\localhost\AndroidTest] for context [/AndroidTest]
Jul 12, 2012 6:18:21 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [175] milliseconds.
Jul 12, 2012 6:18:21 PM org.apache.jasper.EmbeddedServletOptions <init>
SEVERE: The scratchDir you specified: C:\Program Files\Apache Software Foundation\Tomcat 7.0\work\Catalina\localhost\AndroidTest is unusable.
Jul 12, 2012 6:18:21 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\docs
Jul 12, 2012 6:18:21 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\examples
Jul 12, 2012 6:18:21 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
Jul 12, 2012 6:18:21 PM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
Jul 12, 2012 6:18:21 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: attributeAdded('org.apache.jasper.compiler.TldLocationsCache', 'org.apache.jasper.compiler.TldLocationsCache@ff8399')
Jul 12, 2012 6:18:21 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\host-manager
Jul 12, 2012 6:18:22 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\manager
Jul 12, 2012 6:18:22 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ROOT
Jul 12, 2012 6:18:22 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Jul 12, 2012 6:18:22 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Jul 12, 2012 6:18:22 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2225 ms
Jul 12, 2012 6:19:22 PM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: sessionDestroyed('E9A6117FDF54752D80A1B9B72F2B83D3')
</code></pre>
| 0 | 2,678 |
Sonar setup with MySql
|
<p>Iam trying to change the sonar Qube 5.5 default database to Mysql.But it is still connecting to default H2 DB.</p>
<p>Configuration as below.</p>
<p>I have run the below scripts in Mysql DB</p>
<pre><code># Create SonarQube database and user.
#
# Command: mysql -u root -p < create_database.sql
#
CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER 'sonar' IDENTIFIED BY 'sonar';
GRANT ALL ON sonar.* TO 'sonar'@'%' IDENTIFIED BY 'sonar';
GRANT ALL ON sonar.* TO 'sonar'@'localhost' IDENTIFIED BY 'sonar';
FLUSH PRIVILEGES;
</code></pre>
<p>uncommented the sonar.jdbc.url for Mysql,Iam not able to see the configuration for H2 DB to comment it.</p>
<pre><code> # Property values can:
# - reference an environment variable, for example sonar.jdbc.url= ${env:SONAR_JDBC_URL}
# - be encrypted. See http://redirect.sonarsource.com/doc/settings-encryption.html
#--------------------------------------------------------------------------------------------------
# DATABASE
#
# IMPORTANT: the embedded H2 database is used by default. It is recommended for tests but not for
# production use. Supported databases are MySQL, Oracle, PostgreSQL and Microsoft SQLServer.
# User credentials.
# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
#----- Embedded Database (default)
# H2 embedded database server listening port, defaults to 9092
#sonar.embeddedDatabase.port=9092
#----- MySQL 5.x
# Only InnoDB storage engine is supported (not myISAM).
# Only the bundled driver is supported. It can not be changed.
sonar.jdbc.url=jdbc:mysql://10.9.153.6:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
</code></pre>
<p>Then I restarted the server from <strong>Administration->system -> Systeminfo</strong>.</p>
<p>After restart using cmd line getting this error:</p>
<pre><code>2017.07.20 22:32:54 WARN web[o.s.p.ProcessEntryPoint] Fail to start web
java.lang.IllegalStateException: Webapp did not start
at org.sonar.server.app.EmbeddedTomcat.isUp(EmbeddedTomcat.java:84) ~[sonar-server-5.5.jar:na]
at org.sonar.server.app.WebServer.isUp(WebServer.java:48) [sonar-server-5.5.jar:na]
at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:105) ~[sonar-process-5.5.jar:na]
at org.sonar.server.app.WebServer.main(WebServer.java:69) [sonar-server-5.5.jar:na]
2017.07.20 22:32:54 INFO web[o.a.c.h.Http11NioProtocol] Pausing ProtocolHandler ["http-nio-0.0.0.0-9000"]
2017.07.20 22:32:55 INFO web[o.a.c.h.Http11NioProtocol] Stopping ProtocolHandler ["http-nio-0.0.0.0-9000"]
2017.07.20 22:32:55 INFO web[o.a.c.h.Http11NioProtocol] Destroying ProtocolHandler ["http-nio-0.0.0.0-9000"]
2017.07.20 22:32:55 INFO web[o.s.s.a.TomcatAccessLog] Web server is stopped
</code></pre>
| 0 | 3,482 |
Priority queue with Pointers and Comparator C++
|
<p>I just started to learn C++, Half of the time I don't know what am I doing, spend hours and hours searching on Google and blindly put codes inside my project, this might be a basic question, but I just can't seems to get it right.</p>
<p><strong>This is the requirement</strong> of my assignment, I need to have these:</p>
<p><strong>in the Edge class:</strong> </p>
<pre><code>public:
bool operator()(Edge*, Edge*)
</code></pre>
<p><strong>in the Graph class:</strong></p>
<pre><code>private:
priority_queue<Edge*, vector<Edge*>, Edge> edges
</code></pre>
<p><strong>I have problem declaring the priority_queue. Details:</strong> </p>
<p>If I directly use these, the edge class will give me an error of "must have an argument of class", I understand that I can't overload two pointers into the bool operator, so <strong>this is what I have tried:</strong> </p>
<p><strong>in the Edge.cpp:</strong></p>
<pre><code>#include "Edge.h"
using namespace std;
Edge::Edge(Vertex* s, Vertex* d, double w)
{
source = s;
destination = d;
weight = w;
}
double Edge::getWeight()
{
return weight;
}
struct CompareWeight : public std::binary_function<Edge*, Edge*, bool>
{
bool operator()(Edge* e1,Edge* e2)
{
double w1 = e1->getWeight();
double w2 = e2->getWeight();
if(w1>w2){
return true;
}
else {
return false;
}
}
};
</code></pre>
<p>^ I am not even sure about putting struct inside the class is correct or not, Plus in this cause I don't know what to put inside my Edge.h file.</p>
<p><strong>in the Edge.h:</strong> </p>
<pre><code>#include "Vertex.h"
class Edge
{
public:
Edge(Vertex*, Vertex*, double);
double getWeight();
friend struct CompareWeight; // ??? does not seems right
private:
Vertex* source;
Vertex* destination;
double weight;
}
</code></pre>
<p>As for the Graph class is where the real problem is, I can't even get pass declaring the priority queue without getting an error. </p>
<p><strong>in the Graph.h</strong> </p>
<pre><code>#include "Vertex.h"
#include "Edge.h"
#include <vector>
#include <queue>
class Graph
{
public:
...
private:
priority_queue<Edge*, vector<Edge*>, Edge> edges
// This give pointer error: no match for call to '(Edge) (Edge*&, Edge*&)'
}
</code></pre>
<p>second attempt: </p>
<pre><code>// same as above
private:
priority_queue<Edge*, vector<Edge*>, CompareWeight> edges
// This give error: 'CompareWeight' not declared in this scope
</code></pre>
<p>I don't know why for the first error, but the second error I understood it clearly, but I don't know how to fix it, should I put something in front of CompareWeight? I tried many things, nothing work. </p>
<p>Any help will be greatly appreciated! otherwise I would probably just fail this course.
First time asking in stackoverflow, if I did anything wrong please tell me. </p>
| 0 | 1,118 |
Ripple effect on top of Image - Android
|
<p>I've been experimenting with the ripple animation in my latest side project. I'm having some trouble finding an "elegant" solution to using it in certain situations for touch events. Namely with images, especially in list, grid, and recycle views. The animation almost always seems to animate behind the view, not the on top of it. This is a none issue in Buttons and TextViews but if you have a GridView of images, the ripple appears behind or below the actual image. Obviously this is not what I want, and while there are solutions that I consider to be a work around, I'm hoping there is something simpler i'm just unaware of. </p>
<p>I use the following code to achieve a custom grid view with images. I'll give full code <a href="http://pastebin.com/0M62jder">CLICK HERE</a> so you can follow along if you choose.</p>
<p>Now just the important stuff. In order to get my image to animate on touch I need this </p>
<p><strong>button_ripple.xml</strong></p>
<pre><code><ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/cream_background">
<item>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Pressed -->
<item
android:drawable="@color/button_selected"
android:state_pressed="true"/>
<!-- Selected -->
<item
android:drawable="@color/button_selected"
android:state_selected="true"/>
<!-- Focus -->
<item
android:drawable="@color/button_selected"
android:state_focused="true"/>
<!-- Default -->
<item android:drawable="@color/transparent"/>
</selector>
</item>
</ripple>
</code></pre>
<p><strong>custom_grid.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<ImageView
android:id="@+id/sceneGridItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_ripple"
android:gravity="center_horizontal"/>
</LinearLayout>
</code></pre>
<p><strong>activity_main.xml</strong></p>
<pre><code><GridView
android:id="@+id/sceneGrid"
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:verticalSpacing="15dp"
android:numColumns="5" />
</code></pre>
<p>The line where all magic and problems occur is when I set the background. While this does in fact give me a ripple animation on my imageview, it animates <em>behind</em> the imageview. I want the animation to appear <em>on top</em> of the image. So I tried a few different things like</p>
<p><strong>Setting the entire grid background to button_ripple.</strong> </p>
<pre><code><GridView
android:id="@+id/sceneGrid"
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:verticalSpacing="15dp"
android:background="@drawable/button_ripple"
android:numColumns="5" />
</code></pre>
<p>It does exactly what you'd think, now the entire grid has a semi transparent background and no matter what image i press the entire grid animates from the center of the grid. While this is kind of cool, its not what I want. </p>
<p><strong>Setting the root/parent background to button_ripple.</strong> </p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:background="@drawable/button_ripple"
android:orientation="horizontal">
</code></pre>
<p>The area is now larger and fills the entire cell of the grid (not just the image), however it doesn't bring it to the front.</p>
<p><strong>Changing custom_grid.xml to a RelativeLayout and putting two ImageViews on top of each other</strong></p>
<p><strong>custom_grid.xml</strong></p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/gridItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<ImageView
android:id="@+id/gridItemOverlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:background="@drawable/button_ripple" />
</RelativeLayout>
</code></pre>
<p><strong>CustomGridAdapter.java</strong></p>
<pre><code>....
gridItemOverLay = (ImageView) findViewById(R.id.gridItemOverlay);
gridItemOverlay.bringToFront();
</code></pre>
<p>This works. Now the bottom ImageView contains my image, and the top animates, giving the illusion of a ripple animation <em>on top</em> of my image. Honestly though this is a work around. I feel like this is not how it was intended. So I ask you fine people, is there a better way or even a different way? </p>
| 0 | 2,231 |
Why DBSCAN clustering returns single cluster on Movie lens data set?
|
<h2>The Scenario:</h2>
<p>I'm performing Clustering over Movie Lens Dataset, where I have this Dataset in 2 formats:</p>
<p><strong>OLD FORMAT:</strong></p>
<pre><code>uid iid rat
941 1 5
941 7 4
941 15 4
941 117 5
941 124 5
941 147 4
941 181 5
941 222 2
941 257 4
941 258 4
941 273 3
941 294 4
</code></pre>
<p><strong>NEW FORMAT:</strong></p>
<pre><code>uid 1 2 3 4
1 5 3 4 3
2 4 3.6185548023 3.646073985 3.9238342172
3 2.8978348799 2.6692556753 2.7693015618 2.8973463681
4 4.3320762062 4.3407749532 4.3111995162 4.3411425423
940 3.7996234581 3.4979386925 3.5707888503 2
941 5 NaN NaN NaN
942 4.5762594612 4.2752554573 4.2522440019 4.3761477591
943 3.8252406362 5 3.3748860659 3.8487417604
</code></pre>
<p>over which I need to perform Clustering using KMeans, DBSCAN and HDBSCAN.
With KMeans I'm able to set and get clusters. </p>
<h2>The Problem</h2>
<p>The Problem persists only with DBSCAN & HDBSCAN that I'm unable to get enough amount of clusters (I do know we cannot set Clusters manually)</p>
<h2>Techniques Tried:</h2>
<ul>
<li>Tried this with <strong>IRIS</strong> <a href="https://en.wikipedia.org/wiki/Iris_flower_data_set#Data_set" rel="noreferrer">data-set</a>, where I found <em>Species</em> wasn't included. Clearly that is in String and besides is to be predicted, and everything just <a href="http://www.dummies.com/programming/big-data/data-science/how-to-create-an-unsupervised-learning-model-with-dbscan/" rel="noreferrer">works fine</a> with that Dataset (Snippet 1)</li>
<li>Tried with Movie Lens 100K <a href="https://grouplens.org/datasets/movielens/" rel="noreferrer">dataset</a> in OLD FORMAT (with and without UID) since I tried an Analogy that, UID == SPECIES and hence tried without it. (Snippet 2)</li>
<li>Tried same with NEW FORMAT (with and without UID) yet the results ended up in same style.</li>
</ul>
<p><strong>Snippet 1:</strong></p>
<pre><code>print "\n\n FOR IRIS DATA-SET:"
from sklearn.datasets import load_iris
iris = load_iris()
dbscan = DBSCAN()
d = pd.DataFrame(iris.data)
dbscan.fit(d)
print "Clusters", set(dbscan.labels_)
</code></pre>
<p><strong>Snippet 1 (Output):</strong></p>
<pre><code>FOR IRIS DATA-SET:
Clusters set([0, 1, -1])
Out[30]:
array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1,
-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1,
1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1,
1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, -1, -1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
</code></pre>
<p><strong>Snippet 2:</strong></p>
<pre><code>import pandas as pd
from sklearn.cluster import DBSCAN
data_set = pd.DataFrame
ch = int(input("Extended Cluster Methods for:\n1. Main Matrix IBCF \n2. Main Matrix UBCF\nCh:"))
if ch is 1:
data_set = pd.read_csv("MainMatrix_IBCF.csv")
data_set = data_set.iloc[:, 1:]
data_set = data_set.dropna()
elif ch is 2:
data_set = pd.read_csv("MainMatrix_UBCF.csv")
data_set = data_set.iloc[:, 1:]
data_set = data_set.dropna()
else:
print "Enter Proper choice!"
print "Starting with DBSCAN for Clustering on\n", data_set.info()
db_cluster = DBSCAN()
db_cluster.fit(data_set)
print "Clusters assigned are:", set(db_cluster.labels_)
</code></pre>
<p><strong>Snippet 2 (Output):</strong></p>
<pre><code>Extended Cluster Methods for:
1. Main Matrix IBCF
2. Main Matrix UBCF
Ch:>? 1
Starting with DBSCAN for Clustering on
<class 'pandas.core.frame.DataFrame'>
Int64Index: 942 entries, 0 to 942
Columns: 1682 entries, 1 to 1682
dtypes: float64(1682)
memory usage: 12.1 MB
None
Clusters assigned are: set([-1])
</code></pre>
<p>As seen, it returns only 1 Cluster. I'd like to hear what am I doing wrong.</p>
| 0 | 2,102 |
Bootstrap table - dynamic button in row
|
<p>I am using <em>bootstrap v3</em>. I try to get the effect as in the picture. I want a button, what to display <code>"Item Name"</code> in <code>popup</code>. But my button is not displayed.</p>
<p>The problem is that this nature of my table is a dynamic (form <code>JSON</code>) - which makes things difficult. </p>
<p><strong>Picture:</strong>
<a href="https://i.stack.imgur.com/YPVSd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YPVSd.png" alt="enter image description here"></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var $table = $('#table');
var mydata = [{
"id": 0,
"name": "test0",
"price": "$0"
},
{
"id": 1,
"name": "test1",
"price": "$1"
},
{
"id": 2,
"name": "test2",
"price": "$2"
}
];
$(function() {
$('#table').bootstrapTable({
data: mydata
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflarenter code heree.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>
</head>
<body>
<div class="container">
<table id="table" data-search="true">
<thead>
<tr>
<th data-field="id" data-sortable="true">Item ID</th>
<th data-field="name" data-sortable="true">Item Name</th>
<th data-field="price" data-sortable="true">Item Price</th>
<th>Show Name</th>
</tr>
</thead>
<tbody>
<tr></tr>
<tr></tr>
<tr></tr>
<tr>
<td>
<button type="button" class="btn btn-primary btn-sm">Small button</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I will be grateful for your help.</p>
| 0 | 1,278 |
Using CardView and RecyclerView in my layout files throws an exception
|
<p>So I've been taking a shot at the Material Design of Android Preview L. I imported both the <code>CardView</code> and the <code>RecyclerView</code> libraries.</p>
<p>I use the Android Studio preview version 0.8.0. Have the latest SDK packages installed.</p>
<p>Once I use them in my layout files though, the previewer throws an exception for both of them.</p>
<p>Here is the exception for the <code>CardView</code>:</p>
<pre><code>java.lang.ClassFormatError: Illegal field name "CardView.Dark" in class android/support/v7/cardview/R$style
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:792)
at java.lang.ClassLoader.defineClass(ClassLoader.java:635)
at org.jetbrains.android.uipreview.ProjectClassLoader.findClass(ProjectClassLoader.java:63)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at android.support.v7.widget.CardView.initialize(CardView.java:69)
at android.support.v7.widget.CardView.<init>(CardView.java:60)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:375)
at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:100)
at com.android.tools.idea.rendering.LayoutlibCallback.loadView(LayoutlibCallback.java:172)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:207)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:132)
at android.view.LayoutInflater.inflate(LayoutInflater.java:478)
at android.view.LayoutInflater.inflate(LayoutInflater.java:381)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:395)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:329)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:332)
at com.android.tools.idea.rendering.RenderService$3.compute(RenderService.java:575)
at com.android.tools.idea.rendering.RenderService$3.compute(RenderService.java:564)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:932)
at com.android.tools.idea.rendering.RenderService.createRenderSession(RenderService.java:564)
at com.android.tools.idea.rendering.RenderService.render(RenderService.java:691)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:586)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1900(AndroidLayoutPreviewToolWindowManager.java:80)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$6$1.run(AndroidLayoutPreviewToolWindowManager.java:528)
at com.intellij.openapi.progress.impl.ProgressManagerImpl$2.run(ProgressManagerImpl.java:178)
at com.intellij.openapi.progress.ProgressManager.executeProcessUnderProgress(ProgressManager.java:209)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:212)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:171)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$6.run(AndroidLayoutPreviewToolWindowManager.java:523)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
at com.intellij.util.Alarm$Request$1.run(Alarm.java:327)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
</code></pre>
<p>And here is the exception for <code>RecyclerView</code>:</p>
<pre><code>java.lang.NullPointerException
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:1310)
at android.view.View.measure(View.java:16987)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:722)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:458)
at android.view.View.measure(View.java:16987)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5257)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:314)
at android.view.View.measure(View.java:16987)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5257)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:447)
at android.view.View.measure(View.java:16987)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5257)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1083)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:16987)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5257)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:16987)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:875)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:16987)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.measureView(RenderSessionImpl.java:621)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:521)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:331)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:332)
at com.android.tools.idea.rendering.RenderService$3.compute(RenderService.java:575)
at com.android.tools.idea.rendering.RenderService$3.compute(RenderService.java:564)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:932)
at com.android.tools.idea.rendering.RenderService.createRenderSession(RenderService.java:564)
at com.android.tools.idea.rendering.RenderService.render(RenderService.java:691)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:586)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1900(AndroidLayoutPreviewToolWindowManager.java:80)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$6$1.run(AndroidLayoutPreviewToolWindowManager.java:528)
at com.intellij.openapi.progress.impl.ProgressManagerImpl$2.run(ProgressManagerImpl.java:178)
at com.intellij.openapi.progress.ProgressManager.executeProcessUnderProgress(ProgressManager.java:209)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:212)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:171)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$6.run(AndroidLayoutPreviewToolWindowManager.java:523)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
at com.intellij.util.Alarm$Request$1.run(Alarm.java:327)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
</code></pre>
<p>This makes building layout near impossible using these two (amazing) <code>View</code>s, which I'm most curious about.</p>
<p>Is there a fix for this already, or is this actually expected behaviour seeing as they're "custom" <code>View</code>s, in a sense?</p>
| 0 | 3,078 |
Android ScrollView can host only one direct child
|
<p>I have a onclick listener from the gallery that should clear all the rows inside the tableview, then add row/rows to a tableview inside a scrollview. The fragment should change on every button click.</p>
<p>However I am getting: java.lang.IllegalStateException: ScrollView can host only one direct child.</p>
<p><strong>myactivity button listener</strong></p>
<pre><code> TrackerFragment tf = (TrackerFragment) getFragmentManager().findFragmentById(R.id.tracker1);
tf = TrackerFragment.newInstance(listOfList.get(id).get(position));
fragmentTransaction.add(R.id.tracker1, tf);
fragmentTransaction.commit();
t1 = true; //being used
getFragmentManager().executePendingTransactions();
</code></pre>
<p><strong>tracker fragment</strong></p>
<pre><code>public class TrackerFragment extends Fragment
{
private Dish dish;
public static TrackerFragment newInstance(Serializable dish)
{
TrackerFragment tf = new TrackerFragment();
Bundle args = new Bundle();
args.putSerializable("dish", dish);
tf.setArguments(args);
return tf;
}
public static TrackerFragment newInstance(Bundle bundle)
{
Dish dish = (Dish) bundle.getSerializable("dish");
return newInstance(dish);
}
@Override
public void onCreate(Bundle myBundle)
{
super.onCreate(myBundle);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.tracker, container, false);
TableLayout tableLayout = (TableLayout) v.findViewById(R.id.tracker_layout);
tableLayout.removeAllViews();
if (dish != null)
{
//display others
//display subsystem stuff
for (int i = 0; i < dish.getSubsystems().size(); i++)
{
TableRow tableRow = new TableRow(v.getContext());
tableRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView tv = new TextView(v.getContext());
tv.setText(dish.getSubsystems().get(i).getConnFuncAddr());
tableRow.addView(tv);
tableLayout.addView(tableRow);
}
}
else
{
TableRow tableRow = new TableRow(v.getContext());
tableRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView tv = new TextView(v.getContext());
tv.setText("Click on image to view more data");
tableRow.addView(tv);
tableLayout.addView(tableRow);
}
return v;
}
}
</code></pre>
<p><strong>main.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Trackers -->
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="300dp"
android:layout_weight="1"
android:orientation="vertical">
<fragment
android:name="android.gallery.TrackerFragment"
android:id="@+id/tracker1"
android:layout_height="500dp"
android:layout_width="300dp"
android:layout_weight="1">
</fragment>
</LinearLayout>
<!-- Gallery -->
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="600dp"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="245dp">
<Gallery
android:id="@+id/galleryid0"
android:layout_width="fill_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="245dp">
<Gallery
android:id="@+id/galleryid1"
android:layout_width="fill_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="245dp">
<Gallery
android:id="@+id/galleryid2"
android:layout_width="fill_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</code></pre>
<p><strong>tracker.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tracker_layout">
</TableLayout>
</ScrollView>
</code></pre>
<p>Does anyone know whats wrong? I am guessing I am adding a table row to the scrollview and not the tableview, however, I dont see where I am doing that wrong in my code.</p>
| 0 | 2,506 |
Associating string representations with an Enum that uses integer values?
|
<p>I'm trying to create an enum that has integer values, but which can also return a display-friendly string for each value. I was thinking that I could just define a dict mapping values to strings and then implement <code>__str__</code> and a static constructor with a string argument, but there's a problem with that...</p>
<p>(Under different circumstances I could have just made the underlying data type for this Enum a string rather than an integer, but this is being used as a mapping for an enum database table, so both the integer value and the string are meaningful, the former being a primary key.)</p>
<pre><code>from enum import Enum
class Fingers(Enum):
THUMB = 1
INDEX = 2
MIDDLE = 3
RING = 4
PINKY = 5
_display_strings = {
THUMB: "thumb",
INDEX: "index",
MIDDLE: "middle",
RING: "ring",
PINKY: "pinky"
}
def __str__(self):
return self._display_strings[self.value]
@classmethod
def from_string(cls, str1):
for val, str2 in cls._display_strings.items():
if str1 == str2:
return cls(val)
raise ValueError(cls.__name__ + ' has no value matching "' + str1 + '"')
</code></pre>
<p>When converting to string, I get the following error:</p>
<pre class="lang-none prettyprint-override"><code>>>> str(Fingers.RING)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
str(Fingers.RING)
File "D:/src/Hacks/PythonEnums/fingers1.py", line 19, in __str__
return self._display_strings[self.value]
TypeError: 'Fingers' object is not subscriptable
</code></pre>
<p>It seems that the issue is that an Enum will use all class variables as the enum values, which causes them to return objects of the Enum type, rather than their underlying type.</p>
<p>A few workarounds I can think of include:</p>
<ol>
<li>Referring to the dict as <code>Fingers._display_strings.value</code>. (However then <code>Fingers.__display_strings</code> becomes a valid enum value!)</li>
<li>Making the dict a module variable instead of a class variable.</li>
<li>Duplicating the dict (possibly also breaking it down into a series of <code>if</code> statements) in the <code>__str__</code> and <code>from_string</code> functions.</li>
<li>Rather than make the dict a class variable, define a static method <code>_get_display_strings</code> to return the dict, so it doesn't become an enum value.</li>
</ol>
<p>Note that the initial code above and workaround <code>1.</code> uses the underlying integer values as the dict keys. The other options all require that the dict (or <code>if</code> tests) are defined somewhere other than directly in the class itself, and so it must qualify these values with the class name. So you could only use, e.g., <code>Fingers.THUMB</code> to get an enum object, or <code>Fingers.THUMB.value</code> to get the underlying integer value, but not just <code>THUMB</code>. If using the underlying integer value as the dict key, then you must also use it to look up the dict, indexing it with, e.g., <code>[Fingers.THUMB.value]</code> rather than just <code>[Fingers.THUMB]</code>.</p>
<p>So, the question is, what is the best or most Pythonic way to implement a string mapping for an Enum, while preserving an underlying integer value?</p>
| 0 | 1,106 |
What's so special about file descriptor 3 on linux?
|
<p>I'm working on a server application that's going to work on Linux and Mac OS X. It goes like this:</p>
<ul>
<li>start main application</li>
<li>fork of the controller process</li>
<li>call lock_down() in the controller process</li>
<li>terminate main application</li>
<li>the controller process then forks again, creating a worker process</li>
<li>eventually the controller keeps forking more worker processes</li>
</ul>
<p>I can log using several of methods (e.g. syslog or a file) but right now I'm pondering about syslog. The "funny" thing is that no syslog output is ever seen in the controller process unless I include the #ifdef section below. </p>
<p>The worker processes logs flawlessly in Mac OS X and linux with or without the ifdef'ed section below. The controller also logs flawlessly in Mac OS X without the #ifdef'ed section, but on linux the ifdef is needed if I want to see any output into syslog (or the log file for that matter) from the controller process.</p>
<p>So, why is that?</p>
<pre><code>static int
lock_down(void)
{
struct rlimit rl;
unsigned int n;
int fd0;
int fd1;
int fd2;
// Reset file mode mask
umask(0);
// change the working directory
if ((chdir("/")) < 0)
return EXIT_FAILURE;
// close any and all open file descriptors
if (getrlimit(RLIMIT_NOFILE, &rl))
return EXIT_FAILURE;
if (RLIM_INFINITY == rl.rlim_max)
rl.rlim_max = 1024;
for (n = 0; n < rl.rlim_max; n++) {
#ifdef __linux__
if (3 == n) // deep magic...
continue;
#endif
if (close(n) && (EBADF != errno))
return EXIT_FAILURE;
}
// attach file descriptors 0, 1 and 2 to /dev/null
fd0 = open("/dev/null", O_RDWR);
fd1 = dup2(fd0, 1);
fd2 = dup2(fd0, 2);
if (0 != fd0)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
</code></pre>
<p>camh was close, but using closelog() was the idea that did the trick so the honor goes to jilles. Something else, aside from closing a file descriptor from under syslogs feet must go on though. To make the code work I added a call to closelog() just before the loop:</p>
<pre><code>closelog();
for (n = 0; n < rl.rlim_max; n++) {
if (close(n) && (EBADF != errno))
return EXIT_FAILURE;
}
</code></pre>
<p>I was relying on a verbatim understanding of the manual page, saying:</p>
<blockquote>
<p>The use of openlog() is optional; it will automatically be called by syslog() if necessary...</p>
</blockquote>
<p>I interpreted this as saying that syslog would detect if the file descriptor was closed under it. Apparently it did not. An explicit closelog() on linux was needed to tell syslog that the descriptor was closed. </p>
<p>One more thing that still perplexes me is that not using closelog() prevented the first forked process (the controller) from even opening and using a log file. The following forked processes could use syslog or a log file with no problems. Maybe there are some caching effect in the filesystem that make the first forked process having an unreliable "idea" of which file descriptors are available, while the next set of forked process are sufficiently delayed to not be affected by this? </p>
| 0 | 1,128 |
How to use JQuery in TWIG (symfony2)
|
<p>I am currently trying to use JQuery in TWIG. My website was created using Symfony2. I currently have a table in TWIG (it works - see below), for which I would like to make use of JQuery in order to make my table columns sortable.</p>
<pre><code><table><tr><th>cat</th> <th>dog</th> <th>fish</th> </tr> {% for result in results %}<tr><td>{{result.cat_name}}</td><td>{% for dog in result.dogs %} {{dog.dog_name}}{% endfor %} </td> <td>{% if result.fishs is defined %} {% for fish in result.fishs %}
{{fish.fish_uri}}
{% endfor %} {% endif %} </td></tr>{% endfor %}
</code></pre>
<p></p>
<p>I would like to make use of DataTables (see <a href="http://datatables.net/blog/Getting_started_with_DataTables%3a_First_steps" rel="nofollow">here</a>) in order to get my desired functionality from my table. There's a bundle (see <a href="https://github.com/opichon/UAMDatatablesBundle/blob/master/README.md" rel="nofollow">here</a>) which was created to allow the use of DataTables in TWIG. The bundle was successfully installed (web/bundles/uamdatatables/).</p>
<p>What causes me uncertainty (as bundle did not have use instructions) is that I have tried to make the bundle work (to make my table have the features offered by DataTables), and yet my table remains unchanged (no error messages either).</p>
<p>Wondering if someone could tell me what I am doing wrong? I have never used JQuery before, and am new to Symfony. Do I need some kind of "include" statement (to get to js files)?</p>
<p>//view.html.twig</p>
<pre><code><table><table id="table_id" class="display"><thead> {% block stylesheets %}
<link href="{{ asset('/bundles/uamdatatables/css/jquery.dataTables.css') }}" rel="stylesheet" />
<script type="text/javascript" charset="utf-8" src="/bundles/uamdatatables/css/jquery.dataTables.css"></script>
{% endblock %}<tr><th>cat</th> <th>dog</th> <th>fishs</th> </tr></thead> <tbody><?php $(document).ready( function () {
$('#table_id').dataTable();} );?>{% block javascripts %}
<script src="{{ asset('/bundles/uamdatatables/js/jquery.dataTables.js') }}"></script>
{% endblock %}{% for result in results %}<tr><td>{{ result.cat_name}}</td><td>{% for dog in result.dogs %}{{dog.dog_name}}{% endfor %}</td><td>{% if result.fishs is defined %} {% for fish in result.fishs %}{{fish.fish_uri}}{% endfor %}{% endif %}</td></tr>{% endfor %}</tbody> </table>
</code></pre>
<p>Thank you!
Tanya</p>
| 0 | 1,107 |
How do I use "flex-flow: column wrap"?
|
<h1>Short version</h1>
<p>When using <code>flex-flow: column wrap</code> and <code>display: inline-flex</code>, it doesn't shrinkwrap like <code>inline-block</code>:</p>
<p><a href="https://i.stack.imgur.com/Es3ch.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/Es3ch.gif" alt="enter image description here"></a></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function() {
var ascending = true;
setInterval(function() {
var parent = document.getElementById('flex');
if (ascending) {
var child = document.createElement('p');
child.innerHTML = "foo";
parent.appendChild(child);
} else {
parent.removeChild(parent.children[0]);
}
if (parent.children.length <= 1) ascending = true;
if (parent.children.length >= 40) ascending = false;
}, 20);
})();
(function() {
var ascending = true;
setInterval(function() {
var parent = document.getElementById('failex');
if (ascending) {
var child = document.createElement('p');
child.innerHTML = "foo";
parent.appendChild(child);
} else {
parent.removeChild(parent.children[0]);
}
if (parent.children.length <= 1) ascending = true;
if (parent.children.length >= 40) ascending = false;
}, 20);
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#flexdesc {position: absolute; top: 25px;}
#flex {
top: 50px;
position: absolute;
display: inline-flex;
flex-flow: row wrap;
outline: 1px solid black;
padding: 3px;
max-height: 100%;
max-width: 180px;
align-content: flex-start;
transform: matrix(0, 1, 1, 0, 0, 0);
transform-origin: top left;
}
#flex > p {
margin: 0;
outline: 1px solid black;
height: 30px;
width: 30px;
align-self: flex-start;
transform: matrix(0, 1, 1, 0, 0, 0);
}
#failexdesc {position: absolute; top: 275px;}
#failex {
top: 300px;
position: absolute;
display: flex;
flex-flow: column wrap;
outline: 1px solid black;
padding: 3px;
max-height: 200px;
align-content: flex-start;
transform-origin: top left;
}
#failex > p {
margin: 0;
outline: 1px solid black;
height: 30px;
width: 30px;
align-self: flex-start;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="flexdesc">What I expect it to do</div>
<div id="flex">
<p>foo</p>
<!-- add extra "<p>foo</p>" here. -->
</div>
<div id="failexdesc">What it does</div>
<div id="failex">
<p>foo</p>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>Notice how the size of each flex container changes (or doesn't change!)</p>
<p>I want this behavior because I want to place these element side by side for a horizontally scrolling website.</p>
<p><strong>Why doesn't it shrinkwrap? How do I make it shrinkwrap?</strong></p>
<p><br/><br/><br/><br/><hr/></p>
<h1>Original question</h1>
<p><code>flex-flow: row wrap</code> is simple enough to understand. If nothing is "flexing", it acts similar to inline elements; It flows to the right until it can't do so anymore, at which point it makes a new row.</p>
<p><code>flex-flow: column wrap</code> with <code>display: flex</code> is similar. It flows down, until it can't flow down anymore (<code>max-width</code>?), and then starts a new column. Of course, since the parent is <code>display: flex</code>, it's a block-level element, so that column will be halfway over due to the fact that <code>align-content</code> defaults to <code>stretch</code>. I could easily change that to <code>flex-start</code> to make the new column adjacent to the previous.</p>
<p>...but the container is still too wide. It's still a block, and fills the width of it's parent.</p>
<p><strong>I need the flexbox to shrink-to-fit its columns.</strong> Why? I'm trying to use flexbox in a horizontally scrolling website. Granted, I could just let the children overflow, but that overflowing tends to... break things.
So I figured I needed <code>flex-flow: column wrap</code> with <code>display: inline-flex</code>. I was hoping for a "top to bottom, left to right" effect, where the parent has no empty space.</p>
<p>...and then <a href="http://jsbin.com/EGEMUfo/6" rel="noreferrer"><strong>this</strong></a> happened. In chrome, the parent width is equal to the sum of the widths of the children, but otherwise, wrapping is normal. In firefox, the parent is full width, and just grows taller to accomodate the elements (I don't think firefox supports wrapping). In IE11, the width is correct, but the children just overflow down (even out of the body). </p>
<p>I'm so confused.</p>
<p>What am I doing wrong here? I understand that flexbox is a more recent feature, but I can't tell how much of this is my fault vs the browser.</p>
<p>By they way, I'm testing this in chrome. A chrome-only solution is fine by me. (But an elegant catch-all solution is always nice!)</p>
<hr>
<p>Here's <a href="http://jsbin.com/EGEMUfo/6" rel="noreferrer">the code for the demo I linked to</a>, in case jsbin is down:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var ascending = true;
setInterval(function() {
var parent = document.getElementById('flex');
if (ascending) {
var child = document.createElement('p');
child.innerHTML = "f";
parent.appendChild(child);
} else {
parent.removeChild(parent.children[0]);
}
if (parent.children.length <= 1) ascending = true;
if (parent.children.length >= 30) ascending = false;
}, 200);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#flex {
display: inline-flex;
flex-flow: column wrap;
outline: 1px solid black;
padding: 3px;
max-height: 100%;
align-content: flex-start;
}
p {
margin: 0;
outline: 1px solid black;
width: 10px;
}
body {
height: 150px;
width: 300px;
outline: 1px dashed black
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="flex">
<p>f</p>
<!-- add extra "<p>foo</p>" here. -->
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| 0 | 2,566 |
"Failed to load resource: the server responded with a status of 404 (Not Found)" + "Origin … is not allowed by Access-Control-Allow-Origin."
|
<p>I'm creating a react app with 'create-react-app', express, cors and mysql in which a user should enter some details in a form which then will be sent to a db. All the existing entries should be shown on the web app.
I tried that locally and everything worked well. The database has been populated and a request has shown the database entries on the web app.</p>
<p>Then i deployed after a 'npm run build' command to my web-hoster (all-inkl.com). Now, the db entries aren't shown and i also can't populate the db anymore.
The Chrome DevTools and Safari Inspector tell me, that it is something with CORS. After some research i know, that the request to the db should come from the same domain, due to CORS policy (and SOP policy?). But i don't know how to fix it.
In <a href="https://stackoverflow.com/questions/52413398/mobile-only-cors-error-origin-is-not-allowed-by-access-control-allow-origin-in">this post</a> the problem was incorrect db credentials. In my case, I'm pretty sure, that the credentials are correct.</p>
<p>At this code block Chrome throws the corresponding error</p>
<pre><code>getBets = _ => {
fetch("http://www.subdomain.example.de/bets")
.then(response => response.json())
.then(response => this.setState({bets: response.data}))
.catch(err => console.error(err))
};
</code></pre>
<h1>Chrome DevTools Errors:</h1>
<p><em>Failed to load resource: the server responded with a status of 404 (Not Found)</em></p>
<p><em>Access to fetch at '<a href="http://www.subdomain.example.de/test" rel="nofollow noreferrer">http://www.subdomain.example.de/test</a>' from origin '<a href="http://subdomain.example.de" rel="nofollow noreferrer">http://subdomain.example.de</a>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.</em></p>
<p><em>TypeError: Failed to fetch</em></p>
<h1>Safari Inspector Errors:</h1>
<p><em>Origin <a href="http://subdomain.example.de" rel="nofollow noreferrer">http://subdomain.example.de</a> is not allowed by Access-Control-Allow-Origin.</em></p>
<p><em>Fetch API cannot load <a href="http://www.subdomain.example.de/test" rel="nofollow noreferrer">http://www.subdomain.example.de/test</a> due to access control checks.</em></p>
<p><em>Failed to load resource: Origin <a href="http://subdomain.example.de" rel="nofollow noreferrer">http://subdomain.example.de</a> is not allowed by Access-Control-Allow-Origin</em></p>
<p><em>TypeError: Origin <a href="http://subdomain.example.de" rel="nofollow noreferrer">http://subdomain.example.de</a> is not allowed by Access-Control-Allow-Origin</em></p>
<p>Since i don't know which part of the code contains the problem, the whole code is following.</p>
<h2>server.js</h2>
<pre><code>const express = require("express");
const cors = require("cors");
const mysql = require("mysql");
const app = express(); //initialize express
// const PORT = process.env.port;
const SELECT_ALL_BETS_QUERY = "SELECT * FROM markers";
const connection = mysql.createConnection({
host: "http://www.subdomain.example.de",
user: "***",
password: "***",
database: "***"
});
connection.connect(err => {
if (err) {
return err;
}
});
app.use(cors());
app.get("/", (req, res) => {
res.send("go to /test to see tests")
});
app.get("/test", (req, res) => {
connection.query(SELECT_ALL_BETS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
}
})
});
app.get("/test/add", (req, res) => {
const {name, test, count1, count2, type} = req.query;
const INSERT_BET = `INSERT INTO markers (name, test, lat, lng, type) VALUES("${name}", "${test}", 99, 88, "test3")`;
connection.query(INSERT_BET, (err, results) => {
if (err) {
return res.send(err);
}
else {
return res.send("succesfully added your test")
}
})
});
app.listen(4000, () => {
console.log("I'm listening to port 4000")
});
</code></pre>
<h2>App.js</h2>
<pre><code>import React, { Component } from "react";
import './App.css';
class App extends Component {
state = {
tests: [],
test: {
person_name: "Peter Pan",
time: "10:17 Uhr"
}
};
componentDidMount() {
this.getTest();
}
getTests = _ => {
fetch("http://www.subdomain.example.de/test")
.then(response => response.json())
.then(response => this.setState({tests: response.data}))
.catch(err => console.error(err))
};
addTest = _ => {
const { test } = this.state;
fetch(`http://www.subdomain.example.de/tests/add?name=${test.person_name}&bet=${test.time}`)
.then(response => response.json())
.then(this.getTests)
.catch(err => console.error(err))
};
renderBets = ({ test_id, name, test}) =>
<div key={test_id}>
<p>{name}</p>
<p>{test}</p>
</div>;
render() {
const { tests, test } = this.state;
return (
<div>
{tests.map(this.renderTests)}
<div>
<input
value={test.person_name}
onChange={e => this.setState({test: { ...test, person_name: e.target.value}})}
/>
<input
value={test.time}
onChange={e => this.setState({test: { ...test, time: e.target.value}})}
/>
<button onClick={this.addTest}>Click Me</button>
</div>
</div>
)
}
}
export default App;
</code></pre>
<h1>Information to the boundary conditions of the server</h1>
<p>The server ist hosted by <em>all-inkl.com</em>. I working with a premium account due to the possibility of ssh. With ssh i installed node.js in the directory of my project. node.js is required because my project ist built up with reactJS.
If any further information due to the server configuration, please ask since i don't know which information are helpful.
I followed the instructions for installing node.js on <a href="http://mamas-blog.de/2017/05/11/all-inkl-com-node-js-und-composer-im-hosting-einrichten/" rel="nofollow noreferrer">this page</a></p>
<p>In addition, i added the following to the .htaccess-file:</p>
<pre><code><IfModule mod_headers.c>
<FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
</code></pre>
<h1>Edit</h1>
<p>I found a helpful (hopefully) webpage <a href="https://www.test-cors.org" rel="nofollow noreferrer">test-cors</a>. The test outputs the following without passing any request headers:</p>
<pre><code>Fired XHR event: loadstart
Fired XHR event: readystatechange
Fired XHR event: progress
Fired XHR event: readystatechange
Fired XHR event: readystatechange
Fired XHR event: load
XHR status: 200
XHR status text:
XHR exposed response headers:
cache-control: public, max-age=600
content-encoding: gzip
content-type: text/html
date: Fri, 02 Aug 2019 17:36:12 GMT
etag: "1rO4KQ"
expires: Fri, 02 Aug 2019 17:46:12 GMT
server: Google Frontend
x-cloud-trace-context: 2c0391d5a5e09665df3f0b243e2b90a6;o=1
</code></pre>
<p>Does the <em>XHR status</em> mean, that CORS is running and that there isn't any error?</p>
| 0 | 3,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.