source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0052258197.txt"
] | Q:
This call requires a Page access token
I am trying to login with facebook, which is done. I need to get user info like name, email, hometown, location, gender, profile_pic. But i can only get username of the logged in user. I also added fields parameter to api. You can see that in below code.
<div id="container"></div>
<script>
var accessToken;
window.fbAsyncInit = function() {
FB.init({
appId : 'App Id',
cookie : true,
xfbml : true,
version : 'v3.1'
});
FB.AppEvents.logPageView();
function getuserProfile() {
FB.api('/me?fields=id,name,email,birthday,gender,hometown,location,profile_pic', {access_token : accessToken }, function (response){
console.log(response);
});
}
FB.login(function(response) {
if (response.status === 'connected') {
accessToken = response.authResponse.accessToken;
getuserProfile();
} else {
console.log('not connected');
}
}, {scope: 'email'});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
A:
Some fields can be specified wrong and that is why Facebook API is giving such an error even when everything else seems fine. For instance profile_pic field can cause such an error which should be something like picture.type(large). See also: FacebookGraphAPIError: (#210) This call requires a Page access token
|
[
"stackoverflow",
"0062895532.txt"
] | Q:
How do you test whether both sides of an array total the same? | Javascript Algorithm
Question
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.
For example:
Let's say you are given the array {1,2,3,4,3,2,1}: Your function will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.
Answer
function findEvenIndex(arr){
for(let i = 0; i <arr.length; i++){
let arr1 = arr.slice(0, (arr[i] - 1));
let arr2 = arr.slice((arr[i] + 1),);
let arr11 = arr1.reduce((total, item)=>{
return total + item;
}, 0);
let arr22 = arr2.reduce((total, item)=>{
return total + item;
}, 0);
if(arr11 === arr22){
return arr[i];
}
}
return -1;
}
console.log(findEvenIndex([1, 2, 3, 4, 3, 2, 1]))
console.log(findEvenIndex([1, 100, 50, -51, 1, 1]))
console.log(findEvenIndex([1, 2, 3,4,5,6]))
I can't see an error here, but it yields incorrect results. Any ideas?
A:
You have this part:
let arr1 = arr.slice(0, (arr[i] - 1));
let arr2 = arr.slice((arr[i] + 1),);
This is incorrect: arr[i]. That is a value, eg in [2,4,6,8,10] arr[3]==8. You want to slice on the index itself:
let arr1 = arr.slice(0, i - 1);
let arr2 = arr.slice(i + 1,);
Please note: There is another error in the two lines :) I leave that to you. Hint: you're now slicing two values out of the array instead of one. Perform the following code in your head first, then somewhere where you verify your results.
let arr = [0,1,2,3,4]
let x = 2;
console.log(arr.slice(0, x - 1));
console.log(arr.slice(x + 1,));
|
[
"es.stackoverflow",
"0000056597.txt"
] | Q:
Error Django: Page not found (404)
No puedo hacer que funcione mi url de formulario en django.
Descripcion del error:
Using the URLconf defined in django1_project.urls, Django tried these URL patterns, in this order:
1. ^admin/
2. ^mascota ^$ [name='index']
3. ^mascota ^nuevo$ [name='mascotaView']
4. ^mascota ^mascota/nuevo$ [name='mascotaView']
5. ^adopcion
The current URL, mascota/nuevo, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Mi archivo URL.PY dentro de la carpeta del proyecto de django:
from django.conf.urls import url,include
from apps.mascota.views import index, mascotaView
urlpatterns = [
url(r'^$', index,name='index'),
url(r'^nuevo$',mascotaView,name='mascotaView'),
url(r'^mascota/nuevo$',mascotaView,name='mascotaView'),
]
Mi archivo URL.PY dentro de la carpeta raiz del proyecto general de django:
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^mascota', include('apps.mascota.urls', namespace='mascota')),
url(r'^adopcion', include('apps.adopcion.urls',namespace='adopcion')),
]
No puedo encontrar el error. ¿Cual sería la causa de que no me encuntre la url http: //127.0.0.1:8000/mascota/nuevo?
A:
Tu archivo url dentro de la carpeta raiz modificalo a:
from django.conf.urls import url,include from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^mascota/', include('apps.mascota.urls', namespace='mascota')),
url(r'^adopcion', include('apps.adopcion.urls',namespace='adopcion')), ]
Nota la "/" al final de mascota esto indica que todas las urls que incluiras en tu archivos de apps.mascota.urls les va anteponer la "/"
|
[
"stackoverflow",
"0052234506.txt"
] | Q:
How to read data from a FOR loop inside DIV elements
Considering the next code:
HTML GENERATED:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Website TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Ww1</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarWw1" aria-controls="navbarWw1" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarWw1">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current) </span> </a>
</li>
<li class="nav-item">
<a class="nav-link" href="map">Map</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about">About</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="myInput" type="search" onkeyup="myFunction()" placeholder="Find your next memories!">
</form>
</div>
</nav>
<div class="container-fluid" id="networdapp" style="display:none;">
<div class="row" >
<div v-for="result in results" class="col-sm-6" >
<div class="card m-3 h-240 bg-light" >
<div class="card-header text-center" > {{ result.title }} </div>
<div class="card-body" style="height:200px" >
<p class="card-text" v-html="result.prevDesc"></p>
</div>
<div class="card-footer bg-transparent border-info">
<a href="/details" class="btn btn-info" onclick="getData();">Details</a>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"> </script>
<script>
function myFunction() {
var input , filter , OK = false ;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
if(filter.length > 0 ) {
document.getElementById("networdapp").style.display = "";
$( ".col-sm-6" ).each(function( index ) {
if ($(this).text().toUpperCase().indexOf(filter) > -1){
this.style.display="";
}else{
this.style.display="none";
}
});
}
else{
document.getElementById("networdapp").style.display = "none";
}
}
</script>
<script type="text/javascript">
const vm = new Vue({
el: '#networdapp',
data: {
results:[]
},
mounted() {
axios.get('/getJson')
.then(response => {
this.results = response.data;
})
.catch( e => {
console.log(e);
});
}
});
function getData() {
window.alert($(this).parents("#networdapp").find(".card-header.text-center").text());
window.alert(console.log( $(this).closest(".row").find(".card-header.text-center").html() ));
}
</script>
</html>
And there is my code snippet(I'm using EJS):
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('head'); -%>
</head>
<body>
<%- include('navbar'); -%>
<div class="container-fluid" id="networdapp" style="display:none;">
<div class="row" >
<div v-for="result in results" class="col-sm-6" >
<div class="card m-3 h-240 bg-light" >
<div class="card-header text-center" > {{ result.title }} </div>
<div class="card-body" style="height:200px" >
<p class="card-text" v-html="result.prevDesc"></p>
</div>
<div class="card-footer bg-transparent border-info">
<a href="/details" class="btn btn-info" onclick="getData();">Details</a>
</div>
</div>
</div>
</div>
</div>
</body>
<%- include('scripts') -%>
<script type="text/javascript">
const vm = new Vue({
el: '#networdapp',
data: {
results:[]
},
mounted() {
axios.get('/getJson')
.then(response => {
this.results = response.data;
})
.catch( e => {
console.log(e);
});
}
});
function getData() {
window.alert($(this).parents("#networdapp").find(".card-header.text-center").text());
window.alert(console.log( $(this).closest(".row").find(".card-header.text-center").html() ));
}
</script>
</html>
What I want to do:
The within the <div class="container-fluid" id="networdapp"> will be executed the <div v-for="result in results" class="col-sm-6" > let'say for n times and what I want is : I want to click on the "Details" button of a random generated <div v-for="result in results" class="col-sm-6" > and get the data from {{ result.title }} (from the <div class="card-header text-center"> ) and store it into a variable and then use it for another x.ejs page.The point is all I've done till this moment was to read all the content of all divs or....to get undefined just like what will show the 2x window.alert code lines from the code snippet(actually the second one.the first won't show anything).And that's pretty much my problem...I can't read the data from a {{result.title}} from a random div generated by this v-for from <div v-for="result in results" class="col-sm-6" >.I've been trying a lot of things with JQuery to solve this problem but can't figure out what I'm doing wrong.
I'm using EJS,Vue.JS, a bit of JQuery (my tries to read data), and some other libraries like Axios.
Thank you in advance!
A:
Since you're using Vue.js you don't need onclick, you could replace it by @click and pass your result and $event like parameters :
...
<a href="/details" class="btn btn-info" @click="getData(result,$event)">Details</a>
...
and inside your methods call that function as follow :
const vm = new Vue({
el: '#networdapp',
data: {
results:[]
},
methods:{
getData: function(result, event) {
// and do whatever you want with that result and event like
console.log(event.target.outerHTML);
// here your target is a anchor element (<a></a>) which you can access its attributes ..
}
}
...
}
also you can delete that function getData(){...}
|
[
"stackoverflow",
"0031410677.txt"
] | Q:
Trying to animate a circle formation using Swift
I am new to swift animations and would need some help in understanding this.
So say i have the following code which creates a circle based on the input provided.
func drawCircle(percentage:CGFloat){
//Some circle drawing code and the circle is drawn using the percentage % provided.
}
i call this function with
drawCircle(0.5)
i will get this.
i call using
drawCircle(0.75)
i will get this.
So based on the percentage passed i create the circle/semi-circle/ring. Hope i am making some sense.
Now only part i want to animate is the circle formation.
So say when i call drawCircle(0.5) it should animate smoothly from 0.0% to 0.5%
Currently if i call my method with a timer and pass the parameters sequentially (0.00, 0.1, 0.2 etc to 0.5) it can work.
An example:
But I don't think it's the right way to do. So what am looking for is if there is a better way to do this using animations in swift where the transition from 0.0 to 0.5 is smooth.
[I don't want to change my existing codes for the circle creation. Its already an existing code base made by someone i am working and it has some time factor and risk to change anything right now on the existing code. Looking for something where the function "drawCircle(%)" can be used to achieve the desired output. Suggestions are always welcome.]
TIA>
A:
Look up how to do animations with UIBezierPath and CAShapeLayer. Basically, you need to create a UIBezierPath with the equation for a circle. Then use the strokeEnd property to define how much of the circle should be animated. Here is an answer for reference, albeit in objective-c
Draw circle with UIBezierPath
|
[
"stackoverflow",
"0025249991.txt"
] | Q:
When is it appropriate to use a comma to separate two or more conditions in C++?
I recently discovered that this is valid C++ syntax:
int bar = 0;
for(int foo = 0; bar = 0, foo != 10; foo++)
{
//some code
}
I had never seen a comma used as a separator of two conditionals before, so I looked up how it works.
I found that when separating a list of conditions with commas, all of them get executed, but only the last one is used as the condition. So for example:
while(function1(), function2(), function3())
{
//code
}
Here, function1, function2, and function3 will all be run each time through the loop. However, only function3's return value will be used to determine whether or not to keep looping.
My question is this: Are there any situations in which this is the best thing to do?
To me, this makes much more sense:
while(function3())
{
function1();
function2();
//some code
}
When would it be appropriate to instead use commas to separate conditions?
A:
It depends on what you mean by condition: a predicate specifically or just any expression that is appropriate where a condition is expected by the surrounding context.
From the former point of view, I'd say that it is never appropriate to use comma to separate conditions. A condition is, by natural definition, an expression that is valuable specifically for its boolean result and not for its side effects (if any). Comma operator always ignores the results of all of its operands with the exception of the very last one. That immediately means that there's no meaningful way to specify a condition anywhere except for the very last position in the comma-separated sequence.
The first and intermediate operands of comma operator are supposed to be expressions whose whole purpose is in their side-effects. It is hardly justified to refer to such expressions as conditions since their results are ignored.
From the latter point of view, it might indeed make sense to include such side-effect producing sub-expressions in contexts where conditions are expected (like the middle segment of the for cycle header), but in many cases they lead to rather ugly code.
One semi-viable example I can come up with might look as follows
for (ListItem* ptr = list_header;
assert(ptr != NULL), ptr->key != target_key;
ptr = ptr->next);
which is supposed to emphasize the fact that the list absolutely must contain the target_key (i.e. the cycle must never fall off end of the list). But I would personally express it differently.
The transformation in your example with while(function1(), function2(), function3()) is not equivalent, since in general case function3() might depend on the side effects of function1(), function2(). This would mean that the ordering of these calls cannot be changed, which is probably the main reason they all were stuffed into the while condition in the first place. In such situations it might make sense to express it as while(function1(), function2(), function3()), but I'd rather transform it into
do
{
function1();
function2();
if (!function3())
break;
...
} while (true);
|
[
"stackoverflow",
"0017975877.txt"
] | Q:
How do I retrieve a form collection's prototype attribute from within a controller (Symfony2)?
I'm having trouble getting a form collection's prototype attribute within a controller for inclusion in a JSON response, the furthest I have got (i.e. no errors are being thrown) is with the following, however the returned value is empty.
$form = $this->createForm(new MyType());
$prototype = $form->get('myCollection')->getConfig()->getAttribute('prototype');
I've also tried creating the form's view, and pulling the attribute from there, however the prototype key is not defined here...
$form = $this->createForm(new MyType());
$view = $form->createView();
$prototype = $view->children['myCollection']->vars['attr']['prototype'];
Does anyone know where I'm going wrong?
(Symfony 2.2.4)
A:
It seems I can get what I'm after by rendering just the prototype attribute of my form's collection field, this feels like the long way around, but it works.
// Controller method
$form = $this->createForm(new MyType());
$view = $form->createView()->children['myCollection'];
$prototype = $this->renderView('MyBundle:Foo:prototype.html.twig', array('form' => $view));
<!-- Template (MyBundle:Foo:prototype.html.twig) -->
{{ form_widget(form.vars.prototype) }}
|
[
"stackoverflow",
"0027402950.txt"
] | Q:
Alter table or reset auto-increment using CDbMigration
How can I alter table or reset the auto-increment of a field in Yii 1.x, using CDbMigration?
I found alterColumn method, as good as createTable, dropTable, renameTable and truncateTable methods, but either I'm blind or there isn't anything for altering table or resetting the auto-increment of particular column or field.
A:
You can use execute() as Yii defines it:
Executes a SQL statement. This method executes the specified SQL statement using dbConnection.
So,
$this->execute("ALTER TABLE tbl_name AUTO_INCREMENT = 1");
|
[
"stackoverflow",
"0002472441.txt"
] | Q:
How to override Equals on a object created by an Entity Data Model?
I have an Entity Data Model that I have created, and its pulling in records from a SQLite DB.
One of the Tables is People, I want to override the person.Equals() method but I'm unsure where to go to make such a change since the Person object is auto-generated and I don't even see where that autogen code resides. I know how to override Equals on a hand made object, its just where to do that on an autogen one.
A:
You need to create a partial class. Add a new .cs file to your solution, and start it like this:
public partial class Person
{
public override bool Equals(Object obj)
{
//your custom equals method
}
}
A:
You can try using partial classes - I think you can find autogenerated code in the solution. If you find out that Equals is not overriden by default and generated class is partial (I think it should be partial) than you can add another file to your solution and place partial class with implenentation of Equals there:
public partial class Person
{
// Your override of Equals here
}
|
[
"stackoverflow",
"0010349915.txt"
] | Q:
ajax-loaded script not functioning
This code below is loaded via ajax:
<div class="main">
//some content
</div>
<div class="advanced">
//some content
</div>
<div class="other">
//some content
</div>
<div class="pass">
//some content
</div>
<script>$('.advanced,.other,.pass').hide();</script>
They hide fine when loaded normally, but when loaded via ajax it doesn't work anymore. Why is it so? I'm not really sure if $.on() would really help here.
A:
If the example above is loaded via jQuery ajax, why not just call the
$('.advanced,.other,.pass').hide();
upon completion of the ajax request?
For example:
$.ajax({
url: "Your AJAX URL",
dataType: 'html',
type: "POST",
success: function (json) {
// Add you elements to the DOM
},
complete: function () {
$('.advanced,.other,.pass').hide();
}
});
|
[
"stackoverflow",
"0022769051.txt"
] | Q:
How to put 3D animations in HTML looping and change smoothly (using keyframes) to another animation when clicked?
The idea is that there'll be a 3D animation looping (an idle character, probably rotating) and it will change to another animation when someone hovers the cursor over it (say, the character getting nervous), and another animation when clicked (say, the character startling). But if I use the old way of just changing the video it will look kind of weird because it will change drastically most of the time, how do I make this transition look good?
I'm kind of new to HTML so maybe it's easier than what I think, but I really have no idea of how to achieve this. Thank you in advance for your answers! :)
A:
Two options, make it an actual 3d model (hard) or control the flow of the video and wait for the video to finish before showing the next part/animation. Going down that route would require you to use HTML5 video tags for the video and you would have to look into the javascript API it exposes to control it. It's not terribly hard, but too broad an interface to cover in this answer.
|
[
"stackoverflow",
"0001855661.txt"
] | Q:
Build safe search conditions for SQL WHERE clause
I need to build search conditions to be used with WHERE clause. This search condition is then passed to a different application to be executed as a part of SQL query. Because there search conditions can be quite complex (including sub-queries) I don't believe receiving application can intelligently parse them to prevent SQL injection attacks.
Best practices state that parametrized queries should be used. That works fine when you use command object to execute the query yourself. In my case I wish to obtain that query string with parameters merged into it, and parse out where search clause I am interested in. Is there a way to do this?
I work with MS SQL Server and currently simply replace all single quotes with two single quotes in string I receive from a caller. Is there a better way to achieve some level of protection from SQL injection attacks?
A:
Have a look at these 2 links
Does this code prevent SQL injection?
and
Proving SQL Injection
|
[
"stackoverflow",
"0042918883.txt"
] | Q:
membase server to couchbase server migration : Java client
I was using aspymemcached client to connect to my membase server.
code look like :
public static MemcachedClient MemcachedClient(String bucketName){
URI server1 = new URI("http://192.168.100.111:8091/pools");
URI server2 = new URI("http://127.0.0.1:8091/pools");
ArrayList<URI> serverList = new ArrayList<URI>();
serverList.add(server1);
serverList.add(server2);
return new MemcachedClient(serverList, bucketName, "");
}
For putting object in cache :
public static void makeMembaseCacheEntry(final String key, final int expiryTime, final Object value, final String bucketName) {
MemcachedClient client = getMembaseClient(bucketName);
if (client != null) {
client.set(key, expiryTime, value);
}
For getting object from cache :
public static Object getMembaseCacheEntry(String key) {
Object value = null;
try {
MemcachedClient client = getMembaseClient(bucketName);
if (client != null) {
value = client.get(key);
}
} catch (Exception e) {
}
return value;
}
Now I planning to upgrade membase server to couchbase server, hence I have to use couchbase client java API (Ref : http://docs.couchbase.com/developer/java-2.1/java-intro.html).
In cousebase client all operation performed on JsonObject ref :
http://docs.couchbase.com/developer/java-2.0/documents-basics.html
So how can I migrate above two methods to couchbase client
A:
if what you are storing is a serialized Object, the Java SDK offers a SerializableDocument type (see https://developer.couchbase.com/documentation/server/4.6/sdk/java/document-operations.html#story-h2-10).
It is compatible with Object stored by the 1.x client built on top of spymemcached, but it uses flags metadata and I'm not sure how migrating from Memcached to Couchbase would influence these (so you might have to write some migrating code at some point).
Compared to Spymemcached, the Couchbase SDK 2.x has an API that is closer to the Couchbase Cluster organization: you start connecting to a Cluster, on which you open a Bucket, on which you can perform key/value operations like get, update, insert, upsert.
In your first snippet, you'll only need the IPs of at least one couchbase node. Out of that you'll get a Cluster (using CouchbaseCluster.create(...)).
Then open the Bucket using cluster.openBucket(bucketName). That should be pretty much like:
//TODO make both of these singletons
Cluster cluster = CouchbaseCluster.create("192.168.100.111", "127.0.0.1:8091");
Bucket bucket = cluster.openBucket(bucketName, bucketPassword);
Note Cluster and Bucket are thread-safe and should be used as singletons rather than reopened on each call like you do in makeMembaseCacheEntry and getMembaseCacheEntry...
For make you'll need to wrap your value:
Document doc = SerializableDocument.create(key, expiry, value);
bucket.upsert(doc);
(use upsert if you want to create-or-replace, see the docs for other types of kv operations)
For get, you'll need to tell the bucket it deserializes an Object:
SerializableDocument doc = bucket.get(key, SerializableDocument.class);
Object value = doc.content();
|
[
"stackoverflow",
"0022881947.txt"
] | Q:
Why is div not floating correctly?
I want to achieve this:
I am stuck here:
As you can see, the 'Item Description' box is now showing at the right place. I have double-checked the measurements. I don't know what I am doing wrong.
Here is the markup:
<div id="container">
<div id="container2">
<div id="header">
<img src="images/dealstoreconcept-ebay-listing-template2_03.png">
</div>
<div id="nav">
<a href="#"><img src="images/dealstoreconcept-ebay-listing-template2_06.png"></a>
<a href="#"><img src="images/dealstoreconcept-ebay-listing-template2_07.png"></a>
<a href="#"><img src="images/dealstoreconcept-ebay-listing-template2_08.png"></a>
<a href="#"><img src="images/dealstoreconcept-ebay-listing-template2_09.png"></a>
<a href="#"><img src="images/dealstoreconcept-ebay-listing-template2_10.png"></a>
<a href="#"><img src="images/dealstoreconcept-ebay-listing-template2_11.png"></a>
<a href="#"><img src="images/dealstoreconcept-ebay-listing-template2_12.png"></a>
</div>
<div id="content">
<div id="cat">
<div id="cat-head">
Categories
</div>
<div id="cat-content">
</div>
<div>
<div id="content-right">
<div id="des">
<div id="des-head">
Item Description
</div>
<div id="des-content">
</div>
</div>
</div>
</div>
</div>
</div>
Here is the CSS:
#container {
width: 100%;
background-color: #FFFFFF;
background-image: url(images/bg.png);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center top;
}
#container2 {
width: 970px;
margin-top: 0px;
margin-right: auto;
margin-bottom: 0px;
margin-left: auto;
}
#header {
padding-top:14px;
padding-bottom:10px;
}
#nav {
width:970px;
}
#nav img {
float: left;
}
#content {
background-color: #FFFFFF;
border-right-width: 1px;
border-left-width: 1px;
border-right-style: solid;
border-left-style: solid;
border-right-color: #a81717;
border-left-color: #a81717;
width: 968px;
padding-top: 25px;
padding-right: 8px;
padding-bottom: 25px;
padding-left: 8px;
}
#cat {
float: left;
width: 217px;
border: 1px solid #a81717;
}
#cat-head {
width: 209px;
float: left;
background-color: #a81717;
padding-top: 7px;
padding-left: 8px;
padding-bottom: 2px;
font-family: Arial, Helvetica, sans-serif;
font-size: 15px;
font-weight: bold;
text-transform: uppercase;
color: #FFFFFF;
}
#cat-content {
float: left;
padding-top: 15px;
padding-bottom: 15px;
}
#content-right {
float: left;
margin-left:11px;
width: 721px;
}
#des {
float: left;
width: 719px;
border: 1px solid #a81717;
}
#des-head {
width: 711px;
float: left;
background-color: #a81717;
padding-top: 7px;
padding-left: 8px;
padding-bottom: 2px;
font-family: Arial, Helvetica, sans-serif;
font-size: 15px;
font-weight: bold;
text-transform: uppercase;
color: #FFFFFF;
}
#des-content {
float: left;
padding-top: 15px;
padding-bottom: 15px;
width: 689px;
}
Any idea why this is happening?
A:
First problem is
<div id="cat">
<div id="cat-head">
Categories
</div>
<div id="cat-content">
</div>
<div> ---> not closed div
See fiddle http://jsfiddle.net/tamilcselvan/C2pX4/1/
|
[
"stackoverflow",
"0003488702.txt"
] | Q:
How do you turn off Hibernate bean validation with JPA 1.0?
How do you turn off bean validation with Hibernate 3.x in a JPA 1.0 environment?
I tried several things with persistence.xml:
<persistence-unit name="bbstats" transaction-type="RESOURCE_LOCAL">
<properties>
DB stuff
<property name="javax.persistence.validation.mode" value="none" />
<property name="hibernate.validator.autoregister_listeners" value="false" />
</properties>
<validation-mode>NONE</validation-mode>
</persistence-unit>
The last one causing
org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'validation-mode'. One of '{"http://java.sun.com/xml/ns/persistence":jta-data-source, "http://java.sun.com/xml/ns/persistence":non-jta-data-source, "http://java.sun.com/xml/ns/persistence":mapping-file, "http://java.sun.com/xml/ns/persistence":jar-file, "http://java.sun.com/xml/ns/persistence":class, "http://java.sun.com/xml/ns/persistence":exclude-unlisted-classes, "http://java.sun.com/xml/ns/persistence":properties}' is expected.
But nothing of the above work. Can anyone tell me how to do it on a JPA 1.0 implementation?
A:
The javax.persistence.validation.mode property is one of the standardized property from JPA 2.0. It wouldn't expect it to work in a JPA 1.0 environment.
Actually, assuming you're using Hibernate Validator 4, my suggestion would be to remove the JAR from the class path (I'm not sure the configuration settings from Hibernate Validator 3 still apply).
And if you are using Hibernate Validator 3, the following should disable the support of constraints inside the generated DDL and entity validation before an insert or updated:
<property name="hibernate.validator.apply_to_ddl" value="false"/>
<property name="hibernate.validator.autoregister_listeners" value="false"/>
But removing the JAR from the class path would also be straight forward.
If you're facing a more specific problem, please provide more specific details (including the version of Hibernate Validator).
References
Chapter 4. Additional modules in the Hibernate Annotations reference guide
Hibernate Validator 4.0.1.GA Reference Guide
Hibernate Validator 3.1.0.GA Reference Guide
JPA 2.0 specification
3.6.1.1 Enabling Automatic Validation
9.4.3 Persistence Unit Properties
|
[
"stackoverflow",
"0056216373.txt"
] | Q:
how to add column base on one row in sql server?
i have this table
Row Title Code RegDate Amount
----------------------------------------------------------
1 typea 203170 1396/12/29 150760000000 --Eur
1 typea 203251 1396/12/29 169928736 --Usd
2 typeb 201310 1396/12/29 32794373868351
3 typec 201441 1396/12/29 899750000
6 typed 201216 1396/12/29 23411268063599
8 typee 201181 1396/12/29 86687000 --Eur
8 typee 201211 1396/12/29 81483719480611 --Usd
9 typef 201212 1396/12/29 52595043810
10 typeh 201213 1396/12/29 3630924097
how i can combine Row 1 and 8 to one row like this result
Row Title Code RegDate Amount Amount_Usd
----------------------------------------------------------
1 typea 203170 1396/12/29 150760000000 169928736
2 typeb 201310 1396/12/29 32794373868351 0
3 typec 201441 1396/12/29 899750000 0
6 typed 201216 1396/12/29 23411268063599 0
8 typee 201181 1396/12/29 86687000 81483719480611
9 typef 201212 1396/12/29 52595043810 0
10 typeh 201213 1396/12/29 3630924097 0
default amount is eur
thanks
A:
You just need some conditional aggregation here:
--Sample Data
WITH VTE AS(
SELECT *
FROM (VALUES(1 ,'typea',203170,'1396/12/29',150760000000),
(1 ,'typea',203251,'1396/12/29',169928736),
(2 ,'typeb',201310,'1396/12/29',32794373868351),
(3 ,'typec',201441,'1396/12/29',899750000),
(6 ,'typed',201216,'1396/12/29',23411268063599),
(8 ,'typee',201181,'1396/12/29',86687000),
(8 ,'typee',201211,'1396/12/29',81483719480611),
(9 ,'typef',201212,'1396/12/29',52595043810),
(10 ,'typeh',201213,'1396/12/29',3630924097)) V([Row],Title,Code, RegDate, Amount))
--Solution
SELECT Row,
Title,
MIN(CASE WHEN Code NOT IN (203251,201211) THEN Code END) AS Code,
RegDate,
ISNULL(SUM(CASE WHEN Code NOT IN (203251,201211) THEN Amount END),0) AS Amount,
ISNULL(SUM(CASE WHEN Code IN (203251,201211) THEN Amount END),0) AS Amount_Usd
FROM VTE
GROUP BY [Row],[Title],RegDate;
db<>fiddle
No need for a CTE, my coffee hadn't kicked in.
|
[
"stackoverflow",
"0039643048.txt"
] | Q:
Copy column from one vi editor to other
I was trying to yank a column of 1300 lines from one vi editor and paste it on other open vi editor. I could able to paste only 49 lines of a column.
A:
I'm not sure you can yank columns between vim sessions. Your best bet might be two open up both files within one vim session using :sp or :vsp then you can copy and paste as you normally do within one file
If you wanted to copy lines over, in command mode, you can use: :r! sed -n <begining line nubmer>,<end line number>p <path to file>. Where r! runs an external command, and sed searches for only the lines in the range given.
For more information, check out these sources:
http://vimdoc.sourceforge.net/htmldoc/windows.html
https://stackoverflow.com/a/9644522/3865495
|
[
"stackoverflow",
"0003460404.txt"
] | Q:
UI elements for "safety lockout" to choose normal/abnormal operation
I have a GUI which has a couple of checkboxes that control "special" modes of system operation. I want these to always be displayed, and easily edited when the operator intends to edit them, but this condition is infrequent, and most of the time I want the checkboxes to be disabled.
What I'm looking for, is what UI element(s) to use to enable/disable abnormal operation. (so normal operation would leave the checkboxes in a disabled state, abnormal operation would allow user to edit them.)
checkbox or pair of buttons: too easy to press
menu item: too obscure
dialog confirmation box: ("This mode of operation allows ____. Are you sure you want to use it?") too annoying, and I want to avoid modal dialog boxes because they block usage of all other UI elements in important situations.
The UI design of physical objects includes some subtle lockouts, e.g. automatic transmissions in a car require you to press the brake to shift into/out of certain gears; lawnmowers have those handles that you have to press during starting/running; childproof pill bottles require you to press down while turning.
I am looking for something simple/intuitive that's easy to use but will avoid inadvertent use. Any ideas? Someone must have thought of this sort of thing in the software world.
A:
I would follow the "physical object" paradigm of having a 'safety cover' over the actual controls.
In terms of the UI, this would be a checkbox that (and I know you said that you want them always displayed, but..) reveals and enables the special controls.
Disabled:
_____________________________
| O Enable Dangerous mode |
|_____________________________|
Enabled:
_____________________________
| X Enable Dangerous mode |
| |
| O Dangerous Control One |
| O Dangerous Control Two |
|_____________________________|
Post-Comment:
I guess another important question is, is the interface primarily 'hands on keyboard' or 'mouse'.
If its keyboard, then a keycombo, or, again, taking from other interfaces, have the user type 'enable' or something relevant to the actual controls.
If its primarily a mouse interface, how about a more complex interaction like a "swipe" - where the user has to drag an element a reasonable distance.
Disabled:
_____________________________
| Enable Dangerous mode |
| _ _ |
| |*| -------------> |_| |
| off on |
|_____________________________|
Enabled:
_____________________________
| Enable Dangerous mode |
| _ _ |
| |_| -------------> |*| |
| off on |
| |
| O Dangerous Control One |
| O Dangerous Control Two |
|_____________________________|
|
[
"stackoverflow",
"0038434909.txt"
] | Q:
.ics file handling on iOS with Ionic
I have an Ionic application and I have an .ics file URL returned from server, for example:
https://gist.githubusercontent.com/DeMarko/6142417/raw/1cd301a5917141524b712f92c2e955e86a1add19/sample.ics
How can I import it to calendar on iOS 9.3.2 ?
I tried to open it on Safari in order for safari to import to calendar, but it not works, it just prompt a dialog to subscribe to the ICS's event.
A:
According to this similar question, Safari should show a prompt with 'add to Calendar', I unfortunately do not know enough about ICS's to see whether the problem may be with the file. Otherwise you can also check this excellent Cordova plugin by Eddy Verbruggen.
|
[
"stackoverflow",
"0027533730.txt"
] | Q:
Having trouble including a dependancy in package.json
I have an angular project (really just the docs tutorial) and I want to include the node-mysql module in my project- doesn't have to be installed globally.
Not sure I understand how this works but I thought all I have to do was add this module to package.json as a dependency and run npm install, but I get an error:
PS> cat .\package.json
{
"version": "0.0.0",
"private": true,
"name": "angular-phonecat",
...
"dependencies": {
"node-mysql": ">=2.5.0"
},
"devDependencies": {
"karma": "^0.12.16",
...
The error:
PS> npm install
npm WARN package.json [email protected] No README data
npm ERR! notarget No compatible version found: node-mysql@'>=2.5.0'
npm ERR! notarget Valid install targets:
npm ERR! notarget ["0.1.1","0.1.2","0.1.3","0.1.4","0.1.5","0.1.6","0.1.7","0.1.8","0.1.9","0.2.0","0.2.1","0.2.2","0.2.3","0.2.4","0.2.5","0.2.6","0.2.7","0.2.8","0.2.9","0.3.0","0.3.1","0.3.2","0.3.3","0.3.4","0.3.5","0.3.6","0.3.7","0.3.8","0.3.9","0.4.0","0.4.1"]
npm ERR! notarget
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! cwd C:\testangular\ticketsys\angular-phonecat
npm ERR! node -v v0.10.32
npm ERR! npm -v 1.4.28
npm ERR! code ETARGET
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\testangular\ticketsys\angular-phonecat\npm-debug.log
npm ERR! not ok code 0
How can I include this dependency in my project?
A:
Node-mysql version >2.5 is not out yet. Node-mysql is on version 0.4.1. I suspect you are looking for just the regular mysql npm module. Mysql on npm is on version 2.5.4.
Try using this instead:
"mysql": ">=2.5.0"
If you go to this page: https://github.com/felixge/node-mysql . They say in the install instructions to use npm install mysql. This might be a bit confusing since their github page is node-mysql.
Alternatively instead of adding this manually to the dependency you could go ahead and do the following:
npm install mysql --save
This will only install the most up to date one locally (Not globally, if you wanted to install it globally you could add the -g flag, but since you don't need that dont!).
|
[
"stackoverflow",
"0052102910.txt"
] | Q:
button inside modal loads the page even if validations fire
I have a form inside which I have a button1 which triggers the modal.
Inside modal window I have textboxes(to take some credentials) with validations and another button (button2) (type=button) containing onClick definition which is working fine if I provide good data, but when I provide no data in one of the text boxes and click on the button2 the complete page reloads and I get to my main page where I click on button1 and I see the validation messages.
The validation should appear just as the user clicks button2
I have looked around and tried couple of thing but cant figure out why is it happening,
I am using page routing in page_load is that the reason?
here is the code inside the modal in my html.aspx:
<form=from1 runat=server>
<div class="modal fade" id="logger_modal" tabindex="-1" role="dialog" aria-labelledby="logger_model1" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body align-content-center">
<asp:TextBox ID="textbox1" runat="server" Class="form-control" placeholder="sometext" onkeydown = "return (event.keyCode!=13);"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="message1" ControlToValidate="textbox1" EnableClientScript="false" Display="Dynamic" ></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server" Class="form-control" placeholder="sometext" onkeydown = "return (event.keyCode!=13);"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="message2" ControlToValidate="textbox2" EnableClientScript="false" Display="Dynamic"></asp:RequiredFieldValidator>
</div>
<div class="modal-footer">
<asp:Button ID="close" runat="server" Text="Cancel" type="button" class="btn btn-secondary" data-dismiss="modal"/>
<asp:Button ID="button2" runat="server" Text="button2_text" type="button" class="btn btn-primary" CausesValidation="true" OnClick="OnClick_method" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</div>
</div>
</div>
Code inside ONClick_method in html.aspx.cs
if (Page.IsValid)
{
some code which works if i provide right values in textboxes
}
else
{
Label1.Text = "Please provide the details.";
}
A:
This happens because your page does a postback and the page does a complete reload which results in closing the modal which causes probably the lose of values.
To prevent the page from completely reloading you can use a UpdatePanel for partial update of your page.
Example:
<div class="modal-body align-content-center">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="textbox1" runat="server" Class="form-control" placeholder="sometext" onkeydown="return (event.keyCode!=13);"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="message1" ControlToValidate="textbox1" EnableClientScript="false" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server" Class="form-control" placeholder="sometext" onkeydown="return (event.keyCode!=13);"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="message2" ControlToValidate="textbox2" EnableClientScript="false" Display="Dynamic"></asp:RequiredFieldValidator>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="button2" />
</Triggers>
</asp:UpdatePanel>
</div>
You only surround the part that needs to be partially updated so the modal won't close and set the control for the async postback to button2.
|
[
"apple.stackexchange",
"0000218237.txt"
] | Q:
How can I share a large, 60 GB file with iCloud Drive?
I pay Apple for 200 GB of storage with iCloud Drive.
What are the steps to share a 60 GB file with someone?
A:
In general, iCloud is not a person-to-person sharing platform. It is mostly restricted to sharing with your devices, so there is almost no capability to share with others. It does have the ability to share Photos and videos in a limited fashion, called 'Family Sharing".
In El Capitan, Apple introduced a feature called Mail Drop. This feature duplicates what many have done using services such as Dropbox: it automatically uploads a large file to iCloud, and embeds a link to that file in the email message.
If your recipient uses Apple Mail in Yosemite or El Capitan, Apple Mail automatically downloads the file from iCloud, so it looks like the attachment was sent via mail, when really only the link was sent via mail.
For more on how this works, here is the latest Apple support info.
This sounds perfect for your needs. However, Mail Drop has a limit to the file size of 5GB. It claims not to work on file sizes over 5GB (no direct personal experience). Therefore, it likely won't support your use case of 60GB.
Dropbox and Box.com do work in this manner and allow you to create both public and private links to whatever files you wish. Both offer free tiers, however, the free accounts are limited to 5GB, so your 60GB file will required a pay account.
Honestly, given the size of your file, it might be simpler, and far cheaper to put your file on a 64GB USB stick and use snail mail.
A:
In 2018 this is now something you can share out. See Can I share iCloud Drive folder with other iCloud user?
The "no you can't share a folder" won't prelude you from sharing out files.
On Mac - right click the file in question, then share, then Add People and add the email / cellular number / iMessage of the intended recipient.
|
[
"stackoverflow",
"0043546261.txt"
] | Q:
how get value on expando object #
First I read txt files into a folder, and after I hydrated objects with expando Object.
But now I would like to get some value from this objects to fill a listview (winforms).
private void Form1_Load(object sender, EventArgs e)
{
string pattern = "FAC*.txt";
var directory = new DirectoryInfo(@"C:\\TestLoadFiles");
var myFile = (from f in directory.GetFiles(pattern)
orderby f.LastWriteTime descending
select f).First();
hydrate_object_from_metadata("FAC",listBox3);
hydrate_object_from_metadata("BL", listBox4);
this.listBox3.MouseDoubleClick += new MouseEventHandler(listBox3_MouseDoubleClick);
this.listBox1.MouseClick += new MouseEventHandler(listBox1_MouseClick);
}
void hydrate_object_from_metadata(string tag, ListBox listBox)
{
SearchAndPopulateTiers(@"C:\TestLoadFiles", tag + "*.txt", tag);
int count = typeDoc.Count(D => D.Key.StartsWith(tag));
for (int i = 0; i < count; i++)
{
object ob = GetObject(tag + i);
///HERE I WOULD LIKE GET DATA VALUE FROM ob object
}
}
Object GetObject(string foo)
{
if (typeDoc.ContainsKey(foo))
return typeDoc[foo];
return null;
}
void SearchAndPopulateTiers(string path, string extention, string tag)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles(extention);
int i = 0;
foreach (FileInfo file in files)
{
var x = new ExpandoObject() as IDictionary<string, Object>;
string[] strArray;
string s = "";
while ((s = sr.ReadLine()) != null)
{
strArray = s.Split('=');
x.Add(strArray[0],strArray[1]);
}
typeDoc.Add(tag+i,x);
i++;
}
}
So is it possible to get value on expando object?
A:
dynamic eod = eo;
value = eod.Foo;
|
[
"tex.stackexchange",
"0000217479.txt"
] | Q:
Create a new symbol
First of all, I want to say I am a complete layman, so I apologize in advance for the lack of specific terminology or even if I am asking in the wrong place.
I am looking for a character, which most probably does not exist, but I wonder whether it's possible to create it.
It's basically made out of two characters, namely (<) and (=).
I attach a drawing so you can see.
Hope to hear news soon. Thanks in advance!
A:
\documentclass{standalone}
\usepackage{tikz}
\newcommand{\whatzit}{\tikz{\path node[anchor=base,inner sep=0pt](a){$<$}
(a.center) +(0pt,.25ex) node[rotate=-30,scale=.6]{$=$};}}
\begin{document}
Text with \whatzit{} in the middle.
\end{document}
|
[
"stackoverflow",
"0035680252.txt"
] | Q:
Number on keyup add comma in INR standard
I am trying to remove text after numbers typed and add decimal
I have multiple input type="text" where on keypress I am adding a comma in INR (Indian Rupee) standard but when I type more than three numbers the entire value is removed and '0' is added. Also my code is not allowing the decimal .00 number as it should. What am I doing wrong?
JS Fiddle
HTML:
<input name="txtMSExMarCardFee" type="number" id="txtMSExMarCardFee" class="Stylednumber">
<input name="txtMSExMarCardFee1" type="number" id="txtMSExMarCardFee1" class="Stylednumber">
<input name="txtMSExMarCardFee2" type="number" id="txtMSExMarCardFee2" class="Stylednumber">
JS:
$('input.Stylednumber').keyup(function(){
var x=$(this).val();
x=x.toString();
var afterPoint = '';
if(x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'),x.length);
x = Math.floor(x);
x=x.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
$(this).val(res );
});
A:
This requires that you cleanup the input before you pass it to through the regex
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
$('input.Stylednumber').keyup(function() {
var input = $(this).val().replaceAll(',', '');
if (input.length < 1)
$(this).val('0.00');
else {
var val = parseFloat(input);
var formatted = inrFormat(input);
if (formatted.indexOf('.') > 0) {
var split = formatted.split('.');
formatted = split[0] + '.' + split[1].substring(0, 2);
}
$(this).val(formatted);
}
});
function inrFormat(val) {
var x = val;
x = x.toString();
var afterPoint = '';
if (x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'), x.length);
x = Math.floor(x);
x = x.toString();
var lastThree = x.substring(x.length - 3);
var otherNumbers = x.substring(0, x.length - 3);
if (otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
return res;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="txtMSExMarCardFee" type="text" id="txtMSExMarCardFee" class="Stylednumber">
<input name="txtMSExMarCardFee1" type="number" id="txtMSExMarCardFee1" class="Stylednumber">
<input name="txtMSExMarCardFee2" type="number" id="txtMSExMarCardFee2" class="Stylednumber">
|
[
"linguistics.stackexchange",
"0000000634.txt"
] | Q:
Are there examples of pidgins or creoles in sign languages? If so, which are the major ones?
The other day I was wondering, are there occurrences of pidgins or creoles in the world of Sign languages? So I made a quick search but there doesn't seem to be much.
For example, I found the Hawaii Pidgin Sign Language, but it's not an actual pidgin, it's simply named like this after the Hawaii Pidgin.
So, are there examples or they simply don't exist? If they do, which are the major ones? For major, I mean most used, most established, etc.
A:
Spoken creoles are developed in environments where many languages are mixed (for example, in the Caribbean region, there were several major colonial languages and many African languages spoken by slaves). For deaf children learning sign languages, there is the opposite problem – they may have no input that is "linguistic," but only some non-linguistic gestures or non-native sign. There are two sign languages that have been "created" (i.e. arisen by some means other than descent from an extant language) in recent years and have been the subject of research by language-acquisition researchers: Nicaraguan Sign Language and al-Sayyid Bedouin Sign Language. So I'd say that these are the closest thing to a sign language "creole" (although not much is known about the historical genesis of older sign languages, and it's quite possible that all of them arose spontaneously in deaf communities without influence from aural languages).
For the concept of "pidgin," there are so-called home sign systems, which develop when deaf children and hearing caregivers do not have access to instruction in an established sign language. These generally lack some of the traits than linguists ascribe to natural languages (as do pidgins).
If you're interested in the families of sign languages and the phylogenetic relationships between them, you might want to check out this section of Wikipedia, which lists the currently accepted groupings.
|
[
"stackoverflow",
"0017007534.txt"
] | Q:
Nicer Syntax for List>?
I have a method:
public void MyMethod(params KeyValuePair<string, string>[] properties);
Which I invoke like:
MyMethod(
new KeyValuePair("Name","Jack"),
new KeyValuePair("City", "New York"),
new KeyValuePair("Gender", "Male"),
);
I would prefer a prettier syntax to invoke the method though, something similar to:
MyMethod({"Name","Jack"}, {"City","New York"}, {"Gender","Male"});
The closest I've come to that is using changing the method signature to accept a dictionary as the method argument and call :
MyMethod(new Dictionary<string,string>()
{
{"Name", "Jack"},
{"City", "New York"},
{"Gender", "Male"},
};
Are there any other alternatives ?
A:
You can accept just strings as parameters and then dynamically fill a dictionary, like this.
public void MyMethod(params string[] properties)
{
var pairs = new Dictionary<string, string>();
for(int i = 0; i < properties.length - 1; i += 2)
{
pairs.Add(properties[i], properties[i + 1]);
}
}
MyMethod("Name", "Jack", "City", "New York", "Gender", "Male");
|
[
"stackoverflow",
"0055795570.txt"
] | Q:
code explanation about hough_line and hough_line_peaks
I was able to find this link: Calculating the angle between two lines in an image in Python which I then only took the code part that allows to calculate the angle:
import numpy as np
from skimage.transform import (hough_line, hough_line_peaks, probabilistic_hough_line)
from pylab import imread, gray, mean
import matplotlib.pyplot as plt
image = imread('D:\\Pictures\\PyTestPics\\oo.tiff')
image = np.mean(image, axis=2)
h, theta, d = hough_line(image)
angle = []
dist = []
for _, a, d in zip(*hough_line_peaks(h, theta, d)):
angle.append(a)
dist.append(d)
angle = [a*180/np.pi for a in angle]
angle_reel = np.max(angle) - np.min(angle)
print(angle_reel)
can anyone please explain me the code of the for loop and the angle_reel? because I couldn't understand how are there multiple angles and those multiple angles are formed between what line and what other object inside the image? It would be really appreciated.
A:
Your image has two lines, I'll call them line a and line b. Each of those lines will have and angle. The angle between those lines will be the angle of line a - angle of line b.
When your code iterates through the hough_line_peaks in the, it is actually iterating though the data for each line. Each line has a distance, and an angle.
for _, a, d in zip(*hough_line_peaks(h, theta, d)):
angle.append(a)
dist.append(d)
If there are two lines in your image, you will end up with a list of angles that has two values. Those two values will be the angles of the lines in reference to the edge of the image. To find the angle of the lines in reference to each other, subtract the values.
Here is an example image:
The angles of the lines are: [1.3075343725834614, 0.48264691605429766]. That's in radians, so they are converted to degrees with the code: angle = [a*180/np.pi for a in angle]. In degrees the angles are [74.91620111731844, 27.65363128491619]. This seems pretty reasonable, one is a little more than 45 degrees and one is a little less. The angle between the lines is max(angles) - min(angles) or 47.262 degrees.
This image shows the angles drawn on the image:
|
[
"stackoverflow",
"0000941170.txt"
] | Q:
Possible to get Excanvas to work in IE 8?
I used to work on a jQuery plugin named 'BeautyTips' and it was working just fine. But, since I've installed IE 8, this plugin stop working because it needs Excanvas to make IE draw the vectors, images etc.
I've tried to download the newer version of Excanvas but it's not working at all...
A:
The new 'standards' mode of IE8 turns off some nonstandard features. Among them VML, which is used by excanvas. I just set for IE7 'standards' mode, so it still works.
<meta http-equiv="X-UA-Compatible" content="IE=7" />
Frustrating, but i don't know of any advantage brought up by IE8.
A:
Yes, I have got excanvas working in IE8 standards mode (only tested for the usage we required). In the function CanvasRenderingContext2D_ I commented out the line:
//el.style.overflow = 'hidden';//fix IE8
The width and height of the node object el was 0px by 0px, so not setting the overflow to hidden made the rendered item visible.
I did change the order of the creation of the canvasPieTimer a bit, to get the required result. I hope this is helpful.
A:
Try appending the canvas element to the document before initializing it using excanvas:
var foo = document.getElementById("targetElementID");
var canvas = document.createElement('canvas');
canvas.setAttribute("width", 620);
canvas.setAttribute("height", 310);
canvas.setAttribute("class", "mapping");
foo.appendChild(canvas);
canvas = G_vmlCanvasManager.initElement(canvas);
|
[
"stackoverflow",
"0001081843.txt"
] | Q:
Most beautiful open source software written in c++
I was told that to be a good developer, you should read a lot of other peoples source code. I think that sounds reasonable. So I ask you, what is the most beautifully written piece of open source software that is written in c++ out there?
(Apply any definition of beautiful you like.)
A:
IMHO...
Notepad++
A:
You could look at the source code of MySQL GUI Tools. Its written using gtkmm, and the code does some interesting difficult-to-implement GUI things.
|
[
"stackoverflow",
"0014616145.txt"
] | Q:
Why are address are not consecutive when allocating single bytes?
I am dynamically allocating memory as follows:
char* heap_start1 = (char*) malloc(1);
char* heap_start2 = (char*) malloc(1);
When I do printf as follows surprisingly the addresses are not consecutives.
printf("%p, %p \n",heap_start1,heap_start2);
Result:
0x8246008, 0x8246018
As you can see there is a 15 bytes of extra memory that are left defragmented. It's definitely not because of word alignment. Any idea behind this peculiar alignment?
Thanks in advance!
I am using gcc in linux if that matters.
A:
glibc's malloc, for small memory allocations less than 16 bytes, simply allocates the memory as 16 bytes. This is to prevent external fragmentation upon the freeing of this memory, where blocks of free memory are too small to be used in the general case to fulfill new malloc operations.
A block allocated by malloc must also be large enough to store the data required to track it in the data structure which stores free blocks.
This behaviour, while increasing internal fragmentation, decreases overall fragmentation throughout the system.
Source:
http://repo.or.cz/w/glibc.git/blob/HEAD:/malloc/malloc.c
(Read line 108 in particular)
/*
...
Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
...
*/
Furthermore, all addresses returned by the malloc call in glibc are aligned to: 2 * sizeof(size_t) bytes. Which is 64 bits for 32-bit systems (such as yours) and 128 bits for 64-bit systems.
A:
At least three possible reasons:
malloc needs to produce memory that is suitably-aligned for all primitive types. Data for SSE instructions needs to be 128-bit aligned. (There may also be other 128-bit primitive types that your platform supports that don't occur to me at the moment.)
A typical implementation of malloc involves "over-allocation" in order to store bookkeeping information for a speedy free. Not sure if GCC on Linux does this.
It may be allocating guard bytes in order to allow detection of buffer overflows and so on.
|
[
"stackoverflow",
"0053440567.txt"
] | Q:
PostgreSQL removing duplicates without id or unique_key
I'd like to know how I can remove the exact duplicated rows in the table and keep only one.
e.g. this table.
to
Most of the threads, I read, have utilised id or unique_key which I don't have in this case.
EDIT: when I said remove I mean delete those records from the table and again I don't have id to make the reference to create the condition to keep one record. Sorry for the confusion.
Thank you in advance.
This may be the same question as other threads. However, they failed to explain what ctid is which fa06 succeeded to deliver that. So, I would say that what i'm asking using the same word but different question. Pls remove "marked duplicate". Thanks.
A:
You can try below
If you need to specifically target the duplicated records, you can make use of the internal ctid field, which uniquely identifies a row:
DELETE FROM yourtablename
WHERE ctid NOT IN (
SELECT MIN(ctid)
FROM yourtablename
GROUP BY date, value, label,sequence
)
|
[
"stackoverflow",
"0043100905.txt"
] | Q:
How to add and remove class from a matched element?
This is the basic html structure:
<div class="modern">
<button type="button">Modern</button>
</div>
<div class="recent">
<button type="button"><Recent</button>
</div>
<svg>
<path class="modern">A</path>
<path class="recent">B</path>
<path class="recent">C</path>
<path class="modern">D</path>
<path class="recent">E</path>
</svg>
Then on js once I click I check if any path has the same class as per the .parent of the clicked element, and if so add a class fadeIn to each matched element and fade it in sequentially. If not, add a class FadeOut and fade out the paths sequentially.
$("button").on("click", function() {
$(this).addClass("active");
var periodClass = $(this).parent().attr("class");
var gapBetweenEach = 200;
var speedOfFade = 400;
$("svg path").each(function(i, path) {
var cl = $(this).attr('class');
$(this).attr('class', cl.includes(periodClass) ? cl + ' fadeIn' : cl.replace(/fadeIn/g, 'fadeOut'))
$(".fadeIn").delay(gapBetweenEach * i).fadeIn(speedOfFade);
$(".fadeOut").delay(gapBetweenEach * i).fadeOut(speedOfFade);
});
});
The above works but when I start clicking on the different buttons the classes keeps been added and the whole logic of fadeIn and fadeOut sequentially gets broken.
These are the classes I get after a few clicks
fadeOut fadeOut fadeIn
A:
You can jQuery .hasClass(), .addClass() and .removeClass() methods
$("svg path").each(function(i, path) {
var elem = $(this);
if (elem.hasClass(periodClass)) {
elem.removeClass('fadeOut').addClass('fadeIn');
} else {
elem.removeClass('fadeIn').addClass('fadeOut');
}
//Rest of your code ...
$(".fadeIn").delay(gapBetweenEach * i).fadeIn(speedOfFade);
$(".fadeOut").delay(gapBetweenEach * i).fadeOut(speedOfFade);
});
|
[
"math.stackexchange",
"0001550438.txt"
] | Q:
$X_n$ Markov Chain, show Show that: $\mathbb{E}^{\mathbb{P}_x}[\tau_x] \geq \mathbb{P}_x(\tau_y < \tau_x) \mathbb{E}^{\mathbb{P}_y}[\tau_x]$
Let $X_n$ be a Markov Chain on a countable, irreducible state space. Assume that the state $x$ is recurrent and that $\pi(x,y)$ >0, where $\pi(\cdot,\cdot)$ is the one-step transition probability.
Show that:
$$\mathbb{E}^{\mathbb{P}_x}[\tau_x] \geq \mathbb{P}_x(\tau_y < \tau_x) \mathbb{E}^{\mathbb{P}_y}[\tau_x]$$
Where $\tau_x = \inf(n\geq 1\, \vert X_n = x)$, and $\mathbb{P}_x$implies the chain starts at state $x$.
Showing that $0<\mathbb{P}_x(\tau_y < \tau_x)<1$ is easy enough. My question is mainly with the relationship between $\mathbb{E}^{\mathbb{P}_x}[\tau_x]$ and $\mathbb{E}^{\mathbb{P}_y}[\tau_x]$
Is it true that $\mathbb{E}^{\mathbb{P}_x}[\tau_x] = \mathbb{E}^{\mathbb{P}_y}[\tau_x]$? How would you show that?
A:
First of all, it is not true that $\mathbb{E}_x \tau_x=\mathbb{E}_y \tau_x$. For example consider a chain with two states: $\mathcal{S}=\{x,y\}$ with the transition matrix $\pi(i,j)=1_{\{i\neq j\}}$ (i.e. changing state with probability $1$ at every step). In this case $\mathbb{E}_x \tau_x=2>1=\mathbb{E}_y \tau_x$.
One way to show what you want is by using conditional expectation:
$$
\mathbb{E}_x \tau_x=\mathbb{P}(\tau_y<\tau_x)\mathbb{E}_x (\tau_x|\tau_y<\tau_x)+\mathbb{P}(\tau_y\geq \tau_x)\mathbb{E}_x (\tau_x|\tau_y\geq \tau_x) \\
\geq \mathbb{P}(\tau_y<\tau_x)\mathbb{E}_x (\tau_x|\tau_y<\tau_x)\geq \mathbb{P}(\tau_y<\tau_x)\mathbb{E}_y \tau_x.
$$
The last inequality relies on the fact that regardless of the number of steps it took to reach $y$, you will need to take an expected additional number of $\mathbb{E}_y \tau_x$ steps to reach $x$ again.
|
[
"stackoverflow",
"0020882431.txt"
] | Q:
Issues on displaying Toast within onPostExecute of AsyncTask class
There are lot of questions regarding this problem in this forum but not of them worked for me. So I am asking this problem here. I am trying to read the data from MySQL database. After successfully fetching the data from database using PHP web service, I want to display the data. But when I used Toast for this, Eclipse prevent me to write the Toast command and displays me the error
The method makeText(Context, CharSequence, int) in the type Toast is
not applicable for the arguments (VersionReader, String, int)
The Java code for this is:
public class VersionReader extends AsyncTask<URI, Integer, Integer>{
private String TAG = "RESULT";
int version = 0;
int local_version = 0;
public VersionReader(int local_version){
this.local_version = local_version;
}
@Override
protected Integer doInBackground(URI... urls) {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(urls[0]);
HttpResponse response = httpclient.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
version = Integer.parseInt(in.readLine());
}catch(Exception e){
e.printStackTrace();
}
return version;
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
Toast.makeText(this, "The lastest version is " + result, Toast.LENGTH_SHORT).show();
}
}
Do anyone have any idea how can I get rid of this problem?
A:
Just replace
Toast.makeText(this, "The lastest version is " + result, Toast.LENGTH_SHORT).show();
with
Toast.makeText(getApplicationContext(), "The lastest version is " + result, Toast.LENGTH_SHORT).show();
note: valid if your VersionReader class is inside Activity
as your VersionReader class is not insode Activity or Service, create a a Context global variable in your class and acquire it from Constructor...
private Context context;
public VersionReader(Context context) {
this.context = context;
}
and in onPostExecute(), use
Toast.makeText(context, "The lastest version is " + result, Toast.LENGTH_SHORT).show();
A:
Make Constructor like:
Context ctx;
public VersionReader(int local_version , Context c){
this.local_version = local_version;
this.ctx = c;
}
Now use this ctx variable in your Toast.
Toast.makeText(ctx, "The lastest version is " + result, Toast.LENGTH_SHORT).show();
|
[
"stackoverflow",
"0011502099.txt"
] | Q:
Developing admin interface for Apache Lucene
I've developed an app that uses Lucene engine to search. Now I want to develop an admin interface more or less similar to the one in Solr.
I need to interface to include some basic configuration, status report, job manager and maybe even to run some example searches on Lucene's index.
I am thinking if I should develop it from scratch or somehow use some of the code in Solr. I was wondering if anyone knows what framework was used to develop it (if any at all) and where I can find the admin interface code.
Thanks.
A:
I would suggest you to write admin panel from scratch. The reason is solr admin code seems to be coupled with underlaying solr implementation , though you can access the other lucene index from solr panel , to get better control over your lucene configuration you should prefer writing your wrapper like solr , also if you write your own wrapper , you can even have better control than solr have on itself ,reason being if at later point of time you want your lucene index build and search configurable using Web interface it will work seamlessly because programmatic configuration will just about writing a service layer on top of lucene.
Hope my answer helps :)
|
[
"stackoverflow",
"0022385264.txt"
] | Q:
CORS blocking post from jQuery
I am trying to post from a static page that pretends to be a remote web server into my Flask app, running behind uwsgi because of Flask-uWSGI-WebSocket.
Every time I post to my server, the post is blocked because of CORS:
XMLHttpRequest cannot load http://127.0.0.1:5000/tnw/post. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I've installed flask-cors and origins is set to * but I still can't get it to go through. What else am I missing here?
My POST:
$("#ajaxbutton").click(function() {
var json = JSON.stringify(generate_json());
$.post('http://127.0.0.1:5000/tnw/post', json);
});
A:
I can see this being one of two problems:
You're accessing the page that makes the CORS request over the file:// protocol instead of http://. This causes you to have an origin of 'null'. Try using accessing it via http:// instead (e.g. python -m SimpleHTTPServer).
Does your endpoint require cookie-base authentication? jQuery omits cookies on CORS requests by default. If you need to send cookies with your request, add {xhrFields: withCredentials: true} to your ajax requests (docs).
|
[
"stackoverflow",
"0052257516.txt"
] | Q:
How we can close the error messagebar of office react fabric component?
I am trying to use fabric react messageBar component in my application but i am not able to close(dismiss) the message section even i clicked on close icon in the messageBar component.
Please find the below code for reference.
import React from 'react'
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib-commonjs/MessageBar'
class MyMessage extends React.Component{
log=(event)=>{
console.log('close on test');
}
render(){
return(
<div>
<MessageBar
componentRef={(messageBar)=>{this.errorMsgBar = messageBar}}
messageBarType={MessageBarType.error}
isMultiline={false}
onDismiss={(event)=> this.log(event)}
dismissButtonAriaLabel="Close"
>
Error lorem ipsum dolor sit amet, a elit sem interdum consectetur adipiscing elit.{' '}
</MessageBar>
</div>
)
}
}
export default MyMessage;
Office fabric will as default close functionality or do i need to close it ?
If i need to close it please let me know how we can do that?
thanks in advance.
-Nagaraju
A:
You can try something like this:
import React from 'react'
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib-commonjs/MessageBar'
class MyMessage extends React.Component{
constructor(){
super();
this.state = {
showMessageBar: true
}
}
closeMessageBar = () => {
this.setState({showMessageBar: false})
}
render(){
return(
<div>
{this.state.showMessageBar && <MessageBar
componentRef={(messageBar)=>{this.errorMsgBar = messageBar}}
messageBarType={MessageBarType.error}
isMultiline={false}
onDismiss={()=> this.closeMessageBar()}
dismissButtonAriaLabel="Close"
>
Error lorem ipsum dolor sit amet, a elit sem interdum consectetur adipiscing elit.{' '}
</MessageBar>}
</div>
)
}
}
export default MyMessage;
|
[
"stackoverflow",
"0037310550.txt"
] | Q:
Spring Transaction Management not working with Spring Boot + MyBatis?
I am trying to get Spring Transaction Management working in my new Spring Boot + MyBatis application.
So far I have managed to get everything working with minimal issues - it's just getting the @Transactional annotation to function correctly. Currently, all statements are committed immediately regardless of whether the method is annotated or not.
Spring Boot does so much of the boilerplate configuration for you that it's difficult to find the missing link.
My build.gradle contains the following dependencies:
compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.0.0")
compile("mysql:mysql-connector-java:5.1.38")
My application.properties contains the following datasource configuration:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/my_db
spring.datasource.username=my_user
spring.datasource.password=my_pass
A simple example of a method in a bean that is not acting as expected is as follows:
@Transactional
public void performTransactionTest() throws Exception {
Person person = new Person();
person.setPersonId(123);
personMapper.insert(person);
throw new Exception("This should force a rollback!");
}
The Exception gets thrown but the record has already been inserted.
There is basically no documentation currently in existence on transaction configuration for Spring Boot AND MyBatis together but as far as I understand, it should mostly wire itself up as would be done manually in a Spring + MyBatis application and where it doesn't - we are able to configure it further. With that said I have tried the following configurations in my applicationContext.xml with no luck:
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
I can confirm that even without any of the above configurations a DataSourceTransactionManager is configured with the same DataSource that the MyBatis mappers' SqlSession uses.
Any help or ideas that could push me in the right direction would be greatly appreciated. If you require any further information I am happy to provide it!
Thanks in advance!
Xandel
A:
So I got it working by annotating the class definition with @Transactional instead of the method definition.
I am not sure if this is common practice. The Spring Boot Transaction Management documentation doesn't do it like that here but the Mybatis Spring sample does do it that way in their documentation here...
If anyone has further information that could explain this I will happily mark that answer as the correct one.
For now however, my problem is solved.
EDIT
Returning to this problem month's later I have finally gotten to the bottom of it. There were 2 main issues here.
As Kazuki correctly mentioned, you need to explicitly declare that rollbacks need to happen for checked exceptions using the @Transactional(rollbackFor = Exception.class) annotation.
"Transaction boundaries are only created when properly annotated methods are called through a Spring proxy. This means that you need to call your annotated method directly through an @Autowired bean or the transaction will never start." (reference to this source below)
In my sample code I was calling this.performTransactionTest() from the same class. In this way the transaction will be ignored. If I instead call it via a wired reference to my class such as myAutoWiredBean.performTransactionTest() everything works as expected. This also explains why it appeared only the class level annotation was working, but that's because any method called would have been referenced by a wired bean.
Two articles which were MAJOR assistance to me in understanding the finer details of Spring's transaction management are here. A big thanks to the authors Nitin Prabhu and Tim Mattison.
https://dzone.com/articles/spring-transaction-management
http://blog.timmattison.com/archives/2012/04/19/tips-for-debugging-springs-transactional-annotation/
I hope this helps somebody!
|
[
"stackoverflow",
"0006984450.txt"
] | Q:
A super strange bug of os.path.abspath
On My Python 2.6 ( 64bit, win7, ActivePython ),
when i call:
os.path.abspath('D:/PROJECTS/SuiShouBei/www/ssb/static/voices/en/mp3/con.mp3')
It returns:
'\\\\.\\con'
I have no problem with other paths so far.
Anyone has the same issue?
Can someone please tell me why?
A:
I can reproduce this in Python 2.6, 2.7, 3.1 and 3.2.
The reason for this behavior is the fact that CON is an illegal filename in Windows (try os.path.abspath('D:/PROJECTS/SuiShouBei/www/ssb/static/voices/en/mp3/cont.mp3') and see that everything works fine).
So take care that your filenames don't contain
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
Also do not use the following reserved device names for the name of a file (with or without extension):
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9,
LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.
As noticed by slowdog, it is mentioned in the same MSDN document as above that \\.\CON is the correct way to access such a device name directly.
|
[
"stackoverflow",
"0048114461.txt"
] | Q:
Application-defined or Object-defined error vba
Thanks to internet and the help of a friend of mine, I manage to get my vba code working except this specific part:
' colle data / année
Windows(Namepatch3).Activate
For j = 0 To (finas - debutas)
Worksheets(1).Cells(2 + cpt, debutad + j) = Vcol(j)
'MsgBox (Vcol(j))
Next j
cpt = cpt + 1
Returning into an
"Application-defined or Object-defined error"
but I don't know why.
All variables are declared and Namepatch3 is declared As ThisWorkbook.
Can someone help me ?
EDIT: Here the full code of this part:
Sub Chiffres()
Application.ScreenUpdating = True
Dim ThisWorkbook As Workbook
Dim Filt As String
Dim IndexFiltre As Integer
Dim NomFichier As Variant
Dim Titre As String
Dim o As Integer
Dim p As Integer
Dim Msg1 As String
Dim ConsoPDC As Workbook
Dim Fichier As String
Dim chaine As String
Dim feuille As Variant
Dim Reponse As Integer
Dim Config As Integer
Dim nomClasseur As Variant
Dim vclasseur As Workbook
Dim resum As Workbook
[B65000].End(xlUp).Offset(0, -1).Select
Excel.Application.DisplayAlerts = False
' Définit la liste des filtres de fichiers
Filt = "Fichiers texte (*.txt),*.txt," & _
"Fichiers Lotus (*.prn),*.prn," & _
"Fichiers séparés par des virgules (*.csv),*.csv," & _
"Fichiers ASCII (*.asc),*.asc," & _
"Tous les fichiers (*.*),*.*"
' Affiche *.* par défaut
IndexFiltre = 5
' Définit la légende de la boîte de dialogue
Titre = "Sélectionner les fichiers à traiter"
' Obtenir le nom de fichier
NomFichier = Application.GetOpenFilename _
(fileFilter:=Filt, _
FilterIndex:=IndexFiltre, _
Title:=Titre, _
MultiSelect:=True)
' Quitter si la boîte de dialogue est annulée
If Not IsArray(NomFichier) Then
MsgBox "Aucun fichier n'a été sélectionné!"
GoTo TheEnd
End If
' Affiche le chemin complet et le nom des fichiers
Config = vbYesNo + vbInformation + vbDefaultButton2
For o = LBound(NomFichier) To UBound(NomFichier)
Msg = Msg & NomFichier(o)
Next o
Reponse = MsgBox("Ci-dessous vos fichiers selectionnés :" & vbCrLf & Msg & vbCrLf, Config, _
"MAJ resum")
If Reponse = vbNo Then GoTo TheEnd
For p = LBound(NomFichier) To UBound(NomFichier)
Msg1 = NomFichier(p)
Next
Application.ScreenUpdating = False
Workbooks.Open Filename:=Msg1
Application.Calculation = xlCalculationManual
'Declare le classeur actif
Set wkb = ActiveWorkbook
'Affiche la barre de statut en bas à gauche de l'écran (si elle ne l'est pas déjà)
Application.StatusBar = "MAJ resum - Traitement fichier " & ActiveWorkbook.Name & " - merci de patienter SVP ..."
'------------------------------------------------------------------------------------------------------
'Ne selectionne que le nom du fichier à l'intérieur du chemin
fichier1 = Right(Msg1, Len(Msg1) - InStrRev(Msg1, "\", -1, 1))
Fichier = Left(fichier1, InStr(fichier1, ".xls") - 1)
'traitement import
'------------------------------------------------------------------------------------------------------
' ***************
' * Macro1
' ***************
' appel raz dest
'Call M_raz_dest
Dim i As Integer
Dim j As Integer
Dim K As Integer
Dim l As Integer
Dim debutcols As Integer ' année en nombre ?
Dim fincols As Integer ' année en nombre ?
Dim debutas As Integer ' n° col année debut
Dim finas As Integer ' n° col année fin
Dim debutcold As Integer
Dim fincold As Integer
Dim debutad As Integer
Dim finad As Integer
Dim rowmaxwallets As Integer
Dim rowmaxwalletd As Integer
Dim c As Object
Dim therow As Integer
Dim Nlp As String
Dim Vcol(30) As Long ' data col année
Dim com(30) As String ' data col commentaires
Dim cpt As Integer
Windows(fichier1).Activate
Sheets("DataBase").Select
' lire Année début dans col V / 22 onglet source et n° de colonne
debutcols = CInt(Worksheets("DataBase").Cells(1, 22)) ' (col V) XXXX
debutas = 22
fincols = 0
fincold = 0
finas = 0
debutad = 0
finad = 0
' lecture colonne de fin dans Onglet Source
i = 0
For i = 1 To 30
If Len(Worksheets("DataBase").Cells(1, i + 22)) = 4 Then
' année 4 digits trouvée
Else
' plus une colonne Année
i = i - 1
finas = (22 + i)
fincols = CInt(Worksheets("DataBase").Cells(1, i + 22))
GoTo sortie
End If
Next i
sortie:
'MsgBox ("Lettre de colonne de début sur Source :" & ConvertCol(debutas))
'MsgBox ("Lettre de colonne de fin sur Source :" & ConvertCol(finas))
Columns(ConvertCol(debutas) & ":" & ConvertCol(finas)).Select
'ThisWorkbook.Worksheets(1).Select
i = 0
For i = 1 To 70
If Worksheets(1).Cells(2, i) = debutcols Then
debutcold = i
debutad = i
'MsgBox ("N° de colonne de début sur Dest : " & debutad)
GoTo sortie2
End If
Next i
sortie2:
'MsgBox ("Lettre de colonne de début sur onglet Dest :" & ConvertCol(debutad))
finad = debutad + (finas - debutas)
'MsgBox ("Lettre de colonne de fin sur onglet Dest :" & ConvertCol(finad))
Windows(fichier1).Activate
Sheets("DataBase").Select
rowmaxwallets = CInt(Worksheets("DataBase").Cells(Columns(1).Cells.Count, 1).End(xlUp).Row)
'MsgBox ("Nbr de lignes dans onglet Source à traiter : " & rowmaxwallets - 2)
'rowmaxwalletd = CInt(Worksheets("LP").Cells(Columns(1).Cells.Count, 1).End(xlUp).Row)
'MsgBox ("Nbr de LP dans onglet LP à parcourir : " & rowmaxwalletd - 2)
i = 0
cpt = 1
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'lecture fichier source
For l = 1 To rowmaxwallets
' copie data année en dynamique / colonne
Windows(fichier1).Activate
For j = 0 To (finas - debutas)
Vcol(j) = Worksheets("DataBase").Cells(1822 + l, debutas + j)
Next j
' colle data / année
For j = 0 To (finas - debutas)
ThisWorkbook.Worksheets("Feuil1").Cells(2 + cpt, debutad + j) = Vcol(j)
'MsgBox (Vcol(j))
Next j
cpt = cpt + 1
Next l
fin:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Sheets("Dest").Select
Range("A3").Select
MsgBox ("Import terminé !")
TheEnd:
End Sub
I know there is still some .Activate but I need to make the code works before optimizing it :)
PS: Happy New Year ! :)
A:
Remove the Activate line as that is unnecessary. Instead, fully qualify your worksheet reference like this:
Dim Namepatch3 As WorkBook
Set Namepatch3 = ThisWorkbook
Then in your Loop:
Namepatch3.Worksheets(1).Cells(2 + cpt, debutad + j) = Vcol(j)
Or just simplify it all like this:
ThisWorkbook.Worksheets(1).Cells(2 + cpt, debutad + j) = Vcol(j)
|
[
"stackoverflow",
"0032847458.txt"
] | Q:
Image size in Magnific Popup
Is there any way to influence the size of the image displayed? In other words: Can I achieve the same size for the full image even if the original pictures have different sizes?
Many thanks
Michael
The Q&A "found the answer. It can be done by changing the respective class's css properties manually. But, that is also fixed for all images." states like this. Which css property has to be changed?
A:
This solution makes all images appear in full height. If it is higher than the viewport you'll have to scroll to see it completely.
Also, it never exceeds the image dimensions. It simply allows you to see it on the original size
jQuery(document).ready(function(jQuery) {
jQuery('.trigger').magnificPopup({
type: 'image',
callbacks: {
resize: changeImgSize,
imageLoadComplete:changeImgSize,
change:changeImgSize
}
});
});
function changeImgSize(){
var img = this.content.find('img');
img.css('max-height', '100%');
img.css('width', 'auto');
img.css('max-width', 'auto');
}
A:
Are you trying to make the image bigger? Not recommended as this will most likely compromise image quality, but you can give it a width over 100% and a height of auto. Want to make it smaller? Give it a max-width less than 100% and height: auto. Is that what you're looking for?
|
[
"stackoverflow",
"0062092362.txt"
] | Q:
Kivy: How to update popup Label Text without dismiss the popup
I want to open a popup and after 3 seconds change the text of popup label.
I try this code:
from kivy.app import App
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button
import time
Builder.load_string('''
<SimpleButton>:
on_press: self.fire_popup()
<SimplePopup>:
id:pop
size_hint: .4, .4
auto_dismiss: True
title: 'Hello world!!'
Label:
id: lbl_id
text: 'Default Text'
''')
class SimplePopup(Popup):
pass
class SimpleButton(Button):
text = "Fire Popup !"
def fire_popup(self):
pop = SimplePopup()
pop.open()
time.sleep(3)
pop.ids.lbl_id.text = "Changed Text"
class SampleApp(App):
def build(self):
return SimpleButton()
SampleApp().run()
But BEFORE opening popup it sleeps for 3 seconds ,change the label text and then popup will open!!
What's the problem?
A:
Your code:
time.sleep(3)
Is stopping the main thread, so nothing will happen with the GUI until that code finishes. You should schedule the text change using Clock.schedule_once() like this:
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button
Builder.load_string('''
<SimpleButton>:
on_press: self.fire_popup()
<SimplePopup>:
id:pop
size_hint: .4, .4
auto_dismiss: True
title: 'Hello world!!'
Label:
id: lbl_id
text: 'Default Text'
''')
class SimplePopup(Popup):
pass
class SimpleButton(Button):
text = "Fire Popup !"
def fire_popup(self):
self.pop = SimplePopup()
self.pop.open()
Clock.schedule_once(self.change_text, 3)
def change_text(self, dt):
self.pop.ids.lbl_id.text = "Changed Text"
class SampleApp(App):
def build(self):
return SimpleButton()
SampleApp().run()
|
[
"stackoverflow",
"0001802053.txt"
] | Q:
looping through set of elements in jquery
$('form td .hint p') this jquery selector returns back a list [p,p,p,p,p,p].
I would like to know what's the best way to loop through each of those, check their css values, and do something if the css value = something I want.
I have this function to show and hide a tooltip, but I only want one tooltip to be shown at a time. While doing mouseover and mouseout works, it's buggy because currently I'm using parent(), next(), and child(), to find the right element, and jquery instantaneously inserts a div wrapping around the element I'm showing and hiding. So basically I'm trying to force all other p elements that have display:block to hide every time mouseover occurs.
Currently doing this:
target = $('form td .hint p');
target[0].css('display') gives an error.
target.css('display') seems to only return the css of the first one.
A:
Use each():
var displays = '';
$("p").each(function(i, val) {
displays += "Paragraph " + i + ": " + $(this).css("display") + "\n";
});
alert(displays);
The reason this fails:
var target = $("p");
var display = target[0].css("display");
is that target[0] is not a jQuery object. You could do this:
var display = $(target[0]).css("display");
Also, if you read the documentation for css():
Return a style property on the first
matched element.
Two other points worth mentioning.
Firstly, I wouldn't advise doing a tooltip yourself. Get one of the many plugins for this. I've used this one previously and it did the job.
Secondly, if you're checking CSS display values, there may be a shortcut worth using. For instance, you could do this:
$("p").each(function() {
if ($(this).css("display") == "none") {
$(this).addClass("blah");
}
});
but you can also use the :hidden and :visible selectors, so:
$("p:hidden").addClass("blah");
Checking values of css() calls is largely unreliable as you're only checking inline styles and not stylesheet values.
|
[
"stackoverflow",
"0024578804.txt"
] | Q:
weird behaviour in model (ruby on rails 4)
ive weird behaviour in my model code,
but iam not sure if this is my problem or is it some weird issue with ruby on rails.
ive a associated
has_many :chat_user #linked to ChatUser
and ive defined
Class A
def guest
chat_user #returning chat_user from has_many
end
end
ive 2 records of ChatUser which is linked to this model class
when i called object of Chat A .chat_user -> count and each return 2 records
when i called object of .guest -> count return 2, but each loop only once!
what could be the issue?
thank you
using rails 4.0.0 with puma server
A:
found the issue, silly me, ive actually returned a custom where query with limit 1 applied to chat_user, hidden in a function.. sorry for the trouble
|
[
"stackoverflow",
"0019570232.txt"
] | Q:
Javascript function call on wrong pages
Heyo,
Having a few issues with JavaScript function calls. Basically I am using php to create a table, and then on page init JavaScript is called to click a button which is labelled correct answer.
Now this all works fine, however when I return to the main page and try to do the same thing again it fails due to an "Uncaught TypeError: Cannot call method 'click' of null". This is happening because for some reason the script is being incorrectly called again and is then trying to click on something which isn't there, hence the 'null' error.
If I reload the page it works fine again as the JavaScript function is then not loaded until called.
The main issue seems to be that the JavaScript is remaining loaded (probably because jquerymobile uses ajax calls to load the page, and thus the data is never properly refreshed. Other than forcing the page to load without ajax, any suggestions?
JavaScript function:
function showCorrectAnswer(correctAnswer) {
$(document).on("pageinit", function() {
document.getElementById(correctAnswer).click()
})
}
PHP function:
function populatedQuestionUI ($topicID, $questionID, $actionSought) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM questions WHERE Topic = ? and QNo = ?");
$query->bindValue(1, $topicID);
$query->bindValue(2, $questionID);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
?>
<form name="questionUI" action="/MCExamSystemV2/Admin/manageQuestion.php" method="post">
<input type="hidden" name="TopicID" value="<?php echo $_POST['topic']; ?>"/>
<input type="hidden" name="QuestionNo" value="<?php echo $_POST['question']; ?>"/>
<label for="QText">Question Text</label>
<input type="text" name="QText" value="<?php echo $results[0]['QText']; ?>"/>
<label for="AnswerText-1">First Answer</label>
<input type="Text" name="AnswerText-1" value="<?php echo $results[0]['AText1']; ?>"/>
<label for="AnswerText-2">Second Answer</label>
<input type="Text" name="AnswerText-2" value="<?php echo $results[0]['AText2']; ?>"/>
<label for="AnswerText-3">Third Answer</label>
<input type="Text" name="AnswerText-3" value="<?php echo $results[0]['AText3']; ?>"/>
<label for="AnswerText-4">Fourth Answer</label>
<input type="Text" name="AnswerText-4" value="<?php echo $results[0]['AText4']; ?>"/>
<label for="CorrectAnswer">Correct answer:</label>
<div data-role="controlgroup" data-type="horizontal">
<input type="button" name="Answer-1" id="Answer-1" value=1 onClick="document.getElementById('CorrectAnswer').value='1'"/>
<input type="button" name="Answer-2" id="Answer-2" value=2 onClick="document.getElementById('CorrectAnswer').value='2'"/>
<input type="button" name="Answer-3" id="Answer-3" value=3 onClick="document.getElementById('CorrectAnswer').value='3'"/>
<input type="button" name="Answer-4" id="Answer-4" value=4 onClick="document.getElementById('CorrectAnswer').value='4'"/>
</div>
<input type="hidden" name="CorrectAnswer" id="CorrectAnswer" value='0'/>
<input type="submit" value="Confirm <?php echo $actionSought; ?>">
<input type="button" value="Cancel" onClick="location.href='/MCExamSystemV2/Admin'"/>
</form>
<script src="/MCExamSystemV2/includes/scripts.js"></script>>
<script>showCorrectAnswer('Answer-<?php echo $results[0]['CorrectA']; ?>')</script>
<?php
}
A:
The main problem is because you're doing this:
document.getElementById(correctAnswer).click();
You're not checking if the element is on the page. Change it to:
var el = document.getElementById(correctAnswer);
if (el) {
el.click();
}
|
[
"stackoverflow",
"0005622703.txt"
] | Q:
Trying to get Persistence Participant Promotion to work with a xamlx service in WF4
I have implemented workflow persistence participant promotion, just as it shown here on Microsoft's website:http://msdn.microsoft.com/en-us/library/ee364726%28VS.100%29.aspx and while everything seems like everything works. I do not see the data saving to the database when I query? I think I am missing a step or microsoft missed something.
I am using a workflow application .xamlx service and I have overridden the WorkflowServiceHost. This all seems to be working fine, So I am not sure where the problem can be?
So my question here is does anyone have a real working example of how to implement a persistence participant?
I tried a few different takes on this
Andrew Zhu's here http://xhinker.com/post/WF4Promote-persistence-Data.aspx
Microsoft Samples
But I just cannot seem to get this to work.
Just FYI-This code works when I changed the xnamespaces to match. Thanks to Maurice
WorkflowServiceHost Code:
public class ServiceHostFactory :WorkflowServiceHostFactory
{
private static readonly string m_connectionString =
"Data Source=localhost;Initial Catalog=WorkflowInstanceStore;Integrated Security=True";
protected override WorkflowServiceHost CreateWorkflowServiceHost(Activity activity, Uri[] baseAddresses)
{
return base.CreateWorkflowServiceHost(activity, baseAddresses);
}
protected override WorkflowServiceHost CreateWorkflowServiceHost(WorkflowService service, Uri[] baseAddresses)
{
WorkflowServiceHost host = base.CreateWorkflowServiceHost(service, baseAddresses);
host.DurableInstancingOptions.InstanceStore = SetupInstanceStore();
SqlWorkflowInstanceStoreBehavior sqlWorkflowInstanceStoreBehavior = new SqlWorkflowInstanceStoreBehavior(m_connectionString);
XNamespace xNS = XNamespace.Get("http://contoso.com/DocumentStatus");
List<XName> variantProperties = new List<XName>()
{
xNS.GetName("UserName"),
xNS.GetName("ApprovalStatus"),
xNS.GetName("DocumentId"),
xNS.GetName("LastModifiedTime")
};
sqlWorkflowInstanceStoreBehavior.Promote("DocumentStatus", variantProperties, null);
host.Description.Behaviors.Add(sqlWorkflowInstanceStoreBehavior);
//Add persistence extension here:
host.WorkflowExtensions.Add<DocumentStatusExtension>(()=>new DocumentStatusExtension());;
host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });
// Handle the UnknownMessageReceived event.
host.UnknownMessageReceived += delegate(object sender, UnknownMessageReceivedEventArgs e)
{
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Unknow Message Recieved:{0}", e.Message));
};
return host;
}
private static SqlWorkflowInstanceStore SetupInstanceStore()
{
SqlWorkflowInstanceStore sqlWorkflowInstanceStore = new SqlWorkflowInstanceStore(m_connectionString)
{
InstanceCompletionAction = InstanceCompletionAction.DeleteAll,
InstanceLockedExceptionAction = InstanceLockedExceptionAction.BasicRetry,
HostLockRenewalPeriod = System.TimeSpan.Parse("00:00:05")
};
InstanceHandle handle = sqlWorkflowInstanceStore.CreateInstanceHandle();
//InstanceHandle handle = sqlWorkflowInstanceStore.CreateInstanceHandle();
//InstanceView view = sqlWorkflowInstanceStore.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
//handle.Free();
//sqlWorkflowInstanceStore.DefaultInstanceOwner = view.InstanceOwner;
return sqlWorkflowInstanceStore;
}
DocumentStatusExtension Code:
public string DocumentId;
public string ApprovalStatus;
public string UserName;
public DateTime LastUpdateTime;
private XNamespace xNS = XNamespace.Get("http://contoso.com/");
protected override void CollectValues(out IDictionary<XName, object> readWriteValues, out IDictionary<XName, object> writeOnlyValues)
{
readWriteValues = new Dictionary<XName, object>();
readWriteValues.Add(xNS.GetName("UserName"), this.UserName);
readWriteValues.Add(xNS.GetName("ApprovalStatus"), this.ApprovalStatus);
readWriteValues.Add(xNS.GetName("DocumentId"), this.DocumentId);
readWriteValues.Add(xNS.GetName("LastModifiedTime"), this.LastUpdateTime);
writeOnlyValues = null;
}
protected override IDictionary<XName, object> MapValues(IDictionary<XName, object> readWriteValues, IDictionary<XName, object> writeOnlyValues)
{
return base.MapValues(readWriteValues, writeOnlyValues);
}
UpdateExtension Code:
public sealed class UpdateExtension : CodeActivity
{
// Define an activity input argument of type string
public InArgument<string> Text { get; set; }
// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override void Execute(CodeActivityContext context)
{
// Obtain the runtime value of the Text input argument
context.GetExtension<DocumentStatusExtension>().DocumentId = Guid.NewGuid().ToString();
context.GetExtension<DocumentStatusExtension>().UserName = "John Smith";
context.GetExtension<DocumentStatusExtension>().ApprovalStatus = "Approved";
context.GetExtension<DocumentStatusExtension>().LastUpdateTime = DateTime.Now;
}
}
A:
I have them working, unfortunately no sample code I can share just now. A PersistenceParticipant can be a bit tricky to setup with all the XNames involved that have to match up. Additionally there is a bug with using boolean values that stops the whole process without a warning so make sure you avoid booleans.
Update:
You are using different XML namespaces in your code. The CreateWorkflowServiceHost() uses http://contoso.com/DocumentStatus to define the property promotion and the CollectValues() uses http://contoso.com/ as the XML namespace of the values collected. Both should be the same.
|
[
"pt.stackoverflow",
"0000115094.txt"
] | Q:
Como pegar valores de dois selects do html em javascript?
Basicamente eu tenho o código abaixo:
var associar = $("#associar");
var desassociar = $("#desassociar");
var permissoes = $("#permissoes");
var minhasPermissoes = $("#minhasPermissoes");
var gravar = $("#gravar");
associar.click(function() {
minhasPermissoes.append(permissoes.find('option:selected'));
});
desassociar.click(function() {
permissoes.append(minhasPermissoes.find('option:selected'));
});
gravar.click(function(){
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-6">
<label>Permissões</label>
<select id="permissoes" class="form-control" multiple>
<option value="Clientes">Clientes</option>
<option value="Boletos">Boletos</option>
<option value="Usuarios">Usuários</option>
<option value="Configuracoes">Configurações</option>
</select>
</div>
<div class="col-md-6">
<label>Minhas Permissões</label>
<select id="minhasPermissoes" class="form-control" multiple>
</select>
</div>
</div>
<br>
<button id="associar" class="btn btn-primary">Associar</button>
<button id="desassociar" class="btn btn-primary">Desassociar</button>
<button id="gravar" class="btn btn-primary" style="float:right;">Gravar</button>
<div id="texto">
</div>
Como podem ver executando o código, eu passo valores(Object) de uma caixa de seleção pra outra e vice-versa, eu gostaria de que quando clicar em gravar eu passo os objetos dessas caixas de seleção como uma List, para ser tratado no Controller.
Tentei fazer da seguinte forma, que acaba me retornando uma List mas só vem um objeto.
var perfisUtilizados = [];
perfisUtilizados = $('#selectPerfisUtilizados').find('option');
var perfisDisponiveis = [];
perfisDisponiveis = $('#selectPerfisDisponiveis').find('option');
gravar..click(function() {
location.href = '${pageContext.request.contextPath}/permissao/perfis/${id}/' + perfisUtilizados + "," + perfisDisponiveis;
});
E quando clicar no gravar passa pra esse metodo do Controller:
@Get("/permissao/perfis/{id}/{perfisUtilizados},{perfisDisponiveis}")
public void salvarPerfisDaPermissao(Long id, List<Perfil> perfisUtilizados,
List<Perfil> perfisDisponiveis){
//Implementação
}
Como resolver?
A:
Utilizando jQuery, você pode enviar as listas de permissões dentro do corpo da requisição em formato JSON assim
gravar.click(function() {
$.ajax({
headers: {'Content-Type': 'application/json; charset=utf-8'}
type: 'POST',
url: url, // Substitua pela URL do sistema
data: JSON.stringify({
permissoes: permissoes.find('option').map(function() {
return this.value;
}).toArray(),
minhasPermissoes: minhasPermissoes.find('option').map(function() {
return this.value;
}).toArray()
}),
}).done(function(response, event_type) { // Em caso de sucesso
console.log('done', response, event_type);
}).fail(function(response, event_type) { // Em caso de falha
console.log('fail', response, event_type);
}).always(function(response, event_type) { // Depois do sucesso/falha
console.log('always', response, event_type);
})
});
Inspecione as variáveis response e event_type, pela ferramenta de desenvolvedor, para realizar o tratamento necessário no lado do cliente.
Como eu não programo em Java não saberia dizer como os dados serão recebidos no lado do servidor mas a intenção é enviar um objeto com o seguinte padrão:
{
"permissoes": ["Clientes", "Boletos"],
"minhasPermissoes": ["Configuracoes", "Usuarios"],
}
|
[
"stackoverflow",
"0010912544.txt"
] | Q:
Removing duplicate elements with XSLT
I need to eliminate duplicate elements from my XML using a specific node (ItemID)
My XML Looks as follows;
<XML>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>723073</ItemID>
<ColorID>02</ColorID>
<Description>Pentel LR7 Energel Metal Tip Refill 0.7mm</Description>
<MainCategory>WRITING INSTRUMENTS</MainCategory>
<SubCategory>Refill</SubCategory>
<LineNum> 1.0000000</LineNum>
<Qty> 6.0000000</Qty>
<UnitPriceExclTax> 10.0200000</UnitPriceExclTax>
<LineTax> 8.4200000</LineTax>
<LinePriceExclTax> 60.1200000</LinePriceExclTax>
<ColorName>Black</ColorName>
<UOM>EA</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637542_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>903420</ItemID>
<ColorID />
<Description>STEPHENS JUNIOR Stapler Half Strip KW586</Description>
<MainCategory>OFFICE SUNDRIES</MainCategory>
<SubCategory>Staplers</SubCategory>
<LineNum> 2.0000000</LineNum>
<Qty> 3.0000000</Qty>
<UnitPriceExclTax> 32.2500000</UnitPriceExclTax>
<LineTax> 13.5400000</LineTax>
<LinePriceExclTax> 96.7500000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637547_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>867241</ItemID>
<ColorID />
<Description>TRODAT PRINTY S/Inking Stamp Copy 4911</Description>
<MainCategory>STAMPS DATERS NUMBERERS</MainCategory>
<SubCategory>Self Inking Stamps</SubCategory>
<LineNum> 3.0000000</LineNum>
<Qty> 1.0000000</Qty>
<UnitPriceExclTax> 42.1500000</UnitPriceExclTax>
<LineTax> 5.9000000</LineTax>
<LinePriceExclTax> 42.1500000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 1.0000000</Backorder>
<INVENTTRANSID> CAP5637548_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>941151</ItemID>
<ColorID />
<Description>PENTEL Correction Tape 5mx5mm ZT35</Description>
<MainCategory>OFFICE SUNDRIES</MainCategory>
<SubCategory>Correction Fluid/Pens/Tape</SubCategory>
<LineNum> 4.0000000</LineNum>
<Qty> 2.0000000</Qty>
<UnitPriceExclTax> 25.1500000</UnitPriceExclTax>
<LineTax> 7.0400000</LineTax>
<LinePriceExclTax> 50.3000000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637549_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>801215</ItemID>
<ColorID />
<Description>MONDI ROTATRIM Copy Paper A4 80Gsm White</Description>
<MainCategory>A4 Paper</MainCategory>
<SubCategory>White Bond Paper</SubCategory>
<LineNum> 5.0000000</LineNum>
<Qty> 100.0000000</Qty>
<UnitPriceExclTax> 29.0100000</UnitPriceExclTax>
<LineTax> 406.1400000</LineTax>
<LinePriceExclTax> 2901.0000000</LinePriceExclTax>
<ColorName />
<UOM>Pkt 500</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637552_060</INVENTTRANSID>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP />
<LINENUM> 2.0000000</LINENUM>
<ITEMID>805236</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>Ruled Paper A4 Fnt/Marg JD76</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637543_060</INVENTTRANSID>
<QTYSALES> 4.0000000</QTYSALES>
<QTYORDERED> 4.0000000</QTYORDERED>
<QTYBACKORDERSALES> 4.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 4.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392608</RECID>
<RecVersion>1</RecVersion>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP />
<LINENUM> 3.0000000</LINENUM>
<ITEMID>941150</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>PENGUIN Correction Fluid 20ml White</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637546_060</INVENTTRANSID>
<QTYSALES> 6.0000000</QTYSALES>
<QTYORDERED> 6.0000000</QTYORDERED>
<QTYBACKORDERSALES> 6.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 6.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392609</RECID>
<RecVersion>1</RecVersion>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP />
<LINENUM> 5.0000000</LINENUM>
<ITEMID>867241</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>TRODAT PRINTY S/Inking Stamp Copy 4911</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637548_060</INVENTTRANSID>
<QTYSALES> 2.0000000</QTYSALES>
<QTYORDERED> 2.0000000</QTYORDERED>
<QTYBACKORDERSALES> 1.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 1.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392610</RECID>
<RecVersion>1</RecVersion>
</Line>
</XML>
You will see the XML is not identical but the tag is always in the same place, and there is currently 1 duplicate 867241
I do not want the order to change, just the element removed.
Desired output would be;
<XML>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>723073</ItemID>
<ColorID>02</ColorID>
<Description>Pentel LR7 Energel Metal Tip Refill 0.7mm</Description>
<MainCategory>WRITING INSTRUMENTS</MainCategory>
<SubCategory>Refill</SubCategory>
<LineNum> 1.0000000</LineNum>
<Qty> 6.0000000</Qty>
<UnitPriceExclTax> 10.0200000</UnitPriceExclTax>
<LineTax> 8.4200000</LineTax>
<LinePriceExclTax> 60.1200000</LinePriceExclTax>
<ColorName>Black</ColorName>
<UOM>EA</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637542_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>903420</ItemID>
<ColorID />
<Description>STEPHENS JUNIOR Stapler Half Strip KW586</Description>
<MainCategory>OFFICE SUNDRIES</MainCategory>
<SubCategory>Staplers</SubCategory>
<LineNum> 2.0000000</LineNum>
<Qty> 3.0000000</Qty>
<UnitPriceExclTax> 32.2500000</UnitPriceExclTax>
<LineTax> 13.5400000</LineTax>
<LinePriceExclTax> 96.7500000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637547_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>867241</ItemID>
<ColorID />
<Description>TRODAT PRINTY S/Inking Stamp Copy 4911</Description>
<MainCategory>STAMPS DATERS NUMBERERS</MainCategory>
<SubCategory>Self Inking Stamps</SubCategory>
<LineNum> 3.0000000</LineNum>
<Qty> 1.0000000</Qty>
<UnitPriceExclTax> 42.1500000</UnitPriceExclTax>
<LineTax> 5.9000000</LineTax>
<LinePriceExclTax> 42.1500000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 1.0000000</Backorder>
<INVENTTRANSID> CAP5637548_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>941151</ItemID>
<ColorID />
<Description>PENTEL Correction Tape 5mx5mm ZT35</Description>
<MainCategory>OFFICE SUNDRIES</MainCategory>
<SubCategory>Correction Fluid/Pens/Tape</SubCategory>
<LineNum> 4.0000000</LineNum>
<Qty> 2.0000000</Qty>
<UnitPriceExclTax> 25.1500000</UnitPriceExclTax>
<LineTax> 7.0400000</LineTax>
<LinePriceExclTax> 50.3000000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637549_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>801215</ItemID>
<ColorID />
<Description>MONDI ROTATRIM Copy Paper A4 80Gsm White</Description>
<MainCategory>A4 Paper</MainCategory>
<SubCategory>White Bond Paper</SubCategory>
<LineNum> 5.0000000</LineNum>
<Qty> 100.0000000</Qty>
<UnitPriceExclTax> 29.0100000</UnitPriceExclTax>
<LineTax> 406.1400000</LineTax>
<LinePriceExclTax> 2901.0000000</LinePriceExclTax>
<ColorName />
<UOM>Pkt 500</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637552_060</INVENTTRANSID>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP />
<LINENUM> 2.0000000</LINENUM>
<ITEMID>805236</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>Ruled Paper A4 Fnt/Marg JD76</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637543_060</INVENTTRANSID>
<QTYSALES> 4.0000000</QTYSALES>
<QTYORDERED> 4.0000000</QTYORDERED>
<QTYBACKORDERSALES> 4.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 4.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392608</RECID>
<RecVersion>1</RecVersion>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP />
<LINENUM> 3.0000000</LINENUM>
<ITEMID>941150</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>PENGUIN Correction Fluid 20ml White</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637546_060</INVENTTRANSID>
<QTYSALES> 6.0000000</QTYSALES>
<QTYORDERED> 6.0000000</QTYORDERED>
<QTYBACKORDERSALES> 6.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 6.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392609</RECID>
<RecVersion>1</RecVersion>
</Line>
</XML>
I can use XSLT 1 or 2
Regards,
A:
I. XSLT 1.0 solution:
Here is a solution using Muenchian grouping:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="kLineById" match="Line" use="ItemID|ITEMID"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match=
"Line[not(generate-id() = generate-id(key('kLineById', ItemID|ITEMID)[1]))]"
/>
</xsl:stylesheet>
Do Note:
Muenchian grouping is the most efficient known general grouping method for XSLT 1.0.
Pure "push" style used.
II. XSLT 2.0 solution:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<XML>
<xsl:for-each-group select="Line" group-by="ItemID | ITEMID">
<xsl:sequence select="."/>
</xsl:for-each-group>
</XML>
</xsl:template>
</xsl:stylesheet>
Both solutions, when applied on the provided XML document:
<XML>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>723073</ItemID>
<ColorID>02</ColorID>
<Description>Pentel LR7 Energel Metal Tip Refill 0.7mm</Description>
<MainCategory>WRITING INSTRUMENTS</MainCategory>
<SubCategory>Refill</SubCategory>
<LineNum> 1.0000000</LineNum>
<Qty> 6.0000000</Qty>
<UnitPriceExclTax> 10.0200000</UnitPriceExclTax>
<LineTax> 8.4200000</LineTax>
<LinePriceExclTax> 60.1200000</LinePriceExclTax>
<ColorName>Black</ColorName>
<UOM>EA</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637542_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>903420</ItemID>
<ColorID />
<Description>STEPHENS JUNIOR Stapler Half Strip KW586</Description>
<MainCategory>OFFICE SUNDRIES</MainCategory>
<SubCategory>Staplers</SubCategory>
<LineNum> 2.0000000</LineNum>
<Qty> 3.0000000</Qty>
<UnitPriceExclTax> 32.2500000</UnitPriceExclTax>
<LineTax> 13.5400000</LineTax>
<LinePriceExclTax> 96.7500000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637547_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>867241</ItemID>
<ColorID />
<Description>TRODAT PRINTY S/Inking Stamp Copy 4911</Description>
<MainCategory>STAMPS DATERS NUMBERERS</MainCategory>
<SubCategory>Self Inking Stamps</SubCategory>
<LineNum> 3.0000000</LineNum>
<Qty> 1.0000000</Qty>
<UnitPriceExclTax> 42.1500000</UnitPriceExclTax>
<LineTax> 5.9000000</LineTax>
<LinePriceExclTax> 42.1500000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 1.0000000</Backorder>
<INVENTTRANSID> CAP5637548_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>941151</ItemID>
<ColorID />
<Description>PENTEL Correction Tape 5mx5mm ZT35</Description>
<MainCategory>OFFICE SUNDRIES</MainCategory>
<SubCategory>Correction Fluid/Pens/Tape</SubCategory>
<LineNum> 4.0000000</LineNum>
<Qty> 2.0000000</Qty>
<UnitPriceExclTax> 25.1500000</UnitPriceExclTax>
<LineTax> 7.0400000</LineTax>
<LinePriceExclTax> 50.3000000</LinePriceExclTax>
<ColorName />
<UOM>Ea</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637549_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>801215</ItemID>
<ColorID />
<Description>MONDI ROTATRIM Copy Paper A4 80Gsm White</Description>
<MainCategory>A4 Paper</MainCategory>
<SubCategory>White Bond Paper</SubCategory>
<LineNum> 5.0000000</LineNum>
<Qty> 100.0000000</Qty>
<UnitPriceExclTax> 29.0100000</UnitPriceExclTax>
<LineTax> 406.1400000</LineTax>
<LinePriceExclTax> 2901.0000000</LinePriceExclTax>
<ColorName />
<UOM>Pkt 500</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637552_060</INVENTTRANSID>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP />
<LINENUM> 2.0000000</LINENUM>
<ITEMID>805236</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>Ruled Paper A4 Fnt/Marg JD76</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637543_060</INVENTTRANSID>
<QTYSALES> 4.0000000</QTYSALES>
<QTYORDERED> 4.0000000</QTYORDERED>
<QTYBACKORDERSALES> 4.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 4.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392608</RECID>
<RecVersion>1</RecVersion>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP />
<LINENUM> 3.0000000</LINENUM>
<ITEMID>941150</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>PENGUIN Correction Fluid 20ml White</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637546_060</INVENTTRANSID>
<QTYSALES> 6.0000000</QTYSALES>
<QTYORDERED> 6.0000000</QTYORDERED>
<QTYBACKORDERSALES> 6.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 6.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392609</RECID>
<RecVersion>1</RecVersion>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP />
<LINENUM> 5.0000000</LINENUM>
<ITEMID>867241</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>TRODAT PRINTY S/Inking Stamp Copy 4911</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637548_060</INVENTTRANSID>
<QTYSALES> 2.0000000</QTYSALES>
<QTYORDERED> 2.0000000</QTYORDERED>
<QTYBACKORDERSALES> 1.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 1.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392610</RECID>
<RecVersion>1</RecVersion>
</Line>
</XML>
produce the wanted, correct result:
<XML>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>723073</ItemID>
<ColorID>02</ColorID>
<Description>Pentel LR7 Energel Metal Tip Refill 0.7mm</Description>
<MainCategory>WRITING INSTRUMENTS</MainCategory>
<SubCategory>Refill</SubCategory>
<LineNum> 1.0000000</LineNum>
<Qty> 6.0000000</Qty>
<UnitPriceExclTax> 10.0200000</UnitPriceExclTax>
<LineTax> 8.4200000</LineTax>
<LinePriceExclTax> 60.1200000</LinePriceExclTax>
<ColorName>Black</ColorName>
<UOM>EA</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637542_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>903420</ItemID>
<ColorID/>
<Description>STEPHENS JUNIOR Stapler Half Strip KW586</Description>
<MainCategory>OFFICE SUNDRIES</MainCategory>
<SubCategory>Staplers</SubCategory>
<LineNum> 2.0000000</LineNum>
<Qty> 3.0000000</Qty>
<UnitPriceExclTax> 32.2500000</UnitPriceExclTax>
<LineTax> 13.5400000</LineTax>
<LinePriceExclTax> 96.7500000</LinePriceExclTax>
<ColorName/>
<UOM>Ea</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637547_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>867241</ItemID>
<ColorID/>
<Description>TRODAT PRINTY S/Inking Stamp Copy 4911</Description>
<MainCategory>STAMPS DATERS NUMBERERS</MainCategory>
<SubCategory>Self Inking Stamps</SubCategory>
<LineNum> 3.0000000</LineNum>
<Qty> 1.0000000</Qty>
<UnitPriceExclTax> 42.1500000</UnitPriceExclTax>
<LineTax> 5.9000000</LineTax>
<LinePriceExclTax> 42.1500000</LinePriceExclTax>
<ColorName/>
<UOM>Ea</UOM>
<Backorder> 1.0000000</Backorder>
<INVENTTRANSID> CAP5637548_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>941151</ItemID>
<ColorID/>
<Description>PENTEL Correction Tape 5mx5mm ZT35</Description>
<MainCategory>OFFICE SUNDRIES</MainCategory>
<SubCategory>Correction Fluid/Pens/Tape</SubCategory>
<LineNum> 4.0000000</LineNum>
<Qty> 2.0000000</Qty>
<UnitPriceExclTax> 25.1500000</UnitPriceExclTax>
<LineTax> 7.0400000</LineTax>
<LinePriceExclTax> 50.3000000</LinePriceExclTax>
<ColorName/>
<UOM>Ea</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637549_060</INVENTTRANSID>
</Line>
<Line>
<SupplierID>Waltons</SupplierID>
<InvoiceID>CAP600795SI</InvoiceID>
<InvoiceDate>20100506</InvoiceDate>
<ItemID>801215</ItemID>
<ColorID/>
<Description>MONDI ROTATRIM Copy Paper A4 80Gsm White</Description>
<MainCategory>A4 Paper</MainCategory>
<SubCategory>White Bond Paper</SubCategory>
<LineNum> 5.0000000</LineNum>
<Qty> 100.0000000</Qty>
<UnitPriceExclTax> 29.0100000</UnitPriceExclTax>
<LineTax> 406.1400000</LineTax>
<LinePriceExclTax> 2901.0000000</LinePriceExclTax>
<ColorName/>
<UOM>Pkt 500</UOM>
<Backorder> 0.0000000</Backorder>
<INVENTTRANSID> CAP5637552_060</INVENTTRANSID>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP/>
<LINENUM> 2.0000000</LINENUM>
<ITEMID>805236</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>Ruled Paper A4 Fnt/Marg JD76</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637543_060</INVENTTRANSID>
<QTYSALES> 4.0000000</QTYSALES>
<QTYORDERED> 4.0000000</QTYORDERED>
<QTYBACKORDERSALES> 4.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 4.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392608</RECID>
<RecVersion>1</RecVersion>
</Line>
<Line>
<SALESID> CAP716197SO</SALESID>
<INVOICEID> CAP600795SI</INVOICEID>
<INVOICEDATE>2010/05/06</INVOICEDATE>
<NUMBERSEQUENCEGROUP/>
<LINENUM> 3.0000000</LINENUM>
<ITEMID>941150</ITEMID>
<INVENTDIMID> CAP0000594_061</INVENTDIMID>
<NAME>PENGUIN Correction Fluid 20ml White</NAME>
<CONFIRMEDDLV>2010/05/06</CONFIRMEDDLV>
<INVENTTRANSID> CAP5637546_060</INVENTTRANSID>
<QTYSALES> 6.0000000</QTYSALES>
<QTYORDERED> 6.0000000</QTYORDERED>
<QTYBACKORDERSALES> 6.0000000</QTYBACKORDERSALES>
<QTYBACKORDERINVENT> 6.0000000</QTYBACKORDERINVENT>
<SALESUNIT>EA</SALESUNIT>
<ORIGSALESID> CAP716197SO</ORIGSALESID>
<DATAAREAID>wal</DATAAREAID>
<RECID>622392609</RECID>
<RecVersion>1</RecVersion>
</Line>
</XML>
|
[
"stackoverflow",
"0002741768.txt"
] | Q:
How do you make this Haskell power function tail recursive?
How would I make this Haskell power function tail recursive?
turboPower a 0 = 1
turboPower a b
| even b = turboPower (a*a) (b `div` 2)
| otherwise = a * turboPower a (b-1)
A:
turboPower a b = turboPower' 1 a b
where
turboPower' x a 0 = x
turboPower' x a b
| x `seq` a `seq` b `seq` False = undefined
| even b = turboPower' x (a*a) (b `div` 2)
| otherwise = turboPower' (x*a) a (b-1)
Basically, what you want to do is move the multiplication that you're doing in the "otherwise" step (since that's what keeps this from being tail-recursive initially) to another parameter.
Edited to add a line making all three parameters strictly evaluated, instead of lazy, since this is one of those well-known situations where laziness can hurt us.
|
[
"stackoverflow",
"0025217019.txt"
] | Q:
How to get external data in famo.us app
I need to read/write data via Service (e.g. REST). That's easy as long as the famo.us app works within/as a website, as I would host it within the same domain server where the data is hosted on. What if I translate the app into an Android app? How am I supposed to read/write to the server?
JS per se is no allowed to do a simple http request to other sites so I guess it won't work when it's translated into an Android (or iOs) app either?
A:
This should work without a problem in Cordova as it allows cross site requests. Or you could use JSONP
|
[
"stackoverflow",
"0046698346.txt"
] | Q:
Java iterators in Scala
I have some java code I am trying to convert to scala:
package hello;
class HelloWorldApp {
public static void main(String[] args) {
public SortedMap<Long, Long> toDates = new TreeMap<>();
Iterator<Long> iterLong = toDates.keySet().iterator();
while( iterLong.hasNext() )
{
System.out.println("TEST");
}
}
}
I used a converter to get this:
package hello
//remove if not needed
import scala.collection.JavaConversions._
object HelloWorldApp {
def main(args: Array[String]): Unit = {
val toDates: SortedMap[Long, Long] = new TreeMap[Long, Long]()
val iterLong: Iterator[Long] = toDates.keySet.iterator()
while (iterLong.hasNext) println("TEST")
}
}
The problem is the iterator() call really is not liked in scala (which I am executing through spark)
<console>:190: error: type mismatch;
found : java.util.Iterator[Long]
required: scala.collection.Iterator[Long]
val iterLong: Iterator[Long] = toDates.keySet.iterator()
I understand what he error is saying basically. Though, I am not sure how to force the type of scala.collection on the keySet.iterator() call.
I did do this:
val iterLong: scala.collection.Iterator[Long] = toDates.keySet.iterator()
To no avail What else can I add to have that iterator come back and work correclty in the loop?
A:
You can either convert from Java to Scala, or you can just work with the Java one directly.
Converting
Add this import
import collection.JavaConverters._
and then use the new asJava/asScala methods to convert collections:
val iterLong: Iterator[Long] = (...).toScala
Directly Using Java Types
When doing interop with java collections, it’s common to do
import java.{ util => ju }
So that Java collection types can be accesed via ju.??? without fear of naming conflicts. With the above import in scope, write
val iterLong: ju.Iterator[Long] = ... // or let type inference do it for you
and use the Java API
|
[
"stackoverflow",
"0055471795.txt"
] | Q:
What is module option in tsconfig used for?
I am trying to understand the typescript module compiler option.
I went through typescript documentation - docs
It says module option is to Specify module code generation.
What does that mean?
Does it mean if I put module option as commonjs, then the compiler compiles the code to commonjs? But then we have options like esnext, es16. After I went through Docs: Difference between esnext, es6, es2015 module targets, I understood that import() expressions are understood in esnext. Anyway the purpose of compiler is to compile the code into browser understandable syntax(commonjs). So compiling code to the module type given doesn't make sense.
So does it mean the module type you give tells the compiler in what syntax the code is written? Meaning from which code it has to compile it to commonjs? But then we have module type commonjs which is frequently used but we almost never write code in pure commonjs syntax.
what is the purpose of tsconfig.json? stackoverflow answer says module specifies module manager. I don't understand what that means.
I also went through Understanding “target” and “module” in tsconfig and tsconfig module options - does 'System' refer to SystemJS?.
None of these seem to answer my question properly.
tsconfig.json
{
"compilerOptions: {
"module": "esnext"
}
}
A:
TLDR; module in tsconfig.json tells the compiler what syntax to use for the modules in the emitted .js files. Frequently used values are "commonjs" (require/module.exports) or "ES2015" (import/export keywords), but there are other module systems. module affects the module syntax of emitted code while target affects the rest.
What does Specify module code generation mean?
"module" in tsconfig.json tells the Typescript (TS) compiler what module syntax
to use when the files are compiled to Javascript (JS).
When you set "module" to "commonjs" in tsconfig.json, this means that the modules in the compiled .js files will use the commonJS (CJS) syntax, so var x = require(...) and module.exports = {...} to import and export.
If you changed "module" to "ES2015" for example, the compiled code would use the import and export keywords used in ES2015 module syntax. For an overview of the other syntaxes you can take a look here.
There are several different module systems with CJS and the
native ES Module (ESM) format probably being the ones most widely used.
What to choose depends on your requirements. If it's for a server-side project
that uses Node.js then probably CJS, if it's for an Angular front-end application
than perhaps ESM (or their own NgModules but that's going beyond scope here).
A somewhat similar situation is library and package designs and how you would
like to expose them to consumers. This depends on what sort of users are going to consume
the code, what are they working with (browser, Node) and which of the module systems
is best suited for the job?
ES Modules are now the built-in standard for importing/exporting modules in JS but back when there was no native solution other module systems were designed: This is why we also have CJS, AMD and UMD modules around. They are not all obsolete, CJS is still used a lot in Node.js and the AMD module loader for example allows non-JS imports which can be useful in some cases.
Nowadays, all the modern browsers and Node 13.2.0+ support the ESM format (see this page for compatibility data and more background on modules).
But then we have options like esnext
Newer JS versions sometimes contain more features for module import/export.
setting "module" to "ESNext" enables support for these features which often are not added to official specifications yet. Such as the import(...) expression which is a dynamic import.
Does it mean if I put module option as commonjs, then the compiler compiles the code to commonjs?
The "module" setting does not affect the rest of the code, "target" is used for that instead and specifies what JS version the outputs should be compatible with.
This has been explained in other threads, I'm just adding it here for clarity.
Say you want to use require(...) and module.exports = {...} in a Node project but also want the code to utilise ES2015 features like let and const in the code (for readability/performance/other reasons).
In this case you would set "module" to "commonjs" and "target" to "ES2015" in tsconfig.
Anyway the purpose of compiler is to compile the code into browser understandable syntax(commonjs).
Yes, the compiler has to turn TS code into JS that a browser understands.
However, JS is no longer limited to browsers, Node runs in other environments (servers) for example. CJS was in fact intended as a server-side module format while AMD modules were/are used for browser imports/exports.
So does it mean the module type you give tells the compiler in what syntax the code is written?
It tells the compiler in what syntax to write the modules in the output .js files
|
[
"stackoverflow",
"0044377722.txt"
] | Q:
Using the accessibility.js module with highcharter
I'm trying to get the accessibility module to work with highcharter, but I can't seem to figure out how to do it.
I'm trying to integrate it into a shiny app, so here's a very minimal example of where I'm at so far:
library(highcharter)
library(shiny)
x <- c("a", "b", "c", "d")
y <- c(1:4)
z <- c(4:7)
data <- data.frame(x,y,z)
ui <- fluidPage(
fluidRow(
highchartOutput("chart")
)
)
server <- function(input, output, session){
output$chart <- renderHighchart({
hchart(data, "bubble", hcaes(x = x, y = y, size = z))%>%
hc_add_dependency(name = "modules/accessibility.js")
})
}
shinyApp(ui = ui, server = server)
But it still is not allowing me to tab through the bubbles.
A:
Edit:
I can't fix the tab option yet, I will check. sorry.
Previous answer
This was a error from highcharter and it was fixed in the development version. Update and test with:
source("https://install-github.me/jbkunst/highcharter")
Now the accessibility pluging is included by default and you can configure using the hc_accessibility function with options described in the highcharts API documentation.
I tested using the NVDA.
highchart() %>%
hc_add_series(data = 1:3, type = "column") %>%
hc_accessibility(
enabled = TRUE,
keyboardNavigation = list(enabled = FALSE)
)
|
[
"stackoverflow",
"0004208204.txt"
] | Q:
Python: Store the data into two lists and then convert to a dictionary
I am new to python, and have a question regarding store columns in lists and converting them to dictionary as follow:
I have a data in two column shown below, with nodes(N) and edges(E), and I want to first make a list of these two columns and then make a dictionary of those two lists as
{1:[9,2,10],2:[10,111,9],3:[166,175,7],4:[118,155,185]}.
How can I do that? Thanks.
N E
1 9
1 2
1 10
2 10
2 111
2 9
3 166
3 175
3 7
4 118
4 155
4 185
A:
A defaultdict is a subclass of dict which would be useful here:
import collections
result=collections.defaultdict(list)
for n,e in zip(N,E):
result[n].append(e)
|
[
"stackoverflow",
"0042811230.txt"
] | Q:
valgrind doesnt work on my 32bit executable in linux ubuntu 16.04
I'm trying to run the valgrind tool on my 32bit executable(sample), I built under the linux Ubuntu host 16.04(64bit), but it failed to run, error: wrong ELF.
sample application is built to run in arm32, cross-compiled in my host linux machine.
This is the command I ran.
valgrind --tool=callgrind ./sample
valgrind: wrong ELF executable class (eg. 32-bit instead of 64-bit)
valgrind: ./sample: cannot execute binary file
I ran memcheck tool but that also failed.
valgrind --tool=memcheck ./updater
valgrind: wrong ELF executable class (eg. 32-bit instead of 64-bit)
valgrind: ./updater: cannot execute binary file
Then what I did, I exported the valgrind lib path but that didn't help+
$export VALGRIND_LIB="/usr/lib/valgrind"
I jut ls my lib dir, I found entire list and find callgrind and all libs are there.
callgrind-amd64-linux
callgrind-x86-linux
Don't know what is wrong and how to use valgrind on my executables.
Any help, appreciated.
A:
Valgrind does not support a setup where 'host' (where you run valgrind)
differs from 'guest' (the application you run under valgrind.
So, there is no way to run an arm32 application under Valgrind on an
x86/amd64 system.
You should run this on an arm32 system, with a valgrind compiled for arm32.
Alternatively, you can use e.g. an android emulator.
See README.android and README.android_emulator in Valgrind distribution
for more information
|
[
"stackoverflow",
"0036881966.txt"
] | Q:
Mimekit, IMapClient get attachment information without downloading whole message
I am using the following code to obtain subject information.
Is it possible to know if the email contains attachments, and perhaps more specifically excel spreadsheets (xls/xlsx) without downloading the entire message?
client.Connect("imap.gmail.com", 993);
client.Authenticate("spyperson", "secret-word");
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadOnly);
Console.WriteLine("Total messages: {0}", inbox.Count);
Console.WriteLine("Recent messages: {0}", inbox.Recent);
var uids = inbox.Search(SearchQuery.NotSeen);
foreach (var summary in inbox.Fetch(uids, MessageSummaryItems.Full | MessageSummaryItems.UniqueId | MessageSummaryItems.Flags))
{
Console.WriteLine("[summary] {0:D2}: {1}:{2}", summary.Index, summary.Envelope.Subject, summary.Flags);
}
A:
Yes, this is possible. In order to do this, however, you'll need to pass the MessageSummaryItems.BodyStructure flag to the Fetch() method.
This will populate the summary.Body property.
If the Body property is populated, you can use the BodyParts property as a quick & dirty way of iterating over a flattened hierarchy of body parts in the message, checking if any of them are attachments like this:
var hasAttachments = summary.BodyParts.Any (x => x.IsAttachment);
One way to check for xls/xlsx attachments might be the following:
var hasAttachments = summary.BodyParts.Any (x => x.IsAttachment &&
x.FileName != null && (x.FileName.EndsWith (".xls") ||
x.FileName.EndsWith (".xslsx")));
These are very simplistic checks, however, and most likely your interpretation of what is or isn't an attachment will conflict with what the IsAttachment property tells you, so I'd probably recommend using either the Visitor pattern for traversing the MIME hierarchy or else using recursion and using your own logic to determine if a part is an attachment by your own custom definition (everyone seems to have their own unique interpretation of what constitutes an "attachment" when it comes to email).
I've got docs on common MIME hierarchies in the following locations:
http://www.mimekit.net/docs/html/WorkingWithMessages.htm#MessageStructure
http://www.mimekit.net/docs/html/FrequentlyAskedQuestions.htm#MessageBody
...and probably other places.
|
[
"worldbuilding.stackexchange",
"0000055701.txt"
] | Q:
What would happen to Earth if Yellowstone Erupted
In a world I am building; Humanity has left the earth and now only the plants, animals and cities remain. Many animals continue life undisturbed, while other went extinct. But with the disappearance of humans, the sixth great extinction has begun to wind down and the Earth's animals are experiencing a time a great peace, but not for long. Only a few hundred years after humans leave, Yellowstone (the largest volcano on Earth) erupts.
Obviously, many species go into extinction; but what about the larger scale? How does this massive explosion of lava and ash do to the Earth as a whole?
It obviously differs from this question in that:
That question relies on the effects of an earthquake on Yellowstone
That question includes the existence of man on earth
A:
If a volcano erupts in the forest and there's nobody there to see it...
The post humanity nature of this question makes a big difference, what's left of the natural world will be thriving
BBC
Ash
Within 3-4 days, a fine dusting of ash could fall across Europe,
according to a UK Met Office computer forecast commissioned by the
BBC. The computer model predicts how ash would spread following a
nine-day June eruption of 1000 cubic km of ash and gas from
Yellowstone.
The model shows that the fallout from a Yellowstone super-eruption
could affect three quarters of the US. The greatest danger would be
within 1,000 km of the blast where 90 per cent of people could be
killed.
Climate change
The most wide reaching effect of a Yellowstone eruption
would be much colder weather.
Volcanoes can inject sulphur gas into the upper atmosphere, forming
sulphuric acid aerosols that rapidly spread around the globe.
Scientists believe sulphuric aerosols are the main cause of climatic
cooling after an eruption.
Aerosols in the upper atmosphere would also scatter sunlight making
the sky look like a cloudy winter morning all day long. The skies in
Europe would appear red in the days after the eruption.
To predict how the climate may be affected, the BBC relied on historic
data from the Toba supervolcano in Indonesia about 74,000 years ago
and computer model forecasts commissioned from the UK Met Office and
the Max Planck Institute in Hamburg.
Experts believe a Yellowstone eruption would inject 2,000 million
tonnes of sulphur 40-50km above the Earth's surface. Once there it
would take 2-3 weeks for the resulting sulphuric acid aerosols to
cloak the globe – with devastating effects.
Global annual average temperatures would drop by up to 10 degrees,
according to computer predictions. And the Northern Hemisphere could
cool by up to 12 degrees. Experts say colder temperatures could last
6-10 years, gradually returning to normal
The climate change effect is largely dependent on how much damage humanity has done on the way out. If we've pushed up the temperatures a lot by the time we go, then the effect will be to bring them back down to where they should be, and as it all falls out it could end up being a great healer of the climate. If we've managed to control the damage then it could trigger a global ice age.
A:
The eruption would do absolutely nothing to "Earth as a whole". On a geological scale, it's a minor blip, nothing special. Has happened hundreds of times.
The effects it would have on the climate are rather difficult to predict, analyses of previous supervolcano eruption e.g. Lake Toba don't seem to agree well. They vary between "other parts of the world weren't affected very much" and "it triggered a 1000 year ice age".
At minimum you'd get a global average temperature drop of several degrees resulting in severe winters and lukewarm summers for a few years.
Of course, even that could easily be enough to wipe out many less adaptible species, but those that occur in a large geographic range would have a very good chance of surviving even a real ice age in some spots with more favorable conditions and have their population numbers recover afterwards.
A:
Basically there would be a giant crater.
Then a debris field from covering most of western North America with a fall out distance of around Minnesota to Michigan.
Further, thee would be ash in the atmosphere that surrounds the Earth that lowers the temperature.
This would cause suffocation in the fallout area. Famine and long winters for a few decades. The worse part of it would be that those in North America that don't die imediately or starve will have a much higher chance of cancer due to the particles.
The US wouldn't be completely wiped out, but it would require a ton of aid. Canada would suffer less due to farther away and smaller population, but overall it would suffer too.
Secondary effect might be the triggering of San Andreas Faults, the Oil pipelines, the places used for fracking blowing up, Butane deposits blowing up, and Cumbre Vieja falling into the ocean causes by possible earth quakes... All of these are more or less likely to happen, but all could happen or none could. If they did all happen, the US would likely be blown off the map completely.
In other words, the threat that it poses is terrible, but not as terrible as once thought, since it was once thought that it would be a complete or near complete extinction event.
|
[
"stackoverflow",
"0010237837.txt"
] | Q:
To use Active object or not?
The active object design pattern as I understand is tying up a (private/dedicated) thread life time with an object and making it work on independent data. From some of the documentation I read , the evolution of this kind of paradigm was because of two reasons , first , managing raw threads would be pain and second more threads contending for the shared resource doesn't scale well using mutex and locks. while I agree with the first reason , I do not fully comprehend the second . Making an object active just makes the object independent but the problems like contention for lock/mutex is still there (as we still have shared queue/buffer), the object just delegated the sharing responsibility onto the message queue. The only advantage of this design pattern as i see is the case where I had to perform long asynch task on the shared object (now that i am just passing message to a shared queue , the threads no longer have to block for long on mutex/locks but they still will blocka and contend for publishing messages/task). Other than this case could someone tell more scenarios where this kind of design pattern will have other advantages.
The second question I have is (I just started digging around design patterns) , what is the conceptual difference between , active object , reactor and proactor design pattern . How do you decide in which design pattern is more efficient and suits your requirements more. It would be really nice if someone can demonstrate certain examples showing how the three design patterns will behave and which one has comparative advantage/disadvantage in different scenarios.
I am kind of confused as I have used active object (which used shared thread-safe buffer) and boost::asio(Proactor) both to do similar kind of async stuff , I would like to know if any one has more insights on applicability of different patterns when approaching a problem.
A:
The ACE website has some very good papers on the Active Object, Proactor en Reactor design patterns. A short summary of their intents:
The Active Object design pattern decouples method execution
from method invocation to enhance concurrency and
simplify synchronized access to an object that resides in its
own thread of control. Also known as: Concurrent Object, Actor.
The Proactor pattern supports the demultiplexing and dispatching
of multiple event handlers, which are triggered by the completion
of asynchronous events. This pattern is heavily used in Boost.Asio.
The Reactor design pattern handles service requests that are delivered
concurrently to an application by one or more clients. Each service
in an application may consist of several methods and is represented by
a separate event handler that is responsible for dispatching service-specific
requests. Also known as: Dispatcher, Notifier.
|
[
"stackoverflow",
"0005893515.txt"
] | Q:
How do I remove the http header in the string returned by HttpResponse in django?
I am trying to build a web service system between 2 back-end written in django. However, even after changing the HttpResponse to json type:
HttpResponse('{"operation":"done"}',mimetype='application/json')
I still get the http header information in the other django machine:
{u'body': u'{"myjson":"here"}', u'headers': {'status': 200, 'content-length': '235', 'server': 'Google Frontend', 'cache-control': 'private, x-gzip-ok=""', 'date': 'Thu, 05 May 2011 06:16:16 GMT', 'content-type': 'application/json'}}
The header information is simply not necessary for me. Is there any convenient way to strip it?
[Edited]
The lib I use to conduct restFUL request is: http://code.google.com/p/python-rest-client/wiki/Using_Connection
Thanks
A:
I finally discovered that returned response is a collection type:
def getSOAResponse(soa, uri, parameters):
conn = Connection(soa)
value = conn.request_get(uri, args=parameters)
return value
If you take the response with the function above, the value you get here is actually a map.
Then you are able to access the body part of the response simply with:
body = value['body']
Problem solved. The header part of the response is no longer an issue.
[Edited]
Silly me. It's just specified in the doc:
http://code.google.com/p/python-rest-client/wiki/Using_Connection
|
[
"stackoverflow",
"0034951418.txt"
] | Q:
MySQL - Join order number of latest order based on timestamp
I'm selecting one customer from customers table and trying to get the latest order number for the customer from a jobs table, but based on a different timestamp column in that table.
Customers
id | name | ...
Jobs
id | customer_id | order_id | assigned
----------------------------------------------------
1 | 985 | 8020 | 2015-12-03 00:00:00
2 | 985 | 4567 | 2015-04-19 00:00:00
3 | 985 | 9390 | 2016-20-01 00:00:00
4 | 985 | 6381 | 2015-08-26 00:00:00
The latest order_id which should be joined is 9390 because the assigned timestamp is the latest.
SQL
SELECT c.name, j.latest_order
FROM customers c
LEFT JOIN (
SELECT customer_id,
??? AS latest_order
FROM jobs
WHERE withdrawn IS NULL
GROUP BY customer_id
) j ON j.customer_id = c.id
WHERE c.id = 985
I can't really figure out the best way to get the latest_order in the sub query, but it should be the jobs.order_id where jobs.assigned = MAX(jobs.assigned) for that customer.
A:
Use one more derived table to get the order number for the latest order.
SELECT c.name, t.order_id, j.latest_order
FROM customers c
JOIN (
SELECT customer_id,
max(assigned) AS latest_order
FROM jobs
WHERE withdrawn IS NULL
GROUP BY customer_id
) j ON j.customer_id = c.id
JOIN (select customer_id, order_id, assinged
from jobs
where withdrawn is null) t
ON t.customer_id = j.customer_id and t.assigned = j.latest_order
WHERE c.id = 985
|
[
"stackoverflow",
"0034997431.txt"
] | Q:
bind_param(): Number of variables doesn't match number of parameters in prepared statement
Basically the problem is I have a column of dates in my database table and I want to count the number of each particular date and have it stored in an array.I've busted my head around this problem for a week and so far I've come up with this.
<?php
function vref($arr) {
if (strnatcmp(phpversion(),'5.3') >= 0) {
$refs = array();
foreach($arr as $key => $value) $refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
$mysqli = new mysqli("localhost", "root","" , "ti_project");
$bind = 'sssss';
$feedbackdate = array($bind);
$query = "SELECT dateTime FROM feedback";
$result = $mysqli->prepare($query);
$result->execute();
$result->bind_result($Date);
while ($result->fetch()){
$feedbackdate[] = array($Date);
}
$rawQuery = 'SELECT COUNT(*) FROM feedback WHERE dateTime IN (';
$rawQuery .= implode(',',array_fill(0,count($feedbackdate),'?'));
$rawQuery .= ')';
$stmt = $mysqli->prepare($rawQuery);
call_user_func_array(array($stmt,'bind_param'),vref($feedbackdate));
$stmt->execute();
$stmt->bind_result($count);
while ($stmt->fetch()) {
printf ("%s\n", $count);
}
?>
But here I get the error
mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement.
So how to do this?
A:
I am not sure why you need to do two queries to get the result set you are looking for. This query will group the results by date and count them:
SELECT dateTime, COUNT(*) FROM feedback GROUP BY dateTime;
This will output something like:
+-----------------------+-------+
| dateTime | count |
+-----------------------+-------+
|2016-01-25 00:00:00 | 1 |
|2016-01-24 00:00:00 | 2 |
+-----------------------+-------+
Is that the type of data you are after?
|
[
"stackoverflow",
"0056321990.txt"
] | Q:
Auto add a product for cart item from specific product categories in WooCommerce
I have a code to add a product (a deposit) automatically to a customers cart, no matter what product he has chosen - with the code below inside the functions.php. This works fine.
But now, how to extend the code that this product will only be automatically added to the cart when the customer has chosen a product from a specific product category? E.g. the deposit shouldn't be added to the cart when a customer buys a gift card.
Thanks a lot!
/**
* Automatically adds product to cart on visit
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 1267; //product added automatically
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
}
}
}
A:
You will have to use the Wordpress conditional function hast_term() in a completely different way.
The following code will auto add to cart a pre-defined product, if a product from a product category is already in cart:
add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_based_on_product_category', 10, 1 );
function auto_add_item_based_on_product_category( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$required_categories = array('t-shirts'); // Required product category(ies)
$added_product_id = 1267; // Specific product to be added automatically
$matched_category = false;
// Loop through cart items
foreach ( $cart->get_cart() as $item_key => $item ) {
// Check for product category
if( has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
$matched_category = true;
}
// Check if specific product is already auto added
if( $item['data']->get_id() == $added_product_id ) {
$saved_item_key = $item_key; // keep cart item key
}
}
// If specific product is already auto added but without items from product category
if ( isset($saved_item_key) && ! $matched_category ) {
$cart->remove_cart_item( $saved_item_key ); // Remove specific product
}
// If there is an item from defined product category and specific product is not in cart
elseif ( ! isset($saved_item_key) && $matched_category ) {
$cart->add_to_cart( $added_product_id ); // Add specific product
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
|
[
"stackoverflow",
"0007152393.txt"
] | Q:
SQL Query question
i have this query to show
there are 2 tables, i will get the number of renovation from the table renovation while the customer-id and name is from table 1, customer.
SELECT c.[Customer-ID], c.name, COUNT(*)"Number of Renovation"
FROM CUSTOMER c, RENOVATION r
WHERE c.[Customer-ID] = r.[Customer-ID]
GROUP BY c.[Customer-ID], c.name
HAVING Count(*) in
(SELECT COUNT(*) FROM RENOVATION GROUP BY [Customer-ID])
ORDER BY c.[customer-id]
this is not the right way for me to do the query, anybody know how to shorten the query ? or the other ways of doing it ? though it still find the answer. i'm learning SQL server by the way.
A:
OK, so you want customers and the renovations they have - why not just use :
SELECT c.[Customer-ID], c.name, COUNT(*) AS 'Number of Renovations'
FROM dbo.CUSTOMER c
INNER JOIN dbo.RENOVATION r ON c.[Customer-ID] = r.[Customer-ID]
GROUP BY c.[Customer-ID], c.name
I don't quite understand what you're trying to achieve with the HAVING COUNT(*) IN...... part of your query......
If you want to have all customers that have at least one renovation - try this:
SELECT c.[Customer-ID], c.name, COUNT(*) AS 'Number of Renovations'
FROM dbo.CUSTOMER c
INNER JOIN dbo.RENOVATION r ON c.[Customer-ID] = r.[Customer-ID]
GROUP BY c.[Customer-ID], c.name
HAVING COUNT(*) > 0
A:
The HAVING clause does not seem to belong here. HAVING is intended to filter out resulting groups based on the aggregate result. For example, you could use the HAVING clause to exclude records that do not have any renovations:
SELECT c.[Customer-ID], c.name, COUNT(*) AS [Number of Renovations]
FROM dbo.CUSTOMER c
INNER JOIN dbo.RENOVATION r ON c.[Customer-ID] = r.[Customer-ID]
GROUP BY c.[Customer-ID], c.name
HAVING COUNT(*) > 0
|
[
"gis.stackexchange",
"0000228055.txt"
] | Q:
Getting around no data places on Kriging in ArcGIS Desktop?
I'm working with a natural vulnerability research, using a methodology that interpolate data from a high number of wells (around 600) to create a map of the vulnerability of the area.
Following the methodology, I intepolate the data using Kriging.
Since I have and region with almost no wells in my study area, I would like to know if there is any way get around this situation and don't get a map with the kriging error like on the image.
I'm using ArcGis 10.3.1, the interpolation was made on Raster Tool from Surfer.
A:
Assuming this is with just the standard "Kriging" tool of the Spatial Analyst, honestly, the tools in the Interpolation toolset of Spatial Analyst just don't cut it... They lack all kinds of vital function like exploratory data analysis, transformations, cross validation etc.
If you need to deal with potentially problematic datasets, I really recommend you to have a look at the Geostatistical Analyst and its far more sophisticated interpolation options, or one of the other specialized software packages out there.
These tools should also be able to tell you if interpolation across the entire surface is actually sensible, or if errors are to high.
|
[
"meta.stackexchange",
"0000177992.txt"
] | Q:
Have I done the right thing?
I ask this question here because I flagged a question on SO: https://stackoverflow.com/q/16229460/450534 as Not a real question. But I see similar questions popup up all the time. And I figured, let me answer this one since I have come across it. I thought it important keeping in mind new developers joining the Android platform, building apps and publishing on Google Play. However, based on the number of questions being asked, quite a few of them run a risk of getting their apps removed off the Play store.
So, as mentioned above, I answered the question. At the time of writing, it has also been accepted by the OP. But, I marked it as a Community Wiki. Now I have read quite a lot regarding CW's, but in all honesty, I never participated in one nor have I done what I have done in this case (marking the answer Community Wiki). I also point out the reason for doing so right at the start of the question.
So the question is, was / is this the right / accepted use of marking an answer(in this case) a Community Wiki accepted / encouraged?
EDIT:
My sincerest apologies to the author of the question that I have linked to here. It got the question some attention no doubt and now the author (apparently) cannot ask questions on SO. And regardless of the merits of the votes that followed, this end result was not my intention. The context of my question here on Meta was to help me figure out if I did in fact understand the concept of CW's.
A:
There are two main reasons to mark an answer Community Wiki:
You want a lower edit threshold.
You don't want (or you think you do not deserve) the reputation points.
The first is not often needed because (almost) anybody can suggest edits. The second is sometimes used.
In this case, I don't think you should have used the CW option. It is your answer.
|
[
"stackoverflow",
"0026418341.txt"
] | Q:
How to stop synchronous request to server in c#?
I know this has been asked before but my case is different. because i have no idea what the following code does. i am just using it as third party open source tool.
I am using open source tool "UnityHTTP" to get response from server.
I would like to get response request cancelled if it is taking a long time.
I am not an expert of C# so i couldn't understand what's going on inside the code the tool provided.
I'd appreciate if someone could help me out here.
the code for getting response is as follows
private void GetResponse() {
System.Diagnostics.Stopwatch curcall = new System.Diagnostics.Stopwatch();
curcall.Start();
try {
var retry = 0;
while (++retry < maximumRetryCount) {
if (useCache) {
string etag = "";
if (etags.TryGetValue (uri.AbsoluteUri, out etag)) {
SetHeader ("If-None-Match", etag);
}
}
SetHeader ("Host", uri.Host);
var client = new TcpClient ();
client.Connect (uri.Host, uri.Port);
using (var stream = client.GetStream ()) {
var ostream = stream as Stream;
if (uri.Scheme.ToLower() == "https") {
ostream = new SslStream (stream, false, new RemoteCertificateValidationCallback (ValidateServerCertificate));
try {
var ssl = ostream as SslStream;
ssl.AuthenticateAsClient (uri.Host);
} catch (Exception e) {
Debug.LogError ("Exception: " + e.Message);
return;
}
}
WriteToStream (ostream);
response = new Response ();
response.request = this;
state = RequestState.Reading;
response.ReadFromStream(ostream);
}
client.Close ();
switch (response.status) {
case 307:
case 302:
case 301:
uri = new Uri (response.GetHeader ("Location"));
continue;
default:
retry = maximumRetryCount;
break;
}
}
if (useCache) {
string etag = response.GetHeader ("etag");
if (etag.Length > 0)
etags[uri.AbsoluteUri] = etag;
}
} catch (Exception e) {
Console.WriteLine ("Unhandled Exception, aborting request.");
Console.WriteLine (e);
exception = e;
response = null;
}
state = RequestState.Done;
isDone = true;
responseTime = curcall.ElapsedMilliseconds;
if ( completedCallback != null )
{
if (synchronous) {
completedCallback(this);
} else {
// we have to use this dispatcher to avoid executing the callback inside this worker thread
ResponseCallbackDispatcher.Singleton.requests.Enqueue( this );
}
}
if ( LogAllRequests )
{
#if !UNITY_EDITOR
System.Console.WriteLine("NET: " + InfoString( VerboseLogging ));
#else
if ( response != null && response.status >= 200 && response.status < 300 )
{
Debug.Log( InfoString( VerboseLogging ) );
}
else if ( response != null && response.status >= 400 )
{
Debug.LogError( InfoString( VerboseLogging ) );
}
else
{
Debug.LogWarning( InfoString( VerboseLogging ) );
}
#endif
}
}
I can see that it something has to do with
the following line lines:-
System.Diagnostics.Stopwatch curcall = new System.Diagnostics.Stopwatch();
curcall.Start();
A:
The request is being made using the TcpClient class. It has a two properties ReceiveTimeout and SendTimeout. After the TcpClient has been initialized, set the a desired value for both of these properties before the connection is made:
var client = new TcpClient ();
client.ReceiveTimeout = 2000; // 2 seconds
client.SendTimeout = 2000; // 2 seconds
Doing this will cause the TcpClient to automatically cancel the request when the timeout has reached.
FYI - The below is only used for measurement of how long the request took.
System.Diagnostics.Stopwatch curcall = new System.Diagnostics.Stopwatch();
curcall.Start();
...
responseTime = curcall.ElapsedMilliseconds;
|
[
"stackoverflow",
"0044793138.txt"
] | Q:
How to compare date when its save as type text in database
I am using WPDB and here is my SQL
$date = date('d-m-Y');
$reservations = $wpdb->get_results( "SELECT * FROM reservation_db WHERE `date` > '$date'");
I need to select the date in my database when the date in database greater than today.
My date format is dd-mm-yyyy, but I think because it's save in text, it only compares days(dd) which is wrong, any solution to solve this?
A:
MySQL offers a STR_TO_DATE function to convert a date string to date:
SELECT * FROM reservation_db WHERE STR_TO_DATE(`date`) > '$date'
But as ankit suthar mentioned in above comment, it is not recommended to store dates as text.
|
[
"stackoverflow",
"0027479665.txt"
] | Q:
Processing stdin line by line
I'm using process.stdin.read() to process lines of text by handling readable event. In my case it returns either one line at a time or all the input text.
Is this reliable? In other words, which is the possibility that it will return half of the line?
The key requirement is to process as soon as possible, not waiting while all the input data is collected.
A:
Take a look at event-stream's `split. It's made to handle line based buffering.
https://github.com/dominictarr/event-stream#simple-example
var es = require('event-stream')
var inspect = require('util').inspect
process.stdin //connect streams together with `pipe`
.pipe(es.split()) //split stream to break on newlines
.pipe(es.map(function (data, cb) { //turn this async function into a stream
cb(null
, inspect(JSON.parse(data))) //render it nicely
}))
.pipe(process.stdout) // pipe it to stdout !
|
[
"stackoverflow",
"0046440953.txt"
] | Q:
JMeter - How to do setup thread group, many worker threads and then repeat?
The current setup is like that:
Registration / login (setUp Thread Group) 1 thread, 1 loop
spam POST (Thread Group) 100 threads 1000 loops.
Seems simple enough.
But, now I need to do multiple instances in the following order:
Do 1, then do 2. While 2 is spamming, wait 1 minute and then do 1 and then 2. Repeat this for 10 times.
Regardless of whether the 2nd Thread Group is done or not. Every minute, I need the JMeter to register, and if it is successful, spam POST.
How do I achieve this?
A:
First Thread Group (1 thread, 1 loop)
While Controller, condition ${__javaScript(${counter} < 10,)}
Counter configured as:
Your login sampler(s)
Test Action Sampler configured as:
Another Test Action Sampler configured like:
Second Thread Group. (100 Threads, Loop Count: Forever)
Every minute 1st Thread Group will perform Login for 10 times while 2nd Thread Group will be "spamming", when 1st Thread Group will execute login 10 times the test will finish.
|
[
"stackoverflow",
"0009896000.txt"
] | Q:
Using PHP SoapClient, Trying to Chande XSD from http://localhost to http://mysite.com
I am trying to consume a WSDL from WCF using PHPs SoapClient. When using the following code
$client = new SoapClient('http://subdomain.xxxxxxx.com:7575/?WSDL');
I get the following error :
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://localhost:7575/?wsdl=wsdl0' : failed to load external entity "http://localhost:7575/?wsdl=wsdl0"
For the service configuration file for the WSDL the specific port that the WSDL is using, specifies:
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:7574" />
<add baseAddress="http://localhost:7575" />
</baseAddresses>
</host>
The problem is that the WSDL is redirecting to http://localhost:7575 for the wsdl=wsdl0 file... then all the XSD locations are also listing http://localhost:7575.... is there a PHP Soap function that I can use to change that to http://subdomain.xxxxxxx.com:7575/?wsdl=wsdl0
A:
If you have control of the WCF service, it may be easier to configure it to produce "flattened" WSDL. This SO question & answer explains how to configure it to a single WSDL document.
If that isn't possible, may be you can have them (or possibly by you, locally) manually construct a single WSDL document and have them host it on their site so your PHP client can consume it as-is.
|
[
"stackoverflow",
"0016037641.txt"
] | Q:
Oracle database, large plsql code managment
I am working on project, where business logic is implemented in oracle database, using plsql. Code base is becoming big and it's management is becoming nightmare.
For example when code base is in Java, C#, ... you have version control system for project, where history is stored, and you are managing project with branches, tags etc. I do not understand how this can be done with pl/sql code which is stored directly in database server.
I want to know for situations like this, what are best practice of managing plsql codebase ?
A:
There's no reason to only store PL/SQL in the database just because some client tools default to working that way.
I strongly recommend you choose your favourite source control system and store PL/SQL sources in it. Use an all.sql to create all PL/SQL packages and other create-or-replace objects.
See versioning stored procedures/PLSQL? for an alternative approach but this requires a bit more effort to setup.
A:
Just make sure all of your PL/SQL is scripted externally before it is applied to the database, and put those files under source control. My tool of choice is TortiseHG.
I would be very unhappy if the only place my stored proc definitions, etc, existed was on the database, partially for the same reason you are bringing this up.
A:
I've been working with Oracle for something like 20 years, and never seen a satisfactory code management system in use.
However, in the past year I've been working on Ruby on Rails apps, with the distributed version control system "git" augmented by gitflow to help formalise the code branches (master, develop, feature, hotfix etc) and deployment of database (PostgreSQL) migrations using rake. I really wish I'd had the opportunity to use them with Oracle code because it really ticks every box I needed.
|
[
"stackoverflow",
"0035525184.txt"
] | Q:
Confused about how to use command-line form: unbound identifier in module and extracting arguments
I'm trying to make a basic (but specialized) command-line file search tool in Racket for my own personal use. Here is what I have so far:
#! /usr/bin/env racket
#lang racket/base
(require racket/path)
(require racket/cmdline)
(require racket/string)
(define (basename f)
(path->string (file-name-from-path f)))
(define (plain-name? path)
(regexp-match? "^[A-Za-z]+$" (basename path)))
(define (find-csv root [name ""] [loc ""] [owner ""] [max 10000])
(define m 0)
(for ([f (in-directory root plain-name?)]
#:when (and (file-exists? f)
(filename-extension f)
(bytes=? #"csv" (filename-extension f))
(string-contains? (path->string f) loc)
(string-contains? (basename f) name))
#:break (>= m max))
(set! m (add1 m))
(displayln f)))
(define args
(command-line
#:once-each
[("-n" "--max-paths") "Maximum number of file paths to return" (max 10000)]
[("-o" "--owner") "Limit search to certain owners" (owner "")]
[("-t" "--template") "Limit search to certain templates" (template "")]
[("-l" "--location")
"Limit search to directory structure containing location"
(loc "")]
[("-p" "--root-path") "Look under the root path" (root "/home/wdkrnls")]))
My first issue is that I'm getting an error when trying to run it via
./list-files.rkt
list-files.rkt:30:55: owner: unbound identifier in module
in: owner
context...:
standard-module-name-resolver
This use of command-line looks like it follows the greeting example in the Racket documentation, but racket seems to be looking for defined functions where I'm just trying to specify default values to variables I'd like to make available to my find-csv function.
My second issue is it's not clear to me from the documentation how I am supposed to use these arguments to call find-csv from the command line. The example in the documentation only covers a very basic case of one argument. I have no required arguments, but several optional ones.
Can you give me any pointers? Thanks.
A:
In the example in the documentation, all of the flags toggle parameters that are used to communicate the flag settings to the later processing step (which isn't shown in the example).
So in your particular case, you would define parameters like this:
(define max (make-parameter 10000))
(define owner (make-parameter ""))
(define template (make-parameter "")
(define loc (make-parameter ""))
(define root (make-parameter "/home/wdkrnls"))
where the arguments here are the parameter default values. Then you can either call find-csv with the parameter value (by using the parameter as a function, e.g., like (max)), or you can change find-csv so that it doesn't take any arguments and instead just accesses the parameters directly.
Also, your flag syntax is probably not quite right. You probably want something like this for each one:
[("-n" "--max-paths") max-arg
"Maximum number of file paths to return"
(max max-arg)]
Note the max-arg name that's added. You need that to actually set the parameter to the value provided by the user.
|
[
"stackoverflow",
"0012262393.txt"
] | Q:
Must I use port 9000 for XDebug?
I am using:
WAMP
PHP 5.3
XDebug
NetBeans
I want to debug and have the debug port in Netbeans set as 9000 (after following various tutorials, including this one --> Xdebug And Netbeans Problem ). The problem is, I'm unsure as to the purpose of the port 9000.
Does debug port 9000 mean that I must run Wamp on port 9000?
A:
You don't run Wamp on port 9000: it's NetBeans that runs on port 9000!
Your debug client (NetBeans, in this case) needs to listen for incoming connections so Xdebug is able to establish a connection and send the apporpriate info. Please note that there're two requests involved:
Someone (possibly NetBeans) connects to the web server to request the HTML document and start a debug session.
Xdebug connects to whoever requested the debug session (NetBeans) and sends some XML with variables and other debug info.
Details can vary depending on your settings but this is the general idea.
The port you choose is irrelevant as far as:
It's available (no other app is using it) at this moment.
It's reachable from the web server (no firewall / router issues).
|
[
"stackoverflow",
"0042054024.txt"
] | Q:
IOException while reading hadoop sequence file
I'm reading hadoop sequence file in java using following code
SequenceFile.Reader reader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(fileStatus.getPath()));
MyWritable1 key = (MyWritable1) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
MyWritable2 value = (MyWritable2) ReflectionUtils.newInstance(reader.getValueClass(), conf);
while(reader.next(key, value)){ //<- exception on this line
//some code
}
And I'm getting exception
"java.io.IOException: some.package.MyWritable1@4142e91 read 59 bytes,
should read 231"
I'm writing to that file key-value pairs of the exact same classes MyWritable1 and MyWritable2.
What might be the issue here? Appreciate any tips
A:
I found a bug. It was in MyWritable1 readFields function
|
[
"stackoverflow",
"0019105055.txt"
] | Q:
How to a resize a dynamic array?
Let's say I have a dynamic array:
int* p;
ifstream inFile("pop.txt");
int x;
while (inFile >> x)
{
// ????
}
How do I resize p so I am able to to fit x in as like an array. I don't want to use a vector or static array as I am trying to learn the language. I need to use pointers because I don't know the initial size. Any attempt is appreciated.
A:
The simplest answer is that you should use higher level components than raw arrays and raw memory for the reading. That way the library will handle this for you. A simple way of reading a set of numbers into an application (without error handling) could be done with this simple code:
std::vector<int> data;
std::copy(std::istream_iterator<int>(inFile), std::istream_iterator<int>(),
std::back_inserter(data));
The code creates a couple of input iterators out of the stream to read int values, and uses a back_inserter iterator that will push_back onto the vector. The vector itself will manage growing the memory buffer as needed.
If you want to do this manually you can, you just need to allocate a larger chunk of memory, copy the first N elements from the old buffer, release the old buffer and continue reading until the larger buffer gets filled, at which point you follow the same procedure: allocate, copy, deallocate old, continue inserting.
|
[
"stackoverflow",
"0009080128.txt"
] | Q:
How do I reference an alias in a WHERE clause?
Here's my statement:
SELECT
C.Account,
(RTRIM(N.FIRST) + ' ' + RTRIM(LTRIM(N.MIDDLE)) + ' ' + RTRIM(LTRIM(N.LAST)) + ' ' + LTRIM(N.SUFFIX)) AS OwnerName,
DateAdd(dd, -1, C.ExpirationDate) as RealExpirationDate,
C.Description,
C.Type
FROM CARD as C
INNER JOIN NAME as N ON C.Account = N.Account
WHERE (RealExpirationDate BETWEEN @StartDate AND @EndDate)
AND C.Type IN(10,15,17,25)
I keep getting an error saying that RealExpirationDate is an invalid column name. How can I reference that alias?
A:
You can't in your code above, remember WHERE happens before SELECT, so you'd have to use:
WHERE DateAdd(dd, -1, C.ExpirationDate) BETWEEN @StartDate AND @EndDate
The most common way to alias something like this would be some inner view / query like so:
SELECT
n.FooBar, --here we can use FooBar
t.BarFoo
FROM
MyTable t
INNER JOIN
(
SELECT
myTestCase as FooBar
From MyTable2
) n
|
[
"stackoverflow",
"0039426663.txt"
] | Q:
android studio application cannot be run in windows 7 machine
In my Android studio I got following error when run the application.
Error:Error: Could not create the Java Virtual Machine.
Error:Error: A fatal exception has occurred. Program will exit.
Error:Error: Could not create the Java Virtual Machine.
Error:Error: A fatal exception has occurred. Program will exit.
Error:Invalid maximum heap size: -Xmx4g
Error:The specified size exceeds the maximum representable size.
Error:Invalid maximum heap size: -Xmx4g
Error:The specified size exceeds the maximum representable size.
:dmart-android:transformClassesWithDexForDev FAILED
Error:Execution failed for task ':dmart-android:transformClassesWithDexForDev'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_101\bin\java.exe'' finished with non-zero exit value 1
I have 32 bit windows 7 machine and could not able to run.
Please let me know how to clear the errors.
A:
I have installed Windows 7 with 32 bit and used 8 Ram so the system only used 4GB only I have installed 64 bit OS. Now its working.
|
[
"serverfault",
"0000574896.txt"
] | Q:
What are the security risks with running an SMTP server?
I'm running Windows Server 2012 and I would like to set up an SMTP server to work with my hosted websites. I've previously installed various roles on my server which have resulted in exposing security holes. Since then I have tried being extremely careful whenever exposing server roles/features/services to the internet. I couldn't find a clear-cut explanation to the following questions:
What are the most common security threats to SMTP servers (e.g. external use for sending spam)?
Do SMTP Servers (especially one running as a Windows Server role) require additional configuration to be secured against threats on the internet?
What mechanisms are in place to prevent or detect unauthorized use of an installed SMTP server?
A:
Security risks?
The main risk is one of exploitation. You will be used as a spam relay.
By default there are no mechanisms to stop unauthorized access (unless you count your firewall)
In the unlikely event that an attacker was especially crafty, and your mail server was especially vulnerable, someone could send out a virus in such a way that it is stored somewhere on your server before sending out, thereby infecting your server. That's just an example that I made up on the spot.
Non-authenticated SMTP relays which are open to the public are constantly scanned for, and are usually found within 15-45 minutes of being online.
Suggestions
If you are going to run an SMTP relay, make sure that it requires Authentication.
You should also ensure that any repeated attempts to relay from denied IPs are blocked. There should be a software setting for this in any decent mail server client.
If you don't want to pay for a product such as Microsoft Exchange Server or IceWarp, then you should instead look to a Linux based solution using a combination of Postfix and Dovecot, Cyrus or similar in a SASL configuration.
There are numerous tutorials on the net for this. One good source (that I like) is [here]
|
[
"stackoverflow",
"0015207369.txt"
] | Q:
LINQ Type expected
have the following linq code, trying to parse an xml file to a datatable but i get strange values in the resultant datatable all cell values show as
System.Xml.Ling.XContainer+<GetElements>d_11
Here is my LINQ
XDocument doc1 = XDocument.Load(@"D:\m.xml");
var q = from address in doc1.Root.Elements("Address")
let name = address.Elements("Name")
let street = address.Elements("Street")
let city = address.Elements("city")
select new
{
Name = name,
Street = street,
City = city
};
var xdt = new DataTable();
xdt.Columns.Add("Name", typeof(string));
xdt.Columns.Add("Street", typeof(string));
xdt.Columns.Add("City", typeof(string));
foreach (var address in q)
{
xdt.Rows.Add(address.Name, address.Street, address.City);
}
dataGrid1.ItemsSource = xdt.DefaultView;
here is my xml:
<PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
<Address Type="Shipping">
<Name>Ellen Adams</Name>
<Street>123 Maple Street</Street>
<City>Mill Valley</City>
<State>CA</State>
<Zip>10999</Zip>
<Country>USA</Country>
</Address>
<Address Type="Billing">
<Name>Tai Yee</Name>
<Street>8 Oak Avenue</Street>
<City>Old Town</City>
<State>PA</State>
<Zip>95819</Zip>
<Country>USA</Country>
</Address>
</PurchaseOrder>
and here is the result i get!
A:
You forgot to regrieve the inner text of XElements. So you are selecting the whole element with attributes etc. Use this part of code:
var q = from address in doc1.Root.Elements("Address")
let name = address.Element("Name")
let street = address.Element("Street")
let city = address.Element("city")
select new
{
Name = name.Value,
Street = street.Value,
City = city.Value
};
A:
address.Elements("Name") is a collection of all of the elements of type "Name". It so happens that in your case it's a collection of size one, but it's still a collection. You want to get the first item out of that collection (since you know it will be the only one) and then get the text value of that element. If you use Element instead of Elements you'll get the first item that matches, rather than a collection of items.
Now that you have your single element, you also need to get the value of that element, rather than the element itself (which also contains lots of other information in the general case, even though there really isn't anything else interesting about it in this particular case.
var q = from address in doc1.Root.Elements("Address")
select new
{
Name = address.Element("Name").Value,
Street = address.Element("Street").Value,
City = address.Element("City").Value
};
|
[
"stackoverflow",
"0042151948.txt"
] | Q:
Volley setRetryPolicy timeout is not working
I want to set my application timeout duration to 60s, which mean my apps will only dismiss the ProgressDialog if it's getting reply from server or it reach timeout without getting reply from the server.
Currently I'm working with Volley library on android so this is what I do :
private void loginOnline(final String user, final String pwd, final String login_url){
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Communicating with Server");
pd.show();
final RequestQueue queue = Volley.newRequestQueue(this);
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_USERNAME, user);
params.put(KEY_PASSWORD, pwd);
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, login_url, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
pd.dismiss();
try {
int msg = response.getInt("status");
sendMessage(msg);
}
catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
Log.d("D", "onErrorResponse: "+error.getMessage());
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(60000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjReq);
}
The problem is when I try to connect to my server, it shows in the log :
D/D: onErrorResponse: java.net.ConnectException: failed to connect to /192.123.x.xxx (port 3000) after 60000ms: isConnected failed: EHOSTUNREACH (No route to host)
D/Volley: [1] Request.finish: 3072 ms: [ ] http://192.123.4.215:3000/login 0xdde27c7c NORMAL 1
my question is why does it stop to connecting to the server before it reach 60000ms.
Thanks in advance
A:
Because it isn't just failing to connect to the host- its failing to find a route to it. That means it can never talk to the host. As such, it returns immediately. The retry policy is working, but it only applies if a connection is possible. It would also end immediately if the server rejected the connection, or a few other conditions.
|
[
"pt.stackoverflow",
"0000332195.txt"
] | Q:
Angular 6 data e hora em portugues
Boa tarde,
Estou começando a desenvolver uma aplicação em Angular 6, e preciso exibir na tela a data e a hora. Ja consegui apresentar ambas, mas estão no padrão americano. Como posso alterar para o padrão brasileiro?
A:
Consegui. Fiz o seguinte:
import { registerLocaleData } from '@angular/common';
import localeBr from '@angular/common/locales/pt';
No import do NgModule importei tambem LOCALE_ID
Depois
registerLocaleData(localeBr, 'pt')
E na declaração de providers
{ provide: LOCALE_ID, useValue: 'pt' }
Tudo isso no modulo principal(appmodule)
|
[
"stackoverflow",
"0049503662.txt"
] | Q:
In python sympy, how do I apply an external python funtion to each element of the sympy matrix?
To be more specific, I want to apply the following sigmoid function:
def sigmoid(x):
return 1 / (1 + m.exp(-x))
to each element of the following 2x2 Sympy Matrix:
Matrix([[1,3],[2,4]])
Matrix([
[1, 3],
[2, 4]])
Such that on applying the sigmoid function onto the matrix I'll get a new 2x2 Matrix where each individual element of the Matrix had the sigmoid applied to it. Like the following :
Matrix([[ sigmoid(1), sigmoid(3) ],[ sigmoid(2), sigmoid(4) ]])
How can this be done?
A:
>>> M.applyfunc(sigmoid)
Matrix([
[1/(exp(-1) + 1), 1/(exp(-3) + 1)],
[1/(exp(-2) + 1), 1/(exp(-4) + 1)]])
This is using SymPy's exp in the sigmoid function. If m.exp means you are importing exp from math, then the result won't look nice, and will error out if the matrix contains symbols.
If you literally want sigmoid(1) and so on inside the function, then sigmoid needs to be a SymPy function that does not evaluate anything.
class sigmoid(Function):
pass
With this,
>>> M.applyfunc(sigmoid)
Matrix([
[sigmoid(1), sigmoid(3)],
[sigmoid(2), sigmoid(4)]])
|
[
"stackoverflow",
"0041927160.txt"
] | Q:
sklearn test train split - get index to filename of original list
I am using the test_train_split module in sklearn to generate a random combination of dataset for training and testing. I have a list of filepaths that point to the original dataset. I would also like to know how the data has been shuffled, or shuffle the filepath list in the same manner so as to be able to trace the filepaths once the shuffled/split dataset is made available?
A:
If you specify the same random_state in test_train_split and shuffle you will get the same order.
See the snippet below for a demonstration.
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import random
X = list()
y = list()
files = list()
random_state = 42
test_size = 0.9
n = 100
for i in range(n):
X.append(i)
y.append(i + random.random())
files.append('file_{0:02d}.csv'.format(i))
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=test_size,
random_state=random_state)
X_shuffle = shuffle(X, random_state=random_state)
y_shuffle = shuffle(y, random_state=random_state)
file_shuffle = shuffle(files, random_state=random_state)
print(X_train)
print(X_shuffle[int(n * test_size):])
print(y_shuffle[int(n * test_size):])
print(file_shuffle[int(n * test_size):])
print(X_train == X_shuffle[int(n * test_size):])
[91, 74, 86, 82, 20, 60, 71, 14, 92, 51]
[91, 74, 86, 82, 20, 60, 71, 14, 92, 51]
[91.64119581793204, 74.77493553783724, 86.62410189510936, 82.40452263996107, 20.22784747831378, 60.913989700418675, 71.1940538438253, 14.644282494118647, 92.97808337955185, 51.289858815186356]
['file_91.csv', 'file_74.csv', 'file_86.csv', 'file_82.csv', 'file_20.csv', 'file_60.csv', 'file_71.csv', 'file_14.csv', 'file_92.csv', 'file_51.csv']
True
|
[
"stackoverflow",
"0012769681.txt"
] | Q:
Can anyone tell me what causes that white space appear between the contact form and the footer?
I have written the html but the contact form is copied from a another place...and I cant get rid of that white line no matter what I do.
Can anyone tell me what I did wrong?
NOTE: here it is, on jsfiddle.net
http://jsfiddle.net/j6RMW/embedded/result/
or
http://jsfiddle.net/j6RMW/
There the white space is gone....but you can see the screenshot that it is actually there.
NOTE2: this is what causes the problem...it is html issue:
<form name="freecontactform" method="post" action="freecontactformprocess.php" onsubmit="return validate.check(this)">
<table width="400px" class="freecontactform">
<tbody><tr>
<td colspan="2">
<div class="freecontactformheader">Contacto</div>
<div class="freecontactformmessage">Fields marked with <span class="required_star"> * </span> are mandatory.</div>
</td>
</tr>
<tr>
<td valign="top">
<label for="Full_Name" class="required">Nombre/apellidos<span class="required_star"> * </span></label>
</td>
<td valign="top">
<input type="text" name="Full_Name" id="Full_Name" maxlength="80" style="width:230px">
</td>
</tr>
<tr>
<td valign="top">
<label for="Email_Address" class="required">Email<span class="required_star"> * </span></label>
</td>
<td valign="top">
<input type="text" name="Email_Address" id="Email_Address" maxlength="100" style="width:230px">
</td>
</tr>
<tr>
<td valign="top">
<label for="Telephone_Number" class="not-required">Número de telefono</label>
</td>
<td valign="top">
<input type="text" name="Telephone_Number" id="Telephone_Number" maxlength="100" style="width:230px">
</td>
</tr>
<tr>
<td valign="top">
<label for="Your_Message" class="required">Tu mensaje<span class="required_star"> * </span></label>
</td>
<td valign="top">
<textarea style="width:230px;height:160px" name="Your_Message" id="Your_Message" maxlength="2000"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div class="antispammessage">
To help prevent automated spam, please answer this question
<br><br>
<div class="antispamquestion">
<span class="required_star"> * </span>
Using only numbers, what is 10 plus 15?
<input type="text" name="AntiSpam" id="AntiSpam" maxlength="100" style="width:30px">
</div>
</div>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<br><br>
<input type="submit" value=" Submit Form " style="width:200px;height:40px">
<br><br>
<br><br>
</td>
</tr>
</tbody></table>
</form>
I am new to this. Thanks for the info so far...and I'll keep this updated and let you guys know if I can sort it out on my own.
A:
Change your tag to this
<form name="freecontactform" method="post" action="freecontactformprocess.php" onsubmit="return validate.check(this)" style="margin-bottom: 0;">
Because it is inline CSS this takes over any external stylesheet.
|
[
"stackoverflow",
"0036063751.txt"
] | Q:
Don't know how to build task 'db:seed_fu'
I have just added the seed-fu gem to my app for seeding my test-database:
group :test do
gem 'seed-fu'
end
I made a custom rake task (in /lib/tasks/db.rake) for seeding only my test-database:
namespace :db do
desc "seed_fu only in test-database"
task seed_fu_test: :environment do
Rails.env = 'test'
puts "Seeding will be made in test-base ONLY!"
Rake::Task["db:seed_fu"].execute
end
end
If I do rake -T | grep seed then my new custom-made task is shown amongst other seed-tasks:
rake db:seed # Load the seed data from db/seeds.rb
rake db:seed_fu # Loads seed data for the current environment
rake db:seed_fu_test # seed_fu only in test-database
Now when I do rake db:seed_fu_test I get
rake aborted!
Don't know how to build task 'db:seed_fu'
But when I do
rake db:seed_fu RAILS_ENV='test'
then seed_fu seeds my test-database well.
A:
Figured it out- the problem was in my Gemfile. Because I added the seed-fu gem into test-group then in development-environment, which was my default for running also the rake db:seed_fu_test task, the seed_fu gem was not seen.
Therefore when moving gem 'seed-fu' line into my :development-group in Gemfile, the problem was solved.
|
[
"math.stackexchange",
"0001843263.txt"
] | Q:
Let $R$ be an infinite comutative ring with unity, $M,N$ be $R$-modules, $f:M \to N$ be a surjective module homomorphism; then $|M|=|N ||\ker f|$?
Let $R$ be an infinite commutative ring with unity, $M,N$ be modules over $R$, let $f:M \to N$ be a surjective module homomorphism; then is it true that $|M|=|N || \ker f|$ ($M,N$ are not necessarily finite ) ?
A:
I'm on a cell phone so let the kernel be $A$. Using the axiom of choice, construct a set $N'$ consisting of one element from each coset of $A$. There is an obvious bijection of $N'$ with $N$. Then every element of $M$ can be represented uniquely as the sum of an element of $N'$ and an element of $A$, hence there is a bijection between $N'\times A$ and $M$ defined by $(n,a)\mapsto n+a$. Since $|N'\times A|=|N||A|$, the result follows.
|
[
"stackoverflow",
"0030460055.txt"
] | Q:
array_key_exists not working correctly
Running: PHP 5.6.7 on Windows / Apache
The "array_key_exists" function is not returning the correct result, if the key being searched (needle) is the last element in the array being searched (haystack).
echo phpversion(); echo "<br>";
var_dump($modulepriv_ass); echo "<br>"; var_dump($uploadpriv_ass); echo "<br>";
foreach($modulepriv_ass as $menuid) {
$fileuppriv = 0; echo $menuid ;
if (array_key_exists($menuid, $uploadpriv_ass)){
$fileuppriv = 1; echo " T";
} echo "<br>";
}
And this is the output being produced:
5.6.7
array(10) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" [4]=> string(1) "5" [5]=> string(1) "6" [6]=> string(1) "7" [7]=> string(1) "8" [8]=> string(1) "9" [9]=> string(2) "10" }
array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" [4]=> string(1) "5" }
1 T
2 T
3 T
4 T
5
6
7
8
9
10
Clearly the key "5" should have a "T" next to it. Can anyone help?
A:
No, it shouldn't. array_key_exists checks for the existance of keys, not values. Your $uploadpriv_ass array's last key is 4, and you're passing the value of 5 to array_key_exists. Since $uploadpriv_ass[5] is not set, you're not getting the "T".
|
[
"stackoverflow",
"0037621016.txt"
] | Q:
Wordpress 239 charactors of unexpected output error
I am new to wordpress. Here is a task for me.
I need to active a plugin that is created already.
Now, when I try to active it, it gives me following error.
The plugin generated 239 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
So, first thing I did was google. One of the reasong I found was the white-space left behind code somewhere.
So, I followed it and removed blanks from my code. but did not help me out.
Now, I am putting my code herewith this post. Can anyone please help me out. its going really irritating.
<?php
/*
* Plugin Name: Lucky Draw
* Description: Plugin For Lucky Draw Voucher And Spinning
* Author: Techuz Infoweb Pvt. Ltd
*/
/* Die page if access directly from url */
defined('ABSPATH') or die('No script kiddies please!');
ob_start();
/* Runs when plugin is activated */
register_activation_hook(__FILE__, 'luckydraw_install');
/* = Use Wordpress functions in plugin files
---------------------------------------------------- */
if (file_exists(ABSPATH.'wp-load.php')) {
require_once(ABSPATH.'wp-load.php');
}
/* = Include Wordpress datatable class
---------------------------------------------------- */
if(!class_exists('WP_List_Table')){
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
/* = Setup Tables in database
---------------------------------------------------- */
require_once(plugin_dir_path(__FILE__).'ws_setup.php');
register_activation_hook(__FILE__,'ws_luckydraw_setup_tables');
/* = Include All the plugin pages in ws_register_pages.php file
---------------------------------------------------- */
require_once(plugin_dir_path(__FILE__).'ws_register_pages.php');
/* = Include scripts and styles
---------------------------------------------------- */
add_action('admin_enqueue_scripts','ws_luckydraw_load_scripts');
if(!function_exists('ws_luckydraw_load_scripts')) {
function ws_luckydraw_load_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_media();
wp_enqueue_style('thickbox'); // call to media files in wp
wp_enqueue_script('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_style('jquery-ui-css', plugins_url('lucky-draw/css/jquery-ui.css'));
wp_enqueue_style('style', plugins_url('lucky-draw/css/ld_style.css'));
wp_enqueue_script('jquery-ui-js', plugins_url('lucky-draw/js/jquery-ui.js'));
wp_enqueue_script('jquery-datetimepicker-script', plugins_url('lucky-draw/js/jquery.datetimepicker.js'));
wp_enqueue_script('jquery-validate-js', plugins_url('lucky-draw/js/jquery.validate.js'));
wp_enqueue_script('common-js', plugins_url('lucky-draw/js/common.js'));
}
}
/* = Luckydraw Deactivation
---------------------------------------------------- */
if(!function_exists('ws_luckydraw_deactivate')):
function ws_luckydraw_deactivate() {
flush_rewrite_rules();
}
endif;
register_deactivation_hook(__FILE__, 'ws_luckydraw_deactivate');
?>
Thanks in advance.....
A:
I dont know why? no ones gonna answer here. however I found one, it was silly mistake.
register_activation_hook(FILE, 'luckydraw_install');
was called twice, and above call was of no use for me. So I have removed above call, and error has gone.
|
[
"stackoverflow",
"0038210310.txt"
] | Q:
Serialize an object with HashTable property and store in CouchBase
Our team has chosen Couchbase as the cache for our application. What we store in this cache are objects look like this
public class CatalogEntity
{
public int Id { get; set; }
public string Name { get; set; }
// this property gives us trouble
public Hashtable Attributes { get; set;}
}
In our code, after retrieve an object from the CouchBase cache, I found that properties of primary types(Id and Name) are properly deserialized, but the Attributes of Hashtable type is not deserialized and stay as JSON. For example, if I have something like
var entity = new CatalogEntity();
entity.Attributes["foo"] = new Foo();
The object from cache will have Attributes["foo"] property as JSON representation of the Foo class.
I am wondering how to have the Hashtable type properly serialize/deserialized? Should I serialize the object to binary and instead store binary stream in the CouchBase?
A:
Is there a reason you need to use Hashtable? Can you use, for instance, a Dictionary<string,string> instead?
I think the reason for what you're seeing is Json.NET's best attempt to serialize a hashtable (see also this question on StackOverflow: Serialize hashtable using Json.Net).
|
[
"stackoverflow",
"0049549500.txt"
] | Q:
sagemath: convert R Element to float
How can I extract a numerical part of an R Element?
I'm using the R interface in sagemath. And I would like to get float or int values.
I have an R Element, that is an object of class sage.interfaces.r.RElement, that contains a value that I would like to extract.
For example, given the following element:
x = [1] 6.5
How may I extract the 6.5 value as a float?
float(x)
does not work.
float(str(x).split()[1])
seems excessively crude.
For any interested in generating the example R Element, it my be done in a sagemathcell with the following code:
aList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
fences = r.quantile(aList)
x = fences[[3]]
print (type(x))
print (x)
A:
You can convert x back to a float in Sage with x.sage().
If x is defined as in the question:
sage: s = x.sage()
sage: s
6.5
sage: type(s)
<type 'float'>
|
[
"serverfault",
"0000207741.txt"
] | Q:
How do I deploy two zend frame work based apps in apache2 like the one in tomcat
I have two Zend framework applications called finance and fleet. Both of them have the same .htaccess file as indicated below
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
I have created two virtual hosts called fleet.local and finance.local. This is my fleet.local file:
# APACHE CONFIGURATION FOR THE fleet.local APPLICATION
<VirtualHost *:80>
ServerName fleet.local
DocumentRoot /home/user/fleet/public
SetEnv APPLICATION_ENV dev
<Directory /home/user/fleet/public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
DeflateCompressionLevel 9
And this is my finance.local file:
# APACHE CONFIGURATION FOR THE fincance.local APPLICATION
<VirtualHost *:80>
ServerName fincance.local
DocumentRoot /home/user/fincance/public
SetEnv APPLICATION_ENV dev
<Directory /home/user/fincance/public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
DeflateCompressionLevel 9
When I want to use finance I will say http://finance.local and when I want to use fleet I will say http://fleet.local.
Now what I want to do is have a single virtual host called companyX.local and if I want the finance application, I will just type http://companyX.local/finance and http://companyX.local/fleet for my fleet application. How do I go about doing this?
A:
Got it!!!
<VirtualHost *:80>
ServerName companyX.local
Alias /finance "/home/user/finance/public"
<Directory /home/user/finance/public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Alias /fleet "/home/user/fleet/public"
<Directory /home/user/fleet/public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
and changed the rewrite base for finance like this:
RewriteEngine On
RewriteBase /finance
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
and changed the rewrite base for fleet like this:
RewriteEngine On
RewriteBase /fleet
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
Try this — it doesn't even need RewriteBase and will work root relative or in a subdir.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]
|
[
"stackoverflow",
"0013143576.txt"
] | Q:
Different behavior in C regex VS C++11 regex
I need a code that splits math-notation permutations into its elements, lets suppose this permutation:
The permutation string will be:
"(1,2,5)(3,4)" or "(3,4)(1,2,5)" or "(3,4)(5,1,2)"
The patterns i've tried are this:
([0-9]+[ ]*,[ ]*)*[0-9]+ for each permutation cycle. This would split the "(1,2,5)(3,4)" string in two strings "1,2,5" and "3,4".
([0-9]+) for each element in cycle. This would split each cycle in individual numbers.
When i've tried this patterns in this page they work well. And also, i've used them with the C++11 regex library with good results:
#include <iostream>
#include <string>
#include <regex>
void elements(const std::string &input)
{
const std::regex ElementRegEx("[0-9]+");
for (std::sregex_iterator Element(input.begin(), input.end(), ElementRegEx); Element != std::sregex_iterator(); ++Element)
{
const std::string CurrentElement(*Element->begin());
std::cout << '\t' << CurrentElement << '\n';
}
}
void cycles(const std::string &input)
{
const std::regex CycleRegEx("([0-9]+[ ]*,[ ]*)*[0-9]+");
for (std::sregex_iterator Cycle(input.begin(), input.end(), CycleRegEx); Cycle != std::sregex_iterator(); ++Cycle)
{
const std::string CurrentCycle(*Cycle->begin());
std::cout << CurrentCycle << '\n';
elements(CurrentCycle);
}
}
int main(int argc, char **argv)
{
std::string input("(1,2,5)(3,4)");
std::cout << "input: " << input << "\n\n";
cycles(input);
return 0;
}
The Output compiling with Visual Studio 2010 (10.0):
input: (1,2,5)(3,4)
1,2,5
1
2
5
3,4
3
4
But unfortunately, i cannot use the C++11 tools on my project, the project will run under a Linux plataform and it must be compiled with gcc 4.2.3; so i'm forced to use the C regex library in the regex.h header. So, using the same patterns but with different library i'm getting different results:
Here is the test code:
void elements(const std::string &input)
{
regex_t ElementRegEx;
regcomp(&ElementRegEx, "([0-9]+)", REG_EXTENDED);
regmatch_t ElementMatches[MAX_MATCHES];
if (!regexec(&ElementRegEx, input.c_str(), MAX_MATCHES, ElementMatches, 0))
{
int Element = 0;
while ((ElementMatches[Element].rm_so != -1) && (ElementMatches[Element].rm_eo != -1))
{
regmatch_t &ElementMatch = ElementMatches[Element];
std::stringstream CurrentElement(input.substr(ElementMatch.rm_so, ElementMatch.rm_eo - ElementMatch.rm_so));
std::cout << '\t' << CurrentElement << '\n';
++Element;
}
}
regfree(&ElementRegEx);
}
void cycles(const std::string &input)
{
regex_t CycleRegEx;
regcomp(&CycleRegEx, "([0-9]+[ ]*,[ ]*)*[0-9]+", REG_EXTENDED);
regmatch_t CycleMatches[MAX_MATCHES];
if (!regexec(&CycleRegEx, input.c_str(), MAX_MATCHES, CycleMatches, 0))
{
int Cycle = 0;
while ((CycleMatches[Cycle].rm_so != -1) && (CycleMatches[Cycle].rm_eo != -1))
{
regmatch_t &CycleMatch = CycleMatches[Cycle];
const std::string CurrentCycle(input.substr(CycleMatch.rm_so, CycleMatch.rm_eo - CycleMatch.rm_so));
std::cout << CurrentCycle << '\n';
elements(CurrentCycle);
++Cycle;
}
}
regfree(&CycleRegEx);
}
int main(int argc, char **argv)
{
cycles("(1,2,5)(3,4)")
return 0;
}
The expected output is the same as using C++11 regex, but the real ouput was:
input: (1,2,5)(3,4)
1,2,5
1
1
2,
2
2
Finally, the questions are:
Could someone give me a hint about where i'm misunderstanding the C regex engine?
Why the behavior is different in the C regex vs the C++ regex?
A:
You're misunderstanding the output of regexec. The pmatch buffer (after pmatch[0]) is filled with sub-matches of the regex, not with consecutive matches in the string.
For example, if your regex is [a-z]([+ ])([0-9]) matched against x+5, then pmatch[0] will reference x+5 (the whole match), and pmatch[1] and pmatch[2] will reference + and 5 respectively.
You need to repeat the regexec in a loop, starting from the end of the previous match:
int start = 0;
while (!regexec(&ElementRegEx, input.c_str() + start, MAX_MATCHES, ElementMatches, 0))
{
regmatch_t &ElementMatch = ElementMatches[0];
std::string CurrentElement(input.substr(start + ElementMatch.rm_so, ElementMatch.rm_eo - ElementMatch.rm_so));
std::cout << '\t' << CurrentElement << '\n';
start += ElementMatch.rm_eo;
}
|
[
"stackoverflow",
"0035331009.txt"
] | Q:
How to strip slashes from search query
I added the following code to the theme's index.php file on one of my WordPress sites, so that a heading would appear on the search results page that includes the actual search term. In other words, if I search for the word blue, this heading would then read, Search results for: blue.
<?php
if ( is_search() ); ?>
<h3>Search results for: <?php print_r($_GET['s']); ?></h3>
The output isn't great however when a phase in quotes get placed into the search bar. In other words, if I search for the phrase "blue is a color", this heading then reads: Search resulst for: \"blue is a color\"
I'd like to know how to stop those backslashes from appearing. I've done some research but nothing I've found has worked. I'm a php beginner at most.
A:
just use echo:
<?php
if ( is_search() ); ?>
<h3>Search results for: <?php echo $_GET['s']; ?></h3>
you must "escape" this variable before you print it though! Imagine if someone wrote a <script> in the search bar that manpulated your site when it was printed. Read on here: Escaping variables. One example would be like this:
echo htmlspecialchars($_GET['s']);
This removes characters like < and > so nobody can print scripts or html into your site
|
[
"stackoverflow",
"0058647028.txt"
] | Q:
Xcode Error - Profile doesn't include the com.apple.developer.icloud-container-environment entitlement
We have enabled iCloud capability in our application and enabled below services,
Key-value storage
iCloud Documents
But while trying to export the build through the archive, it's throwing me the below error,
Profile doesn't include the com.apple.developer.icloud-container-environment entitlement.
I have tried to set the com.apple.developer.icloud-container-environment entitlement in Entitlements file also as Production or Development but it did not help me either.
Any clue how to resolve this error?
A:
Here's how I fixed it:
I created an iCloud container on the CloudKit dashboard (in the iCloud section of the Signing & Capabilities in Xcode).
I assigned the newly created container to my app (Developer Website > Certificates, Identifiers & Profiles > Identifiers > my app ID > Capabilities > iCloud > Edit button) and saved the app ID configuration.
Then I created a new App Store provisioning profile for this app ID and used it to manually sign the app when I uploaded it in Xcode.
|
[
"stackoverflow",
"0043725305.txt"
] | Q:
Separating grid view events and html to reduce reptition
I'm fairly new to ASP.NET and programming in general, and one of the problems I'm currently struggling to grasp is reducing repetitive code.
My goal is to have a master page that contains a grid view, then numerous pages can contain the grid. However, I want to be able to share code between my grids but at the same time be able to adapt unique code to each and everyone of them as some will have different attributes and data.
I've looked into separation of concerns, and other various posts/blogs but haven't found a definitive answer to how I can actually achieve what I want.
I've already tried using master pages and it worked quite well until my application continued to expand, plus I'd prefer to only use my master pages for presentation.
Could anyone provide a simple example of how I can achieve this?
Happy to provide additional information!
A:
After spending the day doing research and testing numerous possibilities I've pretty much answered my own question.
I've setup a master page that contains the grid, the content page then retrieves the grid using accessors. This grid is then set to a property in the base class which makes it accessible where I need it to be.
edit
Event handlers were created to handle the grid events in the content pages, then those methods were overridden to allow the calls to bubble up to the base class thus allowing me to assign unique, page specific and common code where I needed it to be.
|
[
"stackoverflow",
"0035719758.txt"
] | Q:
MQ AtoB and AtoC communication using a single queue?
I have just started work on a software which uses IBM MQ for some communication.
As I understand that MQ can be used for many to one communication and one to many communication.
Lets say there are 3 Business applications A, B and C. A wants to send a message using MQ to B and another message to C but A is only using one queue Queue1.
Now my question is if we can define (in MQMD or otherwise) that a certain message is only for B NOT for C, hence only B can retrieve it from Queue1 whenever B is available. If not how can we do this if it is at all possible?
One other thing is can we make a separate queue Queue2 only for A-B communication?
A:
It is better to use separate queues. For example use queue QA2B for application A to send messages to application B and QA2C for application A to send messages to application C. This way traffic is separated out and you can administratively restrict application B from receiving message meant for C and vice-versa.
It is possible to use just one queue wherein application A while sending messages sets a message property that says something like "Message is for B" or "Message is for C". Application B uses a selector to match the property value "Message for B" while receiving messages. Similarly application C also uses selector "Message for C" and receives messages. But note if either B or C receives messages without any selector, then messages can go to wrong hands.
|
[
"stackoverflow",
"0025834834.txt"
] | Q:
How can I find my controls on the form in Visual Studio (C#)
I have a form which I have created in Visual Studio and there are some controls on there with strange names which have events associated with them. I think the controls have been added in error. They are labels. I can't see them on the form, they must have no text or be behind something. How can I find them?
A:
Use the View + (Other Windows) + Document Outline menu command. You'll get a tool window that displays all the children of the form. You can drag+drop a control up to its container to put it on top of the Z-order, in case such a label is covered by another control. Or right-click a rogue one and select Delete. Edit + Undo if you made a mistake.
|
[
"stackoverflow",
"0044436504.txt"
] | Q:
Subtracting of a SUM?
I was wondering if I could perform this algebraic use, Here is the ones I am trying to perform with.
JCCM.BilledAmt + JCCM.udGEACrev As REVENUE_2,
(JCCM.udGEACrev + JCCM.BilledAmt) - JCCP.ActualCost As BilledCostDifference,
I tried adding REVENUE_2 between the brackets but the Report Builder does not take it as a column
A:
Yes.
Add a calculated field to your dataset:
-Right click dataset -> Add Calculated Field
Enter the following values in the dialog that pops up:
-Field name: REVENUE_2
-Field source: Fields!JCCM.BilledAmt.Value + Fields!JCCM.udGEACrev.Value
Add another calculated field with the following values:
-Field name: BilledCostDifference
-Field source: Fields!REVENUE_2.Value - Fields!JCCP.ActualCost.Value
Drag the second calculated field to your report.
NOTE:
SSRS will not recognize the first calculated field you added unless you hit OK. So add the first calculated field, hit OK, add the second calculated field.
|
[
"stackoverflow",
"0050732082.txt"
] | Q:
Date input in codeigniter (d-m-Y)
I'm stuck to input date to database.
I've already created helper with format day month Year, and it's work.
But I don't know how to use it to create date in database.
Give me an example of view and controller.
Thanks!
helper tanggal_helper.php
if (!function_exists('bulan')) {
function bulan(){
$bulan = Date('m');
switch ($bulan) {
case 1:
$bulan = "Januari";
break;
case 2,3,4,5,6,....12
}
return $bulan;
}
}
if (!function_exists('tanggal')) {
function tanggal() {
$tanggal = Date('d') . " " .bulan(). " ".Date('Y');
return $tanggal;
}
}
A:
One solution is to change your column data type to varchar and then use date() and strtotime() to insert date with your desired format
$date = date('d-m-Y', strtotime('now')); // Current date
OUTPUT
07-06-2018
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.