title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
wildcard search update in SQL server for XML data coulmn | <p>I have Table T1 which has one XML datatype column C1, here I want to update only domain name.
do need to where for where condition, I have to update this for entire table
Ex:- Data in Column C1 before update</p>
<pre><code> <DocumentElement>
<DeliveryParameters>
<EmailFromAddress>a1@**xyz**.com</EmailFromAddress>
<EmailToAddress>a2@**xyz**.com;a3@**xyz**.com</EmailToAddress>
<EmailCcAddress>a4@**xyz**.com</EmailCcAddress>
</DeliveryParameters>
</DocumentElement>
</code></pre>
<p>Result:- Data should be in C1 after update</p>
<pre><code><DocumentElement>
<DeliveryParameters>
<EmailFromAddress>a1@**abc**.com</EmailFromAddress>
<EmailToAddress>a2@**abc**.com;a3@**abc**.com</EmailToAddress>
<EmailCcAddress>a4@**abc**.com</EmailCcAddress>
</DeliveryParameters>
</DocumentElement>
</code></pre> | 3 |
session method cannot be called 2 times in controller | <p>In the code below, when the #call method executes, it redirects the call to the #connect method to play an audio, then the #connect method redirects to #menu_selection where everything breaks. the error I get in heroku logs is that sessions is nil or defined. </p>
<p>What I dont understand is that I am already using session[:user_id] in the first method #call. why is it no defined in the #menu_selection method?</p>
<pre><code> def call
@list = User.find_by(id: session[:user_id]).contact_lists.find_by(id: session[:last_contact_list_id])
@contacts = @list.contacts
@client = Twilio::REST::Client.new(@@account_sid, @@auth_token)
@contacts.each do |contact|
@call = @client.account.calls.create(
:from => '+18056234397', # From your Twilio number
:to => '+1' + contact.phone , # To any number
:url => root_url + "connect"
)
end
redirect_to root_path
end
def connect
response = Twilio::TwiML::Response.new do |r|
r.Play 'https://clyp.it/l1qz52x5.mp3'
r.Gather numDigits: '1', action: menu_path do |g|
g.Play 'https://a.clyp.it/2mue3ocn.mp3'
end
end
render :xml => response.to_xml
end
def menu_selection
list = User.find_by(id: session[:user_id]).contact_lists.find_by(id: session[:last_contact_list_id])
user_selection = params[:Digits]
@client = Twilio::REST::Client.new(@@account_sid, @@auth_token)
case user_selection
when "1"
@output = "say something."
twiml_say(@output, true)
when "2"
twiml_dial("+1805XXXXX")
when "3"
@output = "Bye Bye..."
twiml_say(@output, true)
end
end
</code></pre>
<p>In the #menu_selection method I get the error : undefined local variable or method `session'</p>
<p>Its in the first line where I'm defining the "list" variable.</p>
<p>I never had this kind of issue before. If anyone knows whats going on, I would appreciate your help.</p>
<p>I tried defining the first @list variable as a class variable outside of the method #call but It gives me the same error that I get now. I also tried making it a class variable inside the #call method to try using it in #menu_selection method, but I get an "@@list is undefined" error.</p> | 3 |
Submit hidden fields with listbox items that have been moved using jQuery | <p>I have two list boxes that I can move items to and from using jQuery. A summary of the code follows:</p>
<pre><code><select multiple size="10" id="from">...</select>
<select multiple id="to" size="10" name="subitted array[]">...</select>
</code></pre>
<p>Some buttons that when clicked move the items from the above list boxes:</p>
<pre><code><a href="javascript:moveSelected('from', 'to')">&gt;</a>...
<a href="javascript:moveSelected('to', 'from')">&lt;</a>
<a href="javascript:moveAll('to', 'from')" href="#">&lt;&lt;</a>
</code></pre>
<p>The jQuery functions:</p>
<pre><code>function moveAll(from, to) {
$('#'+from+' option').remove().appendTo('#'+to);
}
function moveSelected(from, to) {
$('#'+from+' option:selected').remove().appendTo('#'+to);
}
</code></pre>
<p>I also have the following function that I call on submit:</p>
<pre><code><form name="selection" method="post" onSubmit="return selectAll()">... </form>
function selectAll() {
$("select option").attr("selected","selected");
}
</code></pre>
<p>But this only returns by POST the values in the right list box. I would also like to submit other fields present in the form (e.g. hidden fields). How can I do this?</p>
<p>Many thanks. </p> | 3 |
Missing tick label from a plot of data indexed with a PeriodIndex | <p>I'm trying to plot two series and have the x-axis ticks labeled every 5 years. If I index the data with a <code>PeriodIndex</code> for some reason I get ticks every 10 years. If I use a list of integers to index, then it works fine. Is there a way to get the right tick labels with a <code>PeriodIndex</code>?</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
np.random.seed(0)
idx = pd.PeriodIndex(range(2000,2021),freq='A')
data = pd.DataFrame(np.random.normal(size=(len(idx),2)),index=idx)
fig,ax = plt.subplots(1,2,figsize=(10,5))
data.loc[:,0].plot(ax=ax[0])
data.iloc[9:,1].plot(ax=ax[1])
ax[1].xaxis.set_major_locator(mpl.ticker.MultipleLocator(5))
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/7SPHj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7SPHj.png" alt="with PeriodIndex"></a></p>
<pre><code>idx = range(2000,2021)
</code></pre>
<p><a href="https://i.stack.imgur.com/be65y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/be65y.png" alt="with integer idex"></a></p>
<p>The workaround I know is to convert the <code>PeriodIndex</code> to <code>DatetimeIndex</code> and then to an array of <code>datetime.datetime</code>objects and use <code>plt.plot_date()</code> to plot and <code>mpl.dates.YearLocator(5)</code> to format. This seems overly complicated.</p> | 3 |
OAuth2 Single-sign-on component, force reauthentication | <p>Right now I have a Abstract Adapter that handles all the different social medias, the social media adapters just hold the information and pass that to the abstract adapter that then uses OAuth2 to authenticate the user and allows API calls to be made. I want to FORCE the user to reauthenticate everytime they try to login, link or unlink an account. How do I tell OAuth2 I want them to reauth everytime? This is what I pass right now for the authentication:</p>
<pre><code>$this->_oauth = new \League\OAuth2\Client\Provider\GenericProvider(array(
'clientId' => $this->_key,
'clientSecret' => $this->_secret,
'redirectUri' => $this->getObject('request')->getBaseUrl() . $this->_redirect_uri,
'urlAuthorize' => $this->_authorize_uri,
'urlAccessToken' => $this->_access_uri,
'urlResourceOwnerDetails' => ''
));
</code></pre>
<p>So my question, everything works fine, linking, unlinking and signing into an account which has been linked with a social media using that social media. But how do I force the user to reauth everytime even if they logged into Facebook 5 minutes ago and Facebook knows it still has a active session? (Same thing for all other social medias, Facebook is just an example)</p> | 3 |
Medium-editor - link text selection is gone | <p>I am using Medium-editor for content editor. I can able to create link by the help of link button, but while I moved the cursor to input box( link inputbox - placeholder txtbox) the text selection is gone. If it is possible to maintain selection?<a href="https://Anand-cmlmediasoft.tinytake.com/sf/NTI1MzQ0XzI3NTE5NTc" rel="nofollow">Click to see the image reference</a></p>
<p>Here I attached the image. </p> | 3 |
AS3 Does Loader ProgressEvent.PROGRESS event guarantee that server received the request? | <p>I am new to Action Script and I've faced the following code:</p>
<pre><code>var lc: LoaderContext = new LoaderContext();
lc.checkPolicyFile = false;
lc.allowCodeImport = false;
var ldr: Loader = new Loader();
ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadHandler);
ldr.load(new URLRequest(url), lc);
</code></pre>
<p>Does <code>ProgressEvent.PROGRESS</code> event guarantee that server received the request? Can I asume in <code>loadHandler</code> that request has been received or should I use </p>
<pre><code>ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loadHandler);
</code></pre>
<p>instead?</p> | 3 |
getting attribute value updated by removing special characters using lxml | <p>Getting ID attribute and updating its value</p>
<pre><code>for elem in doc.xpath('//@id',namespaces={'leg':'http://www.lexis-nexis.com/glp/leg'}):
s = str(elem)
replaced = re.sub(r'([^a-zA-Z0-9\.\_])','',s)
elem=replaced
</code></pre>
<p>I am getting updated value in value replaced but elem is not updated neither the xml in which i am writing this value.</p> | 3 |
Cannot send file to browser/user | <p>I'm trying to send a zip file to the user.</p>
<pre><code>$file_info = get_file_info($filepath_name);
header("Content-Type: " . get_mime_by_extension($filepath_name));
header("Content-Length: " . $file_info["size"]);
header_remove('Pragma');
header_remove('Cache-Control');
//header("Content-Type: application/force-download");
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.urlencode($filepath_name));
header('Location: file://'.$filepath_name);
readfile($filepath_name);
</code></pre>
<p><code>$filepath_name</code> is set to "D:\dev2.local\storage_users\1\export_data\course_2357.zip".</p>
<p><code>readfile()</code> returns the correct size of file but the file is still not served for downloading.</p>
<p>I've tried all the combinations of headers settings to no avail.</p> | 3 |
How to render series data to a title in sencha charts | <p>I have a chart retrieving data from my store, the four bits of information are the following</p>
<p>Model Code</p>
<pre><code>Ext.define('QvidiApp.model.ClipsViews', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field'
],
config: {
fields: [
{
name: 'meta_id'
},
{
name: 'title'
},
{
name: 'viewed'
},
{
name: 'glances'
}
]
}
});
</code></pre>
<p>Now I have the viewed field and the glances field as the numeric fields in the chart, and the title field as the category title in the chart.</p>
<p>I want to render the title name of the field when I hover over it, reason id this. The titles are too long to fit in the x-axis of the chart so in place of the titles I am putting 'meta_id'. So when I hover over the x-axis meta_id field I want the title name to be shown</p>
<p>so for example</p>
<p>meta_id 100 will equal title value ###</p>
<p>Here's is my chart code so far</p>
<pre><code>{
xtype: 'chart',
centered: true,
height: '150%',
colors: [
'#24ad9a',
'#7c7474',
'#a66111'
],
store: 'ClipsViewed',
axes: [
{
type: 'category',
fields: [
'meta_id'
],
grid: true,
label: {
rotate: {
degrees: 0
},
font: '7px'
},
title: 'Clips'
},
{
type: 'numeric',
fields: [
'viewed'
],
grid: true,
position: 'left',
title: 'Amount'
}
],
series: [
{
type: 'bar',
renderer: function(sprite, config, rendererData, index) {
},
style: {
minGapWidth: 1,
minBarWidth: 60,
maxBarWidth: 70,
opacity: 0.80
},
xField: 'meta_id',
yField: [
'viewed',
'glances'
]
}
],
interactions: [
{
type: 'panzoom'
}
],
legend: {
xtype: 'legend'
}
}
</code></pre>
<p>As you can see in the above code I have a render function but I dont know what to put into it</p> | 3 |
Modifying bash script to take each line in a file and execute command | <p>I need to modify a bash script to to take each line in a file and execute command. I currently have this:</p>
<pre><code>#!/bin/bash
if [ -z "$1" ] ; then
echo "Lipsa IP";
exit;
fi
i=1
ip=$1
while [ $i -le `wc -l pass_file | awk '{print $1}'` ] ; do
if [ -n "$ip" ]; then
rand=`head -$i pass_file | tail -1`
user=`echo $rand | awk '{print $1}'`
pass=`echo $rand | awk '{print $2}'`
CMD=`ps -eaf | grep -c mysql`
if [ "$CMD" -lt "50" ]; then
./mysql $ip $user $pass &
else
sleep 15
fi
i=`expr $i + 1`
fi
done
</code></pre>
<p>The password file is in format and name pfile:</p>
<pre><code>username password
</code></pre>
<p>The intranet hosts file is in this format (line-by-line) and name hlist:</p>
<pre><code>192.168.0.1
192.168.0.2
192.168.0.3
</code></pre>
<p>Any suggestions?</p> | 3 |
Colour polygons of a map in R? | <p>I have used Raster package to upload the map of Spain by provinces (level 2) and I'd like to fill them with colours according to theincome per capita.
Here there's the file with the income per share and the number assigned to each province. Notice that ID_2 is the number assigned by the package Raster, and the variable PROV is the official number assigned by the Spanish Government. </p>
<pre><code>library(raster)
esp<-getData('GADM', country="ESP", level=2)
espPols <- unionSpatialPolygons(esp, esp$ID_2)
renta <- read.table("renta.csv",sep = ";", header=TRUE)
espMapRenta <- SpatialPolygonsDataFrame(espPols, renta)
plot(espMapRenta)
</code></pre>
<p>The first problem I encounter is that there are some provinces repeated in the package, and the second one is that I don't know how to fill each province in a gradient colour by the level of income.</p>
<p>Thank you very much for your help!!
PS. The link to the income per capita data is here: <a href="https://www.dropbox.com/s/si6zpv7p2nap9zg/renta.csv?dl=0" rel="nofollow">https://www.dropbox.com/s/si6zpv7p2nap9zg/renta.csv?dl=0</a></p> | 3 |
invoked storyboard is coming behind all opened window | <p>In a cocoa application i have invoked one storyboard on certain events like button click using :</p>
<pre><code>NSStoryboard *storyBoard = [NSStoryboard storyboardWithName:@"SendStoryboard" bundle:nil];
NSWindowController *myController = [storyBoard instantiateControllerWithIdentifier:@"SendIdentifier"];
[myController showWindow:nil];
</code></pre>
<p>this code is capable of invoking storyboard but i didn't understand why it is coming behind other windows which are already opened in finder.
please help me to resolve the problem. I only want it to be on the top of every window.</p> | 3 |
How to modify object and struct from an existing struct? | <p>I have a struct say</p>
<pre><code>type person struct{
name string
phone string
address string
}
</code></pre>
<p>and I want to transform it to this (modify phone and address) <em>I only have the object not the struct.</em></p>
<pre><code>type person2 struct {
name string
phone []struct {
value string
}
address []struct {
value string
}
}
</code></pre>
<p>How can I create new struct based on one I have ? I want to transform selected fields only.</p>
<p>I looked into reflection but don't know where to start/how to use it.</p> | 3 |
Can't render simple transparent sprites in SharpGL | <p>I know how to generate a plane and map a texture. Now, I am trying to display an alpha-blended PNG on my form, like it was a sprite.</p>
<p>I have come up with the following code from Googling and guessing:</p>
<pre><code>// Get the OpenGL object.
var gl = openGLControl.OpenGL;
// We need to load the texture from file.
var textureImage = Resources.Resource1.bg;
// A bit of extra initialisation here, we have to enable textures.
gl.Enable(OpenGL.GL_TEXTURE_2D);
// Get one texture id, and stick it into the textures array.
gl.GenTextures(1, textures);
// Bind the texture.
gl.BindTexture(OpenGL.GL_TEXTURE_2D, textures[0]);
gl.Enable(OpenGL.GL_BLEND);
gl.BlendFunc(OpenGL.GL_SRC_ALPHA, OpenGL.GL_DST_ALPHA);
var locked = textureImage.LockBits(
new Rectangle(0, 0, textureImage.Width, textureImage.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format32bppArgb
);
gl.TexImage2D(
OpenGL.GL_TEXTURE_2D,
0,
4,
textureImage.Width,
textureImage.Height,
0,
OpenGL.GL_RGBA,
OpenGL.GL_UNSIGNED_BYTE,
locked.Scan0
);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_S, OpenGL.GL_CLAMP);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_T, OpenGL.GL_CLAMP);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, OpenGL.GL_LINEAR);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, OpenGL.GL_LINEAR);
</code></pre>
<p>Here is the original source image that I am using:</p>
<p><a href="https://i.stack.imgur.com/6xnYv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6xnYv.png" alt=""></a></p>
<p>Here is the output when I render this sprite 10 × 10 (100) times on my form:</p>
<p><a href="https://i.stack.imgur.com/0Wxun.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Wxun.jpg" alt=""></a></p>
<p>The output is all messed up, and it doesn't seem to be respecting the image's alpha channel. What changes need to be made to my code to ensure that it renders correctly?</p> | 3 |
How to route posts from firebase to its own section in polymer? | <p>im struggling with some issues regarding routing blog posts from firebase, which i previously pushed it using paper-input and firebase-elements.
this is my code of the custom element:</p>
<pre><code><firebase-collection
location="https://sm-design.firebaseio.com/Blog"
data="{{blog}}"></firebase-collection>
<template is="dom-repeat" items="[[blog]]" as="blog">
<a href="{{baseUrl}}blog/{{blog.link}}"><h1>[[blog.titlu]]</h1></a>
<img src="/images/[[blog.imagine]]">
<p>[[blog.body]]</p>
</template>
</code></pre>
<p>and this is the routing:</p>
<pre><code>page('/blog/{{blog.link}}', function() {
app.route = '{{blog.link}}';
});
</code></pre>
<p>this is the section:</p>
<pre><code> <section data-route="{{blog.link}}">
</section>
</code></pre> | 3 |
Displaying remote images in a firefox add-on panel | <p>I'm trying to display remote images in a FireFox add-on panel, but the <code>src</code> attributes are being converted from something like this:</p>
<p><code>http://example.com/image.jpg</code></p>
<p>to something like this:</p>
<p><code>resource://addon_name/data/%22http://example.com/image.jpg%22</code></p>
<p>I can't figure out if I'm breaking a security policy or not. </p>
<p>In my add-on script (index.js) I'm retrieving image URLs using the sdk/request API and passing them to my content script (data/my-panel.js). My data/my-panel.js file is creating DOM elements in my panel file (data/popup.html) – including images – using the URLs passed from index.js. Here are the relevant bits of code:</p>
<p><code>index.js</code></p>
<pre><code>var Request = require("sdk/request").Request;
var panel = require("sdk/panel").Panel({
width: 500,
height: 500,
contentURL: "./popup.html",
contentScriptFile: "./my-panel.js"
});
Request({
url: url,
onComplete: function(response) {
// Get the JSON data.
json = response.json;
// Launch the popup/panel.
panel.show();
panel.port.emit("sendJSON", json);
}
}).get();
</code></pre>
<p><code>data/my-panel.js</code></p>
<pre><code>var title;
var desc;
var list;
var titleTextNode;
var descTextNode;
self.port.on("sendJSON", function(json) {
json.docs.forEach(function(items) {
title = JSON.stringify(items.sourceResource.title);
desc = JSON.stringify(items.sourceResource.description);
img = JSON.stringify(items.object);
console.log(img);
var node = document.createElement("li"); // Create a <li> node
var imgTag = document.createElement("img"); // Create a <img> node
imgTag.setAttribute('src', img);
imgTag.setAttribute('alt', desc);
imgTag.style.width= '25px';
titleTextNode = document.createTextNode(title);
descTextNode = document.createTextNode(desc);
node.appendChild(titleTextNode); // Append the text to <li>
node.appendChild(descTextNode); // Append the text to <li>
document.getElementById("myList").appendChild(node); // Append <li> to <ul> with id="myList"
document.getElementById("myImgs").appendChild(imgTag);
});
});
</code></pre>
<p>The <code>console.log(img)</code> line is displaying the URLs correctly, but not in popup.html...</p>
<pre><code><!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="myList"></ul>
<p id="myImgs"></p>
</body>
</html>
</code></pre>
<p>How can I make the images' <code>src</code> attributes point directly to the remote URLs?
Thanks!</p> | 3 |
How to set a custom message in the return path? | <p>I'm sending automated emails using java mail to my colleagues in different states (all within our company). I set the <code>return path</code> as their manager's emails. In case the recipient's mail box is full, their manager would get an <code>undeliverable email</code> notification. </p>
<p>Is there any way I can customize that <code>undeliverable message</code>, so that their managers who receive the <code>undeliverable notification</code>, would also get instructions on how to handle those emails and "couch their subordinates" ? </p>
<p>I couldn't find any documentation on this. Is this even possible ? </p> | 3 |
can not get timestamp value inserted in my database table | <p>i have a column called "joined" in my database "users" table which i have created using migration</p>
<pre><code>Schema::create('users',function(Blueprint $table){
$table->increments('user_id');
$table->string('username',100);
$table->string('password',300);
$table->string('full_name',100);
$table->string('email',100);
$table->timestamp('joined');
});
</code></pre>
<p>But whenever i tried to insert a user in my table i get the following error</p>
<blockquote>
<p>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in
'field list' (SQL: insert into <code>users</code> (<code>username</code>, <code>password</code>,
<code>full_name</code>, <code>email</code>, <code>joined</code>, <code>updated_at</code>, <code>created_at</code>) values
(alzami, y$ckR7d.Pt05QRNZXXRGkoOuWDTZAxtDiQ0XA4O2UktSuBd244Oc3qe, al
zami rahman, [email protected], 20-03-16 10-37-11, 2016-03-20
10:37:11, 2016-03-20 10:37:11))</p>
</blockquote>
<p>in my userController i have the following functionality to insert new user in my database</p>
<pre><code> $user=new User();
$user->username=$request->username;
$user->password=bcrypt($request->password);
$user->full_name=$request->full_name;
$user->email=$request->email;
$user->joined=date('d-m-y H-i-s');
$user->save();
</code></pre> | 3 |
Type of expression is ambiguos without more context | <pre><code>text.drawInRect(aRectangle, withFont: font, lineBreakMode: .UILineBreakModeTailTruncation, alignment: .Center)
</code></pre>
<p>I get the error in .UILineBreakModeTailTruncation... so how can i solve it???
I'm working with Xcode 7, swift 2</p>
<p>And im getting another error, which is:
'drawInRect(_:withFont:lineBreakMode:alignment:)' is unavailable.. how can i solve it??</p>
<p>Thanks..!!!</p> | 3 |
Paging issue when data source is changed by ajax - Infragistics WebDataGrid | <p>I have changed data-source of <code>Infragistics</code> <code>WebDataGrid</code> using ajax as below.</p>
<pre><code>$.ajax({
type: "POST",
url: "TestCS.aspx/GetDocumentsAjax",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var grdDoc = $find("DocumentListGrid");
grdDoc.set_dataSource(response);
grdDoc._pi.show(grdDoc);
grdDoc.applyClientBinding();
grdDoc._pi.hide(grdDoc);
}
});
</code></pre>
<p>And it has worked but the data is not divided into pages and I am getting all data at once. Is there any client side thing that could help me persisting paging, sorting info?</p>
<p>Thanks.</p> | 3 |
Quartz .net: with a JobListener, Jobs are not triggered | <p>I have properly created and scheduled a Job (I don't write the Job and Trigger creation here, just to be brief). Scheduler is created and started as follows:</p>
<pre><code>_scheduler = New StdSchedulerFactory().GetScheduler
_scheduler.Start()
</code></pre>
<p>Jobs are executed at the scheduled time.</p>
<p>Then I created a very simple (and empty, at the moment) a JobListener:</p>
<pre><code>Imports Quartz
Public Class JobListener
Implements IJobListener
#Region "Public properties"
Public ReadOnly Property Name As String Implements Quartz.IJobListener.Name
Get
Return "JOB_LISTENER"
End Get
End Property
#End Region
#Region "Methods"
Public Sub JobExecutionVetoed(context As Quartz.IJobExecutionContext) Implements Quartz.IJobListener.JobExecutionVetoed
Throw New NotImplementedException
End Sub
Public Sub JobToBeExecuted(context As Quartz.IJobExecutionContext) Implements Quartz.IJobListener.JobToBeExecuted
Throw New NotImplementedException
End Sub
Public Sub JobWasExecuted(context As Quartz.IJobExecutionContext, jobException As Quartz.JobExecutionException) Implements Quartz.IJobListener.JobWasExecuted
End Sub
#End Region
End Class
</code></pre>
<p>and add it to the scheduler:</p>
<pre><code>_scheduler = New StdSchedulerFactory().GetScheduler
_scheduler.Start()
_jobListener = New JobListener()
_scheduler.ListenerManager.AddJobListener(_jobListener, GroupMatcher(Of JobKey).AnyGroup())
</code></pre>
<p>and now the <strong>Jobs are not executed anymore</strong>.
Any hint why it happens?</p>
<p>Same result if I add the JobListener before starting the Scheduler:</p>
<pre><code>_jobListener = New JobListener()
_scheduler = New StdSchedulerFactory().GetScheduler
_scheduler.ListenerManager.AddJobListener(_jobListener, GroupMatcher(Of JobKey).AnyGroup())
_scheduler.Start()
</code></pre> | 3 |
KafkaException error when using MessageHub Service | <p>Using the Message Hub service recently, I have discovered that previously working apps have begun failing with a <code>KafkaException</code> or <code>Failed to update metadata</code>. </p>
<p>How do I fix this?</p> | 3 |
Do batch scripts treat variables differently in blocks? | <p>I'm running a batch file which updates some variables, notably %PATH%. My environment has a known bug where on of the directories in %PATH% is quoted, i.e.</p>
<pre><code>PATH=c:\windows;...;"c:\program files\foo"\bin;c:\program files\...
</code></pre>
<p>I have a script which appends to PATH. When I do it inside an <code>IF</code> block, I get an error, e.g:</p>
<pre><code>IF "1"=="1" (
SET "PATH=%PATH%;c:\foo"
)
</code></pre>
<p>Gives the error</p>
<blockquote>
<p>\Microsoft was unexpected at this time.</p>
</blockquote>
<p>Where <code>\Microsoft</code> is obviously a fragment from one of the directories in %PATH%.</p>
<p>I don't get the error if the SET is not within a conditional block. Why is this?</p>
<p>Edit: It seems that this has more to do with the fact that PATH also contains parenthesis. Here's a better example of the issue:</p>
<pre><code>C:\temp>SET "FOO=C:\Program Files (x86)\;foo"
C:\temp>ECHO %FOO%
C:\Program Files (x86)\;foo
C:\temp>IF "1"=="1" ( ECHO %FOO% )
\ was unexpected at this time.
C:\temp>IF "1"=="1" ECHO %FOO%
C:\Program Files (x86)\;foo
</code></pre>
<p>So my question is really, why does it break if it's in the paren-delimited block?</p> | 3 |
What is the purpose of using np.random.random(4) for plotting pie charts using matplotlib? | <p>I am relatively new to matplotlib.</p>
<pre><code> ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(0, 0), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(1, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(0, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(1, 0), frame=True)
# Set aspect ratio to be equal so that pie is drawn as a circle.
ax.set_aspect('equal')
</code></pre>
<p><a href="http://%3Chttp://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html%3E" rel="nofollow">http://%3Chttp://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html%3E</a></p> | 3 |
Continuous Scroll Loop between two divs | <p>I am trying to alter this <a href="http://jsfiddle.net/daZmA/535/" rel="nofollow">JSFiddle</a> so that the container is infinitely scrollable both up and down (in a loop). How do I set window.scrollY to handle scrolling up and down on the Y axis? </p>
<p>Here the javascript I am working with:</p>
<pre><code>window.addEventListener('load', function() {
var box = document.getElementById('box'),
box2 = document.getElementById('box2'),
container = document.getElementById('container'),
outer_container = document.getElementById('outer-container'),
current_box = box,
docHeight = document.documentElement.offsetHeight;
window.addEventListener('scroll', function() {
// normalize scroll position as percentage
var scrolled = window.scrollY / (docHeight - window.innerHeight),
scale = 1 - scrolled
transformValue = 'scale(' + (scale) + ')';
current_box.style.WebkitTransform = transformValue;
current_box.style.MozTransform = transformValue;
current_box.style.OTransform = transformValue;
current_box.style.transform = transformValue;
if (scale == 0) {
outer_container.appendChild(current_box);
var older_box = current_box;
current_box = current_box == box ? box2 : box;
container.appendChild(current_box);
window.scrollTo(0, 0);
older_box.style.WebkitTransform = "0";
older_box.style.MozTransform = "0";
older_box.style.OTransform = "0";
older_box.style.transform = "0";
}
}, false);
document.getElementById('nav').addEventListener('click', function(event) {
var level = parseInt(event.target.getAttribute('href').slice(1), 10),
// normalize scroll position
scrollY = (level / 4) * (docHeight - window.innerHeight);
// enable transitions
current_box.className = 'transitions-enabled';
// change scroll position
window.scrollTo(0, scrollY);
}, false);
function transitionEnded(event) {
// disable transition
current_box.className = '';
}
current_box.addEventListener('webkitTransitionEnd', transitionEnded, false);
current_box.addEventListener('transitionend', transitionEnded, false);
current_box.addEventListener('oTransitionEnd', transitionEnded, false);
}, false);
</code></pre> | 3 |
Empty Textarea / Disable Submit for period | <p>I have a problem where I don't know the solution:</p>
<p>I have a form with a small basic validation that only checks if textarea is empty or not.</p>
<p>If it's empty: if-loop should result in the following actions:</p>
<ol>
<li>Show a message (and fade out).</li>
<li>Add a class to submitbutton (black, for "visited")</li>
<li>Add "disabled-attribute" to the button</li>
<li>Wait a period (5000ms)
undo steps 2. and 3., make button clickable again, if it's clicked again with the emptytextarea play game step 1-4 again and again.</li>
</ol>
<p>My function:</p>
<pre><code>$("#abschleppform").submit(function() {
if($("#abschleppkennzeichen").val() == ""){
$("#response").html("<p>Please enter your text!</p>").fadeOut(5000);
$("#submitabschleppdienst").attr("disabled", true).addClass("black");
setTimeout(function(){
$("#submitabschleppdienst").attr("disabled", false).removeClass("black");
}, 5000);
}
else {
alert("Message has been sent");
/*$.ajax({
url: "kundenzufriedenheit/abschleppkundenzufriedenheit.php",
type: "POST",
async: true,
cache: false,
data: $(this).serialize(),
success: function(msg)
{
$("#response").html(msg);
$("#response").fadeOut(5000);
}
});*/
$("#submitabschleppdienst").attr("disabled", true).addClass("black");
}
return false;
});
</code></pre>
<p>My html:</p>
<pre><code><form action = "kundenzufriedenheit/abschleppkundenzufriedenheit.php" method = "POST" id="abschleppform" class="contact-form">
<h4 class="first">Kennzeichen</h4>
<textarea rows="5" id="abschleppkennzeichen" class="kennzeichen" type="text" name="abschleppkennzeichen" ></textarea>
<input type="submit" id="submitabschleppdienst" value="Absenden">
<div id="response"></div>
<div id="response_2"></div>
</form>
</code></pre>
<p>Running: <a href="https://jsfiddle.net/tigercode/60f55L9q/16/" rel="nofollow">https://jsfiddle.net/tigercode/60f55L9q/16/</a></p>
<p>Problem: sending the empty textarea, it doesn't reset to play the steps above (message / disable / enable ...) again. The meesage only shows up once.</p>
<p>Can anybody help me?
Best,
tiger</p> | 3 |
C# Issue sourcing image size - WPF | <p>I am attempting to fit multiple images within the bounds of my screen. I am utilizing a stack panel seeing that this is the best layout for my end goal.
Images from the users local machine should be opened and added to the stack pannel until there is no more screen space to work with.</p>
<p>The issue i am running in to is, when i load my bitmap into memory it is providing me with an inaccurate width (its providing the DPI width however i desire the final width it holds on the screen). ideally, if your screens width is 1000 I would want to load images until 1000 or near 1000 width has been used on screen which is difficult if i cannot source the width of the image (similar to what windows would give me for the width if i looked at the file in explorer)</p>
<p>I am using the following to load the bitmap into memory:</p>
<pre><code> BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(fullFilePath, UriKind.Absolute);
bitmap.EndInit();
MessageBox.Show(bitmap.Height.ToString() + "is the height. this is the width->" + bitmap.Width.ToString());
</code></pre>
<p>The Results i am getting are:
1728 is the height<br>
1152 is the width</p>
<p>for an image which is actually 864 x 1296 (a jpg image).</p>
<p>These images are in a stack pannel, would it be possible to extract the size of a specific stack pannel child?
Example <code>stackpannel.children[0].width</code> Something to that effect?</p> | 3 |
Are the entities with @Lob fields cacheable in Hibernate? | <p>I use Hibernate and MySQL and I need to store the articles in database. The article entity has a field:</p>
<pre><code>@Lob
@Basic(fetch=EAGER)
@Column(name="CONTENT")
private byte[] content;
</code></pre>
<p>Is this entity cacheable in Hibernate?</p> | 3 |
Chai.js: How to correctly use the `and` getter in a language chain | <p><strong>Background</strong></p>
<p>I would appreciate help with learning how to use the <code>and</code> getter as part of a language chain in <a href="http://chaijs.com/api/bdd/" rel="nofollow">Chai</a>. I have tried this code:</p>
<pre><code>describe ('', function () {
it ('', function () {
expect(myVariable).to.be.a('number').and.not.a(NaN);
expect(myVariable).to.be.a('number').and.not.to.be.a(NaN);
}
}
</code></pre>
<p>but both expressions results in the following error message:</p>
<blockquote>
<p>TypeError: type.toLowerCase is not a function </p>
</blockquote>
<p><strong>Question</strong></p>
<p>How do I correctly use the <code>and</code> getter to test if <code>myVariable</code> is a <code>"number"</code> and at the same time ensure that it is not a <code>NaN</code>? </p> | 3 |
Questions about ruby's nil class and rescue | <p>Ruby Koans exercises has a file <code>about_nil.rb</code>. Below is its code:</p>
<pre><code>def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil
begin
nil.some_method_nil_doesnt_know_about
rescue Exception => ex
assert_equal NoMethodError, ex.class
assert_match(/undefined method/, ex.message)
end
end
</code></pre>
<p>What does <code>ex.class</code> mean? What is <code>ex</code> (the error type class)? Why does <code>ex</code> have a class? Also What's the difference between <code>assert_equal</code> and <code>assert_match</code>? Why does the error message need to be between <code>/ /</code>?</p> | 3 |
python original dictionary being modified after each iteration | <p>I have tried to implement Karger's algorithm to compute min cut of a graph by python, and tested my code with a small input graph. Basically I make a copy of the original input graph for every iteration, but after running the code for one iteration the original input graph is somehow modified. Where does my code go wrong? </p>
<pre><code>import random
def random_contraction(graph):
u = random.choice(graph.keys())
v = random.choice(graph[u])
for node in graph[v]:
for vertex in graph[node]:
if vertex == v:
graph[node].remove(vertex)
graph[node].append(u)
graph[u] = graph[u] + graph[v]
graph[u] = [node for node in graph[u] if (node != u and node != v)]
graph.pop(v, None)
def min_cut(graph):
while len(graph) > 2:
random_contraction(graph)
node = random.choice(graph.keys())
return len(graph[node])
graph_input = {0:[1,3,4,5], 1:[0,2,4],2:[1,3,5],3:[0,2],4:[0,1],5:[0,2]}
list_min_cut = []
for dummy_idx in range(100):
print "original", graph_input
#check the original input graph at the beginning of iteration
graph = dict(graph_input)
#make a copy of original input graph
list_min_cut.append(min_cut(graph))
print min(list_min_cut)
</code></pre> | 3 |
add callback function to underscorejs _.invoke | <p>I'm using _.invoke() of Underscore.js to destroy a collection, here is the code:</p>
<pre><code> _.invoke(Labels.selectedItems(), 'destroy', {
error : function (model, response, options) {
self.isFailed = true; // initialized with false
utilities.activateNotification("error", "Deleting label failed", response);
}
});
</code></pre>
<p>How can I add a callback function (or other mechanisms?) to check the value of isFailed after all the destroy functions are finished?</p> | 3 |
Lightswitch HTML: error: value cannot be null. Paramater name: property | <p>has anyone come accross this issue before, all of a sudden one of my details pickers has started displaying this error:</p>
<p><a href="https://i.stack.imgur.com/cVjgL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cVjgL.png" alt="enter image description here"></a></p>
<p>within the database this particular field can be null, and also with the staff tablem which references it, this can also be null, Im not sure on what I should currently do... If i press on the plus symbol however the results are displayed, thankyou for any assistance in this.</p>
<p><a href="https://i.stack.imgur.com/0D3Jv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0D3Jv.png" alt="enter image description here"></a></p> | 3 |
Square API: Batch request to Subscriptions endpoint | <p>The Square <a href="https://docs.connect.squareup.com/api/connect/v1-business/#navsection-subscriptions" rel="nofollow">Subscriptions endpoint</a> works differently from other Square API endpoints. The url begins with <code>/oauth2</code> and requires a special Authorization header to be provided.</p>
<p>Because of these differences, is it possible to include a GET to the Subscriptions endpoint in a <a href="https://docs.connect.squareup.com/api/connect/v1-business/#post-batch" rel="nofollow">Batch request</a>? All of my efforts so far have failed.</p>
<hr>
<p>Here is my POST body to the Batch endpoint:</p>
<pre><code>{
"requests": [
{
"method": "GET",
"relative_path": "/oauth2/clients/MY_CLIENT_ID/subscriptions/SUBSCRIPTION_ID",
"access_token": "Client APPLICATION_SECRET",
"request_id": "MyRequestID"
}
]
}
</code></pre>
<p>And here is the response:</p>
<pre><code>[
{
"status_code": "400",
"type": "bad_request",
"message": "invalid endpoint",
"request_id": "MyRequestID"
}
]
</code></pre> | 3 |
How do I insert a tuple into an existing dictionary in Python | <p>I don't think this is a duplicate question, as I need to add to an existing dictionary, not create a new one.</p>
<pre><code>results = dict()
if xxx:
(rslt_string, rslt_msg) = func1
(rslt_string, rslt_msg) = func2
(rslt_string, rslt_msg) = func5
if yyy:
(rslt_string, rslt_msg) = func3
(rslt_string, rslt_msg) = func5
if zzz:
(rslt_string, rslt_msg) = func2
(rslt_string, rslt_msg) = func5
# How do I add each tuple to the results dict with rslt_string being the key and rslt_msg being the value so that I can do this below?
# Overwriting is ok (good even) if identical key
for (name, msg) in results:
if msg is not "":
test_failed(name)
</code></pre>
<p>Is there a better Python pattern for aggregating the results of some test functions whose call status is dynamic? In my case I have a number of tests to run on the results of a parser. Depending on the type of expression some tests (methods) should be run but not others. I don't know which ones will be needed until run time, but I want to log which ones, if any, fail.</p> | 3 |
How can I find a file within any description of path? | <p>I need find the specific file/folder on my hard drive.
For example i need find a file (do1.bat) and then store the path of the file. But i dont know where can it be stored, so i have to scan all hard drive.
How can i use C# for this?</p> | 3 |
Difficulty understanding condition variable wait | <p>I am having difficulty understanding the condition variable statement</p>
<pre><code>cv.wait(lk, []{return i == 1;});
</code></pre>
<p>from this <a href="http://en.cppreference.com/w/cpp/thread/condition_variable/wait" rel="nofollow">link</a> </p>
<p>what role does the lambda function play here.</p>
<p>Does the above statement mean "Stop blocking when the mutex held by the unique_lock lk is free and i==1 "</p> | 3 |
SSL Handshakes on connection setup | <p>When I test my website performance I noticed SSL handshakes are happening as part of connection setup. I understand the first request (of the page) needs the full SSL handshake.</p>
<p>But, if you notice from the pingdom test, only certain other resources are doing the SSL handshake. The remaining requests in the page do not.</p>
<p>Can someone please explain the logic behind this. </p>
<p><a href="https://i.stack.imgur.com/Enm6e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Enm6e.png" alt="enter image description here"></a></p> | 3 |
Lambda calculus: Apply in Scala | <p>I imagined this would work. Am I doing something clearly wrong?</p>
<pre><code>val apply = (f: Any => Any, v: Any) => f(v)
val square = (x: Int) => x * x
</code></pre>
<p>I imagined apply(square, 10) would result in 100.</p>
<p>But I get an error:</p>
<pre><code>:15: error: type mismatch;
found : Int => Int
required: Any => Any
apply(square, 100)
</code></pre>
<p>What I am missing here?</p> | 3 |
Disabling the iframe overflow:auto; on a Google Apps Script Web App | <p>When creating an apps script web app, I constantly have a vertical scroll bar on the right hand side that is not representative of the pages size and doe snot move when scrolling.</p>
<p>The web app runs inside an iframe, which had an id of <code>userHtmlFrame</code> with <code>overflow-y: scroll;</code> set on it. This causes a scrollbar to always be present whether the page needs to scroll or not. If the page doesn't need to scroll, then it hides content on the right side as seen here: <a href="https://i.stack.imgur.com/fRhtK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fRhtK.png" alt="enter image description here"></a></p>
<p>If the page does need to scroll, it will hide the scrollbar that is supposed to be there.</p>
<p>If I add the appropriate CSS, it does not work. It looks like I cannot change the styling on the iframe from within it.</p>
<p>Is there a way to change the styling on the iframe, or some other property when generating the HTML in apps script to disable the scrolling?</p> | 3 |
Pass a Variable in PHP to Query Database for Deletion | <p>I am trying to create a cron job in php that deletes disabled users found in a csv file and logs the deleted users to a txt file. Everything works except only the last user in the csv file is deleted. Here is what I have so far:</p>
<pre><code>class purgeInactive extends JApplicationCli
{
public function doExecute()
{
$file = '../tmp/purge_user.csv';
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csvRows = array_map('str_getcsv', $contents);
$log = ('../log/purged_users.txt');
$today = date('F j, Y, g:ia');
$row = 1;
if (($handle = fopen("../tmp/purge_user.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
file_put_contents($log, PHP_EOL . 'Removed Disabled User(s): ' . $data[$c] . PHP_EOL . '-' . $today . PHP_EOL, FILE_APPEND);
$disUsers = implode(',', $data);
echo ', ' . $disUsers ; // to test $disUsers output
} // end for statement
} // end while statment
} // end if statement
fclose($handle);
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$userArray = var_export($disUsers,true);
echo PHP_EOL.'This is to test the output of $userArray'.$userArray;
$query
->select($db->quoteName(array('id')))
->from($db->quoteName('#__users'))
//->delete ($db->quoteName('#__users'))
//->where(array($db->quoteName('username') . ' IN(' . $userArray) . ')');
->where(array($db->quoteName('username') . ' = ' . $userArray));
//->where($deleteReq);
$db->setQuery($query);
//$result = $db->execute();
$result = $db->query();
}
}
JApplicationCli::getInstance('purgeInactive')->execute();
</code></pre>
<p>Any suggestions on how to run each user in the csv file individually? I am about brain dead on this as I have been working on it too long.</p>
<p>Note: I am running Joomla that uses ldap and I use echo for <code>$userArray</code> to check results.</p> | 3 |
Functional programming issue is JS | <p>I'm playing around with <code>bind</code> <code>call</code> and <code>apply</code>. I am trying to update a property of an object by passing whatever is returned from one function to the method on that object.</p>
<p>And this updating is attached to the <code>window</code> resize event.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var el = document.getElementById('someElement');
var resolveLeft = function(element) {
return element.offsetLeft;
};
var someObject = {
setDefaultLeft: function(value) {
this.defaultLeft = value;
console.log(this.defaultLeft);
}
};
// this works
window.addEventListener('resize', function() {
someObject.setDefaultLeft(resolveLeft(el));
});
// this one doesn't
window.addEventListener('resize', someObject.setDefaultLeft.bind(someObject, resolveLeft(el)));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#someElement {
position: absolute;
left: 10%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="someElement"></div></code></pre>
</div>
</div>
</p>
<p>I have 2 event bindings. The first one logs out an updated value every single time the window is resized, whereas the second one only logs the initial value that was returned.</p>
<p>I realize that in the second case, the value was returned from <code>resolveLeft</code> already and it doesn't <code>revisit</code> (so to say) the <code>resolveLeft</code> function again. It just passes whatever was returned from the beginning. </p>
<p>Is there a workaround to this?</p>
<p>I have a feeling that currying would solve this? But not sure how to implement in this case.</p> | 3 |
Convert a list and list of list to a dict in python | <p>I have two lists <code>['a', 'b', 'c']</code> and <code>[[1,2,3], [4,5,6]]</code></p>
<p>I am expecting an output <code>{'a':[1,4], 'b':[2,5], 'c':[3,6]}</code> without using a for loop.</p> | 3 |
Expand an ordered series of codes from start/end interval points | <p>I have a data frame of the following kind</p>
<pre><code>> foo <- data.frame(start = c(7, 12, 23, 30), end = c(10, 16, 27, 35), code = rep("A", 4))
> foo
start end code
1 7 10 A
2 12 16 A
3 23 27 A
4 30 35 A
</code></pre>
<p>my goal is to create a new data frame <code>series</code> which expands the ordered series previously compressed in start/end points, and at the same time contains a code B for the points outside the coded intervals in <code>foo</code>:</p>
<pre><code>> series
time code
1 1 B
2 2 B
3 3 B
4 4 B
5 5 B
6 6 B
7 7 A
8 8 A
9 9 A
10 10 B
11 11 B
12 12 A
13 13 A
...
29 29 B
30 30 A
31 31 A
32 32 A
33 33 A
34 34 A
35 35 A
</code></pre>
<p>Any help would be greatly appreciated.</p> | 3 |
DFP sizeMapping Breaks Sponsorships | <p>In my experiences so far, sizeMapping(), for responsive ads in DFP breaks sponsorships. </p>
<p>For example, if I define a sizeMapping like so:</p>
<pre><code>addSize([1024, 768], [970, 90], [728, 90], [320, 50], [300, 250])
</code></pre>
<p>Then I setup a sponsorship on a particular ad unit that's a 728x90.
I also setup a Run of Site (placement) 970x90 that includes all ad units, including the sponsored one, at a lower priority.</p>
<p>The result is that the 970x90 will show before the sponsored 728x90 because of the sizeMapping variable, even on the ad units that are specifically sponsored by the 728x90. </p>
<p>Help!?!</p> | 3 |
How to call a function when a user swipes off the application in android? | <p>I have an application that uses PortSip SDK to make VoIP phone calls, and i need to close the phone call when the users swipes the app off but i want to leave the call when the app is in background. i have a function endCall() which ends the call but if i call it on onDestroy() it gets called even if the app is in background.</p> | 3 |
Why don't two views with shared elevation join and form a seam? | <p>I'm building this app that looks like this:
<a href="http://i.stack.imgur.com/bk2wU.jpg" rel="nofollow">snapshot</a></p>
<p>Here's a break down of the structure of the app.
<a href="http://i.stack.imgur.com/Eci9U.jpg" rel="nofollow">break down</a></p>
<p>It is as simple as this:</p>
<p>I need to constantly change the Fragment within the activity. What I want to achieve is to let the LinearLayout in the Fragment look like as if it is part of the app bar (that is, without shadow casted to it).</p>
<p>theoretically if I set the elevation of the LinearLayout equal to the app bar(4dp or 8dp or whatever), they should be able to bridge the step themselves, but no. Even if I set the elevation of the LinearLayout to 20, it still appears to be underneath the app bar.</p>
<p>Is there any way to tackle this?</p> | 3 |
How to gracefully handle nil checking, with optional paramter values? | <p>I have the following code:</p>
<pre><code>@IBAction func search(sender: AnyObject) {
let searchWord = searchQ.text
let r = searchRadius.text
let latitude = searchLat.text
let longitude = searchLon.text
customSearch(searchWord!, radius: r!, lat: latitude!, lon: longitude!)
}
</code></pre>
<p>the method <code>customSearch</code> has default parameters set in case the user doesn't put anything in, so...</p>
<p>how can I CHECK if searchWord, r, latitude and longitude are nil. If they are nil, then use customSearch functions default parameters, otherwise, use whichever ones were provided and fill out the rest with default values?</p>
<p>Oh and to elaborate, apparently if I take the value of a textfield, and it's empty, it's not nil but an empty string.. so I added the following:</p>
<pre><code>func customSearch(q:String = "", radius:String = "25", lat:String = "33.960", lon:String = "-118.4179") {
let geoSearchWord = (q == "" ? q : "geoSearchWord=\(q)")
let geoSearchLat = (lat == "" ? "33.960" : "&geoSearchWordLat=\(lat)")
let geoSearchLon = (lon == "" ? "-118.4179" : "&geoSearchWordLon=\(lon)")
let geoSearchRadius = (radius == "" ? "25" : "&geoSearchWordRadius=\(radius)")
let twitterURLRequest: String = "https://quiet-cove-5048.herokuapp.com/tw?\(geoSearchWord)\(geoSearchLat)\(geoSearchLon)\(geoSearchRadius)"
alamoRequest(twitterURLRequest)
}
</code></pre>
<p>but I'm still not happy with it.</p> | 3 |
Select value from range based on match | <p>I've got the following set of data and have setup a another table to the right which holds the cost of each location.</p>
<p><a href="https://i.stack.imgur.com/1p12K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1p12K.png" alt="dataset"></a></p>
<p>The cost column currently I've got <code>=IF(EXACT(B2,"Home"),D2*17.2,D2*0.09)</code>, however the cost per kWh can change based on different locations. I want to be able to lookup the cost based on another table which will make things more manageable.</p>
<p><a href="https://i.stack.imgur.com/mfBNq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mfBNq.png" alt="Lookup table"></a></p> | 3 |
SQLite3 issue with getting row ID | <p>it's the first time I am using Sql database and in a quick search I have reached a video explaining how to add an external file called "2SwiftData" , it has many func such as "createTable" etc. now a few Q: <br>
1) am I supposed to close and open the DataBase? <br>
2) why cant I find the table I created in spotlight search? <br>
3) one of the func is <code>SD.lastInsertedRowId()</code> which should return the ID of the row yet no matter what I do, 0 is returned , and the table has info row in<br></p>
<p>The function:</p>
<pre><code>public static func lastInsertedRowID() -> (rowID: Int, error: Int?) {
var result = 0
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
result = SQLiteDB.sharedInstance.lastInsertedRowID()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
</code></pre>
<p>The request:</p>
<pre><code> let ra = SD.lastInsertedRowID() <br>
print(ra)
</code></pre> | 3 |
How do I chart the a second custom data point in Dygraphs? | <p>I'm toying around with Dygraphs and really liking it. However I'm having trouble setting a string value for the second point. I've tried to produce it to be a date, but I would rather keep the custom format for my own date and time.</p>
<p>My simple chart is </p>
<pre><code>new Dygraph(document.getElementById("graphdiv"),
dataload
,
{
labels: [ "x", "A" ],
title: 'Point',
ylabel: 'Value in Eng Units',
xlabel: 'Time & Date'
});
</code></pre>
<p>The code that provides the data into dataload is </p>
<pre><code>i = 0
while ( i < 100){
datappointvalue = [ archivetime[i], archivevalue[i] ] ;
dataload.push(datapidvalue);
}
</code></pre>
<p>As you can guess archivetime and archivevalue are arrays that I populate.
archivetime has the format of a string "22-MAR-2016 20:20:41.26" archivevalue has the format of decimal/int "144.32".</p>
<p>My graph always comes out like
<a href="http://i.stack.imgur.com/XrcZ7.png" rel="nofollow">this</a> - It will always get the values of archivevalue, but never archivetime.</p>
<p>So the question is ultimately how can I display my second value to be the date and time. I would prefer not having to reformat my archivedate into something else, but if necessary that can be done.</p>
<p>Thanks!</p> | 3 |
Codeigniter Url issue: HTTP 404 | <p>I am working on codeigniter
when I used it on xampp server it worked pretty well with this Url
localhost.com/realestate/index.php?class/method/parameter</p>
<p>But when I put similar thing on godaddy host </p>
<p>Same Url segment is showing codeigniter 404 error</p> | 3 |
EWS GetItems response items sort order | <p>I use Exchange 2010 Web Services SDK. And I need to retrieve items using method GetItem.</p>
<p>For example:</p>
<pre class="lang-cs prettyprint-override"><code>var getItemTypes = new GetItemType();
getItemTypes.ItemIds = ids;
getItemTypes.ItemShape = new ItemResponseShapeType()
{
BodyType = BodyTypeResponseType.Best,
BodyTypeSpecified = true,
BaseShape = DefaultShapeNamesType.AllProperties,
IncludeMimeContent = true,
IncludeMimeContentSpecified = true
};
GetItemResponseType getItemResponse = esb.GetItem(getItemTypes);
</code></pre>
<p>And I want to know if items in getItemResponse.ResponseMessages.Items array are strongly corresponds to "ids" array.</p>
<p>The problem is that it is not always possible to retrieve the item ID from response.</p>
<p>Does anybody know the answer?</p> | 3 |
Install chrome extension with Custom text | <p>When installing a chrome extension from the website, we are prompted with the alert box <a href="http://i.stack.imgur.com/w8f0F.png" rel="nofollow">like this</a>. </p>
<p>Is there a way to change the text in the alert box from "Add Extension" to "Add"?</p> | 3 |
merger two dict in python like this | <p>I want merge two dict like this:</p>
<p>from:</p>
<pre><code> a1 = {u'2016-03-11': [u'20:00', u'22:10']}
a2 = {u'2016-03-11': [u'20:00', u'23:10'],u'2016-03-12': [u'20:00', u'22:10']}
</code></pre>
<p>to:</p>
<pre><code> an = {u'2016-03-11': [u'20:00',u'22:10', u'23:10'],u'2016-03-12': [u'20:00', u'22:10']}
</code></pre>
<p>i need a function merge two dict </p> | 3 |
ID increments after each codeception test | <p>I'm using Laravel5 module in Codeception and it works great, but I have a problem which is when I run a test model factory inserts data and rolls back it, but it's effect on 'auto increment' property in id column, which is making the id column is very massive, so how to roll back id also not data only?</p> | 3 |
Wordpress site returns status 500 but still works | <p><a href="http://ststephens.edu/" rel="nofollow noreferrer">http://ststephens.edu/</a></p>
<p>This site returns status code 500 (Internal Server Error) when I do
<code>wget http://ststephens.edu/</code> but works fine on my browser. Also as seen in this screenshot, clearly the homepage is a 500 status but the site seems functional. </p>
<p><a href="https://i.stack.imgur.com/8jZbk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8jZbk.png" alt="enter image description here"></a>
What could make this happen?</p> | 3 |
Miniflux API URL endpoint | <p>I have <a href="http://miniflux.net" rel="nofollow">Miniflux</a> running on an Amazon EC2 instance which I intend to use for my Android application. According to the Miniflux documentation <a href="https://miniflux.net/documentation/json-rpc-api#example-curl" rel="nofollow">here</a> I should be able to get a JSON response with this URL endpoint: </p>
<pre><code>www.mydomain/miniflux/jsonrpc.php
</code></pre>
<p>which in my case is: </p>
<pre><code>{
"jsonrpc":"2.0",
"id":null,
"error":{
"code":-32700,
"message":"Parse error"
}
}
</code></pre>
<p>To get more information in JSON format I need to pass in more arguments but the Miniflux documentation does not explain how. The OpenWeatherMap API on the other hand, has a <a href="http://openweathermap.org/appid" rel="nofollow">guide</a> on how the URL endpoint may be used with the API key. Any advice on this matter will be greatly appreciated.</p> | 3 |
Microsoft.Owin.Host.HttpListener isn't being copied to a referencing projects' build output | <p>I am referencing a one project in Visual Studio solution from another project in the same solution. The project being referenced (Project B) has Microsoft.Owin.Host.HttpListener nuget package and so the .dll referenced in it. The project that is referencing project B (Project A) is being built. The output folder gets all those dlls referenced in Project B, except Microsoft.Owin.Host.HttpListener.dll even though it is marked as Copy Local - true.</p>
<p>The Microsoft.Owin.Host.HttpListener.dll is the only one that I've faced so far that refuses to be copied to the Project A's build output as a part of MSBuild's _CopyFilesMarkedCopyLocal step regardless of the settings.</p>
<p>I've tried to add it to a entries in app.config, it didn't help. </p>
<p>I've arranged the sample project showcasing the referencing problem and uploaded it to GitHub <a href="https://github.com/maxpavlov/HttpListenerTest" rel="nofollow noreferrer">here</a>.</p>
<p>You are free to play with the settings. </p>
<p>I've check out the related questions in Stackoverflow before asking this and they are not answered or unrelated.</p>
<p>Please give me a hint how to get the .HttpListener.dll to be copied along with other .dlls to a referencing projects output as expected.</p> | 3 |
Gradle execution fails when apply Unit Test in Test Artifact | <p>I'm trying to use JUnit in Android Studio but I´m having the following issue when I change the Test Artifcat from <strong>Instrumentation tests ** to **Unit Tests</strong></p>
<pre><code>:app:mockableAndroidJar FAILED
Error:Execution failed for task ':app:mockableAndroidJar'.
> class org.objectweb.asm.tree.ClassNode has interface org.objectweb.asm.ClassVisitor as super class
</code></pre>
<p>Also gives this error:</p>
<pre><code>Error:Execution failed for task ':app:mockableAndroidJar'.
> org/objectweb/asm/tree/ClassNode
</code></pre>
<p>Do someone know why is this happening? </p>
<p>The error not appears when I use the other Test Artifact. </p> | 3 |
Exporting sheet using only values(not formulas) | <p>I am working to export one of the sheet in a workbook.With the following code i was able to do that.However the sheet i am trying to export uses formulas to retrive data in other sheets in workbook.When i change values in main workbook,exported workbook also changes.How can i export the sheet using only values?</p>
<pre><code>Private Sub SAVE()
On Error Resume Next
location = Sheets("data").Range("j2").text
date= Application.text(Now(), "dd/mm/yyyy")
Ad = CreateObject("wscript.Shell")
ActiveSheet.Copy
ActiveWorkbook.SaveAs FileName:=Ad & location & date ".xlsm",FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Application.DisplayAlerts = True
ActiveWorkbook.Close
End Sub
</code></pre> | 3 |
Azure Api Service and Individual accounts | <p>I've originally used Web API 2 with Individual Accounts so that users can create a new account by supplying a username/email and password which is stored in my DB.</p>
<p>I'm now looking to put this API into Azure API service and have looked at the documentation about <a href="https://azure.microsoft.com/en-gb/documentation/articles/app-service-api-dotnet-service-principal-auth/" rel="nofollow">authentication </a> but this mostly talks about external authentication. Can we use Individual Accounts with Azure API or will I need to handle this myself within the actual API?</p>
<p>Also, with the third party authentication all the examples use a redirected website (FaceBook, Google) to get the user to log in. I want to call this from a mobile app so does it support extenal authentication using API calls or will I have to do that myself?</p>
<p>Thanks</p> | 3 |
Can characters be used as indices? | <p>Let's define, for example, </p>
<pre><code>x = 10:10:2000;
</code></pre>
<p>As is well known, integer values can be used as indices:</p>
<pre><code>>> x(9)
ans =
90
</code></pre>
<p>In Matlab, characters can often be used where a number would be expected, with Matlab doing the conversion automatically. For example, since the ASCII code of <code>'a'</code> is <code>97</code>,</p>
<pre><code>>> 'a'+1
ans =
98
</code></pre>
<p>Can characters be also used as indices? Does Matlab convert them into integers?</p> | 3 |
how to format the excel to treat the cell value as text by appending an apostrophe to the cell value in c# | <p>I'm generating excel report in <code>c#</code> in excel.binding data to excel through datatable.</p>
<p>There is one column which will consist of 16 digit number for eg.,<code>1317722825000285</code> but in excel it is coming as <code>1317722825000280</code> last digit is getting replaced by <code>0</code>.</p>
<p>So how to can I format this column value as excel Text ?</p> | 3 |
Python Regex Matching | <p>I am inputting a text file (Line)(all strings). I am trying to make card_type to be true so it can enter the if statement, however, it never enters the IF statement. The output that comes out from the print line is:</p>
<pre><code>imm48-1gb-sfp/imm48-1gb-sfp
imm-2pac-fp3/imm-2pac-fp3
imm5-10gb-xfp/imm5-10gb-xfp
sfm4-12/sfm4-12
</code></pre>
<p>This is the code:</p>
<pre><code> print str(card_type)
if card_type == re.match(r'(.*)/(.*)',line):
card_type = card_type.group(1)
</code></pre> | 3 |
Serialising string arrays into json | <p>So, I've been tinkering with go and have a small problem. I have something that needs to be serialised into a json like so. </p>
<pre><code>{
"name" : "Steel",
"things" : ["Iron", "Carbon"]
}
</code></pre>
<p>The struct to hold this looks like this. </p>
<pre><code>type Message struct {
name string
things []string
}
</code></pre>
<p>and my code itself like this</p>
<pre><code>func main() {
i := Message{"Steel", []string{"Iron", "Carbon"}}
fmt.Println(i);
b, _ := json.Marshal(i)
fmt.Printf(" Json %v\n", b);
var o Message;
json.Unmarshal(b, &o)
fmt.Printf(" Decoded %v\n", o);
}
</code></pre>
<p>When I deserialise the data though, I get back an empty <code>Message</code> like so</p>
<pre><code>{Steel [Iron Carbon]}
Json [123 125]
Decoded { []}
</code></pre>
<p>What am I doing wrong and how do I get it to work?</p> | 3 |
Create a matrix of available pairings in a dataframe | <p>I have a dataframe <code>games</code> that looks like this:</p>
<pre><code> P1 P2
1 Johannes Paul
2 Johannes Falk
3 Paul Falk
4 Paul Kai
. ... ...
</code></pre>
<p>...and so on, where every row matches a game of the two players.
Now I want to have a table or matrix that shows the games that already took place, somewhat like this:</p>
<pre><code> Johannes Paul Falk Kai
Johannes FALSE TRUE TRUE FALSE
Paul TRUE FALSE TRUE TRUE
Falk TRUE TRUE FALSE FALSE
Kai FALSE TRUE FALSE FALSE
</code></pre>
<p>The best I came up with was <code>table(games$P1.Spieler, games$P2.Spieler)</code>, which doesn't quite do the job.</p> | 3 |
How to start and stop video recorder from android application | <p>I need to launch video recorder on click of the button from my application.When user start the recording I need to show count down timer and when the time elapsed video recorder should close automatically.</p>
<p>I searched on many forums and got suggestions to use custom camera recorder, but I don't want use it as I will loose native features like flash,front camera etc.</p>
<p>So the idea is to launch the native video recorder and show timer and when time expires close the recorder and come back to application.</p>
<p>I am able to launch the recorder by 'startActivity()' with camera intent but not able to set timer and close the recorder. Please let me know if it is poosible to do it.</p>
<pre><code>button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launch an intent to capture video from MediaStore
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == ACTION_TAKE_VIDEO) {
Uri videoUri = data.getData();
String filePath = getPath(videoUri);
Log.d("LOGCAT", "Video path is: " + filePath );
}
}
}
</code></pre> | 3 |
Translation and fixed number of letters words | <p>In a part of my software I need, in different languages, lists of words having a fixed number of letters.</p>
<p>My software is already internationalized (using <code>gettext</code>, and it works fine). But, as it's not possible to translate a 4 letters word from english into a 4 letters word in another language (apart from some exceptions maybe), I can't imagine a reasonable way of letting <code>gettext</code> deal with these words lists.</p>
<p>So, for now, I decided to store my words like this (shortened example with english and french names):</p>
<pre><code>FOUR_LETTERS_WORDS = { 'fr': ["ANGE", "ANIS", "ASIE", "AUBE", "AVEN", "AZUR"],
'en': ["LEFT", "LAMP", "ATOM", "GIRL", "PLUM", "NAVY", "GIFT", "DARK"] }
</code></pre>
<p>(This is python syntax, but the problem has not much to do with the programming language used)</p>
<p>The lists do not need to have the same length; they do not need to contain the same words.</p>
<p>My problem is following: if my software is to be translated in another language, like say, german, then all the strings that fall within the scope of <code>gettext</code> will be listed in the pot file and will be available for translation. But then, I also need a list of 4 letters words in german, that won't show up in the translation file.</p>
<p>I would like to know whether I need to think to ask the translator if he/she can also provide a list of such words, or if there's a better way to deal with this situation? (maybe finding a satisfying workaround with <code>gettext</code>?).</p>
<p>EDIT Realized the question has actually not much to do with the programming language, so removed the python* tags</p> | 3 |
How to apply unmerged pull request from original repo into my fork via GitHub website | <p>Trying to do this via the GitHub website.</p>
<p>I am aware of<br>
<a href="https://stackoverflow.com/questions/6022302/how-to-apply-unmerged-upstream-pull-requests-from-other-forks-into-my-fork">How to apply unmerged upstream pull requests from other forks into my fork?</a><br>
and<br>
<a href="https://stackoverflow.com/questions/16254378/github-how-do-i-pull-unmerged-upstream-pull-requests-in-to-my-fork">Github: How do I pull unmerged upstream pull requests in to my fork?</a><br>
but these two are not about doing this via the GitHub website.</p>
<p>So I have made a fork of this repo.<br>
<a href="https://github.com/saabi/vminpoly/" rel="nofollow">https://github.com/saabi/vminpoly/</a><br>
For my understanding this is the original repo. </p>
<p>Now when looking at my fork I obviously do not see the unmerged pull requests from the original repo. </p>
<p>Going to my fork I can see the exact copy of the original repo. However I am at loss trying to get a selection of pull requests from the original repo to appear in my fork via the website. Is this possible at all?</p>
<p>For example how can I get this unmerged pull request<br>
<a href="https://github.com/saabi/vminpoly/pull/29" rel="nofollow">https://github.com/saabi/vminpoly/pull/29</a><br>
to appear in my fork and then of course merge it in my fork?</p>
<p>Can someone please tell me what exactly I need to select to get the mentioned pull request to appear in my fork and then subsequently I can merge it in my forked version?</p> | 3 |
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 on INSERT/SELECT | <p>first of all sorry for my horrible english.</p>
<p>I'm new on android world and now i have so much trouble with sqlite db:</p>
<p>when i try to execute this code:</p>
<pre><code>public void signInOnDB(String name, String surname, String username, String password, String secretQuestion,
String secretAnswer, int g, int m, int a, String regione){
String data = DateTime.setData(g, m, a);
secretAnswer = secretAnswer.toLowerCase();
database.rawQuery("INSERT INTO credenziali (userID, username, password, secretQuestion, secretAnswer) VALUES (null,'" + username + "','" + password + "','" + secretQuestion + "','" +
secretAnswer + "');", null);
Cursor cursor = database.rawQuery("SELECT userID FROM credenziali WHERE username =='"+ username + "';", null);
cursor.moveToFirst();
int id = Integer.parseInt(cursor.getString(0));
cursor.close();
database.rawQuery("INSERT INTO utenti VALUES (" + id + ",'" + name + "','" + surname + "','" + regione + "','" + data + "');", null);
}
</code></pre>
<p>the program generate <code>the android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0</code> when he arrive at <code>int id = Integer.parseInt(cursor.getString(0));</code></p>
<p>I really don't have idea why generate exception, the query can't be null because I insert that value three lines up with the INSERT query.</p>
<p>If I execute that 3 queries on SQLite Browser the returned record is right.</p>
<p>Anyone can help me?</p>
<p>Invoking method:</p>
<pre><code>databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
databaseAccess.signInOnDB(insert_name.getText().toString(), insert_surname.getText().toString(),
insert_username.getText().toString(), insert_password1.getText().toString(), insert_secretQuestion.getText().toString(),
insert_secretAnswer.getText().toString(), g, m, a, regionResidence);
databaseAccess.close();'
</code></pre>
<p>Definition of open()/close():</p>
<pre><code>/**
* Open the database connection.
*/
public void open() {
this.database = openHelper.getWritableDatabase();
}
/**
* Close the database connection.
*/
public void close() {
if (database != null) {
this.database.close();
}
}
</code></pre>
<p>Definition of openHelper:</p>
<pre><code>public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "GDB.db";
private static final int DATABASE_VERSION = 1;
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
</code></pre> | 3 |
Simple Form and routing errors | <p>View/Form</p>
<pre><code><div class="col-lg-12">
<div class="ibox-content">
<div class="row">
<%= simple_form_for supplier_fuel_prices_path(@supplier,@fuel_price), method: :post do |f| %>
<%= f.input :regular, label: "Regular" %>
<%= f.input :medium, label: "Medium"%>
<%= f.input :premium, label: "Premium" %>
<%= f.input :diesel, label: "Diesel" %>
<%= f.button :submit, "Update"%>
<%end%>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>controller </p>
<pre><code>class Supplier::FuelPricesController < Supplier::ApplicationController
before_action :set_supplier
def index
end
def new
@fuel_price = @supplier.fuel_prices.build
end
def create
@fuel_price = @supplier.fuel_price.build(fuel_price_params)
if @fuel_price.save
flash[:notice] = "You have successfully Added new Fuel Price."
redirect_to supplier_fuel_prices_path
else
flash.now[:alert] = "Something went wrong. Please try again."
render "new"
end
end
private
def fuel_price_params
params.require(:fuel_price).permit(:regular, :medium, :premium, :diesel)
end
def set_supplier
@supplier = User.find_by(params[:supplier_id])
end
end
</code></pre>
<p>Models </p>
<p>User model has has_many :fuel_prices, foreign_key: :supplier_id</p>
<p>Fuel Price Model has belongs_to "supplier", class_name: "User"</p>
<p>Error i am getting when submitting the form is </p>
<p><strong>No route matches [POST] "/supplier/fuel_prices/new"</strong></p>
<p>My routes looks like this </p>
<pre><code> namespace :supplier do
root to: 'dashboard#index', as: 'dashboard'
resources :retailers
resources :fuel_prices
end
</code></pre>
<p>Routes</p>
<p>supplier_fuel_prices_path GET /supplier/fuel_prices(.:format)
POST /supplier/fuel_prices(.:format) supplier/fuel_prices#create</p>
<p>new_supplier_fuel_price_path GET /supplier/fuel_prices/new(.:format) supplier/fuel_prices#new</p>
<p>edit_supplier_fuel_price_path GET /supplier/fuel_prices/:id/edit(.:format) supplier/fuel_prices#edit
supplier_fuel_price_path</p> | 3 |
Date class setMonth sets weird values | <p>I have the following test code:</p>
<pre><code> var d1 : Date = new Date("2016/02/20 15:00:00 UTC-0000");
trace(d1.toUTCString());
d1.monthUTC++;
trace(d1.toUTCString());
var d2 : Date = new Date("2016/03/31 15:00:00 UTC-0000");
trace(d2.toUTCString());
d2.monthUTC++;
trace(d2.toUTCString());
</code></pre>
<p>This traces</p>
<pre><code>[trace] Sat Feb 20 15:00:00 2016 UTC
[trace] Sun Mar 20 15:00:00 2016 UTC
[trace] Thu Mar 31 15:00:00 2016 UTC
[trace] Sun May 1 15:00:00 2016 UTC
</code></pre>
<p>Why does date in the second example jump 1 month and 1 day instead of just one month? (from Mar. 31th to May 1st)?</p> | 3 |
android browser does not launch app | <p>I am unable to get the app I have written to launch when a certain url is passed back to the browser.</p>
<p>When the user launches the default browser and goes to the where my server is running for example: www.test.com, a list of films and books are displayed on the remote server. When the user selects one of these items i.e. a film or book - the server sends back a url that starts with bb:// and contains the uri link.fil?data=1. So the url looks like this when sent back from the server:</p>
<pre><code> bb://link.fil?data=1
</code></pre>
<p>Currently I have the manifest which declares the following filter intent:</p>
<pre><code> <intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="bb"
android:host="test.com"
android:path="/.*"
android:pathPattern="/.*\\.*"/>
/>
<data
android:scheme="bb"
android:host="www.test.com"
android:path="/.*"
android:pathPattern="/.*\\.*"
/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</code></pre>
<p>What I am trying to make happen is when the user selects a book of film the returning url launches my app. </p>
<p>After following many of the examples on line I still don't seem to be able to get this to work, and would appreciate any help you can provide.</p> | 3 |
Why does my regular navbar cover header while the collapsed one does not? (bootstrap/fullpage) | <p>I have some problems with my navbar covering my header instead of positioning below relative to the header height. When i use a smaller screen and the navbar goes over to collapse it positions below like it should, how come?</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>main {
position: relative;
background-image: url(asdasdads-321-redigerad-2.jpg);
top: 0;
width: 100%;
height: 100%;
background-color: white;
background-repeat: no-repeat;
background-position: bottom;
background-size: cover;
}
header {
width: 100%;
height: 100px;
position: fixed;
top: 0;
}
.container {
position: relative;
}
.navbar-fixed-top {
position: relative;
}
.navbar-default {
position: relative;
width: 100%;
background-color: rgba(255, 255, 255, 0);
border-bottom: 3px solid rgba(51, 51, 51, 0);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<header>
<h1>header</h1>
<p>asdf asdas dasdadf dgfsd sdf asf fsdfsdf sdfa sfasf df</p>
</header>
<nav class="navbar-default" role="navigation">
<div class="container">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-container">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="collapse navbar-collapse" id="navbar-container">
<ul id="menu">
<li><a href="#firstPage" title="Ab knapp" id="Ab-logo">UPPDRAG</a></li>
<li data-menuanchor="secondPage" id="filosofi"><a href="#secondPage">FILOSOFI</a></li>
<li data-menuanchor="thirdPage" id="uppdrag"><a href="#thirdPage">UPPDRAG</a></li>
<li data-menuanchor="4thpage" id="karriär"><a href="#4thpage">KARRIÄR</a></li>
<li data-menuanchor="5thpage" id="academy"><a href="#5thpage">ACADEMY</a></li>
<li data-menuanchor="lastPage" id="kontakt"><a href="#lastPage">KONTAKT</a></li>
</ul>
</div>
</div>
</nav></code></pre>
</div>
</div>
</p> | 3 |
Why does retain cycle leak memory? | <p>I'm a little confused about retain cycle.As the pictures show,it's a retain cycle.My opinion is when running out of the scope,test0 will release,obj_ will release,so the reference count of object A and B will be one, also when this happens on test1,then the reference count will be zero,finally,free the memory.What's the problem?
<a href="http://i.stack.imgur.com/aJqN6.png" rel="nofollow">enter image description here</a>
<a href="http://i.stack.imgur.com/RVT9N.png" rel="nofollow">enter image description here</a></p> | 3 |
Add contact using contact app to a non google account | <p>While adding a contact from contact app(default) we have a account picker dialog in which we see that (SIM 1,SIM 2,gmail account).</p>
<p><strong>MY QUESTION IS</strong> : I want to add a contact in my custom contact provider using contact app but there is no option to do that because when I click on the add button of contact app I get only these options(SIM 1,SIM 2,gmail account),
Thanks in advance.</p>
<p><a href="https://i.stack.imgur.com/Sxxsg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sxxsg.png" alt="enter image description here"></a></p> | 3 |
Insert "cut off" field in R surface plot | <p>I'm using persp() to create a 3d plot (but I'm open to anything that will get the job done). Now I want to add a 2d field to make it clear where the 3d plot is above a specific Z value. Is there a way to achieve this? Ideally it would ideally be something like a semi transparent surface where you can see the mass under the surface vs over. </p>
<p>Using the example from the persp documentation</p>
<pre><code>f <- function(x, y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
x <- seq(-10, 10, length= 30)
y <- x
z <- outer(x, y, f)
z[is.na(z)] <- 1
persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",
ltheta = 120, shade = 0.75, ticktype = "detailed",
xlab = "X", ylab = "Y", zlab = "Sinc( r )"
)
</code></pre>
<p>How can I insert a field that slices the graph at a certain point of the z-axis?</p> | 3 |
How To Get Most Frequent Words With Association In PHP | <p>I want to get the most frequent search word With Association Rules. </p>
<p>the php code contains two files. In which data is inserted every input is storing in the file along with its association for example :- <strong>if some one has search "apple" and he has also searched for "orange". Now I want to get the most frequent searched words.</strong></p>
<p>I have got the frequency of the words but now i want to show top 10 frequent words with their association</p>
<pre><code><?php
$item = file('item.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
$data = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
$item_array = array();
foreach ($item as $value) {
$total_per_item[$value] = 0;
foreach($data as $item_data) {
if(strpos($item_data, $value) !== false) {
$total_per_item[$value]++;
}
}
}
echo "<pre>";
echo "Occurrance";
print_r($total_per_item);
$item1 = count($item) - 1; // minus 1 from count
echo $item1."<br/>";
$item2 = count($item); // minus 1 from count
echo $item2."<br/>";
$item_loop = (pow($item1,2) + $item1) / 2;
echo $item_loop;
for($i = 0; $i < $item1; $i++) {
for($j = $i+1; $j < $item2; $j++) {
$item_array[$item[$i].'-'.$item[$j]] = 0;
foreach($data as $item_data) {
if((strpos($item_data, $item[$i]) !== false) && (strpos($item_data, $item[$j]) !== false)) {
$item_array[$item[$i].'-'.$item[$j]]++;
}
}
echo $item_array[$item[$i].'-'.$item[$j]]++."<br/>";
}
}
print_r($item_array);
?>
</code></pre>
<p>file.txt contains following data</p>
<pre><code>Milk
Butter
Bread
Oil
Cheese
Burger
</code></pre>
<p>data.txt contains following data:-</p>
<pre><code> Milk,Butter
Butter,Oil
Burger,Milk
Milk,Cheese
Oil,Butter
Burger,Oil
</code></pre> | 3 |
Error while integrating MillenialMedia mediation through AdMob | <p>I have adMob working perfectly (I am getting adMob test ads)and im trying to add MillennialMedia as another adSource. However, after following the instructions I get 31 warnings and most of them look like that </p>
<pre><code>while processing /Users/Wagner/Documents/Xcode Projects/ProjectA/mm-ad-sdk-ios-6.1.0-222a9a3/mediation_adapters/ios-mm-admob-adapter-1.0.1-88fe579/libMMAdMobAdapter.a(MMAdMobAdapter.o):
warning: /Users/stramer/Library/Developer/Xcode/DerivedData/ModuleCache/IBN9JU271CTC/Foundation-A3SOD99KJ0S9.pcm: No such file or directory
while processing /Users/Wagner/Documents/Xcode Projects/ProjectA/mm-ad-sdk-ios-6.1.0-222a9a3/mediation_adapters/ios-mm-admob-adapter-1.0.1-88fe579/libMMAdMobAdapter.a(MMAdMobAdapter.o):
warning: /Users/stramer/Library/Developer/Xcode/DerivedData/ModuleCache/IBN9JU271CTC/Foundation-A3SOD99KJ0S9.pcm: No object file for requested architecture
(null): warning: /Users/stramer/Library/Developer/Xcode/DerivedData/ModuleCache/IBN9JU271CTC/Foundation-A3SOD99KJ0S9.pcm: No such file or directory
(null): warning: /Users/stramer/Library/Developer/Xcode/DerivedData/ModuleCache/IBN9JU271CTC/Foundation-A3SOD99KJ0S9.pcm: No object file for requested architecture
(null): warning: /Users/stramer/Library/Developer/Xcode/DerivedData/ModuleCache/IBN9JU271CTC/GoogleMobileAds-3NBJJMJ6U9J0B.pcm: No such file or directory
(null): warning: /Users/stramer/Library/Developer/Xcode/DerivedData/ModuleCache/IBN9JU271CTC/GoogleMobileAds-3NBJJMJ6U9J0B.pcm: No object file for requested architecture
(null): warning: /Users/stramer/Library/Developer/Xcode/DerivedData/ModuleCache/IBN9JU271CTC/UIKit-2LM3EQU7VVY4O.pcm: No such file or directory
(null): warning: /Users/stramer/Library/Developer/Xcode/DerivedData/ModuleCache/IBN9JU271CTC/UIKit-2LM3EQU7VVY4O.pcm: No object file for requested architecture
</code></pre>
<p>and a much more similar ones. I already have Foundation.framework and all the other required framework linked. (except libxml2.dylib; everytime i add this xCode adds libxml2.2.dylib instead - Not sure if it matters?). I am not sure what is going on. </p> | 3 |
Adding Wildcards to Forge Server later | <p>When I created a server using Laravel Forge, I didn't provision it with wildcards at inception. I would like to add wildcards now, while the server is running. Can this be done?</p> | 3 |
Binding Troubles ViewModel with Command | <p>I have a binding problem.
Maybe I didn't see it.</p>
<p>XAML File</p>
<pre><code><ItemsControl Grid.Row="1" Grid.Column="1" x:Name="itemsControlTiles" ItemsSource="{Binding ProductCatalogLightList}" Margin="10">
<ItemsControl.Template>
<ControlTemplate>
<WrapPanel Width="800" HorizontalAlignment="Left"
FlowDirection="LeftToRight" IsItemsHost="true">
</WrapPanel>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Controls:Tile Title="{Binding Name}"
Margin="3"
Background="{Binding Background}"
Style="{StaticResource PrdukteTileStyle}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding Source={StaticResource productsTileViewModel}, Path=DoSomethingCommand}"
CommandParameter="{Binding ID,ElementName= ProductCatalogLightList}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Controls:Tile>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</code></pre>
<p>So my Problem is the CommandParameter Binding.</p>
<p>My ModelView looks like that</p>
<pre><code>public class Product_Catalog_Light
{
public string Name { get; set; }
public string Description { get; set; }
public int ID{ get; set; }
public System.Windows.Media.Brush Background { get; set; }
}
public class ProductsTileViewModel : INotifyPropertyChanged
{
private ObservableCollection<Product_Catalog_Light> _product_Catalog_LightList;
public ProductsTileViewModel()
{
ProductCatalogLightList = new ObservableCollection<Product_Catalog_Light>();
}
......
public ObservableCollection<Product_Catalog_Light> ProductCatalogLightList
{
get { return _product_Catalog_LightList; }
set
{
_product_Catalog_LightList = value;
OnPropertyChanged("ProductCatalogLightList");
}
}
}
public ICommand DoSomethingCommand
{
get
{
return _doSomethingCommand ??
(_doSomethingCommand = new DelegateCommand<int>(ExecuteDoSomethingWithItem));
}
}
private DelegateCommand<int> _doSomethingCommand;
private void ExecuteDoSomethingWithItem(int db_ID )
{
// Do something wir the _id
int i = 5;
}
</code></pre>
<p>I'm getting an error message that says it can't find the binding source.</p>
<blockquote>
<p>System.Windows.Data Error: 4 : Cannot find source for binding with
reference 'ElementName=ProductCatalogLightList'.
BindingExpression:Path=ID; DataItem=null; target element is
'InvokeCommandAction' (HashCode=11254959); target property is
'CommandParameter' (type 'Object')</p>
</blockquote> | 3 |
include ReadMe.md, convert to markdown and include in html | <p>I am writting a github gh-page <code>index.html</code>: </p>
<p>Is it possible with some javascript, to import the <code>ReadMe.md</code> from a link and send it to the markdown javascript formatter (<a href="https://assets-cdn.github.com/javascripts/ace/mode/markdown.js" rel="nofollow">i think thats the file</a>) of github and append the output somewhere in the <code>index.html</code>?</p>
<p>I am new to javascript and html.</p> | 3 |
JPA Grouping based on a column and collecting results in a list | <p>I am using Spring data JPA I have a table that looks like</p>
<pre><code> NAME AGE GANG
---------------------------------
Iron Man 46 1
Black Panther 45 1
Captain America 96 2
Ant Man 40 2
The hulk 48 3
</code></pre>
<p>I want to map this to the following class without the N+1 selects problem</p>
<pre><code>public class Gang {
private int id;
private List<Member> members;
}
public class Member {
private String name;
private int age;
}
</code></pre>
<p>I tried self join with @OneToMany but I couldn't get through. Any ideas?</p> | 3 |
I'm moving jar file to other PC then the program not showing image | <p>I finished my project and done the compilation. Running the Jar file, program is working.
If I'm moving jar file to other PC then the program is not showing image and not showing information from txt files.
I thinking this is from wrong paths. Can you help me?
This some code:</p>
<pre><code>FileInputStream fr2 = new FileInputStream("C:\\Users\\Nickolskiy\\IdeaProjects\\DeutcheCard\\src\\com\\2.txt");
BufferedReader br2 = new BufferedReader (new InputStreamReader(fr2, "Cp1251"));
</code></pre> | 3 |
Do transactions made using REST API show when using Classic API? | <p>I know that transactions made via Classic API will not return when using the REST API. But what about vice versa? Can I pull all transactions if using the Classic API?</p> | 3 |
ui-sref is not working inside apk | <p>I create an apk using with yeoman angularjs-cordova </p>
<p>I put here only specific require Folder Structure
Module</p>
<ul>
<li><p>Core -> Views -> home.html</p></li>
<li><p>Customer</p>
<p>-> Config -> route.js</p>
<p>-> Views -> dashboard.html</p></li>
</ul>
<p>In home.html a link <code><a ui-sref="dashboard">User Dashboard</a></code> is there. </p>
<p>My route.js of Customer module is</p>
<pre><code>'use strict';
//Setting up route
angular.module('customer').config(['$stateProvider',
function($stateProvider) {
// Customer state routing
$stateProvider.
state('dashboard', {
url: '/dashboard',
views: {
'@':{
templateUrl: 'app/modules/customer/views/dashboard.html',
controller: 'CustomerController'
},
'left@dashboard':{
templateUrl: 'app/modules/customer/common/left.html',
controller: 'CommonController'
},
'header@dashboard':{
templateUrl: 'app/modules/customer/common/header.html',
controller: 'CommonController'
},
},
})
}
]);
</code></pre>
<p>ui-sref is working properly in web browser but in Android device ui-sref is not working</p> | 3 |
googleVis Chart not Displaying in Slidify | <p>I'm trying to get started with slidify and have been trying to reproduce some of the examples shown around the internet. I am not able to get googleVis charts to display inside slidify. I can print the googleVis chart to file and open it outside of slidify to get it to work correctly, but inside slidify I get the following:
<a href="https://i.stack.imgur.com/bsacM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bsacM.png" alt="googleVis in slidify"></a></p>
<p>This is from the Fruits example.</p>
<pre><code>```{r, echo = FALSE, message = FALSE, results = 'hold'}
require(googleVis)
M1 <- gvisMotionChart(Fruits, idvar = "Fruit", timevar = "Year")
plot(M1, tag = 'chart')
```
</code></pre> | 3 |
Customizing the tick marks in D3 LineChart | <p>I am trying to make a line chart as shown below - </p>
<p><a href="https://i.stack.imgur.com/nueIf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nueIf.png" alt="enter image description here"></a></p>
<p>Here there is a small distance between the x-axis first value and the y-axis.</p>
<p>I could achieve as shown below -</p>
<p><a href="https://i.stack.imgur.com/uxQbQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uxQbQ.png" alt="enter image description here"></a></p>
<p>Here I am not able to distance the x-axis first value from y-axis.</p>
<p>Can anyone help me to bring the space between first value in x-axis and y-axis line.</p>
<p>here is the code that I wrote to achieve the same.</p>
<pre><code>$(document).ready (function (a){
var width = 400,
height = 150,
padding = {top: 10, bottom: 30, left: 40, right: 40};
vis = d3.select("#graph").append("svg:svg")
.attr("width", width)
.attr("height", height);
var yScale = d3.scale.linear()
.domain([0, 100])
.range([height - padding.bottom, padding.top]);
var mindate = new Date(2012,0,1),
maxdate = new Date(2012,5,31);
var xScale = d3.time.scale()
.domain([mindate, maxdate])
.range([padding.left , width - padding.right * 2]);
var yAxis = d3.svg.axis()
.orient("left")
.scale(yScale)
.outerTickSize(0)
.ticks(5);
var xAxis = d3.svg.axis()
.scale(xScale) .outerTickSize(0)
.tickFormat(d3.time.format("%b"))
.tickPadding(5)
.ticks(6);
vis.append("g")
.attr("transform", "translate(" + padding.right + ",0)")
.attr("class", "y-axis")
.call(yAxis);
vis.append("g")
.attr("transform", "translate(0," + (height - padding.bottom) + ")")
.attr("class", "x-axis")
.call(xAxis);
var xaxistickmarksY2 = vis.selectAll(".x-axis line")
.attr("y2");
var yaxistickmarksX2 = vis.selectAll(".y-axis line")
.attr("x2");
// Define the line
var valueline = d3.svg.line().x(function(d) {
return xScale(Date.parse(d.date));
}).y(function(d) {
return yScale(d.value);
});
var data = [{date: "January 01, 2012", value: 40},{date: "March 01, 2012", value: 40},{date: "April 01, 2012", value: 50},{date: "May 01, 2012", value: 20}];
vis.append("path")
.attr("class", "line")
.attr("d", valueline(data));
vis.selectAll(".y-axis line")
.attr("x2", (-1 * yaxistickmarksX2));
vis.selectAll(".x-axis line")
.attr("y2", (-1 * xaxistickmarksY2));
removeFirstTicks();
vis.selectAll("path")
.style ("fill", "none")
.style ("stroke", "black")
.style ("stroke-width", "px")
.style ("shape-rendering", "crispEdges");
vis.selectAll("line")
.style ("fill", "none")
.style ("stroke", "black")
.style ("stroke-width", "px")
.style ("shape-rendering", "crispEdges");
function removeFirstTicks() {
vis.selectAll(".x-axis .tick")
.each(function (d,i) {
if ( i === -1 ) {
this.remove();
}
});
vis.selectAll(".y-axis .tick")
.each(function (d,i) {
if ( i === 0 ) {
this.remove();
}
});
}
</code></pre> | 3 |
Angular2 w/ Typescript - Client/Server App the right way? | <p>I'm cutting my teeth on Angular2 (and Angular in general) getting the core concepts under my belt and have been working on my first "real" application. I'm using some sample projects on GitHub and the quickstart on the Angular site as guides but have run into some roadblocks and am looking for some advice on the "right" way to set up the directory structure, integrate typings and reference node modules in the application. Obviously some aspects would be personal coding preference so I'm just out here fishing for some best practices advice.</p>
<p>Application Overview:</p>
<ul>
<li>Application has a server-side component used to connect to a local SQL server and brokers calls from the client side to provide data to be displayed.</li>
<li>Application has a client-side component used to serve pages/template and communicate with the server-side to make calls to retrieve data and display it on the page</li>
<li>Application uses gulp to configure and launch both the server and the client side (different calls - eg: gulp start-server / gulp start-client)</li>
</ul>
<p>I have the basics of all of the working so my question isn't really about that. My issues come up when I have node modules that I need to leverage and what is the right way / best way to integrate those.</p>
<p>Lets say my basic directory structure is like this (based on sample projects I'm using as references)...</p>
<pre><code>- client
|- public
|- app
|- css
|- lib (some js files)
|- etc...
index.html
|- typings
client.ts/js
- node_modules
|- modules installed via npm install
- server
|- core (contains db-connection)
|- typings
server.ts/js
</code></pre>
<p>Now, lets say I needed and installed the node module Rxjs and need to reference it in my client-side...this is where things are getting unclear for me.</p>
<p>I've seen some postings that I should be using the "map" feature of System.config to map to the node_module in conjunction with the packages feature in the index.html file, but I am unable to get that to work. The app launches, but the client side app component doesn't appear to be able to see it. It's almost like an out-of-scope issue. (Sorry, I do not have the exact error message handy). If I use map, am I allowed/supposed to map it to its home in the node_modules directory or should I be putting the needed typescript files within the directory structure of Public?</p>
<p>I've also seen some postings where you can just move the js file to say the lib directory and reference it as a javascript src file in index.html...but I'm getting no joy there either.</p>
<p>I believe that part of the issue is likely ties to requires/dependencies within the various node_modules themselves, but I'm not sure how to deal with that.</p>
<p>So, what is the right/best way to set this all up and integrate the node_modules that I need? Is it simply not possible to reference modules within the node_modules from a client-side app and I need to bring all of the .d.ts/ts/js files into the public scope? If so, do I need to investigate the references within each ts file and bring everything over?</p>
<p>I understand that I may not be providing all or perfectly specific details here, but I hope you can see the higher-level best-practices question that I'm posing here and push me in the right direction.</p> | 3 |
Explanation of android code | <p>i found a code that converts a hex string to binary. This is the code ` </p>
<pre><code>public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
public static byte charToByte(char c) {
System.out.println((byte) "0123456789ABCDEF".indexOf(c));
return (byte) "0123456789ABCDEF".indexOf(c);
}
</code></pre>
<p>The code works perfectly but i am not able to understand the following line of code ie how it is working <code>d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));</code>. Can anyone explain what this code is doing. It is going very difficult to work on binary code. Also can anyone provide a link for some documentation that explains with some example how to work with binary codeing.</p> | 3 |
Header in fixed position is overlapping with container div when the window is reduced in width | <p>i have a small issue with my header, i added a media query which make it taller when the window is reduced in width but it's actually overlapping my container.
I try to add another media query in order to lower the top position of the container but it doesn't work</p>
<p><a href="https://jsfiddle.net/Ltqsjhbz/1/" rel="nofollow">https://jsfiddle.net/Ltqsjhbz/1/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>header {
position: fixed;
width: 100%;
top: 0;
left: 0;
z-index: 100;
background: black;
background-position: center;
height: 200px;
color: white;
}
#menu li {
display: inline;
}
@media screen and (max-width: 600px) {
#menu li {
display: block;
margin: 30px;
}
header {
height: 400px;
}
#container {
position: absolute;
top: 400px;
}
}
#menu a {
background-color: #00BFFF;
color: white;
padding: 10px 20px;
text-decoration: none;
border-radius: 40px 4px;
}
#menu a:hover {
background-color: #0489B1;
}
h1,
h2,
nav {
text-align: center;
margin: 30px;
}
h3,
form,
footer {
text-align: center;
}
#container {
position: absolute;
top: 200px;
left: 0px;
}
.fig {
display: block;
margin: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
<h1>Title</h1>
<h2>title</h2>
<nav>
<ul id="menu">
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
</ul>
</nav>
</header>
<div id="container">
<img class="fig" src="https://www.organicfacts.net/wp-content/uploads/2013/05/watermelon2.jpg" alt="figure 1">
</div></code></pre>
</div>
</div>
</p> | 3 |
Non-blocking write to response from Mongo in JSON format | <p>I am using Node/Express.js so that the GET route will retrieve all documents from a Mongo database (simple enough). I am able, as the code will show, to accomplish this in a non-blocking way. However, when I uncomment the line that sets the response to JSON format, I get a syntax error - because while each document is in JSON format, the aggregation of the documents aren't in JSON format. How can I keep the non-blocking data flow, but send them as <code>application/json</code></p>
<p>I include below the GET route and also the function I am using to get the items form the mongo database.</p>
<p>GET route:</p>
<pre><code>app.get('/people', function(req, res){
//res.set('Content-Type', 'application/json');
mongoDriver.get(null, function(err, code, document){
res.status(code);
if(err) {
res.write(JSON.stringify(err));
} else if(document){
res.write(JSON.stringify(document));
}
if(!document){
res.end();
}
});
});
</code></pre>
<p>relevant portion of my mongo implementation.</p>
<pre><code>var cursor = db.collection(self.collection).find(data);
cursor.each(function(err, doc) {
if(err) {
return callback(err, 500);
} else if (doc !== null) {
return callback(null, 200, doc);
} else {
db.close();
return callback(null, 200, null);
}
});
</code></pre> | 3 |
Unity3D - Detect a vertex on planet mesh without cubes | <p>I have a planet mesh that I am generating procedurally (based on a random seed). The generator creates tectonic plates and moves them creating the land masses, mountains and water depressions you see below; ~2500 points in a planet. The textured surface is just a shader.</p>
<p><a href="https://i.stack.imgur.com/41P6J.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/41P6J.jpg" alt="enter image description here"></a></p>
<p>Each vertex will have information associated with it, and I need to know which vertex they are pointing at to relay this information.</p>
<p>I am looking for a way identify which vertex they are pointing at. The current solution is to generate a cube at each vertex, then use a collider/Ray to identify it. The two white cubes in the picture above are for testing.</p>
<p>What I want to know is if there is a better way to identify the vertex without generating cubes?</p> | 3 |
Recurssion Depth Exceeded While calling an python object | <p>I am making a web crawler for which I am using the following two functions:</p>
<pre><code>#Each queued link is the new job
def create_jobs():
for link in file_to_set(QUEUE_FILE):
queue.put(link)
queue.join()
crawl()
#Check if there are items in the queue then solve them
def crawl():
queued_links = file_to_set(QUEUE_FILE)
if len(queued_links)>0:
print(str(len(queued_links))+' links in the queue')
create_jobs()
</code></pre>
<p>here crawl is called first. Sometimes while crawling the page it shows maximum recurssion depth exceeded whereas sometimes not. (I am running the same script again). Can someone explain me what's the problem?</p>
<p>Please note that the number of links that I need to crawl is around 100 only which is less than the limit for python.</p> | 3 |
JAX WS async client: capture WS-Addressing 202 accepted | <p>I have to invoke several webservices using WS-Addressing.
When invoking a webservice, the ReplyTo is set to a callback endpoint implemented by me.</p>
<p>The client is generated from the target WSDL using async with</p>
<pre><code><enableAsyncMapping>true</enableAsyncMapping>
</code></pre>
<p>which generates the <code>Async</code> version for each webservice with the following signature:</p>
<pre><code>javax.xml.ws.Response<SampleWebServiceOutput> sampleWebService(SampleWebServiceInput input)
</code></pre>
<p>When invoking <code>sampleWebService</code> like, </p>
<pre><code>Response<SampleWebServiceOutput> response = clientWsPort.sampleWebService(input);
</code></pre>
<p>if the request is sucessful, the server will return <code>202 Accepted</code> however I can't figure out how to get it.</p>
<p>If I use <code>response.get()</code>, it will block forever since the response is sent to my callback url (WSA-Addressing Reply To)</p>
<p>Any clues how to know for sure if the server successfully accepted the request ?</p>
<p>Thank you.</p> | 3 |
Jquery result display issue | <p>I am trying to create a bmi calculator and tried the following .</p>
<pre><code>$(document).ready(function() {
// Convert ft to inches
function convertHeight(ft) {
return ft * 12;
}
// calculate total height
function showbmi() {
var weight = document.getElementById('weight').value * 1;
var height_ft = document.getElementById('height_ft').value * 1;
var height_in = document.getElementById('height_in').value * 1;
var height = convertHeight(height_ft) + height_in;
var female_h = (height * height) / 30;
var male_h = (height * height) / 28;
var gender;
var x = document.getElementsByName("gender");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
gender = x[i].value;
break;
}
}
var bmi = "?";
if (gender == "female") {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
} else {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
}
var bmi_msg = "?";
if (bmi < 15) {
bmi_msg = "Very severely underweight";
} else if (bmi <= 16) {
bmi_msg = "Severely underweight";
} else if (bmi <= 18.4) {
bmi_msg = "Underweight";
} else if (bmi <= 24.9) {
bmi_msg = "Normal";
} else if (bmi <= 29.9) {
bmi_msg = "Overweight";
} else if (bmi <= 34.9) {
bmi_msg = "Obese Class I (Moderately obese)";
} else if (bmi <= 39.9) {
bmi_msg = "Obese Class II (Severely obese)";
} else {
bmi_msg = "Obese Class III (Very severely obese)";
}
$("#result").text(bmi);
return bmi;
$("#comment").text(bmi_msg);
return bmi_msg;
}
//bmi infos
//finish
$("form#calc input").bind("keydown", function() {
setTimeout(function() {
showbmi();
}, 100);
return true;
});
$("form#calc input").bind("change", function() {
showbmi();
});
$("form#calc radio").bind("change", function() {
showbmi();
});
$("form#calc").bind("submit", function() {
showbmi();
return false;
});
});
</code></pre>
<p>The bmi displays correctly, but the messages forbmi values are not displaying. i checked the console and it says code unreachable.
Can somebody throw some light where I am goin wrong, and How I can improve this code.</p> | 3 |
How to split repeating pattern? | <p>I have a string that repeats a pattern. I have a regular expression that matches the pattern, but I would like to split them instead.</p>
<pre><code>$target = 'a1v33a33v55a2v43';
</code></pre>
<p>I would like to split them into a1v33, a33v55, and a2v43. Basically, I want to split the string into an array of ['a1v33', 'a33v55', 'a2v43'].</p>
<p>I've tried the following code, but it only matches the pattern. How can I split them instead?</p>
<pre><code>$target = 'a1v33a33v55a2v43';
$pattern = '/(a[0-9]+v[0-9]+)*$/im';
preg_match($pattern, $target, $match);
echo '<pre>';
print_r($match);
</code></pre> | 3 |
Wordpress Theme [WP-simple] Scroll issue | <p>I'm working on a website. I used wordpress them WP-Simple</p>
<p>I modified the theme for my needs and everything works fine, except it is not scrolling on sub pages.</p>
<p><a href="http://pranicenergy.55freehost.com/site/" rel="nofollow">http://pranicenergy.55freehost.com/site/</a> - - Main page works fine.
<a href="http://pranicenergy.55freehost.com/site/healing/" rel="nofollow">http://pranicenergy.55freehost.com/site/healing/</a> - - sub page is not scrolling.</p>
<p>please help.</p> | 3 |
Subsets and Splits