id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23536000
|
All the questions I see use express, I do not want to use express..
Client side:
<script src="https://cdn.socket.io/socket.io-1.4.7.js"></script>
<script>
var socket = new io.connect('http://127.0.0.1:1904');
socket.on('connect', function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message', function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect', function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
Server side:
var http = require('http');
var server = http.createServer();
server.listen(1904);
console.log('Server started.');
var io = require('socket.io')(server, {});
io.sockets.on('connecton', function(socket) {
console.log('A new player connected.');
socket.on('happy', function(data) {
console.log('happy because: ' + data.reason);
})
});
A: Here's the routine I use for all my socket-based node projects, Hope this helps you out. Let me know if you have any other questions I can help with.
file named server.js:
var http = require('http').Server();
var io = require('socket.io')(http);
http.listen(3001, function(){
console.log('listening on *:3001');
});
//for testing, we're just going to send data to the client every second
setInterval( function() {
var msg = Math.random();
io.emit('message', msg);
console.log (msg);
}, 1000);
file named index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<!-- UPDATE THE FOLLOWING TO THE PATH TO YOUR SOCKET.IO.JS FILE OR USE CDN -->
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
$('body').css('width', '100%');
$('div').css('text-align', 'center').css('width', '100%')
$('#message').css('font-size', '2em');
// DEFINE OUR SOCKET...
var socket = io();
// EVERY TIME THE NODE.JS SERVER SENDS US 'MESSAGE' WE'LL DISPLAY THAT UPDATED NUMBER IN A DIV
socket.on('message', function(msg){
document.getElementById("message").innerHTML = msg;
});
</script>
</head>
<body>
<div id="message"></div>
</body>
</html>
| |
doc_23536001
|
*
*https://css-tricks.com/full-jquery-animations/
*jQuery animation without queuing
*http://www.2meter3.de/code/hoverFlow/
The problem in my project is when you click the #new-quote button multiple times quickly, the animation starts doing crazy things.
var getNewQuote = function() {
var quote = {};
$.ajax({
url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&post",
success: function(d) {
quote.text = $(d[0].content).text().trim();
quote.author = d[0].title;
},
datatype: "json",
async: false,
cache: false
});
return quote;
};
var getRandomColor = function() {
var colors = [
"#ff9966",
"#7f00ff",
"#396afc",
"#0cebeb",
"#06beb6",
"#642b73",
"#36d1dc",
"#cb356b",
"#3a1c71",
"#ef3b36",
"#159957",
"#000046",
"#007991",
"#56ccf2",
"#f2994a",
"#e44d26",
"#4ac29a",
"#f7971e",
"#34e89e",
"#6190e8",
"#3494e6",
"#ee0979"
],
randomNumber = Math.floor(Math.random() * colors.length);
return colors[randomNumber];
};
var updateText = function($t, qt) {
var twitter = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
twitter += '"' + qt.text + '" ';
twitter += qt.author;
var tumblr = "https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=";
tumblr += qt.author;
tumblr += "&content=";
tumblr += qt.text;
tumblr += "&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button";
var $icon = $("<i class='fa fa-quote-left'>")
.prop("aria-hidden", true);
$t.find(".quote-text").html("").append($icon, qt.text);
$t.find(".quote-author").html("- " + qt.author);
$("#tweet-quote").attr("href", twitter);
$("#tumblr-quote").attr("href", tumblr);
};
var calcNewHeight = function(q) {
var $temp = $("<div>", {
class: "quote-container temp",
}).appendTo($("body"));
$temp.append($("<div>", {
class: "quote-text"
}), $("<div>", {
class: "quote-author"
}));
updateText($temp, q);
var h = $temp.height() + 40;
$temp.remove();
return h;
};
var changeColor = function(newColor) {
$("body, .button:not(#new-quote)").animate({
backgroundColor: newColor
});
$("#new-quote").animate({
color: newColor
});
$(".quote-text, .quote-author").css("color", newColor);
if ($("#modStyle").length === 0) {
$("head").append(
"<style id='modStyle'>#new-quote:before {background:" + newColor + ";}</style>"
);
} else {
$("head style#modStyle").html("#new-quote:before {background:" + newColor + ";}");
}
};
var getQuote = function(e) {
var nq, nc, nh = 0;
$(".quote-container").queue(function() {
nq = getNewQuote();
nc = getRandomColor();
$(".quote-container").children().css("opacity", 0);
changeColor(nc);
$(this).dequeue();
})
.queue(function() {
nh = calcNewHeight(nq);
$(".quote-container, #new-quote").animate({
height: nh / 16 + "rem",
}, {
duration: 1000,
queue: false
});
$(".quote-container").animate({
padding: "2.5rem"
}, {
duration: 1000,
queue: false
});
$("#new-quote").animate({
padding: "2.5rem .75rem"
}, {
duration: 1000,
queue: false
});
$(this).dequeue();
})
.queue(function() {
updateText($(".quote-container"), nq);
$(".quote-container").children().fadeTo(750, 1);
$(this).dequeue();
})
};
$(function() {
$("#new-quote").on("click", getQuote);
$(".quote-container, #new-quote").css({
visibility: "visible",
height: 0
});
$("#new-quote").css("padding", "0 .75rem");
getQuote();
});
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
padding: 0;
background: #333;
color: #333;
font-family: sans-serif;
}
.v-wrap {
height: 100%;
text-align: center;
}
.v-wrap:before {
content: "";
display: inline-block;
vertical-align: middle;
width: 0;
height: 100%;
}
.quote-container {
width: 31.25rem;
background: #fff;
margin: 0;
display: inline-block;
vertical-align: middle;
border-radius: 0.1875rem;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
visibility: hidden;
padding: 0 2.5rem;
}
.quote-text {
font-size: 1.625rem;
}
.quote-text i {
margin-right: 0.6rem;
}
.quote-text p {
display: inline;
}
.quote-author {
font-size: 1rem;
margin: 0 0.4rem 2rem 0;
text-align: right;
}
.button {
padding: 0.75rem;
text-align: center;
font-size: 1rem;
color: #fff;
border-radius: .1875rem;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.button:not(#new-quote):hover {
opacity: .8 !important;
}
.button:not(#new-quote) {
min-width: 1rem;
min-height: 1rem;
}
.button i {
vertical-align: middle;
}
#new-quote {
white-space: nowrap;
writing-mode: vertical-lr;
height: 50%;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
vertical-align: middle;
background: #fff !important;
margin: 0;
position: relative;
right: 0.25625rem;
color: #333;
visibility: hidden;
}
#new-quote:before {
content: "";
position: absolute;
height: 100%;
width: 0.0625rem;
bottom: 0;
left: 0;
visibility: hidden;
-webkit-transform: scaleY(0);
transform: scaleY(0);
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
#new-quote:hover:before {
visibility: visible;
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
footer {
font-size: 0.85rem;
margin: 1rem 0;
}
footer a {
text-decoration: none;
color: #fff;
position: relative;
}
footer a:before {
content: "";
position: absolute;
width: 100%;
height: .0625rem;
bottom: 0;
left: 0;
background: #fff;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all .3s ease-in-out 0s;
transition: all .3s ease-in-out 0s;
}
footer a:hover:before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<script src="https://use.fontawesome.com/911574fea4.js"></script>
<div class="v-wrap">
<div class="quote-container" style="">
<div class="quote-text">
</div>
<div class="quote-author"></div>
<a id="tweet-quote" class="button"><i class="fa fa-twitter"></i></a>
<a id="tumblr-quote" class="button"><i class="fa fa-tumblr"></i></a>
</div>
<div id="new-quote" class="button">New quote</div>
<footer>
<a href="https://codepen.io/Kestis500">Created by LukasLSC</a>
</footer>
</div>
Link to the codepen project: https://codepen.io/Kestis500/pen/opWGNY?editors=0010
Link to the jsfiddle project: https://jsfiddle.net/z5hds4Lp/2/
Note:
I can't explain why AJAX doesn't work here, using codepen or jsfiddle everything with AJAX is ok.
A: I did not encounter any particularly "crazy things" by rapidly clicking the Get Quote button. But here is one option for exercising more control over the animation by introducing an animation state.
Add a boolean variable
var animating = false;
Toggle the true/false value during animation. If it is already animating, don't let another animation get called.
var getQuote = function(e) {
if (animating) return; // If already animating, don't let it call again
animating = true; // Tell the state that it is animating
var nq, nc, nh = 0;
$(".quote-container").queue(function() {
nq = getNewQuote();
nc = getRandomColor();
$(".quote-container").children().css("opacity", 0);
changeColor(nc);
$(this).dequeue();
})
.queue(function() {
nh = calcNewHeight(nq);
$(".quote-container, #new-quote").animate({
height: nh / 16 + "rem",
}, {
duration: 1000,
queue: false
});
$(".quote-container").animate({
padding: "2.5rem"
}, {
duration: 1000,
queue: false
});
$("#new-quote").animate({
padding: "2.5rem .75rem"
}, {
duration: 1000,
queue: false
});
$(this).dequeue();
})
.queue(function() {
updateText($(".quote-container"), nq);
$(".quote-container").children().fadeTo(750, 1);
$(this).dequeue();
animating = false; // When the animation is done, set animating back to false.
})
};
| |
doc_23536002
|
Using XQuery:
List the id, name, publisher and platforms for each game that is supported by more than one
platform. Platforms should be enclosed in one XML tag delimited by a comma.
I am getting problem in thinking that how do i count the patforms. The platforms that I need to count is given like in the above figure. Playstation3,XBox are the patlforms for one game. Outside the box, under it, that format of data is given.Please help me in it.
A: If your XQuery engine supports XPath 2.0 you can use the tokenize function to count items of a comma separated list:
count(tokenize("Playstation3,XBox",","))
Does that help? If not could you please provide a complete example with XML input and expected result. Thank you.
A: This XQuery:
element result {
for $game in /games/game[tokenize(Platform,',')[2]]
return element game {
$game/(ID|Name|Publisher|Platform)
}
}
With this input:
<games>
<game>
<ID>B003JVKHEQ</ID>
<Name>Duty</Name>
<Publisher>AC</Publisher>
<ESRB>M</ESRB>
<Motion>False</Motion>
<Platform>Playstation3,XBox</Platform>
</game>
</games>
Output:
<result>
<game>
<ID>B003JVKHEQ</ID>
<Name>Duty</Name>
<Publisher>AC</Publisher>
<Platform>Playstation3,XBox</Platform>
</game>
</result>
Edit: With literal result elements
<result>{
for $game in /games/game[tokenize(Platform,',')[2]]
return <game>{
$game/(ID|Name|Publisher|Platform)
}</game>
}</result>
| |
doc_23536003
|
A: Yes.
Applications inside of Facebook can be rendered in two ways. FBML or inside of an iFrame. In the case of FBML you can embed FLV, SWF, and silverlight files. In the case of an iFrame you can render anything you want. You can choose the type of application canvas on the developer settings for the application.
Each of the options has certain benefits and limitations, but if you're only concerned with embedding a shockwave game then this shouldn't matter.
A: Well, I think that technically you can create your facebook app in whatever language you like. The apps aren't hosted on Facebook, they're just accessed through facebook.
| |
doc_23536004
|
if #available(OSX 10.10, *) {
if let b = statusItem.button {
popover.showRelativeToRect(b.bounds, ofView: b, preferredEdge: .MinY)
}
} else {
}
The else block is for OS X Mavericks because NSStatusItem.button is not available. Is there a simple way of showing the popover relative to the status item? If not, is it possible to show the popover in the center of the screen instead without the arrow?
A: before you had access to the statusitem button you had to provide your own view. Then all works the same
to retain the original behaviour, draw a custom view that looks like a status item ;)
e.g.
@interface DDQuickMenuStatusItemView : NSView
@property(weak) NSStatusItem *item;
//...
@end
@implementation DDQuickMenuStatusItemView
//...
- (void)drawRect:(NSRect)dirtyRect {
NSImage *image = nil;
if(self.item) {
[self.item drawStatusBarBackgroundInRect:self.bounds withHighlight:NO];
image = self.item.image;
}
if(image) {
NSRect r = self.bounds;
r.size = [image size];
r = [self.class centerRect:r inRect:self.bounds];
r = [self centerScanRect:r];
[image drawInRect:r fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
}
}
#pragma mark -
+ (CGRect)centerRect:(CGRect)rect inRect:(CGRect)inRect
{
CGRect result = rect;
result.origin.x = inRect.origin.x + (inRect.size.width - result.size.width)*0.5f;
result.origin.y = inRect.origin.y + (inRect.size.height - result.size.height)*0.5f;
return result;
}
@end
Note that the view is a sample and not production ready ;)
| |
doc_23536005
|
String str;
int k;
int n =1000;
String min="";
String max="";
Scanner key = new Scanner(System.in);
str = key.next();
k = key.nextInt();
max = str.substring(0,k);
min = str.substring(0,k);
for (int i=0; i<str.length()-k+1; i++){
if (str.substring(i, i+k).compareTo(max)>0){
max = str.substring(i, i+k);
}
else if (str.substring(i, i+k).compareTo(min)<0){
min = str.substring(i, i+k);
}
}
System.out.println(min + "\n" + max);
A: Do not pass System.in directly, but pass a wrapper to System.in implementing InputStream. In this wrapper, you can easily limit the number of characters you return.
A: A simple fix for you is to get a substring of the returned input string that is at most n characters long:
if (str.length() > n) {
str.substring(0, n+1);
}
Where n is the max length you want str to be. This code snippet would go after str = key.next();
Note that String.substring is inclusive for the beginning index but exclusive for the ending index.
I hope this helps.
A: You can pass a regular expression to the method next(String pattern) (or perhaps findInLine(String)). For example:
str = key.next(".{10}");
will put the next 10 characters into str.
| |
doc_23536006
|
With Javascript I can get a SVG path element using:
var path = document.getElementById("path3388");
I can get the path segments using:
var pathSegments = path.pathSegList
However these path segments are relative to whatever parent SVG element is defined. Transforms are not included in the path segment list.
Is there a way to get the absolute coordinates of this path as they are ultimately used when drawn on the screen?
Example: say I got the following SVG snippet:
<g transform="translate(100, 100)">
<g transform="translate(50, 50)">
<path d="M 0,0 10,0 10,10"></path>
</g>
</g>
What I want is to retrieve is the coordinates of the path with the transforms of the two g elements applied. In this case the coordinates of the path should be:
[150,150], [160, 150], [160, 160]
A: You want is to do something like this to each path segment coordinate...
var root = document.getElementById("root");
var path = document.getElementById("path");
var point = root.createSVGPoint();
point.x = 0; // replace this with the x co-ordinate of the path segment
point.y = 0; // replace this with the y co-ordinate of the path segment
var matrix = path.getTransformToElement(root);
var position = point.matrixTransform(matrix);
alert(position.x + ", " + position.y);
<svg id="root">
<g transform="translate(100, 100)">
<g transform="translate(50, 50)">
<path id="path" d="M 0,0 10,0 10,10"></path>
</g>
</g>
</svg>
If you find that there's no getTransformToElement function any more since it's been removed in SVG 2 then this polyfill will restore that missing method.
A: path.getTransformToElement() is no longer supported in Chrome as of v48.
A slightly simpler method might entail...
const path = document.getElementById("path");
const pathBBox = path.getBBox();
console.log(pathBBox.x, pathBBox.y);
| |
doc_23536007
|
"results": [
{
"Cat1": [
{
"job": String,
"position": Integer
}
]
},
{
"Cat1": [
{
"job": String,
"position": Integer
}
]
},
{
"Cat2": [
{
"job": String,
"position": Integer
}
]
}
]
But I want something like that:
"results": [
{
"Cat1": [
{
"job": String,
"position": Integer
},
{
"job": String,
"position": Integer
}
]
},
{
"Cat2": [
{
"job": String,
"position": Integer
}
]
}
]
I use a serializer like this:
class CustomSerializer(serializers.ModelSerializer):
category = CatSerializer()
job = JobSerializer()
class Meta:
model = MyModel
fields = '__all__'
def to_representation(self, value):
return {
value.category.name: [{"job": value.job.name,
"position": value.position, }]
cat1 and cat2 are dynamics, they are from another table. I don't understand how to create my arrays properly using those serializers. The category is a @Property field in my model who's a foreign key of job.
My models:
class MyModel(models.Model):
CHOICES = [(i, i) for i in range(4)]
partner = models.ForeignKey(Partner, on_delete=models.CASCADE)
job = models.ForeignKey(
Job, on_delete=models.CASCADE)
position = models.IntegerField(choices=CHOICES)
@property
def category(self):
return self.job.category.domain
def __str__(self):
return '%s | %s | %s | position: %s' % (self.partner.name, self.domain.name, self.job.name, self.position)
class Job(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
code = models.CharField(
max_length=255, unique=True)
name = models.CharField(
max_length=255)
class Category(models.Model):
domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
code = models.CharField(
max_length=5)
name = models.CharField(max_length=255)
hourly_rate = models.FloatField(
null=True, blank=True)
How should I deal with serializers to format my data properly ?
EDIT:
I ended with something like that, except for the ListSerializer.
I used 2 ModelSerilizers
class MyModelCustomSerializer(serializers.ModelSerializer):
position = serializers.IntegerField(read_only=True)
job = serializers.CharField(source='job.name', read_only=True)
class Meta:
model = MyModel
fields = ['job', 'position']
def to_representation(self, value):
return {"position": value.position,
"job": {"name": value.job.name, "slug": value.job.slug,
"title": value.job.seo_title}
}
And
class CategoryCustomSerializer(serializers.ModelSerializer):
models = MyModelustomerSerializer(many=True)
class Meta:
model = Category
fields = ['category', 'MyModel']
def to_representation(self, value):
filters = {'job__category__domain__name': value.name}
myModels = MyModel.objects.filter(**filters)
serializer = MyModelCustomSerializer(instance=myModels, many=True,)
return {value.name: serializer.data}
But if I try to use a jobSerializer who already exist instead of
"job": {"name": value.job.name, "slug": value.job.slug,
"title": value.job.seo_title}
},
I got this error: Object of type 'Job' is not JSON serializable, but it's working anyway because i don't need all fields
A: I would go the direction of implementing a custom ListSerializer for the ModelSerializer and overriding its to_representation method.
from rest_framework import serializers
from collections import OrderedDict
class CustomListSerializer(serializers.ListSerializer):
def to_representation(self, data):
iterable = data.all() if isinstance(data, models.Manager) else data
list_rep = OrderedDict()
for item in iterable:
child_rep = self.child.to_representation(item)
k, v = list(child_rep.items()).pop()
list_rep.setdefault(k, []).append(v)
return [
{k: v}
for k, v in list_rep.items()
]
Then set the model Meta to use it
class CustomSerializer(serializers.ModelSerializer):
category = CatSerializer()
job = JobSerializer()
class Meta:
model = MyModel
fields = '__all__'
list_serializer_class = CustomListSerializer
def to_representation(self, value):
return {
value.category.name: [{"job": value.job.name,
"position": value.position, }]
| |
doc_23536008
|
public class StaticVariableTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
AC AC = new AC();
AC.b = 25;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(AC);
oos.flush();
oos.close();
bos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
AC na = (AC) ois.readObject();
System.out.println(na.b);
}
}
class AC implements Externalizable {
private static final long serialVersionUID = 1L;
int b = 20;
@Override
public void writeExternal(ObjectOutput objectOutput) throws IOException {
}
@Override
public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException {
}
}
Why in the above program I am getting InvalidClassException?
Exception in thread "main" java.io.InvalidClassException:
serializationExamples.AC; no valid constructor at
java.base/java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:159)
at
java.base/java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:864)
at
java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2061)
at
java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1594)
at
java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
at
serializationExamples.StaticVariableTest.main(StaticVariableTest.java:18)
It says no valid constructor but a default no-arg constructor should have been provided by java for class A.
A: From the Javadoc:
When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor
You don't have a public no-arg constructor, because the class isn't public.
From JLS 8.8.9 Default Constructor:
The default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access (§6.6).
| |
doc_23536009
|
the following CaddyFile works fine:
www.mydomain.com:443 {
root * /var/www
file_server
log {
output file /var/log/caddy/access.log {
roll_size 1mb
roll_keep 4
roll_keep_for 24h
}
}
}
But the following doesn't, and i dont know what is wrong here.
www.mydomain.com:443 {
root /web/* /var/www
file_server
log {
output file /var/log/caddy/access.log {
roll_size 1mb
roll_keep 4
roll_keep_for 24h
}
}
}
please any help would be appreciated
| |
doc_23536010
|
`%+%` <- function(x, y) paste0(x, y)
"a" %+% "b" # returns "ab"
However, I'm wondering if it is possible to do the same with an S3 method. You could do it by creating a new class, let's say char, and do something like:
# Create a function to coerce to class 'char'
as.char <- function(x, ...) structure(as.character(x, ...), class = "char")
# S3 method to paste 'char' objects
"+.char" <- function(x, y) paste0(x, y)
a <- as.char("a")
b <- as.char("b")
c(class(a), class(b)) # [1] "char" "char"
a + b # returns "ab"
But, if you try to create a +.character method, it does not work:
"+.character" <- function(x, y) paste0(x, y)
a <- "a"
b <- "b"
c(class(a), class(b)) # [1] "character" "character"
a + b # Error in a + b : non-numeric argument to binary operator
However, if you assign the class character manually it does work:
as.character_ <- function(x, ...) structure(as.character(x, ...), class = "character")
a <- as.character_("a")
b <- as.character_("b")
c(class(a), class(b)) # [1] "character" "character"
a + b # returns "ab"
So I'm just wondering what I'm missing here, and if it is possible to actually define an S3 method for a generic class.
Edit: Based on @Csd answer, it is not clear that this is due to the attributes, because if you define your own function, e.g.:
concat <- function(e1, e2) UseMethod("concat")
concat.character <- function(e1, e2) paste0(e1, e2)
concat("a", "b") # returns "ab"
Then it does work.
A: It seems that you need to define the class of the variable to be "character". That's exactly what you do! except one thing... which I didn't know either...
Here is an example:
a <- "a"
class(a) # "character"
attributes(a) # NULL!!!
while using you function:
a <- as.character_("a")
class(a) # "character"
attributes(a) # "class" is "character"
So it seems that it has to be defined the attribute class of the variable.
| |
doc_23536011
|
client = Savon::Client.new do
wsdl.document = "http://services.carsolize.com/BookingServices/dynamicdataservice.svc?wsdl"
end
response = client.request "ServiceRequest", "xmlns" => "http://tempuri.org/" do |soap, wsdl|
client.http.headers["SOAPAction"] = '"http://tempuri.org/IDynamicDataService/ServiceRequest"'
soap.body = {
"rqst" => {
"Credentials" => {
"UserName" => 'user',
"Password" => 'pass'
},
"RequestType" => "Login",
"TypeOfService" => "Unknown",
},
}
end
But all I get is a Savon::HTTP::Error in HomeController#index (and no more info) for the line starting with response.
A: I was facing the same error although it's not timely answer BUT posting it may in future this could be helpful for someone.
Implement OAuth2.0 with Savon
we need to put content type in request headers "Content-Type" => "text/xml"
along with Bearer token
client = Savon.client(
wsdl: [URL],
logger: Rails.logger,
log_level: :debug,
log: true,
ssl_ca_cert_file: file_path,
ssl_verify_mode: :none,
headers: { "Authorization" => "Bearer #{auth_token}", "Content-Type" => "text/xml" },
follow_redirects: true
)
A: I've tried to do it this way
client = Savon.client 'http://services.carsolize.com/BookingServices/dynamicdataservice.svc?wsdl'
username = '*********'
password = '*********'
response = client.request :wsdl, :login do
http.headers["SOAPAction"] = '"http://tempuri.org/IDynamicDataService/ServiceRequest"'
soap.xml = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><ServiceRequest xmlns='http://tempuri.org/'><rqst xmlns:i='http://www.w3.org/2001/XMLSchema-instance'><Credentials xmlns=''>
<Password>#{password}</Password><UserName>#{username}</UserName></Credentials><RequestType xmlns=''>Login</RequestType><TypeOfService xmlns=''>Unknown</TypeOfService></rqst></ServiceRequest></s:Body></s:Envelope>"
end
And it works fine
| |
doc_23536012
|
Tkinter event bindings have two problems:
*
*First, when I use an event binding for <Key> and then, in the
function, use evt.keysym, I can see that the program can't register
both at the same time. I could use a timer and then see if it works,
but I would prefer one line that fixes it all.
*Second, I find that tkinter event bindings only work when the binded widget's window (or window itself) is FOCUSED. I will hide my root and TopLevel at all times, and so is not focused.
I would appreciate any help on this. If your suggestion uses another module, I don't really care, as long as it works on Windows 10 (not Mac OS X, not Linux, but Windows). I'm also using Python 3, but any version (aka 2) would also be okay, as I could either try to port YOUR suggestion to Py3, or port MY code to Py2. Thanks!
A: I figured it out with Furas's help - with Pyhook I can wait for events globally, and then tie in the event with tkinter events.
| |
doc_23536013
|
I have used the following code to load the file.
pd.read_csv(collating_data, sep="\t", header=0)
The affected column looks like this
item_id
0 DB009600110C25
1 6.0642E+12
2 1.10517E+12
3 1.10517E+12
4 2.2007E+12
I would appreciate your feedback. Thanks
| |
doc_23536014
|
string someString = "hello world";
string_view strView( someString );
// QStringView(const Char (&)[N] string = N) or
// QStringView(const Char *str, qsizetype len)
QStringView qStrView1(strView.data(), strView.size());
// QStringView(const Char *first, const Char *last)
QStringView qStrView2(strView.data(), strView.data() + strView.size());
// QStringView(const Char *first, const Char *last)
QStringView qStrView3(strView.begin(), strView.end());
QStringView qStrView3a(strView.cbegin(), strView.cend());
// QStringView(const Char *str)
QStringView qStrView4(strView.data());
(I thought the 1st or 2nd conversion might work, and tried the 3rd and 4th just out of disappointment.)
*
*Can someone please point me to the right conversion? Do I miss something?
*Or do I need to dublicate all std::strings as QStrings and create QStringViews from these, by reusing the begin/end positions?
*( Besides that, I did not now figure out, how to insert a QStringView into a QTableWidgetItem. I would appreciate any help on this problem as well. )
Context
I read out file content as std::string and split it into lines of fields based on separators. In order to do this efficiently, I generated a std::vector of std::string_view to store the fields. Now I want to visualize the strings in a Qt GUI (actually aiming at QTableWidgetItems) and thought QStringView might serve me well for the GUI part. I want to keep BusinessLogic independent of the GUI an therefore avoided any includes of Qt libraries there.
Setting
*
*Qt 5.15.0
CONFIG += c++17
*MSVC2019 amd64
*Windows 10
Errors
(I removed note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided, note: candidate constructor template not viable: requires single argument 'str', but 2 arguments were provided and alike)
qStrView1:
qstringview.h:173:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleCharType<char>::value' was not satisfied [with Char = char]
qstringview.h:178:22: note: candidate template ignored: could not match 'const Char *' against 'std::basic_string_view::size_type' (aka 'unsigned long long')
qstringview.h:191:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleArray<const char *>::value' was not satisfied [with Array = const char *]
qStrView2:
qstringview.h:173:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleCharType<char>::value' was not satisfied [with Char = char]
qstringview.h:178:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleCharType<char>::value' was not satisfied [with Char = char]
qstringview.h:191:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleArray<const char *>::value' was not satisfied [with Array = const char *]
qStrView3:
qstringview.h:173:22: note: candidate template ignored: could not match 'const Char *' against 'std::basic_string_view<char, std::char_traits<char> >::const_iterator' (aka '_String_view_iterator<std::char_traits<char> >')
qstringview.h:178:22: note: candidate template ignored: could not match 'const Char *' against 'std::basic_string_view<char, std::char_traits<char> >::const_iterator' (aka '_String_view_iterator<std::char_traits<char> >')
qstringview.h:191:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleArray<std::_String_view_iterator<std::char_traits<char> > >::value' was not satisfied [with Array = std::_String_view_iterator<std::char_traits<char> >]
qStrView3a:
qstringview.h:173:22: note: candidate template ignored: could not match 'const Char *' against 'std::basic_string_view<char, std::char_traits<char> >::const_iterator' (aka '_String_view_iterator<std::char_traits<char> >')
qstringview.h:178:22: note: candidate template ignored: could not match 'const Char *' against 'std::basic_string_view<char, std::char_traits<char> >::const_iterator' (aka '_String_view_iterator<std::char_traits<char> >')
qstringview.h:191:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleArray<std::_String_view_iterator<std::char_traits<char> > >::value' was not satisfied [with Array = std::_String_view_iterator<std::char_traits<char> >]
qStrView4:
qstringview.h:103:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'std::basic_string_view<char, std::char_traits<char> >::const_pointer' (aka 'const char *') to 'const QStringView' for 1st argument
qstringview.h:103:7: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'std::basic_string_view<char, std::char_traits<char> >::const_pointer' (aka 'const char *') to 'QStringView' for 1st argument
qstringview.h:169:22: note: candidate constructor not viable: no known conversion from 'std::basic_string_view<char, std::char_traits<char> >::const_pointer' (aka 'const char *') to 'std::nullptr_t' (aka 'nullptr_t') for 1st argument
qstringview.h:196:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleArray<const char *>::value' was not satisfied [with Array = const char *]
qstringview.h:200:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatiblePointer<const char *>::value' was not satisfied [with Pointer = const char *]
qstringview.h:209:5: note: candidate template ignored: requirement 'std::is_same<const char *, QString>::value || std::is_same<const char *, QStringRef>::value' was not satisfied [with String = const char *]
qstringview.h:214:22: note: candidate template ignored: requirement 'QtPrivate::IsCompatibleStdBasicString<const char *>::value' was not satisfied [with StdBasicString = const char *]
A: Thanks for pointing me towards std::wstring. It took me a while understand the wchar_t , wstring, wcout, wifstream, ... stuff, but finally I have the following code working:
Note: still requires CONFIG += 17 in .pro file and following includes
#include <QStringView>
#include <string_view>
#include <string>
// create wstring and convert to QStringView
wstring somewstring = L"abc -ä-ö-ü-ß-"; //!< example string
wstring_view wview(somewstring);
// either work:
QStringView qstrv2a(wview.data(), wview.size());
QStringView qstrv2b(wview.data(), wview.data() + wview.size());
where either of the above constructors works fine.
Example using QStringView inside a QLabel
// setup minimum GUI
QWidget* mainWidget = new QWidget(this);
setCentralWidget(mainWidget);
QVBoxLayout* mainLayout = new QVBoxLayout;
mainWidget->setLayout(mainLayout);
// create wstring and convert to QStringView
wstring somewstring = L"abc -ä-ö-ü-ß-"; //!< example string
wstring_view wview(somewstring);
// either work:
QStringView qstrv1(wview.data(), wview.size());
// convert to label
QLabel* otherLabel = new QLabel(qstrv1.toLocal8Bit());
mainLayout->addWidget(otherLabel);
Example from file to QLabel
// additinonal standard libararies:
#include <fstream>
#include <sstream>
// setup minimum GUI
QWidget* mainWidget = new QWidget(this);
setCentralWidget(mainWidget);
QVBoxLayout* mainLayout = new QVBoxLayout;
mainWidget->setLayout(mainLayout);
// read file with UTF-8 characters (to a std::string)
std::string tempFileContent;
ifstream file("./infile.txt", ios::binary);
file.seekg(0, file.end);
tempFileContent.resize(file.tellg());
file.seekg(0, file.beg);
file.read(&tempFileContent[0], tempFileContent.size());
file.close();
// convert std::string -> std::wstring
std::wstringstream wss;
wss << tempFileContent.c_str();
std::wstring fileContent = wss.str();
// convert std::wstring -> QStringView
// - either work:
QStringView qstrv2(fileContent.data(), fileContent.size());
// convert to label
QLabel* someLabel = new QLabel(qstrv2.toLatin1()); //!< WORKS
mainLayout->addWidget(someLabel);
/* these did not work:
// total garbage
QLabel(QString::fromUtf8(qstrv2.toString().toStdString().c_str()));
// misses just the 'ß'
QLabel* someLabel = new QLabel(qstrv2.toLocal8Bit());
*/
where file content was
a-b-c-ä-ö-ü-ß-0-1-2
interestingly reading a text file with wifstream to a wstring takes much longer than converting a read string to a wstring using wstringstream. (which is still much slower than reading to std::string itself)
| |
doc_23536015
|
const AuthProvider = ({ children }) => {
const token = localStorage.getItem("token");
const userInfo = localStorage.getItem("userInfo");
const expiresAt = localStorage.getItem("expiresAt");
const [authState, setAuthState] = useState({
token,
expiresAt,
userInfo: userInfo ? JSON.parse(userInfo) : {},
});
const setAuthInfo = ({ token, userInfo, expiresAt }) => {
localStorage.setItem("token", token);
localStorage.setItem("userInfo", JSON.stringify(userInfo));
localStorage.setItem("expiresAt", expiresAt);
setAuthState({
token,
userInfo,
expiresAt,
});
};
Unfortunately i have a problem with updating user details.
In context i made another function:
Edit: I forgot to write that after the function is executed userDetails changes to undefined so I get a cross-origin error
const setUserInfo = ({ userInfo }) => {
localStorage.removeItem("userInfo");
localStorage.setItem("userInfo", JSON.stringify(userInfo));
setAuthState({
userInfo,
});
};
I have rest-api route to update-details , exemplary response:
{
"success": true,
"user": {
"role": role,
"_id": id,
"username": name,
"email": email,
"createdAd": createdAt,
"__v": 0
}
}
And user rest-api response when user login, example:
{
"success": true,
"token": token,
"expiresAt": expiresAt,
"userInfo": {
"role": role,
"_id": id,
"username": name,
"email": email,
"_id": id
}
}
Updating details working when i call it but after i get cross site error.
And heres Submit function
const handleUpdate = async (info) => {
setError("");
setLoading(true);
try {
const { data } = await fetchContext.authAxios.put(
"http://localhost:5000/api/v1/auth/update-details",
info
);
const user = data.user;
console.log(user);
auth.setUserState(data);
setError(null);
setLoading(false);
} catch (err) {
setLoading(false);
// const { data } = err.response;
// setError(data.error);
console.log(err);
}
};
A: Ok i dumb
const setUserInfo = ({ userInfo }) => {};
should be
const setUserInfo = ( userInfo ) => {};
| |
doc_23536016
|
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import {Client} from "../clients/client";
import {Observable} from "rxjs/Observable";
@Injectable()
export class ClientsService {
private clientUrl = './client.json';
private headers = new Headers({ 'Accept': 'application/json' });
private options = new RequestOptions({ headers: this.headers });
private client : Client;
constructor(private http:Http) {}
getClient() : Observable<any>{
return this.http.get(this.clientUrl, this.options)
.map(res => res);
}
}
and in my component I'm calling it:
this.client = this.clientsService.getClient()
.subscribe(data => {
console.log(data);
});
But I'm getting 404 error
But I have this json file in the same folder where my service is.
What's wrong?
A: You need to give the absolute path from your base path. Like, path/to/Services/client.json
Here's an example: https://plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p=preview
A: If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory
In your case you need to create file like assets/client.json
return this.http.get('/client.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Note: here you only need to give path inside assets folder like assets/client.json then you need to write path like /client.json
If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.
A: Please add this code in file the typings.d.ts
declare module "*.json"
{ const value: any;
export default value;
}
declare module "json!*"
{ const value: any;
export default value;
}
and simply import using import * as data1 from 'path.json';
| |
doc_23536017
|
var formattedList = from a in value
select new
{
a.value,
currencyId = a.currencyId == -1 ? "" : a.currencyId + ""
};
A: The syntax your looking a LINQ query which uses LAMBDA expressions:
http://en.wikipedia.org/wiki/Language_Integrated_Query
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
http://msdn.microsoft.com/en-us/library/bb397687.aspx
There are various ways to use LINQ, check out those pages for some examples
A: That's LINQ :) There's a pretty good summary here.
| |
doc_23536018
|
...
10-MAY-95 14:16:21*(CONNECT_DATA=(SID=reltest)(CID=(PROGRAM=C:\ORAWIN\BIN\PLUS31.EXE) (HOST=WINDOWSPC)(USER=CCLOW))*(ADDRESS=(PROTOCOL=tcp)(HOST=144.25.23.246)(PORT=3366))*establish*reltest*0
...
Log parameters are entered in the appropriate component configuration files in the form:
log_parameter_component = value
So, goal is to parse the above output and display result only with key=value, key=value, etc:
log_parameter_component = value, log_parameter_component = value, etc.
The result should look as following after parsing:
...
SID=reltest, USER=CCLOW, HOST=144.25.23.246
...
How to solve this task?
A: This should work in perl but I admit the second part could probably be avoided:
perl -p -e 's/.*?\(([^()]+?)=([^()]+?)\).*?/$1=$2,/g' myfile.log | perl -p -e 's/(.*),.*/$1/'
A: Found very close soulution.
But, how script will be look like if I want to add some additional patterns? If I will use awk script?
Ex. only for: SID, USER, SERVER, HOST.
| |
doc_23536019
|
First I have a list of LINESTRING and point value. How do I have the nearest LINESTRING to the POINT (5.41 3.9) and maybee the distance?
from shapely.geometry import Point, LineString
line_string = [LINESTRING (-1.15.12 9.9, -1.15.13 9.93), LINESTRING (-2.15.12 8.9, -2.15.13 8.93)]
point = POINT (5.41 3.9)
#distance
line_string [0].distance(point)
So far I think I got the distance value by doing line_string [0].distance(point) for the first LINESTRING so far but I just want to make sure I am going about it the right way.
A: Here's a function that takes a list of LineStrings and a point , and returns the LineString closest to the point, as well as the distance.
from shapely.geometry import Point, LineString
# set up lines and points
line_string_list = [LineString([(-1,1),(1,.5)]), LineString([(-1,-.5),(.5,-1)]), LineString([(-1,0),(.5,-.5)])]
point = Point(.25,-.75)
def closest_line(lines, point):
# get distances
distance_list = [line.distance(point) for line in line_string_list]
shortest_distance = min(distance_list) # find the line closest to the point
return(lines[distance_list.index(shortest_distance)], # return the closest line
shortest_distance) # return the distance to that line
print(closest_line(line_string_list, point))
A: *
*your sample geometry is invalid for line strings, have modified
*it's simple to achieve with sjoin_nearest()
import geopandas as gpd
import shapely.wkt
import shapely.geometry
line_string = ["LINESTRING (-1.15.12 9.9, -1.15.13 9.93)", "LINESTRING (-2.15.12 8.9, -2.15.13 8.93)"]
# fix invalid wkt string...
line_string = ["LINESTRING (-1.15 9.9, -1.15 9.93)", "LINESTRING (-2.15 8.9, -2.15 8.93)"]
point = "POINT (5.41 3.9)"
gdf_p = gpd.GeoDataFrame(geometry=[shapely.wkt.loads(point)])
gdf_l = gpd.GeoDataFrame(geometry=pd.Series(line_string).apply(shapely.wkt.loads))
df_n = gpd.sjoin_nearest(gdf_p, gdf_l).merge(gdf_l, left_on="index_right", right_index=True)
df_n["distance"] = df_n.apply(lambda r: r["geometry_x"].distance(r["geometry_y"]), axis=1)
df_n
geometry_x
index_right
geometry_y
distance
0
POINT (5.41 3.9)
0
LINESTRING (-1.15 9.9, -1.15 9.93)
8.89008
distance in meters
*
*use a CRS that is in meters. UTM has it's limitations if all points are not in same zone
import geopandas as gpd
import shapely.wkt
import shapely.geometry
line_string = ["LINESTRING (-1.15.12 9.9, -1.15.13 9.93)", "LINESTRING (-2.15.12 8.9, -2.15.13 8.93)"]
# fix invalid wkt string...
line_string = ["LINESTRING (-1.15 9.9, -1.15 9.93)", "LINESTRING (-2.15 8.9, -2.15 8.93)"]
point = "POINT (5.41 3.9)"
gdf_p = gpd.GeoDataFrame(geometry=[shapely.wkt.loads(point)], crs="epsg:4326")
gdf_l = gpd.GeoDataFrame(geometry=pd.Series(line_string).apply(shapely.wkt.loads), crs="epsg:4326")
gdf_p = gdf_p.to_crs(gdf_p.estimate_utm_crs())
gdf_l = gdf_l.to_crs(gdf_p.crs)
df_n = gpd.sjoin_nearest(gdf_p, gdf_l).merge(gdf_l, left_on="index_right", right_index=True)
df_n["distance"] = df_n.apply(lambda r: r["geometry_x"].distance(r["geometry_y"]), axis=1)
df_n
| |
doc_23536020
|
extension UIView{
func anchorSize(to view: UIView){
widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero){
translatesAutoresizingMaskIntoConstraints = false
if let top = top{
topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
}
if let leading = leading{
leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
}
if let trailing = trailing{
trailingAnchor.constraint(equalTo: trailing, constant: padding.right).isActive = true
}
if let bottom = bottom{
bottomAnchor.constraint(equalTo: bottom, constant: padding.bottom).isActive = true
}
if size.width != 0 {
widthAnchor.constraint(equalToConstant: size.width).isActive = true
}
if size.height != 0 {
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
}
}
However, I've come across an issue in which when displaying my views on different screen sizes the views become squished or simply don't fit. How would I go about resizing the views through auto-layout to fit multiple screen sizes? This is also the code for when I apply the constraints to something like a label:
logo.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.safeAreaLayoutGuide.leadingAnchor, bottom: nil, trailing: view.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 20, left: 0, bottom: 0, right: 0))
logo.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
subLogo.anchor(top: logo.bottomAnchor, leading: logo.leadingAnchor, bottom: nil, trailing: logo.trailingAnchor, padding: .init(top: 20, left: 0, bottom: 0, right: 0))
subLogo.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
The iPhone 11 is the correct way of how I would auto layout. I really want to universally resize all my views for other devices.
Here are the screenshots of the example devices
Thanks in advance.
A: If you can show what you are actually talking about from screenshots, would help me a lot to see what’s going on.
By the way you are missing translatesAutoresizingMaskIntoConstraints = false in func anchorSize(). Also what are you trying to achieve by having a negative padding amount for top?
| |
doc_23536021
|
I have a LINQ query:
var points = from p in ContextDB.Points
//join v in ContextDB.PointValues on p.PointID equals v.PointID
where p.InstanceID == instanceId
orderby p.PointInTime descending
select new
{
Point = p,
Values = p.PointValues.Take(16).ToList()
};
As you can see from the commented out join and the "Values" assignment, the "Point" table has a relation to "PointValue" (called "Points" and "PointValues" by LINQ).
When iterating through the "var points" IQueryable (say, when binding it to a GridView, etc.) the initial query is very fast, however iterating through the "Values" property is very slow. SQL Profiler shows me that for each value in the "points" IQueryable another query is executed.
How do I get this to be one query?
Interestingly, the initial query becomes very slow when the join is uncommented.
A: I think you want to use the DataLoadOptions.LoadWith method, described here:
http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.loadwith.aspx
In your case you would do something like the following, when creating your DataContext:
DataLoadOptions options = new DataLoadOptions();
ContextDB.LoadOptions = options;
options.LoadWith((Point p) => p.PointValues);
A: You should make sure that the PointValues table has an index on the PointID column.
See also this SO question: Does Foreign Key improve query performance?
| |
doc_23536022
|
The following line creates an input for the field, where the user can choose the date.
<%= f.date_select :start_date %>
How can I make it display only weekdays as input options?
A: It's not possible to do what you want with a date_select helper. You have two alternatives (and one isn't really an alternative):
1) Write a validation in the model that fails if the date selected is not a weekend; or
2) Use a JavaScript date picker (like jQuery DatePicker), which is the only real solution. You can disable specific days or categories of days with DatePicker.
| |
doc_23536023
|
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
modifying entry "cn=config"
ldap_modify: Other (e.g., implementation specific) error (80)
| |
doc_23536024
|
Any ideas or recomended approaches?
A: Create a 50MB file on the HDD. Use memory-mapped access. Don't delete it.
A: You could look at memory mapped files. OS is probably more relevant than language.
A: *
*Adapt your file format by adding a header, that contains the real
file length
*On installation create a file of site 50MB filled with random data (to avoid sparsity) and a header saying 0 bytes used.
*When fseek()ing make sure you use your header length, not file length
| |
doc_23536025
|
var line_points = Array();
var lineLayer = new OpenLayers.Layer.Vector(label);
this.map.addLayer(lineLayer);
this.map.addControl(new OpenLayers.Control.DrawFeature(lineLayer, OpenLayers.Handler.Path));
for ( x in points ) {
var point = points[x].split(',');
var lat = parseFloat( point[0] );
var lon = parseFloat( point[1] );
line_points[x] = new OpenLayers.Geometry.Point(this.Lon2Merc(lon), this.Lat2Merc(lat));
}
var line = new OpenLayers.Geometry.LineString(line_points);
var lineFeature = new OpenLayers.Feature.Vector(line, null, style);
lineLayer.addFeatures([lineFeature]);
I'm trying to pull the latitudes and longitudes out of this feature whenever a point is moved or created to update a HTML form which is then used to save that data. I've heard about the protocols and stuff, but don't think that's the right thing for me.
Could someone point me in the right direction please?
EDIT:
I've tried getting the details from the HTML directly:
var x = 0;
var y = 0;
$.each(document.getElementById("OpenLayers.Geometry.LineString_195").getAttribute("points").split(','), function(index, value) {
if(index%2){
y = value;
console.log(MercatorToLatLon(x,y).Lat + "," + MercatorToLatLon(x,y).Lon);
} else {
x = value;
}
//console.log(value);
});
but this doesn't seem to give any useful values, and in no particular order which I find strange.
A: You can use the getVertices operation to retrieve all the latest latitudes and longitudes of the points in the feature.
So call the following whenever you want to update your html.
console.log(lineFeature.geometry.getVertices());
Update per comment:
function report(event) {
console.log(event.feature.geometry.getVertices());
console.log(event.type, event.feature ? event.feature.id : event.components);
}
lineLayer.events.on({
"beforefeaturemodified": report,
"featuremodified": report,
"afterfeaturemodified": report,
"vertexmodified": report,
"sketchmodified": report,
"sketchstarted": report,
"sketchcomplete": report
});
A: Accessing geometry values directly from dom is probably not the best idea. Better and easier to use OpenLayers API.
You can subscribe to layer's featuremodified event and then access modified feature:
lineLayer.events.on({"featuremodified": function(feature){
console.log(feature.geometry.getVertices());
}});
You can listen to other events too, for instance "featureadded", "featureremoved", etc.
Hope you get the idea.
| |
doc_23536026
|
my client code:
import socket
msgFromClient="f"
bytesToSend=msgFromClient.encode()
UDPClientSocket =socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM)
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
my server code:
server_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
server_socket.bind((UDP_IP,UDP_PORT_NO))
while True:
adress,byte_message=server_socket.revfrom(1024)
print (adress)
print(byte_message)
and what i get:
b'f'
('192.168.4.15',55924)
each time i send it the integer in the tuple is different.
what i need is encode one letter to byte and decode it after receiving it.
| |
doc_23536027
|
\ud83c\udf00 New ReadyStock \ud83c\udf00 EAR-EL380 : Rp 55,000\n\nOrder thru : BBM \/ LINE\n\n#premiumaccessories #accessories #marpaungs #jewelry #jualanku #jualankaka #trustedseller
For some reason webstagram is able to show this nicely on their website as can be seen here. How do I parse this string along with the new lines and stuff so I can get something formatted correctly with the new lines and everything?
| |
doc_23536028
|
I am trying to rename a column with the following query:
alter table audit_schema rename column object to objectname;.
What is the problem
oracle return this strange error ORA-30512: Cannot modify AHTI.AUDIT_SCHEMA more than once in a transaction after renaming the column.
Table:
Name Null? Type
----------------------------------------- -------- ----------------------------
USERNAME VARCHAR2(30)
CURRENTDATE VARCHAR2(30)
OBJECT VARCHAR2(30)
Trigger:
CREATE OR REPLACE TRIGGER audit_schema_tr
AFTER DDL ON Schema
BEGIN
insert into audit_schema values (user, sysdate,ora_dict_obj_type);
END;
/
A: You can try disabling the trigger and then renaming the column.
ALTER trigger trigg_name disable
If it doesn't work, drop your trigger -
DROP Trigger trig_name
rename the column and recreate the trigger.
A: This is only a problem if you're trying to audit changes to your audit table. Another solution to this is to add the following to your trigger. This will prevent having to remember to disable/drop the trigger whenever you are modifying it:
if (NOT (ORA_DICT_OBJ_NAME = 'AUDIT_SCHEMA') AND
ORA_DICT_OBJ_TYPE = 'TABLE')) Then
insert into audit_schema values (user, sysdate,ora_dict_obj_type);
End if;
| |
doc_23536029
|
This is my first time designing a website and i have never worked with MySQL before but i have developed a quick understanding of how it all works.
I understand that i need to create sessions to 'store' their information when they log in then i can display it as i wish ?
Does anyone have any code that i could use?
My SQL info:
*
*db: taxretur_login
*table: members
aspects i would like to show:
*
*name
*email
*username
Thanks.
Stan.
UPDATE:
This code works and pulls all my table info accross to a users page but i only want data unique to that paticular user:
<?php
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id_user, email,
name, username
FROM members';
mysql_select_db('taxretur_login');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo "User ID :{$row['id_user']} <br> ".
"Email: {$row['email']} <br> ".
"Name: {$row['name']} <br> ".
"Username : {$row['username']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
A: Create members table in your database
CREATE TABLE `members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` char(20) NOT NULL,
`name` char(30) NOT NULL,
`email` char(40) NOT NULL,
`pass` char(20) NOT NULL,
PRIMARY KEY (`id`)
);
Add an user into table members
INSERT INTO `members` VALUES ('1', 'user1', 'mr. x', 'email@domain.com', '123');
Just change the variable as your mysql user in page connection.php
connection.php
<?php
$mysql_host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
$mysl_database = "taxretur_login";
$conn = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_select_db($mysl_database, $conn);
?>
login.php
<?php
include("connection.php");
if(isset($_POST["submit"])) {
$username = $_POST["username"];
$pass = $_POST["pass"];
$sql = "SELECT * FROM members
WHERE username='$username' AND pass='$pass'";
$result = mysql_query($sql);
$numRows = mysql_num_rows($result);
if($numRows==1) {
session_start();
$_SESSION["username"] = $username;
header("Location: ./profile.php");
} else {
echo "Invalid Login Information";
}
}
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post">
<table>
<tr><td>User Name</td><td><input type="text" name="username" /></td></tr>
<tr><td>Password</td><td><input type="password" name="pass" /></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Login" /></td></tr>
</table>
</form>
profile.php
<?php
session_start();
include("connection.php");
$username = $_SESSION["username"];
$sql = "SELECT * FROM members WHERE username='$username'";
$result = mysql_query($sql);
if($row = mysql_fetch_array($result)) {
$username = $row["username"];
$name = $row["name"];
$email = $row["email"];
echo "
<table>
<tr><td>User Name</td><td> : </td><td>$username</td></tr>
<tr><td>Name</td><td> : </td><td>$name</td></tr>
<tr><td>Email</td><td> : </td><td>$email</td></tr>
</table>
";
}
?>
A: You should try yourself first, help is here. database connection with select statement and print first name
http://www.w3schools.com/php/php_mysql_select.asp
http://www.tutorialspoint.com/mysql/mysql-select-query.htm
A: Assuming your user has a user id (uid), you should be able to fetch information from the database, relative to their said 'uid'.
An example query would look something like:
SELECT firstname, lastname, email FROM `users` WHERE `id` = 'UID_HERE';
If your table had firstname, lastname & email fields/columns in it.
Definitely look into using Mysqli to do all database work, because mysql_ is no longer being developed.
A: Modify your query
$sql = 'SELECT id_user, email, name, username
FROM members';
to
$sql = "SELECT id_user, email, name, username
FROM members where id_user = '$dbuser'";
| |
doc_23536030
|
For example
Input <html and when i press '>'
i hope this <html></html>
how to do this ?
A: It's not supported natively in neovim. You have to add a plugin like https://github.com/alvan/vim-closetag
A: As mentioned, neovim doesn't natively do this. The other answer helps for HTML but for (most) other programming language I use endwise:
For HTML tags: https://github.com/alvan/vim-closetag
For other languages: https://github.com/alvan/vim-closetag
| |
doc_23536031
|
I know how to use an embed to get named links, but I can't figure out how to make those links point to other specific locations within the channel. I found this post that looks like what I want, but there is no description about how it was accomplished. They need to link back and forth, so I can't just post the first message and then copy a link to that.
| |
doc_23536032
|
Now i got the the text and image in blog like form just the way I wanted.
But i also wanted to add borders to the whole content. So that it looks like the text and image are in a box.
But the border are not able to cover the image's height and width.
<html>
<head>
<title>Float</title>
</head>
<style>
img {
float: right;
}
</style>
<body>
<div>
<p><img src="https://s27363.pcdn.co/wp-content/uploads/2017/02/Tigers-Nest-Hike.jpg.optimal.jpg" alt="Tiger's Nest"
style="width:200px; height:200px; margin-left:15px;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem
egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor
vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in
odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed
ullamcorper ipsum dignissim ac...
</p>
</div>
</body>
</html>
A: You need to add display: flex; to the div:
<html>
<head>
<title>Float</title>
</head>
<style>
div {
display: flex;
border: 5px solid blue;
}
img {
float: right;
}
</style>
<body>
<div>
<p><img src="https://s27363.pcdn.co/wp-content/uploads/2017/02/Tigers-Nest-Hike.jpg.optimal.jpg" alt="Tiger's Nest"
style="width:200px; height:200px; margin-left:15px;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem
egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor
vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in
odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed
ullamcorper ipsum dignissim ac...
</p>
</div>
</body>
</html>
| |
doc_23536033
|
*
*I create an appointment on my client application
*The client application insert the appointment in the online database
Now I'm not an expert of synchronization, but I'm actually develop an API that's based simply with an insert statement of the query. The problem's that If I insert the appointment in the online database I've different ID and this is wrong 'cause the id must be the same. So the questions at this point is this:
1.There's a system that allow me to synchronize my data from localhost database to online database?
2. For the ID problem I should create another field like ID_Client or there's something do have the same id as in the client app? If yes I need certainly to check if the ID is already created in the online database and this is quite annoying. I need a simple and power solution for doing this.
What suggest?
A: For the issue of ID, you should use a GUID for the ID, do not even attempt this with an identity primary key. This allows you to create the ID on the client, web server, etc and they won't duplicate.
For the issue of synchronization, there are different tools and 3rd party applications that will do this for you but I wouldn't suggest doing that with your program because you may have 1000's of clients that would all need complex/expensive synchronization tools. You should write an Web Service that you can send/get changes from and add a DateTime field to your tables so you can tell which database has the latest data when the record already exists. It takes a little work but this is how I would do it.
BTW, if you are using VS2015 and your clients are all Windows 10, there are some build in features for building apps that synchronize for you. But it will be a while before we can expect users to have Windows 10.
| |
doc_23536034
|
@interface MyClass : NSObject {
}
@property (nonatomic) AnotherClass *obj;
@end
and
@interface MyClass : NSObject {
@property (nonatomic) AnotherClass *obj;
}
@end
??
A: The second one is incorrect. That's the only difference.
A: The { } are the area where instance variables are defined. But in modern Objective-C they are not needed in the @interface section in order to define instance variables (you can now do that in the @implementation section), and they were never needed if, as is the case here, there are no instance variables being defined. So what I would suggest you do is remove the { } altogether. They are evidently just confusing you, and they serve no purpose.
A: Second one is the correct one. The space between the brackets are only for instance variables e.g.:
NSMutableArray *array
But below that is for methods and properties.
| |
doc_23536035
|
For instance, right now I am using Postgresql and need serializable isolation for specific single transactions. I use both plain Squeryl and Squeryl-Record with the Lift web framework.
Others may of course need other isolation levels for other databases for entire sessions (rather than single transactions), so general answers are preferable.
Update:
I ended up with this modified version of Dave Whittaker's code:
def transactionWith[T](isolation: Int)(block: => T): T =
transaction {
val connection = Session.currentSession.connection
connection.rollback // isolation cannot be changed in the middle of a tx
connection.setTransactionIsolation(isolation)
block
}
The thing is that if a transaction has already been started, you can't change the isolation level. This was the case for me and without the rollback I would get:
org.postgresql.util.PSQLException: Cannot change transaction isolation level in the middle of a transaction.
As long as I am using transaction{} and not inTransaction{} I think doing an immediate rollback should do no harm.
The isolation level should be reset after transaction{} commits or rollbacks, but before the connection is returned to the connection pool. I'm not sure how to accomplish that. But in my case the c3p0 connection pool seems to reset the isolation level and every transaction{} starts with default isolation level even if I never clean them up myself.
The thing I'm not so happy with is the exception when there is a conflict. I would like to catch such an exception specifically and retry the transaction. But it's just a generic runtime exception:
java.lang.RuntimeException: Exception while executing statement : ERROR: could not serialize access due to concurrent update
It wraps another exception which unfortunately also is generic (org.postgresql.util.PSQLException).
Not perfect, but it does the job until Squeryl hopefully gets support for transaction isolation. I am using the above code with Squeryl 0.9.4.
A: Right now it would be a somewhat manual process. If you need it for the entire session then I suppose you could simply set the appropriate level in your SessionFactory, i.e.
SessionFactory.concreteFactory = Some(()=> {
val connection = java.sql.DriverManager.getConnection("...")
connection.setTransactionIsolation(...)
Session.create(connection, new PostgreSqlAdapter)
})
For a single transaction it would be a bit more difficult. You can access the current session with Session.currentSession or Session.currentSessionOption and you would have to set the isolation level before your transaction occurred and then set it back afterwards. Of course, it wouldn't be too difficult to create your own function that does just that:
def transactionWith(isolation: Int)(block: => T): T = {
trasaction{
val connection = Session.currentSession.connection
val oldIsolation = connection.getTransactionIsolation()
connection.setTransactionIsolation(isolation)
try {
block
} finally {
connection.setTransactionIsolation(oldIsolation)
}
}
}
Then you would use it like
transactionWith(Connection.TRANSACTION_SERIALIZABLE){
from(blablabla)(......)
}
I think that would work but a) I'm not entirely sure when the isolation level is supposed to be set, I'm assuming that setting it within the current transaction before executing any other statements will work and b) I haven't tried to compile the above so there may be syntactic errors. Anyway, I think it will give you the general idea.
A: Regarding the exception: org.postgresql.util.PSQLException extends java.sql.SQLException, which has a getSQLState() method. Exceptions caused by serialization failures like this will return "40001" from this method.
| |
doc_23536036
|
It is saved in format "dd.MM.yyyy" and it's a string.
Now why it's a string and formated that way, is because my boss has special wishes. And when I want to sort it from the newest date to older it does something like this:
26.05.2015
24.06.2014
22.04.2015
21.04.2015
20.03.2014
It starts sorting by day.
Is there a way to make it sort it like it should?
I see that i can write a Computed value to Sort column in view column header for date. But i don't know how to even start.
A: If the date time value doesn't solve your problem and you do not transform your date via @Text (as mentioned in the comments) then create another (hidden) column BEFORE your column that should be displayed. Make this a true date (from your item), sort it and unsort the column to display.
Otherwise use this formula in the newly created sorted column:
@Text(@Year(yourDate))+"-"+@Right("00"+@Text(@Month(yourDate));2)+"-"+@Right("00"+@Text(@Day(yourDate));2)
A: Change the underlying Notes view to get your date column into right order.
Convert the date strings to real date values in views column formula. Assuming your field is called DateText then your formula would be
@Date(@ToNumber(@Right(DateText; 4));
@ToNumber(@Middle(DateText; 3; 2));
@ToNumber(@Left(DateText; 2)))
It would be easier to use just @ToTime(DateText) but this can fail depending on server's local settings. Your date string format would work for a server with German locale settings but not for US. That's why is my suggested solution "safer".
| |
doc_23536037
|
https://jsfiddle.net/tf5xd7px/
$(document).ready(function() {
$('proj1').hover(function() {
$('proj1').animate({
transform: 'rotateX(40deg)'
}, 'slow');
});
});
#proj1 {
background-image: url('http://i.imgur.com/FddIcrz.png');
background-position: center;
width: 300px;
height: 300px;
/*position:relative;
bottom:300px;*/
left: 150px;
border: 2px solid gray;
box-shadow: 3px 3px 5px gray;
/*-webkit-transition: rotateX 4s;*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='projects'>
<div id='proj1'>
</div>
</div>
A: transform: 'rotateX(40deg)'
is not an animatable property (jquery animation works with basic numbers). You also had a few errors with the jsfiddle setup that was preventing this from running (like not turning on jquery and only using proj1 as your jquery selectors instead of #proj1).
If you're looking to turn it and turn it back on hover-out, use
#proj1:hover {
transform: rotateX(40deg);
}
If you want it to rotate and stay there, you can add a class on hover, like so:
https://jsfiddle.net/tf5xd7px/3/
Update
It looks like you're looking for a 3d card flip style, not a flat rotation. Add perspective to your container like so:
https://jsfiddle.net/tf5xd7px/4/
A: No JavaScript needed for this. This simple CSS style work (you should add the prefixes):
#proj1:hover {
transform: rotate(40deg);
}
Check the fiddle:
https://jsfiddle.net/lmgonzalves/tf5xd7px/2/
| |
doc_23536038
|
template <class T>
class A {
T* arr;
int size;
public:
A(int size) : arr(new T[size]) , size(size) {
}
//..
A& operator=(const A& a){
if(this == &a){
return *this;
}
this->size = a.size;
T* ar=new T[a.size];
for(int i=0 ; i<size ; i++){
ar[i]=a.arr[i]; // I need to do it at "try-catch" ?
}
delete[] this->arr;
this->arr=ar;
return *this;
}
//...
};
When I copy the elements from the given array, do I need to do it with a try-catch clause or not? is it a good idea or not?
A: I can see that potentially your T copy could throw due to its own alloc failure or other reasons.
On the other hand your A copy could already throw because it had alloc failure.
Currently you would need to handle the destruction because you have not concreted the array that you have allocated, and all the T instances that you have created need to be destroyed if one of them exceptions, perhaps due to allocation failure.
One quick way to fix that would be to hold the array in a unique_ptr. Then it will be destroyed on exiting context.
Another way may be to reconsider your contract on A after the assignment has exceptioned: It must be valid, i.e. survive being used, but perhaps it need not guarantee to still contain its previous contents, nor all the new contents, so you could decide to destroy its existing array before allocating and assigning a new array, then copying the members. You could decide not to reallocate if the size has not changed, but just re-assign - this would leave a mess of new and old members after an exception, but they would all be valid and safe to delete.
Please ensure that size matches the actual attached array size at all times! Your existing code makes this mistake, but in particular that it is set to null and 0 after the delete and before the assignment; and it is only set to new new size after the assignment of the new pointer.
| |
doc_23536039
|
foreach (pq('body')->children() as $children) {
// do some code here
}
However, I need to know which element is being parsed (table, div, p...).
How can I do this?
A: Ok, I dit it. As phpQuery is based on DOMDocument I just had to use the attribute nodeName, like this:
foreach (pq('body')->children() as $children) {
echo $children->nodeName;
}
Perfectly works.
| |
doc_23536040
|
java.lang.IllegalArgumentException: Invalid URL or resource not found
Here is the code:
File ff=new File("images/a.jpg");
if (ff.exists()) {Image ii=new Image(ff.getPath());}
A: From the Javadocs:
All URLs supported by URL can be passed to the constructor. If the
passed string is not a valid URL, but a path instead, the Image is
searched on the classpath in that case.
The path you get is a relative path, but not (necessarily) relative to the classpath, which is how the Image constructor is interpreting it.
Try
Image ii=new Image(ff.toURI().toURL().toExternalForm());
or, depending on how you have your project structure set up
Image ii=new Image(getClass().getResource("images/a.jpg").toExternalForm());
The second version will work if the image file is packaged along with the application in a jar file.
| |
doc_23536041
|
*
*Is that a feature or a bug?
*How so I switch it off? I always restart Android Studio to get out of that mode.
A: Finally found the key stroke as I accidentally hit it:
On Mac: Cmd + Shift + 8
| |
doc_23536042
|
My problem is that after an encryption without a decryption it stops working for one decryption function call. Here's my code:
var crypto = require('crypto');
var encryptionMethod = 'aes-256-cbc';
var vector = new Buffer([0xF1, 0x4C, 0xB6, 0xBD, 0x82, 0x93, 0x3C, 0x97, 0x6A, 0x4B, 0x4A, 0xD2, 0xAD, 0xD5, 0xA8, 0x6D]);
var key = new Buffer([59, 92, 128, 239, 136, 26, 19, 26, 226, 234, 53, 71, 157, 113, 209, 96, 111, 83, 167, 123, 217, 107, 124, 31, 238, 176, 58, 110, 161, 82, 81, 69]);
var cipher = crypto.createCipheriv(encryptionMethod, key, vector);
cipher.setAutoPadding(false);
var decipher = crypto.createDecipheriv(encryptionMethod, key, vector);
decipher.setAutoPadding(false);
var encrypt = function(array) {
return cipher.update(new Buffer(array));
};
var decrypt = function(buffer) {
return decipher.update(buffer);
};
var data = [];
for (var i = 0; i < 32; i++) {
data.push(i);
}
// no problem here (probably because the vector updates itself?)
console.log(decrypt(encrypt(data))); // <Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f>
console.log(decrypt(encrypt(data))); // <Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f>
console.log(decrypt(encrypt(data))); // <Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f>
// after one encryption without a decryption it stops working.
console.log((encrypt(data)));
// why can't this be decrypted correctly? The last 16 entries are correct.
console.log(decrypt(encrypt(data))); // <Buffer e2 df 50 63 c7 eb 06 4c 28 19 6d 04 41 bd c0 db 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f>
// expected result
console.log(decrypt(encrypt(data))); // <Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f>
Please see the comments above the console.log calls for more information. How can I make sure that the decrypt function works all the time?
A: TL;DR: This is expected behavior.
You're using the Cipher-Block Chaining (CBC) mode. Where the encryption and decryption one block (16 byte) depends on the previous block. A block cipher is a pseudo-random permutation which means that it will always encrypt or decrypt anything as long as you give it 16 bytes of data.
With the code console.log(decrypt(encrypt(data))); you're encrypting two blocks and give them to the decryption. The last ciphertext block that was processed is remembered for the next update or final call.
Now, when you call console.log((encrypt(data)));, you're not passing the ciphertext to the decryption function which doesn't know the intermediate ciphertext block for the next console.log(decrypt(encrypt(data)));.
Here's an illustration:
The last 16 entries are correct.
That's because CBC is not an error-propagating mode. You've encrypting two blocks at the same time. Since the second ciphertext block of the decrypt is intact, it will decrypt correctly.
| |
doc_23536043
|
my code- http://codepad.org/eneTDVfw
| |
doc_23536044
|
This is my code :
<table id="table">
<tr>
<td id="col1">
<form>
<p><label for="text"> your text</label>:<input type="text" id="text"></input></p>
<input type="submit" value="tester" onclick="addImage()" />
</form>
</td>
<td id = "img"></td>
</tr>
</table>
<script>
function addImage(){
document.getElementById("img").innerHTML = "<img src='newWatermark.png'/>"
}
</script>
<style>
#table{width:100%}
#col1{width:50%}
</style>
It's work but just half a time ... And just during a few second ...
I don't understand why
Moreover I think that when I click on the button I refresh the page.
In the URL I have : /watermark.html at the beginning and /watermark.html?your+text= when I click on the button.
But I just want to add an image on the same page. How can I do this?
A: You submitting Your form.
Change type of input from submit to button.
A: To avoid page refresh use input type button not submit
function addImage(){
document.getElementById("img").innerHTML = "<img src='newWatermark.png'/>"; //This will overwrite previous image
}
function appendImage(){
document.getElementById("img").innerHTML += "<img src='newWatermark.png'/>"; //This will append image
}
#table{width:100%}
#col1{width:50%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<tr>
<td id="col1">
<form>
<p><label for="text"> your text</label>:<input type="text" id="text"></input></p>
<input type="button" value="tester" onclick="addImage()" />
<input type="button" value="Append" onclick="appendImage()" />
</form>
</td>
<td id = "img"></td>
</tr>
</table>
| |
doc_23536045
|
I am making a call to an API that is returning the following. Excuse the formatting but it is directly copied from the Xcode console.
["type": success, "value": <__NSArrayI 0x600000030340>(
{
categories = ();
id = 155;
joke = "Chuck Norris does not "style" his hair. It lays perfectly in place out of sheer terror.";
},
{
categories = (nerdy);
id = 69;
joke = "Scientists have estimated that the energy given off during the Big Bang is roughly equal to 1CNRhK (Chuck Norris Roundhouse Kick).";
}
)
]
I want to loop over the response and add to an array. In JavaScript it would look like the following:
let jokes = [];
response.value.forEach(item => {
jokes.push(item.joke)
})
It doesn't have to be exactly like the above. I am confident using loops in swift and appending to an array. What I am struggling to do is access the jokes in the value array returned from the API.
My controller looks like the following:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
} catch let error as NSError {
print(error)
}
}).resume()
}
}
A: You can try
if let va = json["value"] as? [[String:Any]] {
va.forEach { print($0["joke"]) }
}
I would prefer to write a Codable structs for this
struct Root: Codable {
let type: String
let value: [Value]
}
struct Value: Codable {
let categories: [Category]
let id: Int
let joke: String
}
struct Category: Codable {
}
let res = try? JSONDecoder().decode(Root.self,from:data)
print(res.value)
A: As you can see from logs the variable json["value"] is of type NSArray so you can do something like this to get your data (there are so many ways to do that).
First of all you can create the object Joke you wanna take like this
class Joke: NSObject {
var categories = [String]()
var id: Int?
var joke: String?
init(json: [String: Any]) {
if let categories = json["categories"] as? String {
for category in categories {
self.categories.append(category)
}
}
if let id = json["id"] as? Int {
self.id = id
}
if let joke = json[""] as? String {
self.joke = joke
}
}
}
And then you do this in your ViewController
class ViewController: UIViewController {
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
let arrayOfObject = json["value"] as! NSArray
for object in arrayOfObject {
if let json = object as? [String: Any] {
let object = Joke(json: json)
// Now you have your object containing the data from the JSON and you can insert it in your array of Object
jokes.append(object)
}
}
} catch let error as NSError {
print(error)
}
}).resume()
}
}
Remember, there are so many ways to do that, I showed you a simply way to do it, hope it will be helpful.
| |
doc_23536046
|
So normally I'd have something like
String valueForParam = "";
if(condition == true){
valueForParam = "value";
}
given().request().param("parameter",valueForParam).when().put(URL)
But the problem is in my case if the parameter is sent in with a blank value (when condition is false) the service will throw an error.
I know I could make an if statement to call a completely different given() when the parameter is false, but I'm curious if there is a way to stop the parameter from being sent in when the value is blank.
A: Use RequestSpecBuilder:
String valueForParam = "";
Map<String, String> params = new HashMap<>;
if(condition == true){
params.put("parameter", "value");
}
RequestSpecification s = new RequestSpecBuilder().addParams(params).build();
given().spec(s).when().put(URL);
| |
doc_23536047
|
device has_many health_records
health_records belong_to device.
I want to get the LAST 10 devices that has the most recently created health_records.
I can get it using this, but this gets ALL of the records:
Device
.select("devices.id, MAX(health_records.id) AS latest_health_id")
.joins(:health_records)
.group("devices.id")
.order("latest_health_id DESC")
If I add .limit(10), it just gives me a Device::ActiveRecord_Relation which i cannot inspect. (when i inspect it says Invalid column name 'latest_health_id'.). Adding .first(10) does not work too.
A: As per the description shared below mentioned query will fetch devices of last 10 created health records.
Device
.select("devices.id")
.joins(:health_records)
.group("devices.id")
.order("health_records.created_at DESC").limit(10)
A: I think you can achieve your goal with the following query:
Device
.joins(:health_records)
.order('health_records.created_at DESC')
.group(:id)
.distinct
.limit(10)
This will return Device::ActiveRecord_Relation object. If you want only ids, just add pluck(:id) at the end, which will change your query from SELECT DISTINCT "devices".* to SELECT DISTINCT "devices"."id" and return Array of ids.
A: Here is another solution that should probably work for you (albeit untested):
Device.where(id: HealthRecord.select(:device_id)
.group(:device_id)
.order("MAX(health_records.id) DESC")
.limit(10)
)
This should result in a query similar to
SELECT
devices.*
FROM
devices
WHERE
id IN (
SELECT
health_records.device_id
FROM
health_records
GROUP BY
health_records.device_id
ORDER BY
MAX(health_records.id) DESC
LIMIT 10 OFFSET 0
)
A: For now I ended up using either of this two:
Device
.select("devices.id, MAX(health_records.id) AS latest_health_id")
.joins(:health_records)
.group("devices.id")
.order("latest_health_id DESC")
.map(&:id).first(10)
Device
.joins(:health_records)
.order('health_records.created_at DESC')
.pluck(:id).uniq.first(10)
it gives me an array of the last 10 device ids that most recently created a health_record
| |
doc_23536048
|
I've googled the django docs because I'm curious as to what's going on here. Is my template tag's context variable only available within the template that includes it and not beyond, as it seems?
A: In the Django library, django.template.base you have the parse_bits function. In this function, the view context is copied into a new variable.
if takes_context:
if params[0] == 'context':
params = params[1:]
else:
raise TemplateSyntaxError(
"'%s' is decorated with takes_context=True so it must "
"have a first argument of 'context'" % name)
And in the class InclusionNode class render function, a new context object is created to render the template of the template tag:
class InclusionNode(TagHelperNode):
def render(self, context):
"""
Renders the specified template and context. Caches the
template object in render_context to avoid reparsing and
loading when used in a for loop.
"""
resolved_args, resolved_kwargs = self.get_resolved_arguments(context)
_dict = func(*resolved_args, **resolved_kwargs)
t = context.render_context.get(self)
if t is None:
if isinstance(file_name, Template):
t = file_name
elif isinstance(getattr(file_name, 'template', None), Template):
t = file_name.template
elif not isinstance(file_name, six.string_types) and is_iterable(file_name):
t = context.template.engine.select_template(file_name)
else:
t = context.template.engine.get_template(file_name)
context.render_context[self] = t
new_context = context.new(_dict)
# Copy across the CSRF token, if present, because
# inclusion tags are often used for forms, and we need
# instructions for using CSRF protection to be as simple
# as possible.
csrf_token = context.get('csrf_token', None)
if csrf_token is not None:
new_context['csrf_token'] = csrf_token
return t.render(new_context)
So it should not propagate the templatetag context to the calling template.
| |
doc_23536049
|
I'm using AdventureWorks2017, if that helps.
I was able to do this with a JOIN
SELECT
DepartmentID, MAX(Rate) 'Rate'
FROM
HumanResources.EmployeeDepartmentHistory h
JOIN
HumanResources.EmployeePayHistory p ON h.BusinessEntityID = p.BusinessEntityID
GROUP BY
DepartmentID
Here is a subquery solution I tried but didn't work
SELECT DISTINCT
DepartmentID,
(SELECT MAX(Rate)
FROM HumanResources.EmployeePayHistory p
WHERE p.BusinessEntityID = h.BusinessEntityID) 'Rate'
FROM
HumanResources.EmployeeDepartmentHistory h
GROUP BY
DepartmentID, BusinessEntityID
A: OK, it really is best with a join but if you don't want one, you could do this:
SELECT ds.DepartmentID, MAX(Rate) AS MaximumRate
FROM
(
SELECT edh.DepartmentID,
(SELECT MAX(Rate)
FROM HumanResources.EmployeePayHistory p
WHERE p.BusinessEntityID = edh.BusinessEntityID) AS Rate
FROM HumanResources.EmployeeDepartmentHistory AS edh
GROUP BY edh.DepartmentID, edh.BusinessEntityID
) AS ds
GROUP BY ds.DepartmentID;
I think that does what you're wanting.
A: You need to just group by DepartmentID in order to only return a row for each department.
SELECT h.DepartmentID,
(SELECT MAX(Rate)
FROM HumanResources.EmployeePayHistory p
WHERE p.BusinessEntityID = h.BusinessEntityID) AS Rate
FROM
HumanResources.EmployeeDepartmentHistory AS h
GROUP BY
h.DepartmentID;
This should return the same results than your first query.
A: Please see the Following Code for your reference
declare @tab table (DepartID integer, Name1 varchar(50))
declare @tab1 table (ID integer,DepartID integer, value1 float)
insert into @tab
select 1,'Sandy'
union all
select 2,'Ramesh'
union all
select 3,'Rani'
insert into @tab1
select 1,1,26.5
union all
select 2,1,29.0
union all
select 3,1,15.66
union all
select 4,2,60.3
union all
select 5,2,60.4
union all
select 6,3,10.0
union all
select 7,3,90.0
--select * from @tab
--select * from @tab1
select t.DepartID,max(t1.value1) as Rate
from @tab t
join @tab1 t1 on t.DepartID = t1.DepartID
group by t.DepartID
select t.DepartID,(select max(t1.value1) from @tab1 t1 where t1.DepartID = t.DepartID) as Rate
from @tab t
Result:
DepartID Rate
1 29
2 60.4
3 90
A: To be honest I don't think there's no clean way to select columns from 2 tables without a join. You could try replicate it by ordering both tables, but I think its not a good idea.
SELECT DISTINCT
DepartmentID,
BusinessEntityID,
(SELECT MAX(Rate)
FROM HumanResources.EmployeePayHistory p
WHERE p.BusinessEntityID = h.BusinessEntityID
GROUP BY BusinessEntityID
ORDER BY BusinessEntityID DESC) 'Rate'
FROM
HumanResources.EmployeeDepartmentHistory h
GROUP BY
DepartmentID,
ORDER BY
BusinessEntityID DESC
You could try Subquery in a join. This will be much cleaner
SELECT DISTINCT
h.DepartmentID,
b.Rate
FROM
HumanResources.EmployeeDepartmentHistory h join
(SELECT MAX(Rate),
BusinessEntityID
FROM HumanResources.EmployeePayHistory
GROUP BY BusinessEntityID
) p
GROUP BY
h.DepartmentID, h.BusinessEntityID
A: Can't believe I got it to work but here.
SELECT DISTINCT
DepartmentID,
(
SELECT highest
FROM
(
SELECT MAX(Rate) AS 'highest'
FROM HumanResources.EmployeePayHistory b
WHERE b.BusinessEntityID IN
(
SELECT DISTINCT
a.BusinessEntityID
FROM HumanResources.EmployeeDepartmentHistory a
WHERE a.DepartmentID = h.DepartmentID
)
) AS highest
) AS Rate
FROM HumanResources.EmployeeDepartmentHistory h;
| |
doc_23536050
|
I've tried the following:
<div class="row no-gutters flex-nowrap">
<div class="col-md col-12 d-none d-xs-block d-sm-block ">
Main area
</div>
<div class="col-md-4 col-12 sidebar">
Sidebar
</div>
</div>
.sidebar {
max-width: 600px; min-width: 600px
}
And this mostly works, but what happens is that between 768 to 576 pixels the sidebar disappears entirely.
What I'm after is for the sidebar to be a fixed width with the main area shrinking and eventually disappearing.
A: With few lines of CSS you can achieve this with Flexbox. Please have a look in snippet I added with this answer.
To know more about Flexbox you can checkout those links.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
https://yoksel.github.io/flex-cheatsheet/
.wrapper {
display: flex;
height: 100vh;
}
.sidebar {
min-width: 150px;
max-width: 150px;
height: 100%;
background: grey;
padding: 20px;
}
.content {
padding: 20px;
height: 100%;
background: lightgrey;
}
<div class="wrapper">
<div class="sidebar">
sidebar
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis modi adipisci autem illo labore ipsum numquam explicabo excepturi similique, perspiciatis doloremque, quo asperiores at veniam culpa aperiam maiores, dolores eligendi. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis modi adipisci autem illo labore ipsum numquam explicabo excepturi similique, perspiciatis doloremque, quo asperiores at veniam culpa aperiam maiores, dolores eligendi.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis modi adipisci autem illo labore ipsum numquam explicabo excepturi similique, perspiciatis doloremque, quo asperiores at veniam culpa aperiam maiores, dolores eligendi.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis modi adipisci autem illo labore ipsum numquam explicabo excepturi similique, perspiciatis doloremque, quo asperiores at veniam culpa aperiam maiores
</div>
</div>
A: I believe you're looking for this:
@media (min-width:768px) {
.sidebar {
max-width: 600px; min-width: 600px;
}
}
.sidebar {
background-color: #f5f5f5;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row no-gutters flex-nowrap">
<div class="col d-none d-md-block">
Main area
</div>
<div class="col sidebar">
Sidebar
</div>
</div>
I wrapped the fixed size rule in a @media query condition only applying on md and up and I revised classes applied to columns accordingly.
Since you're setting the custom width of your sidebar anyway, you don't need col-* classes on your columns.
| |
doc_23536051
|
The complete programs are shown in the next section. When you run the programs, they display the following output:
Route for vehicle 0:
0 -> 8 -> 6 -> 2 -> 5 -> 0
Distance of route: 1552m
Route for vehicle 1: 0 -> 7 -> 1 -> 4 -> 3 -> 0 Distance of route:
1552m
Route for vehicle 2: 0 -> 9 -> 10 -> 16 -> 14 -> 0 Distance of route:
1552m
Route for vehicle 3: 0 -> 12 -> 11 -> 15 -> 13 -> 0 Distance of
route: 1552m
Total distance of all routes: 6208m
However, when I run the example given on that page:
"""Simple Vehicles Routing Problem (VRP).
This is a sample using the routing library python wrapper to solve a VRP
problem.
A description of the problem can be found here:
http://en.wikipedia.org/wiki/Vehicle_routing_problem.
Distances are in meters.
"""
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
def create_data_model():
"""Stores the data for the problem."""
data = {}
data['distance_matrix'] = [
[
0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354,
468, 776, 662
],
[
548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674,
1016, 868, 1210
],
[
776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164,
1130, 788, 1552, 754
],
[
696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822,
1164, 560, 1358
],
[
582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708,
1050, 674, 1244
],
[
274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628,
514, 1050, 708
],
[
502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856,
514, 1278, 480
],
[
194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320,
662, 742, 856
],
[
308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662,
320, 1084, 514
],
[
194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388,
274, 810, 468
],
[
536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764,
730, 388, 1152, 354
],
[
502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114,
308, 650, 274, 844
],
[
388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194,
536, 388, 730
],
[
354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0,
342, 422, 536
],
[
468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536,
342, 0, 764, 194
],
[
776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274,
388, 422, 764, 0, 798
],
[
662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730,
536, 194, 798, 0
],
]
data['num_vehicles'] = 4
data['depot'] = 0
return data
def print_solution(data, manager, routing, solution):
"""Prints solution on console."""
print(f'Objective: {solution.ObjectiveValue()}')
max_route_distance = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
previous_index = index
index = solution.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(
previous_index, index, vehicle_id)
plan_output += '{}\n'.format(manager.IndexToNode(index))
plan_output += 'Distance of the route: {}m\n'.format(route_distance)
print(plan_output)
max_route_distance = max(route_distance, max_route_distance)
print('Maximum of the route distances: {}m'.format(max_route_distance))
def main():
"""Entry point of the program."""
# Instantiate the data problem.
data = create_data_model()
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
data['num_vehicles'], data['depot'])
# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)
# Create and register a transit callback.
def distance_callback(from_index, to_index):
"""Returns the distance between the two nodes."""
# Convert from routing variable Index to distance matrix NodeIndex.
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['distance_matrix'][from_node][to_node]
transit_callback_index = routing.RegisterTransitCallback(distance_callback)
# Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
# Add Distance constraint.
dimension_name = 'Distance'
routing.AddDimension(
transit_callback_index,
0, # no slack
3000, # vehicle maximum travel distance
True, # start cumul to zero
dimension_name)
distance_dimension = routing.GetDimensionOrDie(dimension_name)
distance_dimension.SetGlobalSpanCostCoefficient(100)
# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = (
routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
# Solve the problem.
solution = routing.SolveWithParameters(search_parameters)
# Print solution on console.
if solution:
print_solution(data, manager, routing, solution)
else:
print('No solution found !')
if __name__ == '__main__':
main()
I get the following output:
Objective: 177500
Route for vehicle 0: 0 -> 9 -> 10 -> 2 -> 6 ->
5 -> 0 Distance of the route: 1712m
Route for vehicle 1: 0 -> 16 -> 14 -> 8 -> 0 Distance of the
route: 1484m
Route for vehicle 2: 0 -> 7 -> 1 -> 4 -> 3 -> 0 Distance of the
route: 1552m
Route for vehicle 3: 0 -> 13 -> 15 -> 11 -> 12 -> 0 Distance of
the route: 1552m
Maximum of the route distances: 1712m
I'm running the latest version of the python ortools library (9.5) with Python 3.11.
So
Are the docs wrong?
Or is the code in the latest release bugged (the solution it gives is worse than the docs, so it may be a regression)?
Or is there something messed up with my local environment that is causing the difference? Is it happening for other people too?
A: These are simple examples with just a greedy descent.
The result is very dependent on how we chain local search operators. This changed in a recent release but the docs were not updated.
If you add any meta-heuristic, you will easily get the best solution.
See discussion in the issue #3570
| |
doc_23536052
|
This seems to be time consuming and is also very distracting. Do you know of an option to disable this?
A: This particular behavior comes about because of how Vim's builtin :vimgrep command works. From Vim's documentation:
To be able to do this Vim loads each file as if it is being edited.
This must be what causes the side-effect of the flashing windows. If you find this distracting, you can consider using the external grep command :grep instead of the :vimgrep command. By default, EasyGrep is configured to use :vimgrep. You can switch to :grep by setting your .vimrc with the following setting.
let g:EasyGrepCommand=1
| |
doc_23536053
|
How can i recognize which person paid me through Paypal.
I can pass any value (his mail id, name, phone number or a unique key) but i don't know how Paypal will return values to me so i can maintain user payment history in DB
is there any good forum on this ?
Please anybody help me.
A: You can use the CUSTOM parameter for that. It will hold up to 256 characters, so if you need more than one value you can do something like value1|value2|etc and then split it back up on the other end.
When you include the CUSTOM parameter in API requests or standard buttons it will come back in IPN notifications so you can automate processing utilizing that data however you need to.
| |
doc_23536054
|
So in order to do that, I created two Frames, one for menu items and the other one to display the content. Strange thing, when I initialize the frames with the given width and height the program seems to work as expected, but when I put some widgets inside the window resizes, it looks like this
Could somebody please explain this weird behaviour to me? What am I missing? Also, I would like to mention that when I add the buttons to the menu frame the width changes to fit the button width, not vice versa as I would like
app = tk.Tk()
app.resizable(False, False)
menu_frame_users = tk.Frame(app, width=200, background='red')
content_frame = tk.Frame(app, height=600, width=600, background='blue')
hello_label = tk.Label(menu_frame_users, text='Hello, User').grid(column=0, row=0, sticky='we')
view_profile_button = tk.Button(menu_frame_users, text="View Profile").grid(column=0, row=1, sticky='we')
invoices_button = tk.Button(menu_frame_users, text="Invoices").grid(column=0, row=2, sticky='we')
bookings_button = tk.Button(menu_frame_users, text="View bookings").grid(column=0, row=3, sticky='we')
tools_button = tk.Button(menu_frame_users, text="Search tools").grid(column=0, row=4, sticky='we')
test_label = tk.Label(content_frame, text='View profile')
test_label.grid(column=0, row=0, sticky='we')
menu_frame_users.grid(column=0, row=0, sticky='nswe')
content_frame.grid(column=1, row=0, sticky='nswe')
A: The frames in tkinter will only be as big as the widgets contained within unless you add weight to row and columns to make them expand.
You can get the frame to expand by setting the size of the window and then adding weight to the appropriate row and column.
app.geometry('500x400')
app.grid_columnconfigure(1, weight=1)
app.grid_rowconfigure(0, weight=1)
You can play around with the size of the window and then resize and position your buttons until you get the layout you want.
You can also use:
app.grid_columnconfigure(1, minsize=300)
However this only applies when the column contains a widget.
A: I'm not sure if I fully understand the question, but maybe this will help. Note I removed the explicit frame dimensions for the sake of the example.
import tkinter as tk
app = tk.Tk()
app.resizable(False, False)
menu_frame_users = tk.Frame(app,background='red')
content_frame = tk.Frame(app, background='blue')
app.geometry("500x500")
app.rowconfigure(0, weight=1)
app.columnconfigure(0, weight=1)
menu_frame_users.columnconfigure(0, weight=1)
hello_label = tk.Label(menu_frame_users, text='Hello, User').grid(column=0, row=0, sticky='we')
view_profile_button = tk.Button(menu_frame_users, text="View Profile").grid(column=0, row=1, sticky='we')
invoices_button = tk.Button(menu_frame_users, text="Invoices").grid(column=0, row=2, sticky='we')
bookings_button = tk.Button(menu_frame_users, text="View bookings").grid(column=0, row=3, sticky='we')
tools_button = tk.Button(menu_frame_users, text="Search tools").grid(column=0, row=4, sticky='we')
test_label = tk.Label(content_frame, text='View profile')
test_label.grid(column=0, row=0, sticky='we', padx=20, pady=20)
menu_frame_users.grid(column=0, row=0, sticky='nswe')
content_frame.grid(column=1, row=0, sticky='nswe')
app.mainloop()
Documentation for tkinter is a bit limited but there's some great info regarding grid configuration on this page.
Generally speaking, the widgets in a given container are what give the container it's dimensions, unless explicitly coded otherwise. (In other words, the frame will grow as you add things into it, not the other way around)
In your example, I added an arbitrary window size (you can also specify an offset in that string argument). My guess is you're looking for rowconfigure() and columnconfigure(). Also, you can add some padding to space things out with .grid()
I almost exclusively use the grid geometry manager, but sometimes you might find it more pragmatic to use pack() or place(), just make sure you don't use both at the same time.
Cheers.
| |
doc_23536055
|
The update statement is simple:
UPDATE table SET count = count + 1
However, the updates are very frequent (not required show updated value constantly), so that it might be appropriate to find a way to upgrade in blocks (for save connections):
Instead of +1, +1, +1, +1, +1, +1, +1, +1, +1, +1 in short time periods (every one or few seconds), make a +80 in long time periods blocks (every 5 minutes).
How I can update counter value for save frequent connections?
(Note: I see UPDATE LOW_PRIORITY in MySQL databases, I find things similar)
A: A counter is a very simple thing. You could save the number in a text file if you want. Saving to a local file is usually easier on the server than running a query on the database and it sounds like you are already interested in reducing the load on the database. Use a file block (such as flock) if you are worried about the race condition; then have a script synchronize the database with the text file(s) with the frequency you think is appropriate (perhaps using a cron job).
A: Auto-answer: I found fast and efficient system for temporary storage (instead of file):
*
*Redis: http://redis.io/ (ideally, persistent)
*Memcached: http://memcached.org/
| |
doc_23536056
|
I found several solutions on that suggest to use the PackageManager.
I think that the Intent to be used is ACTION_SEND, but when i run my code i always receive an empty List.
This is my code:
Intent mainIntent = new Intent(Intent.ACTION_SEND, null);
List<ResolveInfo> pkgAppsList = getApplicationContext().getPackageManager().queryIntentActivities( mainIntent, PackageManager.GET_RESOLVED_FILTER);
int size = pkgAppsList.size();
int i = 0;
Log.i(TAG, "Size: " + size);
for(ResolveInfo infos : pkgAppsList){
String name = infos.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString();
Log.i(TAG, "name: " + name);
}
Any idea?
A: You haven't set the MIME type for the Intent. For example:
mainIntent.setType("text/plain");
That will produce results. However, be mindful that this won't exactly return "applications capable of sending text messages", rather those that can accept a text, not necessarily for the purpose of sending a message (as an example, the Google Translate app is capable of receving text).
| |
doc_23536057
|
1) /tmp/main.sh
if [ "$output" = "1" ]; then
# here in this window the driver.sh ouput should show
dialog --msgbox "Here it should show the output of driver.sh" 10 100
configure=`/tmp/driver.sh`;
fi
2) /tmp/driver.sh
cd /tmp;
if [ ! -d "${pkgdirectory}/test" ]; then
cd ${pkgdirectory}
git clone git://code.test.com/git/test.git;
cd ${pkgdirectory}/test;
./autogen.sh;
make;
make install;
else
cd ${pkgdirectory}/test;
./autogen.sh;
make;
make install;
fi
A: dialog has a --tailbox option (and also a --tailboxbg one) that does pretty much what you need.
| |
doc_23536058
|
String[] names{ "a", "b"};
findViewById(R.drawable.names[0]);
A: EDIT: Just so you know, you can only call findViewById on R.id types. Thus, your code is bound to fail since you're calling it on R.drawable types.
Try getIdentifier(). Documentation
int resourceId = getResources().getIdentifier(names[0], "drawable", getPackageName());
findViewById(resourceId);
Note: The Android Documentation says:
use of this function is discouraged. It is much more efficient to
retrieve resources by identifier than by name.
In this case, it'll probably be better if you defined an array of int, and those contained the ids of the drawable resources.
A: No you cannot do that, but instead there is a work around for that. Try something like this:-
String[] names{ "a", "b"};
int drawableId = this.getResources().getIdentifier(names[0], "drawable", this.getPackageName());
findViewById(drawableId);
Where this is an Activity, written just to clarify.
In case you want a String in strings.xml or an identifier of a UI element, substitute the "drawable"
int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
I must warn you, this way of obtaining identifiers is really slow, use only where needed.
A: findViewById() accept int not string. So you can use like..
int[] txtViewIdsform1;
txtViewIdsform1 = new int[] { R.drawable.txt_phone1, R.drawable.txt_phone2,
R.drawable.txt_fax, R.drawable.txt_contact_name, R.drawable.txt_contact_ph};
A: No this can't be done
You can do it other way like
int[] ids={R.drawable.a,R.drawable.b};
findViewById(ids[0]);
| |
doc_23536059
|
I tried this:
::AjaxDatatablesRails::Extensions
# >> NameError: uninitialized constant AjaxDatatablesRails::Extensions
A: Module.constants.grep /AjaxDatatablesRails/
Module.constants returns an array of the names of all constants accessible from the point of call.
Enumerable#grep then loops through this array, and filters out the names matching the given pattern.
| |
doc_23536060
|
I want my app to use JSF components and also Primefaces (on frontend). But also, on backend I want to have repositories, services and managed beans and to be able to inject a @Repository into a @Servive, and also a @Service into a bean @Named and @ViewScoped.
For example:
Persistence layer:
public interface UserRepository {
List<User> getAllUsers();
}
@Repository
public class UserRepositoryImpl implements UserRepository{
@Override
public List<User> getAllUsers() {
return entityManager.createQuery("select u from User u").getResultList();
}
}
Business layer:
public interface UserService {
List<User> getAllUsers();
}
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserRepository userRepository;
@Override
public List<User> getAllUsers() {
return userRepository.getAllUsers();
}
}
Presentation layer:
@Named
@ViewScoped
public class UserManagement{
@Autowired
protected UserService userService;
protected List<User> users;
public List<User> getUsers() {
if(users.isEmpty()) {
users = userService.getAllUsers();
}
return users;
}
public void setUsers(List<User> users) {
this.users= users;
}
}
And, as view let say I have an xhtml with jsf components. For example, I have a dataTable in which I'll store all users.
I was reading this post but it is not that clear.
| |
doc_23536061
|
And I have Sellers collection and inside Sellers collection have another Fruits collection :
I want to get data in orders collection only orders collection fruit_ID equals Sellers/Fruits collection Document ID and add into recyclerview
Is it possible?
Activity class:
package com.example.freshbucket.Seller;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.widget.Toast;
import com.example.freshbucket.Adapter.OrdersSellerRecylerAdapter;
import com.example.freshbucket.Model.PlaceOrder;
import com.example.freshbucket.R;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import javax.annotation.Nullable;
import static android.support.constraint.Constraints.TAG;
public class SellerGetOrdersActivity extends AppCompatActivity {
String fid, pro;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
String user_id = mAuth.getCurrentUser().getUid();
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference orders = db.collection("Orders");
private CollectionReference sellers = db.collection("Sellers/"+user_id+"/Fruits");
private OrdersSellerRecylerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_get_orders);
setupRecyclerView();
}
private void setupRecyclerView()
{
Query query =orders.orderBy("timestamp", Query.Direction.DESCENDING).whereEqualTo("fruit_ID",fid);
FirestoreRecyclerOptions<PlaceOrder> options = new FirestoreRecyclerOptions.Builder<PlaceOrder>().setQuery(query, PlaceOrder.class).build();
adapter = new OrdersSellerRecylerAdapter(options);
RecyclerView recyclerView = findViewById(R.id.ordersReView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
//swipe delete
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
sellers.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error:" + e.getMessage());
} else {
for (DocumentSnapshot doc :queryDocumentSnapshots){
fid = doc.getId();
// pro = doc.getString("province");
// fid = doc.getString("fruit_ID");
Toast.makeText(SellerGetOrdersActivity.this, "Register error:" +fid , Toast.LENGTH_SHORT).show();
}
}
}
});
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Adapter:
package com.example.freshbucket.Adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.example.freshbucket.Model.PlaceOrder;
import com.example.freshbucket.R;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
public class OrdersSellerRecylerAdapter extends FirestoreRecyclerAdapter<PlaceOrder, OrdersSellerRecylerAdapter.OrdersSellerHolder> {
Context context;
public OrdersSellerRecylerAdapter(@NonNull FirestoreRecyclerOptions<PlaceOrder> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull final OrdersSellerHolder holder, int position, @NonNull final PlaceOrder model) {
holder.txtfruitname.setText(model.getName());
holder.txtqun.setText(model.getQun());
holder.txtcusname.setText(model.getCustomer_Name());
holder.txtaddress1.setText(model.getAddressLine1());
holder.txtaddress2.setText(model.getAddressLine2());
holder.txtcity.setText(model.getCity());
}
@NonNull
@Override
public OrdersSellerHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.order_list_item_seller,viewGroup, false);
context = viewGroup.getContext();
return new OrdersSellerHolder(v);
}
class OrdersSellerHolder extends RecyclerView.ViewHolder{
TextView txtfruitname, txtqun, txtcusname, txtaddress1, txtaddress2, txtcity;
EditText tctBprice;
public OrdersSellerHolder(@NonNull View itemView) {
super(itemView);
txtfruitname = itemView.findViewById(R.id.fruitnametext);
txtqun = itemView.findViewById(R.id.fruitquntext);
txtcusname = itemView.findViewById(R.id.cusnametext);
txtaddress1 = itemView.findViewById(R.id.addres1text);
txtaddress2 = itemView.findViewById(R.id.addres2text);
txtcity = itemView.findViewById(R.id.citytext);
}
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
}
A:
I want to get data in orders collection only orders collection
fruit_ID
OK, you want to get fruit_ID?
equals Sellers/Fruits collection Document ID and add into recyclerview
and you want to get fruit_ID, which equals with Sellers/Fruits ?
like if (fruit_ID.equals(sellerFruits_ID) {// get fruit_ID}
I will try to answer it.
PROBLEM
1. you as a seller and have your seller uid in your Sellers collection and want to get V4x1Dh..
2. You have buyer uid in your Orders collection and want to get 83Fmf..
3. You want to get Banana in Sellers/Fruits, which the Banana as id.
Lastly, you want to load datas of Sellers/Fruits into recyclerView because
you want to get data in orders collection only orders collection
fruit_ID
ANSWER
Answer number one: Please retrieve the Sellers ids and get V4x1Dh based ViewHolder position that I will explain later.
Answer number two: Please retrieve the Orders ids and get 83Fmf based ViewHolder position that I will explain later.
Answer number two: Please retrieve the Sellers Fruits ids let's say sellerFruit_ID and get Banana based ViewHolder position that I will explain later. NOTE: Since Banana in document it will be id.
DETAILS:
Retrieving the Sellers ids and get V4x1Dh:
firebaseFirestore
.collection("Sellers")
.addSnapshotListener(new EventListener<QuerySnapshot>(){
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e){
for (DocumentChange doc : documentSnapshots.getDocumentChanges()){
if (doc.getType() == DocumentChange.Type.ADDED){
// RETRIEVING Orders id
String orders_ID = doc.getDocument().getId();
YourContentOrdersHere contentOrders = doc.getDocument().toObject(YourContentOrdersHere.class).withId(orders_ID);
// RETRIEVING Sellers id
String sellers_ID = doc.getDocument().getId();
YourContentSellersHere contentSellers = doc.getDocument().toObject(YourContentSellersHere.class).withId(sellers_ID);
contentListOrders.add(contentOrders); //example: List<YourContentOrdersHere> contentList
adapter.notifyDataSetChanged(); // before of course, you add this in onCreate adapterOrders = new YourAdapterOrders(contentListOrders);
contentListSellers.add(contents); //example: List<YourContentSellersHere> contentList
adapter.notifyDataSetChanged(); // before of course, you add this in onCreate adapterSellers = new YourAdapterSellers(contentListSellers);
}
}
}
});
make sure your content class extends the ids
public class YourContentOrdersHere extends OrdersId {
// make your constructor here of course
// make your getter to get id
}
and make OrdersId.class
public class OrdersId{
@Exclude
public String OrdersId;
public <T extends OrdersId> T withId(@NonNull final String id) {
this.OrdersId = id;
return (T) this;
}
}
and last one , from your adapter class retrieving OrdersId. As Example:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// GET YOUR `Sellers` id based position and getSellerId() from getter of your content class
String sellers_ID = contentListSeller.get(position).getSellerId(); // don't forget List<YourContentSellers> contentList = new ArrayList<>();
firebaseFirestore
.collection("Sellers")
.document(sellers_ID)
.collection("Fruits")
.document("Banana")
// STORE 'LIKE TAP' USING LIKE BUTTON
holder.likeHome.seOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
/* RETRIEVING VALUE UNDER currentUserId */
firebaseFirestore.collection("Posts/" + postId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>(){
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task){
if (!task.getResult().exists()) {
/* STORE NEW VALUE */
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp);
firebaseFirestore.collection("Posts/" + postId + "/Likes").document(currentUserId).set(likesMap);
} else {
// retrieve like timestamp
String whenToLike = task.getResult().getString("timestamp");
holder.setWhenToLike(whenToLike);
/* DELETE VALUE */
firebaseFirestore.collection("Posts/" + postId + "/Likes").document(currentUserId).delete();
}
}
});
}
});
}
| |
doc_23536062
|
class ApiVIew(TemplateView):
template_name = 'payment.html'
def post(self,request):
r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
return HttpResponse(json.dumps({'response':r.json(),'status':'ok'}))
I call this class is ajax and parse there,so if r gives no error then i redirect(window.location=localhost:8000/success) to the success-payment.html page. so response gives me a json data:
{'isSuccess': 1, 'order_id': 1cq2,}
so i want to get this order_id and pass it to another function/class written below.
def payment_successfullView(request):
return render(request,'payment-successfull.html')
How can i achieve so? Thanks in advance.
A: 1. Most simple way
urls.py:
...
path('<str:order_id>/success/', views.payment_successfullView, name='success'),
...
Views:
from django.shortcuts import redirect, reverse
class ApiVIew(TemplateView):
template_name = 'payment.html'
def post(self, request):
r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
if r.isSuccess:
return redirect(reverse('success', args=(r.order_id, )))
# do your stuff in case of failure here
def payment_successfullView(request, order_id):
return render(request,'payment-successfull.html', {
'order_id': order_id,
})
2. Another method using sessions:
urls.py:
...
path('success/', views.payment_successfullView, name='success'),
...
Views:
from django.shortcuts import redirect, reverse
from django.http import HttpResponseForbidden
class ApiVIew(TemplateView):
template_name = 'payment.html'
def post(self, request):
r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
if r.isSuccess:
request.session['order_id'] = r.order_id # Put order id in session
return redirect(reverse('success', args=(r.order_id, )))
# do your stuff in case of failure here
def payment_successfullView(request):
if 'order_id' in request.session:
order_id = request.session['order_id'] # Get order_id from session
del request.session['order_id'] # Delete order_id from session if you no longer need it
return render(request,'payment-successfull.html', {
'order_id': order_id,
})
# order_id doesn't exists in session for some reason, eg. someone tried to open this link directly, handle that here.
return HttpResponseForbidden()
A: Ok, I think the best answer points you in the right direction and let you figure out the fun part.
Tips:
*
*Your APIView has to redirect to payment_successfullView
*You have the order_id so you could use a DetailView
*If you want to display a list of orders (order_id's) use ListView
I think using those tips, you'll be fine. Happy coding.
Note
You might want to read about Form views also, such view has an attribute called success_url. Ring a bell?
| |
doc_23536063
|
"local variable 'password1' referenced before assignment"
Below i Have include admin.py
from django.contrib import admin
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label= 'Password' , widget =
forms.PasswordInput)
password2 = forms.CharField(label = 'Password Confirmation', widget =
forms.PasswordInput)
class Meta:
model = CustomUser
#with my added feilds in AbstractBaseUser
fields = ('email','first_name','last_name', 'Mobile',
'Aadhar_Card', 'Address','is_supervisor','is_employee','is_driver')
def clean_password2(self):
password1 = self.cleaned_data.get(password1)
password2 = self.cleaned_data.get(password2)
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords Dont Match")
return password2
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
A: Your clean_password2 method is indeed referencing undefined variables. You need to use strings:
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
| |
doc_23536064
|
The app has the permission
<action android:name="android.intent.action.BOOT_COMPLETED" />
but apart from that nothing is ever "started".
Nevertheless the application shows up in the threads/ processes in Eclipse's LogCat after boot and the BroadcastReceivers receive the intents that they filter for.
*
*Does Android start every installed app in the background? Why is my app started after boot? - Are BroadcastReceivers active although they were not registered?
I couldnt find anything official for that.
A: Your app starts after boot up is because of the permission
Not every app had this character except for those in which this permission is added
| |
doc_23536065
|
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsactivity);
Bundle extras = getIntent().getExtras();
value= extras.getString("myid");
Intent intent = new Intent(this, newsservice.class);
intent.putExtra("behid", value);
startService(intent);
}
and in the my service fetch the image url from server,and i want Load this image on the activity ImageView,my service code is:
public class newimageService extends Service {
String Behid;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Behid= intent.getStringExtra("behid");
new HttpAsyncTask().execute("http://sample.org/shownewsimage.aspx");
//in this part show the image into image view
this.stopSelf();
return Service.START_FLAG_REDELIVERY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
how can i run the findViewByid(R.imageView) into this service method?
A: You need to set Broadcast Receiver after image successfully downloaded. Register broadcast receiver in you activity and do update your image view.
Or You can simply create Async task only. No need to create service.
A: My 1st instinct is that you should instead have the Activity bind to your service and handle the UI update on its side instead of the Service directly modifying the Activity.
See more info here:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
And an example here:
Example: Communication between Activity and Service using Messaging
| |
doc_23536066
|
jQuery("#"+this.questionId+" .QuestionText").html(...)
How would I do something similar to this for choice descriptions? Here is what I thought would work based on names in the Workflow tab:
jQuery("#"+this.questionId+" .ChoiceDescription/1").html(...)
Because there are thousands of possible questions and they have their respective choices, I would prefer to do this purely through JavaScript as I have a JSON object of all the data I need. But alternatives are welcome.
A: You need to use the correct selector. You can use your browser's inspect feature to find the correct element to update. For a PGR choice description 1 it would be:
jQuery("#"+this.questionId+" .Items li[data-choiceid=1] label>span").html(...)
| |
doc_23536067
|
A: This can be accomplished using PubNub Functions. Functions are your own scripts that run automatically in the cloud when a message is published on one or many PubNub Channels.
It has a key-value store with increment, decrement, and retrieve functionality. This can be used very intuitively with an unread message pattern on PubNub.
Channel: room.*
Event: On-Before Publish
// Access to Distributed Database
const db = require('kvstore');
export default (request) => {
// Conventionally build the Key ID based on the request parameters and channel name.
let counterId = request.channels[0] + '/' + request.params.uuid;
// Increment or Decrement the unread message counter
let method = request.message.read ? -1 : 1;
// Increment/Decrement and read the unread message counter
return db.incrCounter( counterId, method ).then(()=>{
return db.getCounter(counterId).then((counter) => {
request.message.unread = counter || 0;
return request.ok();
});
});
}
Following this official guide you can integrate this new functionality into an existing app.
| |
doc_23536068
|
<% @values.each do |val| -%>
Some stuff with <%= val %>
<% end -%>
How to do the same using Go?
A: The question is a bit unclear, but Go has a very powerful template engine built in: https://golang.org/pkg/text/template/
There's even a special HTML extension package of it that does automatic escaping based on context (attributes, tags, text, etc) - https://golang.org/pkg/html/template/
The above example would look something like:
{{ range .Values }}
Some stuff with {{ . }}
{{ end }}
| |
doc_23536069
|
Per mine understanding Views should have been marginally better than query when coming from web server. Reason is when query is executed through code in Web server, the query text needs to travel on network which is not the case in views. I believe both query(prepared statement) and Views are pre-compiled ? . So same in that sense. Is my understanding correct here ?
This resource says opposite
Performance – What may seem like a simple query against a view could
turn out to be a hugely complex job for the database engine. That is
because each time a view is referenced, the query used to define it,
is rerun.
But this is true for query also. Is not it ?
This question is for simple views not materialized/indexed view
Reference resources are
Is a view faster than a simple query?
Query vs. View
A: (Speaking about Oracle here, because that's my area of knowledge)
Views are not "pre-compiled" as such. They are simply stored text, and thus conceptually, when you run
select * from my_view
it is logically equivalent to
select * from ( [query that defines view] )
With regard to
"Reason is when query is executed through code in Web server, the query text needs to travel on network which is not the case in views"
this is true, but it is pretty rare for your web server and your database to be separated by such a bad network that a 100 byte query against a view versus a 500 byte against the base tables would be noticeable.
And finally, with respect to performance, it depends on the view. When a view is referenced in a query, there are two mechanisms that might come into play.
One is "view merging" where we can integrate the text of the view into the query as if the view never existed, eg
view: select * from t
query: select * from my_view where x=1
could be merged into:
select * from t where x=1
and thus the text of the view is never actually executed.
But another option is "view resolution" where the view is sufficiently complex or contains definitions that would prohibit it being merged. For example, a view containing a window function:
view: select t.*, row_number() over ( order by blah ) from t
query: select * from my_view where x=1
cannot be merged into:
select t.*, row_number() over ( order by blah ) from t
where x=1
because the window function would no longer return the same result. (One returns the ranking across the entire table, the other returns the ranking only for rows where x=1).
So in the case of view resolution, you could see performance implications, but simply because we need to guarantee correctness of results, not through a limitation of views in general.
| |
doc_23536070
|
The code:
import pandas
import io
s = """2,e,4,w
3,f,5,x
4,g,6,z"""
df = pandas.read_csv(io.StringIO(s))
print(df.dtypes)
df = pandas.read_csv(
io.StringIO(s),
dtype=dict.fromkeys([1, 3], pandas.StringDtype()))
print(df.dtypes)
This results in:
2 int64
e object
4 int64
w object
dtype: object
2 int64
e string
4 int64
w string
dtype: object
I'm using pandas 1.0.0rc0. Reading all as string dtype directly should prevent problems with mixed types when writing an HDFStore.
A: This is not possible in pandas 1.0. There is currently (2020-01-22) an open issue on github and an open pull request adding this feature. The feature is currently targeted for pandas 1.1:
With the new dtypes (IntegerArray, StringArray, etc.), if you want to use them when reading in data, you have to specify the types for all of the columns. It would be nice to have the option to use the new dtypes for all columns as a keyword to read_csv(), read_excel(), etc.
The exact API is still to be decided, I will update this answer when it is.
For now, you will have to pass explicitly the names of all the columns that shall be read as strings.
| |
doc_23536071
|
I have Ubuntu, and when I inserted an SD-card, it notices that it is in fact an SD card. Same counts for USB sticks.
But how can I determine on low level when a new device is inserted, what kind of type it is?
There seems to be no information to be found on this at all.
edit: just to be more complete: I said it is a Linux environment, but actually it is Android in an Embedded environment. I tagged it Linux because I am indeed trying to check from command line.
The udevadm command is not available, and lsusb -vv shows:
Bus 001 Device 001: ID 1d6b:0002
Bus 001 Device 002: ID 0424:2640
Bus 001 Device 003: ID 0424:4040
Bus 002 Device 001: ID 1d6b:0001
which is very little info.
A: The lsusb command lists the USB devices registered in the system.
Try lsusb -vv for more detailed info. You can use the -s flag to target specific device.
UPDATE:
It depends on the permissions of your account, some details require higher privileges. For example here's the output for my mouse:
Bus 003 Device 003: ID 04f3:0230 Elan Microelectronics Corp.
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 1.10
bDeviceClass 0 (Defined at Interface level)
bDeviceSubClass 0
bDeviceProtocol 0
bMaxPacketSize0 8
idVendor 0x04f3 Elan Microelectronics Corp.
idProduct 0x0230
bcdDevice 24.58
iManufacturer 0
iProduct 2 USB+PS/2 Optical Mouse
iSerial 0
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 34
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xa0
(Bus Powered)
Remote Wakeup
MaxPower 100mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 3 Human Interface Device
bInterfaceSubClass 1 Boot Interface Subclass
bInterfaceProtocol 2 Mouse
iInterface 0
HID Device Descriptor:
bLength 9
bDescriptorType 33
bcdHID 1.11
bCountryCode 0 Not supported
bNumDescriptors 1
bDescriptorType 34 Report
wDescriptorLength 52
Report Descriptors:
** UNAVAILABLE **
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0004 1x 4 bytes
bInterval 10
Device Status: 0x0000
A: It may be useful to run such a command:
$ udevadm info -a -p $(udevadm info -q path -n /dev/sdX)
The output may looks like follows:
[...]
looking at parent device '/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.5':
KERNELS=="1-1.5"
SUBSYSTEMS=="usb"
DRIVERS=="usb"
ATTRS{configuration}==""
ATTRS{bNumInterfaces}==" 1"
ATTRS{bConfigurationValue}=="1"
ATTRS{bmAttributes}=="80"
ATTRS{bMaxPower}=="200mA"
ATTRS{urbnum}=="6519"
ATTRS{idVendor}=="13fe"
ATTRS{idProduct}=="1d00"
ATTRS{bcdDevice}=="0100"
ATTRS{bDeviceClass}=="00"
ATTRS{bDeviceSubClass}=="00"
ATTRS{bDeviceProtocol}=="00"
ATTRS{bNumConfigurations}=="1"
ATTRS{bMaxPacketSize0}=="64"
ATTRS{speed}=="480"
ATTRS{busnum}=="1"
ATTRS{devnum}=="3"
ATTRS{devpath}=="1.5"
ATTRS{version}==" 2.00"
ATTRS{maxchild}=="0"
ATTRS{quirks}=="0x0"
ATTRS{avoid_reset_quirk}=="0"
ATTRS{authorized}=="1"
ATTRS{manufacturer}=="Kingston"
ATTRS{product}=="DataTraveler 2.0"
ATTRS{serial}=="5B7A08A1010F"
[...]
You can see some ATTRS that describes the device.
A:
how to determine if USB device is a USB stick
SCNR. USB devices usually do not advertise their shape. Think of:
*
*stick-based CDROM devices out there — usually in form of a mobile connections device to ship its own windows drivers
*sticks for wireless keyboard/mice/HIDs/etc, or for audio jacks
*that fat MP3 player that blocks all the other USB ports nearby
| |
doc_23536072
|
When I am using Next.JS Link somehow framer evaluate start transition point for shared item not based on the position of the element on the screen, but on the position of the element on the html.
Here is my result https://0vb1lm-3000.preview.csb.app/
And code itself: https://codesandbox.io/p/github/SweetSquid/smooth-transition
Expected behavior:
layoutId animation to follow the page scroll position and then zoom in
| |
doc_23536073
|
var expectedExperiment = new Experiment
{
Number= "12345",
AllocatedInstrument = "Instrument 1",
Experimenters = new List<Experimenter>
{
new Experimenter
{
Name = "Sue"
Role = "Scientist",
Id = 1,
Initials = "S"
},
new Experimenter()
{
Name = "Mark",
Role = "Technician",
Id = 2,
Initials = "M"
},
}
};
How can I compare it to my actual object when I only want to include certain properties on the list of child objects.
For example, I'd like to write something like this to compare all the parent object properties and some of the child object properties:
actualExperiment.ShouldBeEquivalentTo(expectedExperiment, options => options
.Including(o => o.Number)
.Including(o => o.AllocatedInstrument)
.Including(o => o.Experimenters.Select(e => e.Role))
.Including(o => o.Experimenters.Select(e => e.Name)));
But I get an exception:
System.ArgumentException : Expression <o.Experimenters.Select(e => e.Role)> cannot be used to select a member.
I don't mind in this case what order the child items are in but I want to assert that properties I care about match expectation.
A: You can do this by checking run-time type and selected member path of current object:
.Including(subjectInfo => subjectInfo.RuntimeType == typeof(Experimenter) &&
subjectInfo.SelectedMemberPath.EndsWith("Role"))
This can be extracted to a method for further reuse:
private Expression<Func<ISubjectInfo, bool>> BuildMemberExpression<TSource, TProperty>(Expression<Func<TSource,TProperty>> propertySelector)
{
var memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
{
throw new NotSupportedException();
}
return subjectInfo => subjectInfo.RuntimeType == typeof(TSource) &&
subjectInfo.SelectedMemberPath.EndsWith(memberExpression.Member.Name);
}
And now use it this way:
.Including(BuildMemberExpression((Experimenter e) => e.Name))
.Including(BuildMemberExpression((Experimenter e) => e.Role))
| |
doc_23536074
|
I have been given the following assignment and would like to learn how to see if a file or directory exists.
"Prompt the user to type in one parameter (note that this script only takes in one parameter and should report warnings/errors if the user input contains zero or multiple parameters), check if the input parameter is a filename or a directory name.
1) If the user input is a file, exit when the file is an empty file, and print the last line of the file.
2) If the user input is a directory, exit when the directory is empty, use a hash table to record the filenames inside this directory and the assess ages of these files (the number of days since the files were lastly assessed), find the oldest file (based on modification time) in the directory, and print the absolute path to this file."
I have spent the last 2 days looking a detailed explanation of how to use File::Find but cannot it. Below is my code and I'd like to replace -e $input sections with File::Find because with the -e file operator, I can only search in my current directory and not my entire system. I look forward to your replies and greatly appreciate your time.
#! /usr/bin/perl
# Assignment 9, check and read files and directories
use strict;
use warnings;
use Module1;
assnintro();
my @parameter;
my $input;
do { # This loop keeps calling pamcheck subroutine until the 1 param entered
# is a file in the directory, but I'd to expand the file test operator
# to all directories
$input = ();
@parameter = ();
pamcheck( \@parameter );
$input = $parameter[0];
if ( -e $input ) { } # Instead of simply checking current directory, I want to
# I want to see that the file exists in my system
else {
print color 'red';
print "The file or directory you entered, doesn't exist.\n";
print color 'reset';
}
} until ( -e $input );
if ( -d $input ) {
print "I am a directory.\n";
} else {
}
exit;
sub pamcheck { # This subroutine asks user to to enter a file or directory name
my ($parameter) = @_; # In the terminal, "parameters" are separated by space
my $elementcount; # Do elem ct. to make sure usr only entered 1 parameter
do {
@$parameter = ();
print "Enter one file or directory name: ";
@_ = split( /\s+/, <> ); # "Enter" key act as Ctrl D to avoid infinite
# param entry
push( @$parameter, @_ );
$elementcount = 0;
foreach (@_) {
$elementcount++;
}
if ( $elementcount != 1 ) { # Error msg if 1 param isn't entered
print color 'red';
print "Please enter only ONE parameter.\n";
print color 'reset';
} else {
}
} until ( $elementcount eq 1 ); # Loop continues until one param is entered
}
A: File::Find doesn't do what you think it does. It's based on the Unix find command which traverses a directory tree. (And may do stuff to all files in a directory tree).
The reason you need this is it's harder than you might think to do a deep traversal of a filesystem, in a world with symbolic links, mountpoints etc. Hence a utility to do it.
What File::Find will let you do is specify a chunk of code to run on e.g. each file if find.
As an example -
sub do_something {
print $File::Find::name,"\n";
}
find ( \&do_something, "." );
That aside - there's several things in your code that seems to suggest you're going off in an odd direction.
*
*counting elements in an array is much simpler by testing the array in a scalar context.
Instead of:
for ( @array ) {
$elementcount++;
}
You can just do:
my $elementcount = @array;
*
*splitting STDIN on spaces is a bit risky, because it assumes you have no filename with spaces in. But lets stick with it for now.
*NEVER assign values to @_. This is a built in variable, and messing with it can break things in strange and horrible ways.
*Why have you encapsulated the 'getting input' into a subroutine?
Anyway - assuming you need to traverse the filesystem to find your directory/files:
use strict;
use warnings;
use File::Find;
sub find_matches {
my ( $search, $results_ref ) = @_;
if ( $_ eq $search ) {
push( @$results_ref, $File::Find::name );
}
}
while (<STDIN>) {
print "Please enter directory or file name:\n";
my @parameters = split(/\s+/); #split input in one or more whitespace.
#won't work if filename includes whitespace!
unless ( scalar @parameters == 1 ) {
print "Please enter only one value\n";
next;
}
my $search_text = pop @parameters;
my @results;
find( sub { \&find_matches( $search_text, \@results ) },
"/path/to/search" );
#now results has a list of all full paths to your files.
#because you traversed, you may well have duplicates.
if ( not @results ) {
print "No matches found\n";
}
foreach my $full_file_path (@results) {
if ( -d $full_file_path ) {
print "$full_file_path is a directory\n";
# do directory stuff;
last;
}
if ( -z $full_file_path ) {
print "$full_file_path is zero length\n";
}
}
last; #breaks you out the while loop - the 'next' above will skip this line
#if you don't have a valid parameter.
}
Hopefully that should get you started? What's happening is - you're using File::Find to give you a list of matches for a text string, that you can then go through and process individually. Bear in mind that your assignment spec is unclear on what you should do if you have a directory and a file that matches, which is why I'm not convinced you need to do the traversal.
| |
doc_23536075
|
This is the AJAX call to serialize the form and post it to the controller. This code is in _Layout.cshtml:
$("#btn_SaveProfile").click(function (e) {
e.preventDefault();
var form = $("#form_UpdateProfile");
var serialized = form.serialize();
$.ajax({
url: '@Url.Action("UpdateProfile", "Account")',
data: serialized,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
type: 'POST',
success: function (data) {//This is successfully
}}).error(function (xhr, status) {
$("body").append(xhr.responseText);
})
})
This is the _Partial View:
@model UpdateProfileViewModel
<form name="form_Update" id="form_UpdateProfile" enctype="multipart/form-data"> @* method="post" action="/Account/UpdateProfile"*@
@Html.HiddenFor(m => m.Id)
<div class="modal fade" id="modalUpdateProfile" tabindex="-1" role="dialog" aria-labelledby="modalUpdateProfileLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Update Profile</h4>
</div>
<div class="modal-body">
<ul class="nav nav-tabs" style="margin-top: 15px;" id="myTab">
<li class="active"><a href="#mainProfile" data-toggle="tab" id="update_profile">Update Profile</a></li>
<li><a href="#anonymousProf" data-toggle="tab" id="anonymous_profile">Anonymous Profile</a></li>
<li><a href="#cropPhoto" data-toggle="tab" id="crop_photo">Crop Profile Photo</a></li>
<li><a href="#updatePassword" data-toggle="tab" id="change_password">Change Password</a></li>
</ul>
<div class="tab-content" style="margin-top: 15px;">
<div id="mainProfile" class="tab-pane fade in active">
<div class="form-group">
@Html.LabelFor(m => m.FirstName, new { htmlAttributes = new { @class = "control-label" } })
@Html.EditorFor(m => m.FirstName, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="form-group table-condensed">
@Html.LabelFor(m => m.LastName, new { @class = "control-label" })
@Html.EditorFor(m => m.LastName, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="form-group table-condensed">
@Html.LabelFor(m => m.IsProfilePublic, new { @class = "control-label" })
@Html.CheckBoxFor(m => m.IsProfilePublic, new { @checked = Model.IsProfilePublic })
<span class="small text-muted">(When your profile is public, others can access your achievements such as points, badges, etc.)</span>
</div>
<div class="form-group table-condensed">
@Html.LabelFor(m => m.Email, new { @class = "control-label" })
@Html.EditorFor(m => m.Email, new { htmlAttributes = new { @class = "form-control" } })
<span class="small text-muted">(Make sure your email address is valid. This is important for receiving email notifications.)</span>
</div>
<div class="form-group table-condensed">
@Html.LabelFor(m => m.ImageUploadPublic, new { @class = "control-label" })
<span class="text-muted small">(If you want to add a new photo or replace the existing photo, click "Choose File" below. Otherwise, leave this field blank.)</span>
@Html.TextBoxFor(m => m.ImageUploadPublic, new { type = "file", htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div id="anonymousProf" class="tab-pane fade">
<div class="form-group table-condensed">
@Html.LabelFor(m => m.AnonymousName, new { @class = "control-label" })
@Html.EditorFor(m => m.AnonymousName, new { htmlAttributes = new { @class = "form-control" } })
<span class="text-muted small">(used when you choose to post an entry anonymously)</span>
</div>
<div class="form-group table-condensed">
@Html.LabelFor(m => m.ImageUploadAnonymous, new { @class = "control-label" })
<span class="text-muted small">(If you want to add a new photo or replace the existing photo, click "Choose File" below. Otherwise, leave this field blank.)</span>
@Html.TextBoxFor(m => m.ImageUploadAnonymous, new { type = "file", htmlAttributes = new { @class = "form-control" } })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal" >Close</button>
<button type="button" class="btn btn-default btn-primary pull-right" id="btn_SaveProfile">Update</button>
</div>
</div>
</div>
</div>
</form>
This is the Model:
public class UpdateProfileViewModel
{
public string Id { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Display(Name = "Public Profile Photo")]
public string ProfilePhoto { get; set; }
[Required]
[DataType(DataType.Upload)]
[Display(Name = "Public Profile Photo")]
public HttpPostedFileBase ImageUploadPublic { get; set; }
[Required]
[Display(Name = "Anonymous Name")]
public string AnonymousName { get; set; }
[Display(Name = "Anonymous Profile Photo")]
public string AnonymousPhoto { get; set; }
[Required]
[DataType(DataType.Upload)]
[Display(Name = "Anonymous Profile Photo")]
public HttpPostedFileBase ImageUploadAnonymous { get; set; }
[Display(Name = "Make My Profile Public")]
public bool IsProfilePublic { get; set; }
}
And, here is the Action:
public ActionResult UpdateProfile(UpdateProfileViewModel model)
{
//Here model.ImageUploadPublic and model.ImageUploadAnonymous are empty.
}
I have spend a day to resolve this issue, but cannot figure out the mistake. Any ideas?
| |
doc_23536076
|
Caused by: org.postgresql.util.PSQLException: Connection to localhost:6432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:285)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:211)
at org.postgresql.Driver.makeConnection(Driver.java:459)
at org.postgresql.Driver.connect(Driver.java:261)
at io.debezium.jdbc.JdbcConnection.lambda$patternBasedFactory$1(JdbcConnection.java:190)
at io.debezium.jdbc.JdbcConnection.connection(JdbcConnection.java:788)
at io.debezium.jdbc.JdbcConnection.connection(JdbcConnection.java:783)
at io.debezium.connector.postgresql.connection.PostgresConnection.determineDatabaseCharset(PostgresConnection.java:431)
... 13 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
Here is the connector configuration
"config":{
"connector.class":"io.debezium.connector.postgresql.PostgresConnector",
"tasks.max":"1",
"database.hostname":"localhost",
"database.port":"6432",
"database.user":"test",
"database.password":"testpassword",
"database.dbname":"postgres",
"database.server.name":"localhost",
"transforms":"unwrap",
"transforms.unwrap.type":"io.debezium.transforms.ExtractNewRecordState",
"transforms":"route",
"transforms.route.type":"org.apache.kafka.connect.transforms.RegexRouter",
"transforms.route.regex":"([^.]+).(^.]+).([^.]+)",
"transforms.route.replacement":"$3"
}
Although the connection to database through Database manager i.e Dbeaver or Pgdmin has been successful.
| |
doc_23536077
|
My string: <?php $test = 'hello'; ?>
A: use str_replace
$test =" 'hello';"
str_replace("&apos","'",$test )
| |
doc_23536078
|
xxx-yy.biz. 39405 A 156.154.66.33
mail.global.com. 3464 A 115.113.9.64
xyx xyx xyx
webmail.xyz.com. 1463 A 115.113.9.64
gmail.com. 3464 A 115.113.9.22
I am trying to extact the URL and its IP address with string "mail" in it:
for line in (dnsfile):
match = re.search(r'(.*mail.*?)\s+(.*)\s+A\s+(.*)', line)
and match.group(1) and match.group(2) is giving me URL and IP.
I want to extent this search so that I don't want to parse public emails like: gmail, hotmail, yahoo,mail. More general : exclude a list of words in this
search.
A: You can use a negative look ahead, but you need to add the start and end anchors so you need re.DOTALL flags too (make the anchors to match from start and end of each line), you can create your negative look-ahead with joining the list of words with | :
re.search(r'^(?!{})(.*mail.*?)\s+(.*)\s+A\s+(.*)$'.format('|'.join(list_of_domin)),line,re.DOTALL)
See demo https://regex101.com/r/bF5xQ3/1
A: If it's not a requirement to have it as part of the regexp you could do a simple array search
nothanks = ['gmail.com', 'hotmail.com']
for line in (dnsfile):
match = re.search(r'(.*mail.*?)\.\s+(.*)\s+A\s+(.*)', line)
if match:
if not match.group(1) in nothanks:
print match.group(1)
| |
doc_23536079
|
Right now I have a DetailsView of a single client... what I want is that before the view is displayed, if the client doesnt have an email defined, redirect to a different page.. how can I get the data from the objectdatasource and redirect??
help please.
Here's my ObjectDataSource
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
InsertMethod="Insert" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetDataByCodigo"
TypeName="PanamaBanks.DataSetTableAdapters.ClientesTableAdapter">
<InsertParameters>
<asp:Parameter Name="Codigo" Type="String" />
<asp:Parameter Name="CodigoBanco" Type="String" />
<asp:Parameter Name="Nombre" Type="String" />
<asp:Parameter Name="Apellido" Type="String" />
<asp:Parameter Name="Negocio" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="Telefono" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:FormParameter DefaultValue="0" FormField="codigo" Name="Codigo"
Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
A: You can check emails value while DetailsView is being binded to data by attaching DataBound event like this: in aspx page
<asp:DetailsView runat="server" ID="detailsView"
ondatabound="detailsView_DataBound"></asp:DetailsView>
and in code behind
protected void detailsView_DataBound(object sender, EventArgs e)
{
DetailsView view = (DetailsView)sender;
DataRowView drv = (DataRowView)view.DataItem;
if (drv != null)
{
if (Convert.IsDBNull(drv["Email"]))
//redirect - email column has null value
Redirect();
if (drv["Email"].ToString().Trim() == string.Empty)
//redirect - email column is empty
Redirect();
}
}
A: Do this in your codebehind. Check for a null value in the email field, and redirect if found. Something like this (C#):
if(client.email==""){
HttpContext.Current.Response.ReDirect("differentPage.aspx");
}
| |
doc_23536080
|
If value is true I would render this template part
$(go.TextBlock, { row: 1, column: 0, font: '12px \'Open Sans\'', margin: 3, stroke: '#707070' }, $localize`:@@step-view-4: Paramètres:`),
$(go.TextBlock, { row: 1, column: 1, font: '12px \'Open Sans\'', margin: 3, stroke: '#707070' }, new go.Binding('text', 'Apple')),
$(go.TextBlock, { row: 2, column: 0, font: '12px \'Open Sans\'', margin: 3, stroke: '#707070' }, 'Input:'),
$(go.TextBlock, { row: 2, column: 1, font: '12px \'Open Sans\'', margin: 3, stroke: '#707070' }, new go.Binding('text', 'InputValue')),
if not I would render:
$(go.TextBlock, { row: 1, column: 0, font: '12px \'Open Sans\'', margin: 3, stroke: '#707070' }, $localize`:@@step-view-4: Banana:`),
$(go.TextBlock, { row: 1, column: 1, font: '12px \'Open Sans\'', margin: 3, stroke: '#707070' }, new go.Binding('text', 'BananaValue')),
I have a first solution is to render two different templates depending on item value
But I would like to use only one template.
A: You can wrap template into a Panel and bind to GraphObject's property "visible" with a convertion function.
See: GoJS API - Class Binding
For example (not tested, just schematic):
var displTempl = true;
$( go.Panel, {},
$(go.TextBlock,
{row: 2,column: 0,font: "12px 'Open Sans'",margin: 3,stroke: "#707070"},
"Input:"
),
$(go.TextBlock,
{ row: 2, column: 1, font: "12px 'Open Sans'", margin: 3, stroke: "#707070" },
new go.Binding("text", "InputValue")
),
new go.Binding("visible", false, (obj) => {
return this.displTempl;
})
)
| |
doc_23536081
|
A: There are several options you have. You can use Amazon Textract which is exactly what you want
https://aws.amazon.com/blogs/machine-learning/automatically-extract-text-and-structured-data-from-documents-with-amazon-textract/
You can also attempt to build your own code with a starting point as
https://medium.com/@datamonsters/text-preprocessing-in-python-steps-tools-and-examples-bf025f872908
| |
doc_23536082
|
What is the right approach to add the databse to my project so that I could execute the program without any database errors?
The project was executing properly before I moved the project to another location. Now I have again moved the project back to the old location.
| |
doc_23536083
|
bin/logstash -f logstash-test.conf
Conf File content is below:
input{
file
{
path=> "/home/abhinav/ELK/logstash/testfile.txt"
type => "test"
start_position => "beginning"
}
}
output{
elasticsearch { host => localhost
index => "test_index"
}
stdout { codec => rubydebug }
}
The ElasticSearch Log shows the follwing error:
[2015-05-04 14:52:23,082][INFO ][cluster.service ] [Argo]
added
{[logstash-abhinav-HP-15-Notebook-PC-10919-4006][CPk1djqFRnO-j-DlUMJIzg][abhinav-HP-15-Notebook-PC][inet[/192.168.1.2:9301]]{client=true,
data=false},}, reason: zen-disco-receive(join from
node[[logstash-abhinav-HP-15-Notebook-PC-10919-4006][CPk1djqFRnO-j-DlUMJIzg][abhinav-HP-15-Notebook-PC][inet[/192.168.1.2:9301]]{client=true,
data=false}])
I tried following things:
Tried with simple std input(stdin) to ES n stdout . It worked.
A: If you are using the same file repeatedly to test with, you are running into the "sincedb" problem -- see How to force Logstash to reparse a file?
You need to add sincedb_path => "/dev/null" to your file input. Generally this is not needed in a production scenario, but it is when testing.
A: I have found solution to my problem and also found things we can check, if logstash & ES not working/communicating properly. :
*
*Make sure ES & Logstash are properly installed
*Versions installed are compatible with each other
*Even while testing, try making different Logstash conf file for different test case, as suggested by Mr. Alcanzar in above comment.
You can also refer to below links , for help regarding this issue :
Cannot load index to elasticsearch from external file, using logstash
https://logstash.jira.com/browse/LOGSTASH-1800
| |
doc_23536084
|
MQTT offers the concept of persistent sessions meaning that former subscriptions are kept and messages with qos > 0 are queued while a client is disconnected. That means for my client implementation I could skip subscribing after connecting to the broker, except for the very first time.
The question is: how can I be sure that my subscriptions are still there? I imagine that there could be a case where a new server is started which has no information about my former session and thus my subscriptions.
A: To contradict my co-answerers, MQTT v3.1.1 provides a mechanism for the broker to tell a client that is reconnecting that a session was restored. This is the "session present" flag provided during the CONNACK message.
Clients/brokers that say they support MQTT v3.1.1 should support this flag. For example, the Paho 1.0 clients should all do so (the Python client certainly does) and the upcoming 1.4 release of mosquitto adds support for this flag to its existing support for MQTT v3.1.1.
It's also worth noting that this is a useful feature now that MQTT v3.1.1 requires that retained messages be transmitted on each SUBSCRIBE, regardless of whether a subscription existed previously.
A: Brokers implementing persistent sessions should be storing that info to disk/db so it survives over a restart. Enterprise brokers (e.g. IBM MQ) can even federate this information across multiple broker instances to provide fail over.
Having said that, what do you actually save by skipping requesting the subscription again?
A: There is no way in MQTT protocol specification to know if your subscriptions are there.
It depends on the broker : it could support a permanent storage to save persistent subscriptions to avoid lost them in the case of a fault (shutdown).
On the client side, based on the protocol, you know that with clean session = FALSE in connect message you don't need to subscribe on next reconnection. It doesn't depend on you but by broker.
Paolo.
A: You can't be sure, which is why I recommend subscribing to the topics you're interested in at the start of the application every time, also when connecting with clean_session = False.
| |
doc_23536085
|
However I noticed that the only thing that happens in my subclass is that it calls super(), with the control type set to 'button'. Button also makes certain control properties become mandatory. It feels wrong. Should I really be using a subclass? What would be the good OOP way for doing this?
interface ControlOptions {
type: string;
label?: string;
onClick?: () => void; // optional here
submit?: boolean;
transition?: Transition
}
class Control {
constructor(options: ControlOptions) {
}
// Some methods left out for brevity.
}
interface ButtonOptions {
label: string
onClick: () => any // mandatory here
submit?: boolean
transition?: Transition
}
// should this be a subclass?
class Button extends Control {
constructor(options: ButtonOptions) {
let controlProps = { type: 'button', ...options };
super(controlProps);
if (options.transition) {
options.transition.setSource(this);
}
}
}
A: Seems ok to me. Just because the subclass only has a small amount of changes doesn't mean it's not necessary or wrong. I quite often create classes that are very small or hardly do anything.
Also, having a subclass enforce certain data being passed to it be mandatory is perfectly fine in this case because the base class allows for it—the base class expects a value or undefined, so it's ok to just pass it a value from the sub class. On the other hand, having the base class expect a value and making it optional in the sub class would indeed be wrong and a compile error.
I'd recommend these changes for brevity though:
interface ControlOptions {
label?: string;
onClick?: () => void;
submit?: boolean;
transition?: Transition;
}
class Control {
constructor(type: string, options: ControlOptions = {}) {
}
}
interface ButtonOptions extends ControlOptions {
onClick: () => void; // make mandatory
}
class Button extends Control {
constructor(options: ButtonOptions) {
super('button', options);
if (options.transition) {
options.transition.setSource(this);
}
}
}
Or alternatively:
class Control {
constructor(options: { type: string; } & ControlOptions) {
}
}
class Button extends Control {
constructor(options: ButtonOptions) {
super({ type: 'button', ...options });
// etc...
}
}
| |
doc_23536086
|
package com;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import xtrim.util.i;
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.DfQuery;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfLoginInfo;
import com.documentum.fc.common.IDfLoginInfo;
public class Adlookup {
IDfSessionManager sessionMrg = null;
IDfSession session=null;
IDfClient dfclient = null;
IDfClientX clientX = new DfClientX();
IDfCollection total = null;
int j;
int flag = 0;
WriteToExcel ex = new WriteToExcel();
public void LookupReport(String docbaseName, String username, String password) throws DfException, IOException
{
dfclient = clientX.getLocalClient();
String Docbase = docbaseName;
IDfLoginInfo loginInfo = new DfLoginInfo();
loginInfo.setUser(username);
loginInfo.setPassword(password);
sessionMrg = dfclient.newSessionManager();
sessionMrg.setIdentity(Docbase, loginInfo);
session = sessionMrg.getSession(Docbase);
System.out.println("connection created for adlookup");
String query = Getquery();
IDfQuery dql = new DfQuery();
dql.setDQL(query);
total = dql.execute(session, IDfQuery.DF_EXEC_QUERY);
System.out.println("all good for lookup");
//String[] columnNames = new String[] { "User Name","User Login Name","Email"};
List<String> lstValues = new ArrayList<String>();
Map<Integer, ArrayList<String>> myMap = new HashMap<Integer, ArrayList<String>>();
while (total.next())
{
lstValues.add(total.getString("uname")+","+total.getString("loginname")+","+total.getString("uadd"));
myMap.put(flag, (ArrayList<String>) lstValues);
flag++;
System.out.println("Flag value: " +flag);
// lstValues.clear();
}
Set setofKeys = myMap.keySet();
Iterator itr = setofKeys.iterator();
while(itr.hasNext())
{
Integer key = (Integer) itr.next();
ArrayList<String> value = myMap.get(key);
System.out.println("\nResult :"+value);
}
}
private String Getquery() {
// TODO Auto-generated method stub
String query = "select user_name as uname, user_login_name as loginname, user_address as uadd from dm_user dmu, dm_dbo.MV_V_MIDAS_MERCK_PRSN1 dma where upper(dmu.user_login_name)=upper(dma.isid) and dmu.user_state=0 and directory_display_ind='I'";
return query;
}
}
I'm getting output like this
Result :
[Sayre,Joseph,sayrej,joseph.sayre@abc.com, Kapoor,Rohit,kapoorro,rohit.kapoor@abc.com, Pineiros-Vallejo, Miguel,pineirom,rajendra.baxi@abc.com]
Result :[Sayre,Joseph,sayrej,joseph.sayre@abc.com, Kapoor,Rohit,kapoorro,rohit.kapoor@abc.com, Pineiros-Vallejo, Miguel,pineirom,rajendra.baxi@abc.com]
Result :[Sayre,Joseph,sayrej,joseph.sayre@abc.com, Kapoor,Rohit,kapoorro,rohit.kapoor@abc.com, Pineiros-Vallejo, Miguel,pineirom,rajendra.baxi@abc.com]
but I want something like this :
Result : Sayre,Joseph,sayrej,joseph.sayre@abc.com
Result : Kapoor,Rohit,kapoorro,rohit.kapoor@abc.com
Result : Pineiros-Vallejo, Miguel,pineirom,rajendra.baxi@abc.com
Also I need to print this values in an excelsheet.
Any kind of help will appreciated.
A: Instead of using toString() on the ArrayList itself, iterate over its contents and print the individual members. Add another loop inside the while(itr.hasNext()) loop.
A: If the content of the ArrayList are attributes of a user, then why don't you create a class UserAttributes having fields to store the values and overrides toString() to output them?
A: I'd create an object "user" with fields for each entry:
lstValues.add(total.getString("uname")+","+total.getString("loginname")+","+total.getString("uadd"));
to
lstValues.add(new User(total.getString("uname"), total.getString("loginname"), total.getString("uadd")));
Then override toString() inside the User object.
Tip:
You can also use map.entrySet() to iterate.
Your code:
Set setofKeys = myMap.keySet();
Iterator itr = setofKeys.iterator();
while(itr.hasNext())
{
Integer key = (Integer) itr.next();
ArrayList<String> value = myMap.get(key);
System.out.println("\nResult :"+value);
}
My Code:
Map<Integer, User> map = new HashMap<>();
for( Entry<Integer, User> entry : map.entrySet() ) {
entry.getKey();
entry.getValue(); // the user object you want
}
A: Use advanced for to display the String value like below,
while(itr.hasNext())
{
Integer key = (Integer) itr.next();
ArrayList<String> value = myMap.get(key);
System.out.print("\nResult : ");
for(String strValue:value){
System.out.println(strValue + ",");
}
}
Thanks
Raju
A: Instead of
while(itr.hasNext())
{
Integer key = (Integer) itr.next();
ArrayList<String> value = myMap.get(key);
System.out.println("\nResult :"+value);
}
use this
while (total.next) {
System.out.println("\nResult :"
+ itr.getString("uname") + ", "
+ itr.getString("loginname") + ", "
+ itr.getString("uadd") );
}
EDIT: switched from using itr object to total object. I see you are using IDfCollection total for adding some flag which you don't use later anywhere. Lose everything and just loop through collection total. Your code is big mixture of your temporarily ideas that survived when you changed your mind. Change your code. :)
| |
doc_23536087
|
[Update: Responding to the first comment here because the max comment length is too short.]
If you successfully play a movie on iOS4, you get:
*
*MPMoviePlayerContentPreloadDidFinishNotification with no error object (deprecated)
*MPMoviePlayerLoadStateDidChangeNotification and player.loadState=MPMovieLoadStatePlayable
*MPMoviePlayerPlaybackDidFinishNotification and player.loadState=MPMovieLoadStatePlaythroughOK
If it fails (for instance because of an incorrect URL), you get:
*
*MPMoviePlayerPlaybackDidFinishNotification loadState=MPMovieLoadStateUnknown
And that's it. No MPMoviePlayerContentPreloadDidFinishNotification with an error object like in 3.0, no MPMoviePlayerLoadStateDidChangeNotification. So is the only way to detect a failed load to inspect the player.loadState for MPMovieLoadStateUnknown in MPMoviePlayerPlaybackDidFinishNotification?
It seems counterintuitive, to say the least.
A: Register for the MPMoviePlayerLoadStateDidChangeNotification notification, and then check the loadState property of the MPMoviePlayerController.
Source: ADC Developer Documentation
| |
doc_23536088
|
The program is a retirement calculator and I am having an issue with the code not flowing directly into the next code that I wrote.
System.out.println("What investment style best suits your needs? i.e.(Very Aggressive, Aggressive, Moderate, Conservative)");
String investmentstyle = scanner.toString();
if (investmentstyle == "Very Aggressive") {
System.out.println("With this type of fund, almost 100% of your funds would go towards stocks. you could expect a 12% rate of return on your investment.");
}
else if (investmentstyle == "Aggressive") {
System.out.println("With this type of fund, 75% of your funds would go towards stocks and 25% would go towards bonds. You could expect a 9% rate of return on your investment.");
}
else if (investmentstyle == "Moderate") {
System.out.println("With this type of fund, 50% of your funds would go towards stocks and 50% would go towards bonds. You could expect a 6% rate of return on your investment.");
}
else if (investmentstyle == "Conservative") {
System.out.println("With this type of fund, 25% of your funds would go towards stocks and 75% would go towards bonds. You could expect a 3% rate of return on your investment.");
}
System.out.println("Please enter the expected return rate that is in accordance with the investment style you have chosen.\n Make sure you don't enter the percentage sign (%).");
double interestrate = scanner.nextDouble();
As you can see here, I am asking the user what type of fund he/she would be interested in. I want that input to be processed by the if/else to display the statement that correlates to the fund they chose. As of now, when I run the program it completely bypasses the if/else and moves on to then next question I ask. How would I go about fixing this?
As always, any and all help is appreciated. Thank you in advance!
A: == compares the object reference of the two strings. In order to compare two string character by character you need to use equals()
Example:
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1.equals(s2)); // True
A: == checks if the two references point at the same object, where the method equals will actually check for equality in your case:
if ("Very Aggressive".equals(investmentstyle)) {
System.out.println("With this type of fund, almost 100% of your funds would go towards stocks. you could expect a 12% rate of return on your investment.");
}
else if ("Aggressive".equals(investmentstyle)) {
System.out.println("With this type of fund, 75% of your funds would go towards stocks and 25% would go towards bonds. You could expect a 9% rate of return on your investment.");
}
else if ("Moderate".equals(investmentstyle)) {
System.out.println("With this type of fund, 50% of your funds would go towards stocks and 50% would go towards bonds. You could expect a 6% rate of return on your investment.");
}
else if ("Conservative".equals(investmentstyle)) {
System.out.println("With this type of fund, 25% of your funds would go towards stocks and 75% would go towards bonds. You could expect a 3% rate of return on your investment.");
}
A: *
*String investmentstyle = scanner.nextLine();//To Fetch Whole Line
As you are looking for comparison with String which contains space .
*if (investmentstyle.equalsIgnoreCase("Very Aggressive")) { because it will allow user to enter data irrespective of case.
You will love to read answers of How Do I compare Strings in Java
A: if (investmentstyle == "Very Aggressive") // wrong. use .equals() instead of "=="
A: Do not use == to check string equality.
Use switch case instead:
switch(investmentstyle) {
case "Very Aggressive":
// do something
break;
case "Aggressive":
// do something
break;
// ...
default: // do nothing
}
| |
doc_23536089
|
#include <string>
int main() {
char s2;
s2 = '1' - '0';
std::cout << s2;
std::cout << std::endl;
std::cout << '1' - '0';
std::cin >> s2;
}
The output produced is:
☺
1
My question is, why are the two lines different? I expected and wanted both results to be 1. By my understanding they should be the same but that is obviously wrong, could somebody please explain this to me? Thank you
A:
why are the two lines different?
The type of the first expression (s2) is char. The type of the second ('1' - '0') is int.
This is why they are rendered differently even though they have the same numeric value, 1. The first is displayed as ASCII 1, whereas the second is displayed as the number 1.
If you are wondering why '1' - '0' gives an int, see Addition of two chars produces int
A: s2 is char, '1'-'0' is int.
so it types the char value of 1 which is the smile, and 1 for the int value.
A: Type of s2 is char, std::cout << s2 will call std::ostream::operator<<(char) to echo a ASCII character 1 (smile);
'1' - '0' is interpreted as a int value, so std::ostream::operator<<(int) will be called and integer 1 will be printed.
| |
doc_23536090
|
However the return I get for each parameter is 'undefined'.
The code I am using is below (this is referenced as external JS doc in the HTML head):
function navigator(){
alert("YOUR COMPUTER INFO SIR: \n\nBrowser Code Name: " + navigator.appCodeName + "\nBrowser Name: " + navigator.appName + "\nBrowser Version: " + navigator.appVersion + "\nCookies Enabled: " + navigator.cookieEnabled + "\nPlatform: " + navigator.platform + "\nUser-agent header: " + navigator.userAgent + "\nUser-agent language: " + navigator.systemLanguage );
}
I am calling the function in the HTML body as:
<input type="button" onclick="navigator()" value="Click Me to get your computer Info!"/>
And the data is returned as:
YOUR COMPUTER INFO SIR:
Browser Code Name: undefined
Browser Name: undefined
Browser Version: undefined
Cookies Enabled: undefined
Platform: undefined
User-agent header: undefined
User-agent language: undefined
Any ideas?
Update:
Thanks, Renamed the function as suggested to navigatorInfo and got data returned as follows:
Browser Code Name: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.29.13 (KHTML, like Gecko) Version/6.0.4 Safari/536.29.13
Cookies Enabled: true
Platform: MacIntel
User-agent header: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.29.13 (KHTML, like Gecko) Version/6.0.4 Safari/536.29.13
User-agent language: undefined.
However I am using a Safari browser and the Browser returned is Mozilla....
UPDATE:
OK, got it, thanks for the help....
http://www.quirksmode.org/js/detect.html
A: navigator is an object that exists in browsers. You must rename your function to something other than navigator like navigatorInfo or something.
A: OK, got it, thanks for the help....
http://www.quirksmode.org/js/detect.html
| |
doc_23536091
|
Using "required": ["snapshots"] together with "additionalProperties": False I managed to allow only the key "snapshots", but doing that analogous for the dictionary value of the key "string" ("required": ["source","dest", "keep"]) didn't add the desired constraints to my json config.
I tested latter, by changing e.g. the key "source" to "somethingElse" in my config.json file, but jsonschema.validate() didn't raise any errors, though I expected it to.
schemaTest.py:
import json
from jsonschema import validate
schema = {
"$schema": "http://json-schema.org/schema",
"required": ["snapshots"],
"additionalProperties": False,
"properties":
{
"snapshots":
{
"type": "object",
"properties":
{
"string":
{
"type": "object",
"items": { "type": "string" },
"uniqueItems": True,
"properties":
{
"source": {"type": "string"},
"dest": {"type": "string"},
"keep": {"type": "string"}
},
"required": ["source","dest", "keep"],
"additionalProperties": False
}
}
}
}
}
path = "/home/user/test/config.json"
jsonConfig = json.load(open(path))
print(validate(jsonConfig, schema))
config.JSON:
{
"snapshots":
{
"@snapshot1":
{
"source": "/mnt/subvolContainer/@snapshot1",
"dest": "/mnt/subvolContainer/",
"keep": "w=10,m=10"
},
"@snapshot2":
{
"source": "/mnt/subvolContainer/@snapshot2",
"dest": "/mnt/subvolContainer/",
"keep": "w=10,m=10"
}
}
}
A: You have some extra layers of nesting inside the definition of your snapshot object. string, for example, is not a property name you are using. To validate properties of the children of unknown keys in an object, you need to put your types inside the additionalProperties object. items and uniqueItems apply to arrays, not objects.
This works:
schema = {
"$schema": "http://json-schema.org/schema",
"required": ["snapshots"],
"additionalProperties": False,
"properties":
{
"snapshots":
{
"type": "object",
"additionalProperties":
{
"type": "object",
"properties":
{
"source": {"type": "string"},
"dest": {"type": "string"},
"keep": {"type": "string"}
},
"required": ["source","dest", "keep"],
"additionalProperties": False
}
}
}
}
| |
doc_23536092
|
Github Code
In my SecondActivity class, when someone choose english for example.
LocaleHelper.setLocale(this, "en")
recreate()
But my issue is how to change MainActivity in english
A: UPDATE
Found a Solution by creating a new class for every Activity. You should make a new class for every activity, to take the instance of objects of Activities. After that work with cases. If something change call the setLocale(this, "languageCode"). Define this to your Activity class.
fun setLocale(activity: Activity, languageCode: String?) {
val locale = Locale(languageCode)
Locale.setDefault(locale)
val resources = activity.resources
val config = resources.configuration
config.setLocale(locale)
resources.updateConfiguration(config, resources.displayMetrics)
}
Make a new class like this:
public class Main {
public Main(MainActivity act, String s) {
act.setLocale(act,s);
}
}
and then call it like this when changes happen:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var lang = SettingsActivity()
if (lang.STH_CHANGE) {
if (lang.ENGLISH) {
val myobj = Main(this, "en")
}
if (lang.GREEK) {
val myobj = Main(this, "gr")
}
}
setContentView(R.layout.activity_main)
SettingsActivity() is my Activity where there is a button which changes to English-Greek.
| |
doc_23536093
|
r.Route("/api/v1", func(r chi.Router) {
r.Route("/case", func(r chi.Router) {
// generic case - for everyone
r.Get("/{uuid}", caseGetByUuid)
r.Put("/", casePut)
// all cases only available to admins
// r.Use(ensureAdminUser) // ← this is the place I have an error
r.Get("/", caseGetAll)
}
// admin endpoint
r.Route("/admin", func(r chi.Router) {
// ensure that the user is an admin
r.Use(ensureAdminUser)
r.Route("/user", func(r chi.Router) {
r.Route("/token", func(r chi.Router) { // /admin/user/token
r.Get("/", userTokenGetAll)
r.Put("/", userTokenCreate)
r.Delete("/", userTokenDelete)
})
})
})
})
The second route (/admin) is restricted by a middleware that will break the chain if specific constraints are not met. The middleware is placed ahead of all the routes.
I wanted to do similar filtering in the first route (/case), but only for one route (out of the three). Uncommenting r.Use(ensureAdminUser) leads to
panic: chi: all middlewares must be defined before routes on a mux
I cannot have two routes for /case either.
Is there a way to keep the route /case and restrict one of the methods for the root call?
If not I will create an alternative route for the restricted case.
A: You can wrap the middleware and subsequent routes in their own group (emphasis mine):
// Group adds a new inline-Router along the current routing
// path, with a fresh middleware stack for the inline-Route.
Group(fn func(r Router)) Router
r.Route("/api/v1", func(r chi.Router) {
r.Route("/case", func(r chi.Router) {
// generic case - for everyone
r.Get("/{uuid}", caseGetByUuid)
r.Put("/", casePut)
// all cases only available to admins
r.Group(func(r chi.Router) {
r.Use(ensureAdminUser)
r.Get("/", caseGetAll)
})
}
})
It will work also with a sub-router with r.Route.
Another option when a middleware is applied to only one route is r.With which allows you to “inline” the middleware:
r.Route("/api/v1", func(r chi.Router) {
r.Route("/case", func(r chi.Router) {
// generic case - for everyone
r.Get("/{uuid}", caseGetByUuid)
r.Put("/", casePut)
// all cases only available to admins
r.With(ensureAdminUser).Get("/", caseGetAll)
}
})
| |
doc_23536094
|
I wrote this matcher, but don't quite know how to integrate it into the test.
public static Matcher<View> withListSize (final int size) {
return new TypeSafeMatcher<View> () {
@Override public boolean matchesSafely (final View view) {
return ((ListView) view).getChildCount () == size;
}
@Override public void describeTo (final Description description) {
description.appendText ("ListView should have " + size + " items");
}
};
}
A: There are two different approaches of getting items count in a list with espresso:
First one is as @CoryRoy mentioned above - using TypeSafeMatcher, the other one is to use BoundedMatcher.
And because @CoryRoy already showed how to assert it, here I'd like to tell how to get(return) the number using different matchers.
public class CountHelper {
private static int count;
public static int getCountFromListUsingTypeSafeMatcher(@IdRes int listViewId) {
count = 0;
Matcher matcher = new TypeSafeMatcher<View>() {
@Override
protected boolean matchesSafely(View item) {
count = ((ListView) item).getCount();
return true;
}
@Override
public void describeTo(Description description) {
}
};
onView(withId(listViewId)).check(matches(matcher));
int result = count;
count = 0;
return result;
}
public static int getCountFromListUsingBoundedMatcher(@IdRes int listViewId) {
count = 0;
Matcher<Object> matcher = new BoundedMatcher<Object, String>(String.class) {
@Override
protected boolean matchesSafely(String item) {
count += 1;
return true;
}
@Override
public void describeTo(Description description) {
}
};
try {
// do a nonsense operation with no impact
// because ViewMatchers would only start matching when action is performed on DataInteraction
onData(matcher).inAdapterView(withId(listViewId)).perform(typeText(""));
} catch (Exception e) {
}
int result = count;
count = 0;
return result;
}
}
Also want to mention that you should use ListView#getCount() instead of ListView#getChildCount():
*
*getCount() - number of data items owned by the Adapter, which may be larger than the number of visible views.
*getChildCount() - number of children in the ViewGroup, which may be reused by the ViewGroup.
A: Figured this out.
class Matchers {
public static Matcher<View> withListSize (final int size) {
return new TypeSafeMatcher<View> () {
@Override public boolean matchesSafely (final View view) {
return ((ListView) view).getCount () == size;
}
@Override public void describeTo (final Description description) {
description.appendText ("ListView should have " + size + " items");
}
};
}
}
If expecting one item in the list, put this in the actual test script.
onView (withId (android.R.id.list)).check (ViewAssertions.matches (Matchers.withListSize (1)));
| |
doc_23536095
|
I want the image for full screen.
can someone help me with that?
thanks
A: *
*In your case ImageBackground should be most parent view of all the views here. It seems like your toolbar is wrapped with ImageBackground or with its parent.
*Another reason can be possible if your Toolbar has an white background, then how will this image be visible. So make Toolbar transparent.
A: It's seems you are using React-navigation, if so, you can modify your StackNavigator to not display the header:
createStackNavigator({
PageName: { screen: PageName },
// all your routes
},
{
headerMode: 'none', --> here
})
You will find more informations in the react-navigation doc
A: Thanks, Everyone for your time to answer I have solved the issue by adding some styles to my image and also making the header to null.
static navigationOptions={
header:null
}
| |
doc_23536096
|
How can I fix this?
A: Actually redis session state provider does use a connection multiplexer keeping a very low number (like 2 or 3) of open connection for the application. The racking up was because of a third party dll...
| |
doc_23536097
|
It looks like [1 2 ... given number]
thanks!
A: NetLogo has primitive for that called n-values. Very simply:
n-values 10 [ ? + 1 ]
will give you the list:
[1 2 3 4 5 6 7 8 9 10]
But there is plenty of other neat stuff you can do with n-values. You should take a look at the documentation.
Update:
NetLogo 6.0 now has the range primitive which can be used for the same purpose:
observer> print (range 1 11)
[1 2 3 4 5 6 7 8 9 10]
| |
doc_23536098
|
Example:
Regex: (.{1,}-)(.{1,}-)(.{1,}-)(\d{4,4})
Good input: A-AAAA-A-0001
Bad input: A-AAAA-A-00011
My Regex fails, it picks up A-AAAA-A-0001 from both inputs
A: The following regex will pick up matches from inside of a string (i.e. it will find matching substrings):
(?<=\s|^)([^\s]+-){3}(\d{4})(?=\s|$)
The following will pick up matches for the whole string only
^([^\s]+-){3}(\d{4})$
I've simplified your regex a bit, but made the assumption that you weren't using each group of characters for something.
I turned your:
(.{1,}-)(.{1,}-)(.{1,}-)
Into
([^\s]+-){3}
Which says "match anything that isn't whitespace and ends with a dash exactly 3 times. The '+' operator is shorthand for saying {1,] or "at least once".
Can we be more specific?
I suspect that you're probably only wanting to match alphanumeric values. For example, I'm doubting that $-A%^A-@-0001 is a valid match for you. If I'm right about this, you'll want to use a shorthand character class, which would make your regex look like this instead (I'm assuming your regex is case sensitive):
Match Substrings:
(?<=\s|^)([A-Za-z\d]+-){3}(\d{4})(?=\s|$)
Match Whole Strings:
^([A-Za-z\d]+-){3}(\d{4})$
A couple of pointers:
*
*Instead of specifying {4,4} to say "exactly 4 times", just use
{4}
*Instead of specifying {1,} to say "1 or more times", just use
+
*(?={regex in here}) means, look ahead in the string and match the following, but don't add it to my result (it's called a positive lookahead)
*(?<={regex in here}) means, look backwards in the string and match the following, but don't add it to my result (it's called a positive lookbehind)
*There are also negative lookarounds that do the opposite, but I'll leave that to you to research.
A: Anchor your regular expression with ^ and $ for beginning and end of a string correspondingly.
If it's not the whole string then the negative lookahead assertion would help you (?!\d)
References:
*
*http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx (search for "negative lookahead assertion" string)
A: Firstly, I'd advise you to simplify your Regex a little bit. My suggestion is:
(\w+-){3}(\d{4})
Since you have 3 groups of word characters followed by a - sign, this is pretty straightforward.
Now, in order to capture only those desired matches, if you are testing exactly those strings, you only need to add the ^ and $ delimiters.
^(\w+-){3}(\d{4})$
Please check this Regex101 link to see it in action.
| |
doc_23536099
|
I would like to display Months on the X-Axis and Expenses in Y-Axis, and I would like to fetch data from database for the particular category like Food, Personal Expenses etc.. and fetch the graph according to the data.
Please refer the below website code .
http://androidplot.com/wiki/Quickstart
How can I pass List data which is fetched from database(SQLite) to the variables?
Number[] series1Numbers = {1, 8, 5, 2, 7, 4};
Number[] series2Numbers = {4, 6, 3, 8, 2, 10};
A: fetch the data and store in an Int[] and then pass this int array wherever you are using series1Numbers and series2Numbers because the Number class is nothing but an int array.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.