source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0017349167.txt"
] | Q:
Stopping a Fabric Task From Running
The method I currently use if one fabric task fails on one of my servers is
to
try:
sudo(...)
except SystemExit():
raise Exception("You should fix this with...")
However, this leaves an unpleasant stack trace from the exception when all I want to do is print the message from the exception. However, if I don't throw this exception then the fabric script will continue to run on my other servers when I want it to stop.
Is there a way to stop all fabric tasks?
A:
If I understand you correctly, you want to stop execution of script on all servers with log message, but no stacktrace. You can do it with:
import sys
try:
sudo(...)
except SystemExit():
print "You should fix this with..." # you can use logging here
sys.exit()
|
[
"travel.stackexchange",
"0000155018.txt"
] | Q:
How to request a refund from Condor Airlines without calling them?
A friend of mine had a ticket with Condor airlines from Seattle to Prague, scheduled to depart on March 16th via Frankfurt. The Frankfurt-Prague flight (LH1400) was cancelled, so my friend would like to receive a refund on the return part of their flight.
However Condor's phone agents are impossible to reach right now. Is it possible to somehow ask for a refund via email? Their website doesn't seem to offer such an option.
A:
You can use the contact form mentioned in the website.
https://www.condor.com/us/help-contact/faq.jsp
You can also try to reach them using social media. I was able to reach a different airline through social media when calls was not going through.
|
[
"stackoverflow",
"0031198293.txt"
] | Q:
Meteor: Why am I losing my data context by switching function() { } to () => { }?
So I'm experimenting with ES6, installed the grigio:babel package, and am starting to go through my es5 code and update it to some of the new ES6 syntax when I ran into a problem.
Originally my template helpers looked something like this:
Template.exampleTemplateName.helpers({
exampleHelper: function() {
//returns an array from Mongo Collection
}
});
which is used in a Blaze each loop as such
{{#each exampleHelper}}
{{/each}}
As you'd expect, all of my event handlers for the elements in this event loop had access to the fields in the Mongo Collection that is being returned by exampleHelper via the this keyword. this.exampleField would return exactly what I'd expect it to return.
So now's the point at which I started to update to ES6. For some reason the following syntax breaks the data context, so instead of this returning what you'd expect, it returns Window instead:
Template.exampleTemplateName.helpers({
exampleHelper() {
//returns an array from Mongo Collection
}
});
The above was my first attempt, then I tried:
Template.exampleTemplateName.helpers({
exampleHelper: () => {
//returns an array from Mongo Collection
}
});
So I ran the above ES6 code through Babeljs's online translator and received the following, which is obviously incorrect as I don't want a named function:
Template.exampleTemplateName.helpers({
exampleHelper: function exampleHelper() {}
});
Can someone tell me what the correct syntax should look like?
A:
Can someone tell me what the correct syntax should look like?
Your original code was totally fine. You don't have to abuse the features and use them just in order to use them, save few keystokes, etc. In this case normal anonymous function is what you should use.
The reason why you have this confusion with this pointing to global object, is because this is how arrow functions work: they have lexical this, not dynamic. This means that this reference is bound statically to function context at the time of the function creation (in your case it was window), and not resolved dynamically at runtime.
|
[
"physics.stackexchange",
"0000192923.txt"
] | Q:
Can the stress energy tensor have nonzero value in a vacuum region?
In general relativity, when solving for the schwartzchild solution, we set $T=0$.
1) Is it possible for the stress energy tensor to have nonzero value in a vacuum region?
2) Is the stress $T=0$ in a vacuum region in $f(R)$ modified gravity?
A:
In the original $f(R)$ gravity, the action is
$$
S = \int \sqrt{-g} \left[ \frac{f(R)}{16 \pi G} + \mathcal{L}_\text{mat}(g^{ab}, \psi) \right] \, d^4x.
$$
Here, $\psi$ represents the collection of matter fields present. The Euler-Lagrange equation for the metric resulting from this action is
$$
f'(R) R_{ab} - \frac{1}{2} f(R) g_{ab} + \left[ g_{ab} \nabla_c \nabla^c - \nabla_{(a} \nabla_{b)} \right] f'(R) = 8 \pi G T_{ab},
$$
where
$$
T_{ab} = - \frac{\delta \mathcal{L}_\text{mat}}{\delta g^{ab}}.
$$
Now, when we're constructing these models, we usually think of them as "modifying the gravitational dynamics" rather than "modifying the matter dynamics"; so usually we just take the standard matter Lagrangian for whatever matter want to study (electromagnetic fields, perfect fluids, etc.) and drop it into the modified Lagrangian. So in that sense, $T_{ab} = 0$ in the absence of matter ($\psi = 0$) in $f(R)$ gravity if and only if the same statement holds in conventional gravity.
However, there's one small ambiguity here. Consider adding a cosmological constant to the above action:
$$
S' = \int \sqrt{-g} \left[ \frac{f(R)}{16 \pi G} + \mathcal{L}_\text{mat}(g^{ab}, \psi) + \Lambda \right] \, d^4x.
$$
Do we view this $\Lambda$ as part of $f(R)$? Or as part of $\mathcal{L}_\text{mat}$? It could equally well be viewed as a trivial function of $R$, or as a trivial function of $g^{ab}$ and $\psi$. But depending on the meaning we assign to $\Lambda$, it will end up contributing to the $f(R) g_{ab}$ term in the first case, or contributing to $T_{ab}$ in the second case.
|
[
"stackoverflow",
"0061121371.txt"
] | Q:
Extract Numeric Date Value from short Date Format in SQL
I am trying to convert short date format to numeric date format in SQL.
Here are the dates I am trying to convert:
16-Mar-20
18-Mar-20
12-Mar-20
I have seen many methods to re-format dates based on numeric numbers but I am working with a dataset which has varied date-types. To ensure smoothness, I wanted to know what's the way to convert these numbers to numeric date. Note that even if I extract the day month and year individually I could multiply them with respective values to get the dates. Here's what I have done: (Although I have tried multiple things but this is the one which has yielded me the closest result, Note that my end goal is to convert the date into numeric value)
FROM_UNIXTIME(`Start Date`, 'dd-MMM-yy') AS 'Date Numeric'
Here Start Date is formatted in the way I have mentioned above. (14-Mar-20).
A:
UNIX_TIMESTAMP is what you need, but first you have do transform your data to a Date
UNIX_TIMESTAMP(STR_TO_DATE(`Start Date`, '%d-%b-%y'))
With
SELECT UNIX_TIMESTAMP(STR_TO_DATE( "14-Mar-20", "%d-%b-%y"))
You get
UNIX_TIMESTAMP(STR_TO_DATE( "14-Mar-20", "%d-%b-%y"))
1584144000
|
[
"stackoverflow",
"0040963716.txt"
] | Q:
Promise fired before waiting for result
I'm very new to promises and my following code produces some unexpected results but I don't know why.
The Taskrunner.SyncObjects function in Main.js should wait for the filled selectedCourses variable, but instead of that it just fires instantly. This results in an empty selectedCourses variable being used.
Why is it that the TaskRuner.SyncObjects function runs before having a result?
Main.js
function StartSync(){
var a = Settings.LoadCourseList(standardOSPathUserData);
var b = a.then(function(){
console.log("b is running");
var selectedCourses = Settings.courseList;
return TaskRunner.SyncObjects(selectedCourses).then(function(){
fileSyncRunning = false;
});
}).catch(function(error){
console.log("StartSync Error message: " + error);
});
}
Settings.js
Settings.LoadCourseList = function(osPath){
var pathToCourseListSettings = osPath + courseListFileName;
return new Promise(function(resolve, reject){
try {
return connection.Login().then(function(){
return connection.GetCourseList().then(function(result){
var allCourses = [];
for(var p=0; p<=result.length-1;p++){
allCourses.push({courseID: result[p].courseID, courseName: result[p].courseName, selected: true});
}
courseListJSON = JSON.stringify(allCourses);
return courseListJSON;
}).then(function(courseListJSON){
fs.appendFileSync(pathToCourseListSettings,courseListJSON,encoding='utf8');
console.log("New Course settings file created and filled: " + pathToCourseListSettings);
return resolve();
});
}).then(function(){
return resolve();
});
} catch (e) {
console.log("FAIL courseList settingsfile creation - Error: " + e.code);
return reject(e);
}
});
};
A:
It appears Settings.courseList is never assigned a value in Settings.js
You could try adding
Settings.courseList = allCourses;
on the line before
courseListJSON = JSON.stringify(allCourses);
Or better yet you could do it the promise way and resolve the promise with allCourses.
To make the promise from Settings.LoadCourseList(standardOSPathUserData); return allCourse, change
return connection.Login().then(function(){
return connection.GetCourseList().then(function(result){
var allCourses = [];
for(var p=0; p<=result.length-1;p++){
allCourses.push({courseID: result[p].courseID, courseName: result[p].courseName, selected: true});
}
courseListJSON = JSON.stringify(allCourses);
return courseListJSON;
}).then(function(courseListJSON){
fs.appendFileSync(pathToCourseListSettings,courseListJSON,encoding='utf8');
console.log("New Course settings file created and filled: " + pathToCourseListSettings);
return resolve();
});
}).then(function(){
return resolve();
});
to
return connection.Login().then(function(){
return connection.GetCourseList().then(function(result){
var allCourses = [];
for(var p=0; p<=result.length-1;p++){
allCourses.push({courseID: result[p].courseID, courseName: result[p].courseName, selected: true});
}
var courseListJSON = JSON.stringify(allCourses);
fs.appendFileSync(pathToCourseListSettings,courseListJSON,encoding='utf8');
console.log("New Course settings file created and filled: " + pathToCourseListSettings);
return allCourses;
});
});
and to receive that promise result change
var b = a.then(function(){
console.log("b is running");
var selectedCourses = Settings.courseList;
to
var b = a.then(function(allCourses){
console.log("b is running");
var selectedCourses = allCourses;
|
[
"gamedev.stackexchange",
"0000037133.txt"
] | Q:
Techniques for displaying vehicle damage
I wonder how I can displaying vehicle damage.
I am talking about a good way to show damage on screen. Which kind of models are common in games and what are the benefits of them? What is state of the art?
One way I can imagine is to save a set of textures (normal/color/lightmaps, etc.) to a state of the car (normal, damage, burnt out) and switch or blending them. But is this really good without changing the model?
Another way I was thinking about is preparing animations for different locations on my car, something like damage on the front, on the left side/right side or on the back, and start blending the specific animation. But is this working with good textures?
Whats about physics engines? Is it useful to use it for deforming vertex data? I think losing parts of my car (doors, sirens, weapons) can looks really nice.
My game is a kind of RTS in a top down view. vehicles are not the really most important units (its no racing game), but I have quite a lot in.
A:
you could start incrementally adding car scratches or dust by using the stored textures as you first mentioned. The advantage of this method is its good performance. Another advantage is that with bump mapping effects you can realisticly simulate small damage.
If all this works as you expected i would recommend to complement this with a physics engine library and handle all the collisions and parts that could fly off.
Soft-body deformations may or not be supported by the physics engine.
I would discard premade animations or colision states, since most of the times they generate an unrealistic feeling.
|
[
"stackoverflow",
"0008177846.txt"
] | Q:
Setting heap size for rmiregistry
I want to set heap size for RMI registry. Is that similar to java or any other format
A:
rmiregistry -J-Xmx64m
-J Pass argument to the java interpreter
|
[
"stackoverflow",
"0001616805.txt"
] | Q:
How many controller classes are typical in a cocoa app?
When designing my application how many controllers should I have? Is it good practice to have one controller for the entire app, the entire window, or for each class? Additionally how many objects are to many created in the doc window in Interface Builder. Tutorials generally have one called AppController. Do full applications typically have App Controller or n*XYZController?
A:
In a non-document-based app, one per window. I'm only talking about controllers you write yourself, not window controllers, view controllers, object controllers, array controllers, tree controllers, or dictionary controllers. (Note that some people do make their custom controller an NSWindowController.) I'm also not counting the app delegate, which owns your root controller(s).
In a single-window app, that usually means one custom controller.
In a document-based app, you generally don't write controllers at all, but write one or more NSDocument subclasses instead—one per document type. Each document object generally owns exactly one window.
Regardless of what kind of app you're writing, you may also want to make controllers for any floating utility panels (such as an Inspector) that you have, although you should consider the alternative: Make the panel be its own controller, as NSFontPanel and NSColorPanel are.
|
[
"stackoverflow",
"0063569395.txt"
] | Q:
Intersection of 2 columns within a single Dataframe pandas
import pandas as pd
df = pd.DataFrame({'Environment': [['AppleOS X','postgres','Apache','tomcat']], 'Description': [['Apache', 'Commons', 'Base32', 'decoding', 'invalid', 'rejecting', '.', 'via','valid', '.']] })
Environment Description
0 [AppleOS X, postgres, Apache, tomcat] [Apache, Commons, Base32, decoding, invalid, rejecting, ., via, valid, .]
I am new to Pandas and dataframes, and I have to doubt in finding the intersection of two columns mentioned above.
Objective:
Environment and Description are two columns in a dataframe. The objective is to create a new column with the intersection of strings present in the first two columns.
Existing Implementation:
def f(param):
return set.intersection(set(param['Environment']),set(param['Description']))
df['unique_words'] = df.apply(f, axis=1)
print(df['unique_words'])
This set intersection syntax is something I referred in https://www.kite.com/python/answers/how-to-find-the-intersection-of-two-lists-in-python
Problem:
I am not sure how the above syntax works, but it returns with {}
Expected Output:
As ['Apache'] is present in both the columns, it should be the value in the new column created in the dataframe.
Kindly let me know if anyone had done a similar function or any help is appreciated.
A:
use set.intersection
map lowercase to the values in the list
In terms of natural langue processing, the list values should all be converted to lowercase.
# assumes only the two columns in the dataframe
df['common_words'] = df.apply(lambda x: list(set(map(str.lower, x[0])).intersection(map(str.lower, x[1]))), axis=1)
# if there are many columns, specify the two desired columns to compare
df['common_words'] = df[['Environment', 'Description']].apply(lambda x: list(set(map(str.lower, x[0])).intersection(map(str.lower, x[1]))), axis=1)
# display(df)
Environment Description common_words
0 [AppleOS X, postgres, Apache, tomcat] [Apache, Commons, Base32, decoding, invalid, rejecting, ., via, valid, .] [apache]
|
[
"stackoverflow",
"0014816180.txt"
] | Q:
Wait for Infinite Scroll result in Backbone.js View
i have a problem with a InfiniteScrolls calls, this is a part of code in 'Friends' for example:
var InfiniteScrollView = Backbone.View.extend({
el : window,
container : '#profile-friends',
triggerHeight : 10, //px
events : {
'scroll' : 'throttledDetectBottomPage'
},
initialize : function() {
this.throttledDetectBottomPage = _.throttle(this.detectBottomPage, 1000);
},
detectBottomPage : function() {
var self = this;
var offset = $(this.container).height() - this.$el.height() - this.triggerHeight;
if (this.$el.scrollTop() >= offset) {
self.nextPage();
}
},
stop : function() {
this.$el.unbind('scroll');
},
nextPage : function() {
if (this.collection.activeScroll == true) {
this.collection.nextPage();
if (!this.collection.isPaginated) {
if (this.collection.length == 0) {
this.renderNotFoundPage();
this.stop();
return false;
}
} else {
if (this.collection.length == 0) {
this.renderNotFoundMoreResults();
this.stop();
return false;
}
}
}
},
renderNotFoundMoreResults : function() {
$('#profile-friends').append('No more results');
},
renderNotFoundPage : function() {
var container = $(this.container);
container.html('0 results');
}
});
In this.collection.nextPage() is called 'api/friends/pag', pag = page number.
Here the code of the collection:
// profile friends collection
define(
['underscore',
'backbone',
'models/user'],
function(_, Backbone, User){
var PFriendsCollection = Backbone.Collection.extend({
// Reference to this collection's model.
model: User,
initialize: function(){
this.isPaginated = false;
this.active = false;
},
//Call in render
search: function() {
this.page = 1;
this.isPaginated = false;
this.active = true;
this.fetch();
},
//Call in Infinite Scroll view NextPage
nextPage: function() {
if(this.active) {
this.isPaginated = true;
this.page = parseInt(this.page) + 1;
this.fetch({update: true});
}
},
// Url, points to the server API
url: function() {
return 'api/pfriends/' + this.page;
},
// Url, points to the server API
// ATM it is just a json test file
parse: function(response){
// extract items from response.
return response.items;
}
});
return new PFriendsCollection;
});
I created this view in the render() function of FriendsView, and down I surje a problem: i go bottom and trigger launch, but he launch a lot of times if i move the scroll, he call api/pfriends/2, api/pfriends/3, api/friends/4 (For example, is random the number of calls) in the same moment, because he don't wail the first response and launch trigger :(
I do not know where to put a trigger, result or something that blocks the execution of that scroll trigger whenever there pending fetch response.
Thanks =)
A:
fetch returns a jQuery deferred, so you could try this in your collection's nextPage:
return this.fetch({update: true});
Then in your view:
nextPage : function() {
if (this.collection.activeScroll == true && !this.updating) {
var self = this;
this.updating = true;
// function passed to 'always' is called whether the fetch succeeded or failed
this.collection.nextPage().always(function(){
self.updating = false;
if (!self.collection.isPaginated) {
if (self.collection.length == 0) {
self.renderNotFoundPage();
self.stop();
return false;
}
} else {
if (self.collection.length == 0) {
self.renderNotFoundMoreResults();
self.stop();
return false;
}
}
}
}
},
You might want to actually use done and fail instead of always. Check the documentation for more info.
|
[
"stackoverflow",
"0043375725.txt"
] | Q:
Auto fill database name on query
I have Microsoft SQL Server 2014 express.
I have databases named by year and an "ID", for example:
2010CB
2010PL
2011CB
2011YK
2012CB
2013CB
...
20NNCB
And I have to do a query that detects the last year with "CB", so that:
SELECT * FROM [20NNCB][.DBO].FIELD; --being NN the higher year.
Any way? The years are upper than 2000 and lower than 2100.
Thanks!!
A:
If you just want to get the database name, you can use something like this:
SELECT TOP 1 name
FROM sys.databases
WHERE name LIKE '%CB'
ORDER BY name DESC
You could assign this to a variable, and then use that variable in building dynamic SQL if you wish.
DECLARE @dbName sysname;
DECLARE @sql nvarchar(max);
SELECT TOP 1 @dbName = name
FROM sys.databases
WHERE name LIKE '%CB'
ORDER BY name DESC
SELECT @sql = 'SELECT * FROM ' + QUOTENAME(@dbName) + '.[DBO].[TABLENAME];'
EXEC (@sql);
|
[
"stackoverflow",
"0027605970.txt"
] | Q:
Array manipulation leads to foreign key removal
I want to query the database and store it in an array. I then want to remove one item from the array and give the whole array and pass it to the view.
In this schema every Family has_many users.
if user_logged_in
users = @current_family.users
users.each do |user|
if user.id == @current_user.id
users.delete(user)
end
end
@users = users.map {|user| [user.id, user.name]}
end
Whenever I go to delete the user from the array the family_id field entry of the user that gets deleted from the array is removed from the database (The user still remains).
How would I structure this to make sure no database entries (foreign keys etc) are touched.
Thank you
A:
@current_family.users is not array, it's an ActiveRecord::Relation delete
So you delete a record from the DB, not an element from the array.
Try to narrow the query, something like
if user_logged_in
@users = @current_family.users.where("id != ?", @current_user.id).map {|user| [user.id, user.name]}
end
|
[
"stackoverflow",
"0017727852.txt"
] | Q:
JQuery-ui : tabs with heightstyle fill, in a resizable panel, tab content height is not updated
My problem is that when I have a tabs element with the heightStyle set to 'fill', and this tab is inside a resizable element, when the parent resize, the tab content does not resize accordingly.
The code is pretty straightforward:
$("#tabs").tabs({
heightStyle: 'fill'
});
$('#resize').resizable({
handles: 's'
});
The css, p being the content of the tabs:
body {
font-size:62.5%;
}
#tabs {
height:100%;
}
p {
background-color:yellow;
width:100%;
height:100%;
}
And here is a fiddle showing what I mean: http://jsfiddle.net/C27dF/1/
Basically, you can see that the tab container is resized, but not the content.
Does anybody knows how I could get the tabs to update the height of its content ?
Thanks a lot.
A:
you can use the alsoResize paremeter in your resizable function and set it to a class on all the tabbed content.
something like this(I just picked an arbitrary class placed on the tabs by the ui so oyu could use it or another):
$('#resize').resizable({
handles: 's',
alsoResize: '.ui-tabs-panel'
});
heres a working jsfiddle
|
[
"stackoverflow",
"0026586598.txt"
] | Q:
Reading a list of lists into Python
I have made a list of lists to store score data for a given student. The list is called "class1" and each student has a name followed by 3 scores. I can sort this list fine and can write to a file which show the data in the correct format:
class1=[["Tom",7,2,1],["Jo",8,0,0],["Adelphe",9,0,0]]
When written look like this which I am happy with:
['Tom', 7, 2, 1]
['Jo', 8, 0, 0]
['Adelphe', 9, 0, 0]
The problem comes when I try to read the same list in. Each sublist is read as a string. I can't seem to change this.
Here is the code:
class1 = [line.strip() for line in open("data2.txt", 'r')]
This is what the list looks like when read, as you can see there are apostrophes around each sub list, meaning they are strings within the class1 list:
["['Tom', 7, 2, 1]", "['Jo', 8, 0, 0]", "['Adelphe', 9, 0, 0]"]
Can anyone help me, I've done a lot of searching, but can't find anyone with the same problem.
Thanks, Tom
A:
>>> import ast
>>> with open('/path/to/data2.txt', 'r') as classes:
lines = [ast.literal_eval(line.strip()) for line in classes]
>>> print lines
[['Tom', 7, 2, 1], ['Jo', 8, 0, 0], ['Adelphe', 9, 0, 0]]
|
[
"stackoverflow",
"0031926390.txt"
] | Q:
Increment every 33 line of 6 column by 1
I have file of the following type,
ATOM 4 C4 UNK X 1 7.747 4.310 5.563 1.00 0.00 C
ATOM 5 C5 UNK X 1 8.900 3.705 6.021 1.00 0.00 C
ATOM 6 C6 UNK X 1 9.622 2.872 5.185 1.00 0.00 C
-- upto 3564 lines.
I want to increase the sixth column by 1 every 33 lines. I have seen earlier posts and found this code,
gawk -v n=1 '
match($0,/^(.{22})....(.*)/, f) {printf "%s%4d%s\n", f[1], n, f[2]}
NR % 20 == 0 {n++}
{print}
' file
The output from the above file is :
ATOM 3556 H10 UNK X 178 30.121 19.518 46.272 1.00 0.00 H
ATOM 3556 H10 UNK X 1 30.121 19.518 46.272 1.00 0.00 H
Could suggest me , how to increase sixth column every 33 lines?
A:
If you want to increment only the (33*n)th rows, you can do this.
awk '!(NR%33){$6+=++p} 1'
line 33 will be incremented by 1, line 66 by 2, etc.
|
[
"stackapps",
"0000003109.txt"
] | Q:
Possible to return newest questions with a certain tag?
I am not finding a way to return a list of new questions by tag with the new stack exchange api.
Am I missing something or is this not available? If this is not available, I most certainly request this feature.
Thanks.
A:
There are 2 ways to get the 10 most recent questions of a tag, either on the /questions method or /search method.
The parameters on both routes are the same, just set tagged to your tag (eg iphone), and sort to creation, and order to desc
So that's either:
https://api.stackexchange.com/2.0/questions?order=desc&sort=creation&tagged=iphone&site=stackoverflow
or
https://api.stackexchange.com/2.0/search?order=desc&sort=creation&tagged=iphone&site=stackoverflow
The difference between the two is that if you search with multiple tags (seperated by semi-colons), eg (c#;iphone):
The /questions method will return questions which have both the c# and iphone tags.
Whereas the /search method will return questions tagged either c# or iphone (or both).
|
[
"stackoverflow",
"0032257814.txt"
] | Q:
Find all domains under a TLD
I'm trying to find a way to list all registered domains under a top-level domain (TLD). I.e. everything under .com, .net, etc. All the tools I find only applies to finding subdomains under a domain.
A:
The information you seek isn't openly available. However, there are a few options you can try:
You might want to try inquiring at the respective registries directly about getting access to the Zone files. However, the process can take weeks and some registries choose not to offer access at all. For newer GTLDs you can apply at ICANN's Centralized Zone Data Service. You might need to provide a good reason to access the full lists. The Zone file can only be pulled once a day, though, so for more up to date information the only option is a paid service.
Whois API offers the entire whois database download in major GTLDs (.com, .net, .org, .us, .biz, .mobi, etc). It also provides archived historic whois database in both parsed and raw format for download as CSV files, as well as a daily download of newly registered domains.
A similar, popular question exists already but the answers and links are a bit outdated.
|
[
"stackoverflow",
"0021484355.txt"
] | Q:
Python mapping between lists for duplicates
I have two parallel lists like the following:
List1 - List2
1 -------- A
1 -------- B
1 -------- C
2 -------- D
2 -------- D
2 -------- D
2 -------- E
2 -------- A
3 -------- A
3 -------- L
3 -------- M
I am looking for a fast way in python to count how many attributes of list 2 map to different attributes in list 1. In this example I would like to get an ouput like:
A maps to 1, 2, 3
A:
Use zip() to pair up the values from both lists and collections.defaultdict() to produce a mapping:
from collections import defaultdict
mapping = defaultdict(set)
for v1, v2 in zip(List1, List2):
mapping[v2].add(v1)
Now you have a dictionary mapping values from list 2 to sets containing unique values from list 1; you can print these to match your sample output with:
for v2 in sorted(mapping):
print '{} maps to {}'.format(v2, ', '.join(map(str, sorted(mapping[v2]))))
For your sample input, this produces:
>>> mapping
defaultdict(<type 'set'>, {'A': set([1, 2, 3]), 'C': set([1]), 'B': set([1]), 'E': set([2]), 'D': set([2]), 'M': set([3]), 'L': set([3])})
>>> for v2 in sorted(mapping):
... print '{} maps to {}'.format(v2, ', '.join(map(str, sorted(mapping[v2]))))
...
A maps to 1, 2, 3
B maps to 1
C maps to 1
D maps to 2
E maps to 2
L maps to 3
M maps to 3
|
[
"stackoverflow",
"0025363151.txt"
] | Q:
How to fetch "Hindi" text (Indian local language) from MySQL database?
I have store Hindi data in MySQL database. See the following image-
Now I want to fetch that data and display on my JSP page, but when I'm trying to fetch data in my java code I'm getting text into the following formate
UID= ????/??????????/????/?????/?????/Test upgrade/1
UID= ????/??????????/??????/??????/??????????/159/1
UID= ????/??????????/??????/??????/??????????/190/1
UID= ????/??????????/??????/??????/??????????/194/1
UID= ????/??????????/??????/???????/?????? (??.)/730/1
UID= ????/??????????/??????/???????/?????? (??.)/742/1/1
UID= ????/??????????/??????/???????/?????? (??.)/732/1
UID= ????/??????????/??????/??????/??????/98/8/1
UID= ????/??????????/??????/??????/??????/48/10/1
Referring to this question I have changed my database charset to "utf8_unicode_ci", but Still not working. I have written following code to fetch the data
// Method to fetch data from database.
public void getDetails()
{
// Establish connection to the database
DBConnection bdConnection = new DBConnection();
java.sql.Connection connectionObject = null;
java.sql.ResultSet resultSetObject;
java.sql.PreparedStatement preparedStatementObj = null;
// Get DB connection.
connectionObject = bdConnection.getDbConnection();
// Check if connection not null..?
if (connectionObject != null)
{
// Query String.
String strQuery = "SELECT * FROM tbl_test_master";
try
{
preparedStatementObj=connectionObject.prepareStatement(strQuery);
// Execute Query and get query result in ResultSet Object.
resultSetObject = preparedStatementObj.executeQuery(strQuery);
//Process the result
while(resultSetObject.next())
{
String strUserId=resultSetObject.getString("user_id");
System.out.println("UID= "+strUserId);
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Following is my "DBConnection" class--
public class DBConnection
{
// Create Connection Object.
public static Connection connectionObject;
//
//Method Name: getDbConnection()
//Purpose: This is generic method to establish connection to the database.
//
public Connection getDbConnection()
{
try
{
// Load the Drivers
Class.forName("com.mysql.jdbc.Driver");
// URL string to connect to the database.
// Production Server
String strURL = "jdbc:mysql://xx.xx.xxx.xxx:xxxx/my_db?user=db_user&password=db_pass";
// Establish the connection.
connectionObject = (Connection) DriverManager.getConnection(strURL);
System.out.println("Connection Successfull");
}
catch (Exception e)
{
System.out.println(e);
}
return connectionObject;
}
//
// Method Name: closeConnection()
// Purpose: Generic method to disconnect database connection.
//
public void closeConnection(Connection connectionObj )
{
try
{
connectionObj.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Thank you..!
A:
Finally I got the answer-
When you get "?" character instead of the desired character, then it means that the messenger who's responsible for transferring the characters is by itself aware of the character encoding which is used in both the source and destination. Any character which is not supported by the character encoding used in the destination will be replaced by "?". Particularly In my case there were 2 mistakes as below--
1] The transfer of characters from the DB server to my Java code by the JDBC driver was not using a character encoding which supports those characters.
So I changed my connection string from
String strConnectionURL = "jdbc:mysql://xx.xx.xxx.xxx:xxxx/db_name?user=db_user&password=db_pass";
to
String strConnectionURL = "jdbc:mysql://xx.xx.xxx.xxx:xxxx/db_name?useUnicode=yes&characterEncoding=UTF-8&user=db_user&password=db_pass";
2] The transfer of characters from my Java code to the HTTP response body by the JSP API was not using a character encoding which supports those characters.
So I changed very first line of my jsp page from
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
to
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
And the problem got solved. For more info. please refer this article. Thank you..!
|
[
"stackoverflow",
"0007688445.txt"
] | Q:
Extract Common Name from Distinguished Name
Is there a call in .NET that parses the CN from a rfc-2253 encoded distinguished name? I know there are some third-party libraries that do this, but I would prefer to use native .NET libraries if possible.
Examples of a string encoded DN
CN=L. Eagle,O=Sue\, Grabbit and Runn,C=GB
CN=Jeff Smith,OU=Sales,DC=Fabrikam,DC=COM
A:
If you are working with an X509Certificate2, there is a native method that you can use to extract the Simple Name. The Simple Name is equivalent to the Common Name RDN within the Subject field of the main certificate:
x5092Cert.GetNameInfo(X509NameType.SimpleName, false);
Alternatively, X509NameType.DnsName can be used to retrieve the Subject Alternative Name, if present; otherwise, it will default to the Common Name:
x5092Cert.GetNameInfo(X509NameType.DnsName, false);
A:
After digging around in the .NET source code it looks like there is an internal utility class that can parse Distinguished Names into their different components. Unfortunately the utility class is not made public, but you can access it using reflection:
string dn = "CN=TestGroup,OU=Groups,OU=UT-SLC,OU=US,DC=Company,DC=com";
Assembly dirsvc = Assembly.Load("System.DirectoryServices");
Type asmType = dirsvc.GetType("System.DirectoryServices.ActiveDirectory.Utils");
MethodInfo mi = asmType.GetMethod("GetDNComponents", BindingFlags.NonPublic | BindingFlags.Static);
string[] parameters = { dn };
var test = mi.Invoke(null, parameters);
//test.Dump("test1");//shows details when using Linqpad
//Convert Distinguished Name (DN) to Relative Distinguished Names (RDN)
MethodInfo mi2 = asmType.GetMethod("GetRdnFromDN", BindingFlags.NonPublic | BindingFlags.Static);
var test2 = mi2.Invoke(null, parameters);
//test2.Dump("test2");//shows details when using Linqpad
The results would look like this:
//test1 is array of internal "Component" struct that has name/values as strings
Name Value
CN TestGroup
OU Groups
OU UT-SLC
OU US
DC company
DC com
//test2 is a string with CN=RDN
CN=TestGroup
Please not this is an internal utility class and could change in a future release.
A:
I had the same question, myself, when I found yours. Didn't find anything in the BCL; however, I did stumble across this CodeProject article that hit the nail squarely on the head.
I hope it helps you out, too.
http://www.codeproject.com/Articles/9788/An-RFC-2253-Compliant-Distinguished-Name-Parser
|
[
"stackoverflow",
"0047120509.txt"
] | Q:
About shapes when reading data from tfrecords
I'm going to read 'image'(2000) and 'landmarks'(388) from tfrecords.
this is the part of code.
filename_queue = tf.train.string_input_producer([savepath])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example, features={'label': tf.FixedLenFeature([], tf.string), 'img_raw':tf.FixedLenFeature([], tf.string), })
image = tf.decode_raw(features['img_raw'], tf.uint8)
image = tf.reshape(image, [224, 224, 3])
image = tf.cast(image, tf.float32)
label = tf.decode_raw(features['label'], tf.float64) # problem is here
label = tf.cast(label, tf.float32)
label = tf.reshape(label, [388])
error is
InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 291 values, but the requested shape has 388.
when I change 'float64' to 'float32':
label = tf.decode_raw(features['label'], tf.float32) # problem is here
#Error: InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 582 values, but the requested shape has 388
or to 'float16':
label = tf.decode_raw(features['label'], tf.float16) # problem is here
#Error: InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 1164 values, but the requested shape has 388
And here is how I made tfrecords:(to make it simple, I simplify some code)
writer = tf.python_io.TFRecordWriter(savepath)
for i in range(number_of_images):
img = Image.open(ImagePath[i]) # load one image from path
landmark = landmark_read_from_csv[i] # shape of landmark_read_from_csv is (number_of_images, 388)
example = tf.train.Example(features=tf.train.Features(feature={
"label": tf.train.Feature(bytes_list=tf.train.BytesList(value=[landmark.tobytes()])),
'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img.tobytes()]))}))
writer.write(example.SerializeToString())
writer.close()
I have 3 questions:
why does shape change after data type was changed?
how to choose a proper data type? (because sometimes I can successfully decode image with 'tf.float64', but sometimes 'tf.uint8' with different data set)
Is there any problem with the code of creating tfrecords?
A:
I have recently come across a very similar issue and from my personal experience I am pretty confident I was able to infer the answer to what you are asking even though I am not 100% sure.
List item the shape changes because different data types have different lengths when encoded as byte lists and since a float16 has half the length of a float32 the same byte list can either be read as a sequence of n float32 values or as twice as many float16 values. In other words the byte list you are trying to decode doesn't change when you change data type but what does change is the partitions you make of this array list.
You should check the data type of the the data you use to generate the tfrecord file with and use the same datatype to decode the byte_list when reading it (you can check the data type of a numpy array with the .dtype attribute).
None that I can see but I may be wrong.
|
[
"stackoverflow",
"0030962993.txt"
] | Q:
How to write the content in MS Excel 2007?
Consider I have a Excel sheet and when I (typed the data in the A1 cell that
will automatically load on the Cell B1
How can I do that in the Microsoft Excel 2007?.. Please give a solution for that.. Thanks in advance..
A:
Try typing =A1 in your B1 cell.
|
[
"stackoverflow",
"0012389410.txt"
] | Q:
How do I change a UIButton's title using KVC?
I have an array of UIButtons and want to set all their titles to a specific value at once, without looping through the array. The only solution I've found is by means of Key-Value Coding, i.e. something like this:
[self.board setValue:@"X" forKeyPath:@"titleLabel.text"];
However, the button's titleLabel property is readonly and cannot be changed. I also tried using the button's title property as the keypath, but it doesn't work either.
I've done this before by changing the "enabled" property of all the buttons at once using KVC and it worked great, but if I want to change the titles it just won't work (I'm assuming this is because of the new ControlState feature of the UIButton which allows multiple titles for its various states).
So, does anyone have a one-liner solution (with no loops) to change the title of every button from the array?
A:
Actually, KVC is working and is setting your text value. From the Apple Documentation: Although this property is read-only, its own properties are read/write. Use these properties to configure the appearance of the button label So textLabel is a UILabel and the text property on UILabel is not read only. The reason it does not appear to be working is that you are only changing the text of UILabel and not the frame size of the label which has a default value of (0, 0, 0, 0). If you initialise your buttons with a default value of "(three blanks)" for instance (rather than nil) then it will work. (However, there does still seem to be an issue where iOS resets the button value to it's initial value after you click on it)
|
[
"tex.stackexchange",
"0000467283.txt"
] | Q:
How can I put a black square in an algorithm?
I used to write pseudocode in libreoffice and it looked like this:
I'm trying to write something similar in latex.I use algorithm2e.This is the closest thing I got.
How can I put a black square at the of the while?
This is what I've tried:
\documentclass{article}
\usepackage[vlined]{algorithm2e}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\begin{document}
\begin{algorithm}
\textbf{positive integers }$a,b,r$\;
\textbf{read } $a,b$\;
\While{$ b \neq 0 $}{
$r \gets a\%b$\;
$a \gets b$\;
$b \gets r$\;
\qed
}
\textbf{print } $a$\;
\textbf{positive integers }$a,b,r$\;
\textbf{read } $a,b$\;
\While{$ b \neq 0 $}{
$r \gets a\%b$\;
$a \gets b$\;
$b \gets r$\;
}\qed
\textbf{print } $a$\;
\end{algorithm}
\end{document}
And I get this:
A:
Hope this help:
\documentclass{article}
\usepackage[vlined]{algorithm2e}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\DeclareRobustCommand{\qed}{%
\ifmmode \mathqed
\else
\hbox{\vbox{\vspace*{3pt}$\blacksquare$\vspace*{-3pt}}}%
\fi
}
\begin{document}
\begin{algorithm}
\textbf{positive integers }$a,b,r$\;
\textbf{read } $a,b$\;
\While{$ b \neq 0 $}{
$r \gets a\%b$\;
$a \gets b$\;
$b \gets r$\;
\qed}
\textbf{print } $a$\;
\textbf{positive integers }$a,b,r$\;
\textbf{read } $a,b$\;
\While{$ b \neq 0 $}{
$r \gets a\%b$\;
$a \gets b$\;
$b \gets r$\;
\qed}
\textbf{print } $a$\;
\end{algorithm}
\end{document}
A:
Below I change \algocf@Hlne that is responsible for adding the bottom stub of the L-shaped rule, adding a vertically-centred black square.
\documentclass{article}
\usepackage[vlined]{algorithm2e}
\makeatletter
\renewcommand{\algocf@Hlne}{%
\rule{.5em}{.4pt}% horizontal rule
\smash{\rule[\dimexpr-.5ex+.2pt]{1ex}{1ex}}% ending block
}
\makeatother
\begin{document}
\begin{algorithm}
\textbf{positive integers }$a,b,r$\;
\textbf{read } $a,b$\;
\While{$ b \neq 0 $}{
$r \gets a\%b$\;
$a \gets b$\;
$b \gets r$\;
}
\textbf{print } $a$\;
\end{algorithm}
\end{document}
|
[
"askubuntu",
"0000112681.txt"
] | Q:
LibreOffice doesn't display images
My LibreOffice is not showing images. They look like this:
Can someone help?
A:
Maybe displaying images is disabled? This is possible and very useful to speed up working with large documents holding a lot of images. Check Menu Tools > Options > LibreOffice Writer > View:
Make sure Graphics and Objects isn't disabled.
|
[
"stackoverflow",
"0029991525.txt"
] | Q:
Javascript Async calls unrelated callback in parallel
When using a third party library that doesn't depend on the async library, somehow handling an error in the results callback calls an arbitrary callback inside one of the parallel tasks.
eg.
var async = require('async'),
bloomjs = require('bloom-js');
var client = new bloomjs.Client({url: "http://localhost:3005/api"});
async.parallel([function (cb) {
console.log('callback1');
client.find('usgov.hhs.npi', '1558490003', function (err, results) {
console.log('callback2');
if (err) return cb(err);
cb(results);
});
}], function (err, results) {
console.log('callback3');
throw "hello";
if(err) return console.dir(err);
console.dir(results);
});
generates the output
callback1
callback2
callback3
callback2
/Users/untoldone/Source/async-demo/node_modules/async/lib/async.js:30
if (called) throw new Error("Callback was already called.");
^
Error: Callback was already called.
at /Users/untoldone/Source/async-demo/node_modules/async/lib/async.js:30:31
at /Users/untoldone/Source/async-demo/node_modules/async/lib/async.js:251:21
at /Users/untoldone/Source/async-demo/node_modules/async/lib/async.js:575:34
at /Users/untoldone/Source/async-demo/demo.js:9:21
at /Users/untoldone/Source/async-demo/node_modules/bloom-js/src/bloom.js:117:18
at IncomingMessage.<anonymous> (/Users/untoldone/Source/async-demo/node_modules/bloom-js/src/bloom.js:219:22)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
It seems the callback2 is somehow being used to handle an exception in callback3. But given bloomjs never uses the async library, I have no idea how this is possible. Thoughts?
A:
I suspect that inside bloomjs.Client.find, the callback code contains something like this:
try {
callback(false, result);
} catch (e) {
callback(e, result);
}
So when your callback throws the hello error, this gets caught by the above code, and re-calls the client.find callback. This would again call cb(), but async.js detects this loop and signals its own error.
|
[
"stackoverflow",
"0031612414.txt"
] | Q:
python in-line for loops
I'm wondering if there is a way in python to use a simplified, in-line for loop to do different things.
For example:
for x in range(5):
print(x)
to be written in a simpler form, such as
print (x) for x in range(5)
but this does not seem to be working.
I've been googling for finding the right syntax for a couple hours without success. The only alternative I found is, when the in-line for loop is used to access elements of a list:
print ([x for x in range(5)])
is working, but it is doing something else, than what I'm looking for.
Can someone point to the right syntax or let me know if there are any restrictions? (maybe in-line for loops work only about lists?)
A:
Quick answer:
There is no such a thing as "in line for loops" in python
A trick that works:
in python 3.*:
[print(x) for x in range(5)]
Because print is a function
In python 2.* printis not a function but you could define myprint and use it like this:
>>> def myprint(x):
... print x
...
>>> _=[ myprint(x) for x in range(5)]
0
1
2
3
4
More in depth:
What you call "in-line for loops" or "shortforms" are actually list comprehensions and (quoting documentation)
provide a concise way to create lists
The first part of a list comprehension (before the forkeyword) must contain an expression used to create list values. If your expression contains a function that has the (side) effect of printing something it works... but it is exactly a side effect. What you are really doing is creating a list and then discarding it.
Note that you can't assign values (like q += (x * y)) in a list comprehension because assignments are not expressions.
|
[
"stackoverflow",
"0026501456.txt"
] | Q:
Clear previous activity array when backpressed, android
In my android app, i have three activities. The first activity takes the user input and passes the value of a long through Intent extras to second activity, on the basis of which the second activity shows content. Then this second activity takes some user inputs and passes a long array to third activity though Intent , on the basis of which it shows the content.
Now when i backpress from third activity to second activity, i want the user inputs of second activity to be cleared that were store in long array, but my string value which second activity gets from first activity to be remained as it is.
Can anyone guide me , how to achieve this.
EDIT:
SECOND_ACTIVITY_CODE:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_details);
//get long from first activity
Bundle firstactivitybundle = getIntent().getExtras();
myLong1 = firstactivitybundle.getLong("key");
//send this long to SQLITE db and get details
Dbadapter details = new Dbadapter(this);
details.open();
data =details.getDetailedSymps(myLong1);
details.close();
//Display these details in form of checkboxes
for (int i = 0; i < data.length; i++) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setTextColor(Color.BLACK);
cb.setButtonDrawable(id);
cb.setText(data[i]);
checkboxLayout1.addView(cb);
//saving checkbox state in an singleton class for later use
AppData.getInstance().setSensation(data[i]);
}
//second activity button
next1 = (Button) findViewById(R.id.Next1);
next1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < checkboxLayout1.getChildCount(); i++) {
if (checkboxLayout1.getChildAt(i) instanceof CheckBox) {
CheckBox cb = (CheckBox) checkboxLayout1.getChildAt(i);
if (cb.isChecked()) {
senssymp = cb.getText().toString();
//getting Ids of checkboxes that are checked from SQLITE db
Dbadapter senscheck = new Dbadapter(getApplicationContext());
senscheck.open();
sensdetailId = senscheck.getsensdetailId(senssymp);
senscheck.close();
//saving ids in a list
sensIdList.add(sensdetailId);
}
}
}
//converting list to long array
String[] getSym = sensIdList.toArray(new String[sensIdList.size()]);
long[] sens_checked_ids = new long[getSym.length];
for (int i = 0; i < getSym.length; i++) {
sens_checked_ids[i] = Long.valueOf(getSym[i]);
}
// finally create a bundle and sending the long array containg Ids to 3rd activity
Bundle bundle_sensIds = new Bundle();
bundle_sensIds.putLongArray("sens ids", sens_checked_ids);
Intent final_intent = new Intent(DetailActivity.this,FinalActivity.class);
final_intent.putExtras(bundle_sensIds);
startActivity(final_intent);
}
});
}
SOLUTION:
In onStop() of my second activity , i cleared the sensIdList that was saving all the Ids
@Override
protected void onStop() {
super.onStop();
sens_checked_ids= new long[sens_checked_ids.length];
sensIdList.clear();
}
and the problem solved.
A:
For opening a new instance of activity, you can try this:
Intent intent = new Intent(ActivityC.this, ActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); //this combination of flags would start a new instance even if the instance of same Activity exists.
intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
finish();
startActivity(intent);
And if you don't want that and just need to clear data, then you can try this in onResume of activityB:
myArray = new String[]; //reinitialize all data structure
myArrayList= new ArrayList<String>();
sens_checked_ids = new long[];
Hope it helps.
|
[
"magento.stackexchange",
"0000232399.txt"
] | Q:
Magento 2 : How to get total review count and get ratings percentage
In Magento 2, I need to get details of how many reviews approved in specific product and how many average ratings percentage of specific product.
How to get this both details ?
Please help me.
Thanks.
A:
You need to inject \Magento\Review\Model\ReviewFactory and \Magento\Review\Model\Rating $ratingFactory in your construct.
Add this below code in your file :
protected $_reviewFactory;
protected $_ratingFactory;
public function __construct(
..........
\Magento\Framework\App\Action\Context $context,
\Magento\Review\Model\ReviewFactory $reviewFactory,
\Magento\Review\Model\Rating $ratingFactory,
..........
) {
..........
$this->_reviewFactory = $reviewFactory;
$this->_ratingFactory = $ratingFactory;
..........
parent::__construct($context);
}
public function execute()
{
..........
$product_id = '1';
$_ratingSummary = $this->_ratingFactory->getEntitySummary($product_id);
$ratingCollection = $this->_reviewFactory->create()->getResourceCollection()->addStoreFilter(
$this->_storeManager->getStore()->getId())->addStatusFilter(\Magento\Review\Model\Review::STATUS_APPROVED)->addEntityFilter('product', $product_id);
$review_count = count($ratingCollection); // How many review in that specific product
$product_rating = $_ratingSummary->getSum() / $_ratingSummary->getCount(); // Product rating in percentage
..........
}
Clean cache and refresh it. Hope it will helpful for you !!
|
[
"stackoverflow",
"0057680143.txt"
] | Q:
I have to return filtered object
I have array, which i get from checkbox checking.
And I have array of objects with categrories.
I want to get an array filteredPeople that contains only objects with categories that contains at least one of from selectedClicents
let selectClients = ['Web', 'Design'];
let people = [
{ category: ['Web', 'Design'] },
{ category: ['Web'] },
{ category: ['PWA', 'Design'] },
{ category: ['Ecommerce'] },
];
A:
You can use filter, some and includes
let selectClients = ['Web', 'Design'];
let people = [
{ category: ['Web', 'Design'] },
{ category: ['Web'] },
{ category: ['PWA', 'Design'] },
{ category: ['Ecommerce'] },
];
let final = people.filter(({category})=> selectClients.some(v=>category.includes(v)))
console.log(final)
A:
You can use Array.prototype.some and Set.prototype.has along with filter to get the filtered list from people array
I've used a ES6 Set for O(1) lookup:
const selectClients = ['Web', 'Design'];
const keys = new Set(selectClients);
const people = [
{ category: ['Web', 'Design'] },
{ category: ['Web'] },
{ category: ['PWA', 'Design'] },
{ category: ['Ecommerce'] },
];
const res = people.filter(({category}) => category.some(cat => keys.has(cat)));
console.log(res);
|
[
"stackoverflow",
"0003031497.txt"
] | Q:
How to Verify if file exist with VB script
How do I verify via VBScript if the file conf exist under Program Files (i.e. C:\Program Files\conf)?
For example if it exists, then msgBox "File exists"
If not, then msgbox "File doesn't exist"
A:
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
|
[
"stackoverflow",
"0012647584.txt"
] | Q:
VSTO: Visual Studio 2005 with Office 2010 64
I was developing a Office 2003 Add-In with Visual Studio 2005. But after unistall Office 2003 and intall Office 2010 x64, my project stops working.
It's present some errors:
Error 7 The type or namespace name 'IRibbonControl' could not be found (are you missing a using directive or an assembly reference?) x.cs 83 45 x
Error 5 The type or namespace name 'IRibbonUI' could not be found (are you missing a using directive or an assembly reference?) x.cs 358 38 x
Error 3 The type or namespace name 'IRibbonExtensibility' does not exist in the namespace 'Microsoft.Office.Core' (are you missing an assembly reference?) x.cs 45 43 x
There is some way to make my AddIn run?
A:
Not sure if you have seen this or not, but here's some of the explanations:
Office 2010 32-bit should run VSTO 2005 SE add-ins without
modifications, but Office 2010 64-bit will not load VSTO 2005 SE
add-ins.
Office solutions that require the Visual Studio 2005 Tools for Office
Second Edition Runtime are not compatible with 64-bit versions of
Microsoft Office 2010. To run these solutions in the 64-bit edition of
Microsoft Office 2010, you must upgrade the project to Visual Studio
2010 or to a Visual Studio 2008 project that targets the 2007
Microsoft Office system.
More details here.
Also check out VSTO compatibility table on Wikipedia which might be useful info
|
[
"stackoverflow",
"0051865175.txt"
] | Q:
Gremlin/Neptune vertex lookup by property using gremlinpython
Using the graph traversal object g, I can look up a vertex by ID:
>>> g.V().has("~id", "foo").toList()
[vp[category->my category], vp[title->my title], vp[description->my description], vp[myprop->my property]]
Looking up by "category" also works:
>>> g.V().has("category", "my category").toList()
[vp[category->my category], vp[title->my title], vp[description->my description], vp[myprop->my property]]
But looking up via another property produces no results:
>>> g.V().has("myprop", "my property").toList()
[]
What might be different? The values are simple uppercase letters with dashes, so I doubt there's any escaping/unescaping going on.
(property names have been changed to protect the innocent)
A:
The load process was overwriting the expected property value with a different one, but not providing sufficient feedback to identify that behavior.
|
[
"stackoverflow",
"0017913613.txt"
] | Q:
Custom HTML5 video player controls with AngularJS
I'm new with AngularJS. I must create customs controls for a video player (HTML5 <video>).
Basically, I would use getElementById('myvideotag'), listen clicks on the video for play/pause.
How I can do this with AngularJS ? Binding the click with ng-click="videoPlayPause()" but then, how I play or pause the video. How I use the classic methods of <video> ?
I guess it's really simple... I didn't get all the AngularJS concepts yet !
Thank you :)
Oh, the code... in the view:
<video autoplay="autoplay" preload="auto" ng-click="video()">
<source src="{{ current.url }}" type="video/mp4" />
</video>
In the right controller:
$scope.video = function() {
this.pause(); // ???
}
A:
For full control, like behaviour and look&feel, I'm using videoJS in angular.
I have a ui-video directive that wraps the video HTML5 element. This is necessary to overcome a problem of integration with AngularJS:
m.directive('uiVideo', function () {
var vp; // video player object to overcome one of the angularjs issues in #1352 (https://github.com/angular/angular.js/issues/1352). when the videojs player is removed from the dom, the player object is not destroyed and can't be reused.
var videoId = Math.floor((Math.random() * 1000) + 100); // in random we trust. you can use a hash of the video uri
return {
template: '<div class="video">' +
'<video ng-src="{{ properties.src }}" id="video-' + videoId + '" class="video-js vjs-default-skin" controls preload="auto" >' +
//'<source type="video/mp4"> '+ /* seems not yet supported in angular */
'Your browser does not support the video tag. ' +
'</video></div>',
link: function (scope, element, attrs) {
scope.properties = 'whatever url';
if (vp) vp.dispose();
vp = videojs('video-' + videoId, {width: 640, height: 480 });
}
};
});
A:
How about this:
In your HTML, set ng-click="video($event)" (don't forget the $event argument), which calls the following function:
$scope.video = function(e) {
var videoElements = angular.element(e.srcElement);
videoElements[0].pause();
}
I believe this is the simplest method.
Documentation for angular.element
Also, this might help you get used to Angular: How do I “think in AngularJS/EmberJS(or other client MVC framework)” if I have a jQuery background?
A:
You could also take a look to my project Videogular.
https://github.com/2fdevs/videogular
It's a video player written in AngularJS, so you will have all the benefits of bindings and scope variables. Also you could write your own themes and plugins.
|
[
"stackoverflow",
"0038090732.txt"
] | Q:
Ruby on rails - Changing hyperlinks to table columns
I've made a list with hyper links to columns in a table called "Categories", there are 5 categories and the first set of code below makes hyperlinks to all 5.
I want to make a dropdown menu, but only show two of the categories, instead of all 5. Currently, i'm just using a href to the url, but is there some other way I can link to two columns in the "Categories" table?
Links:
<ul>
<% Category.all.each do |category| %>
<li><%= link_to category.name, items_path(category: category.name) %></li>
<% end %>
</ul>
Dropdown Menu:
<div class="container">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Canon
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="http://localhost:3000/items?category=Canon+Camera">Canon Cameras</a></li>
<li><a href="http://localhost:3000/items?category=Canon+Lens">Canon Lenses</a></li>
</ul>
</div>
</div>
A:
Use take() or limit() methods to limit how many items you want to get:
<ul>
<% Category.take(2).each do |category| %>
<li><%= link_to category.name, items_path(category: category.name) %></li>
<% end %>
</ul>
|
[
"stackoverflow",
"0022268136.txt"
] | Q:
Java SQL-statement problems
I have a table in a database, list, and the columns are NR, FNAME, SNAME and ADDRESS. I also have a person class with all these attributes. Now I want to add a Person to the database.
Statement stmt = anslutning.createStatement();
stmt.executeUpdate("INSERT INTO person (nr, fnamn, snamn, address) VALUES (" + p.getNr() + "," + p.getFname()+ "," + p.getSname()+","+ p.getAddress() + ")");
If the p.getFname is "Hank" then I get this error message:
mar 08, 2014 11:30:44 FM dblab.PersonAccessor addPerson
Allvarlig: null
java.sql.SQLException: Column not found: HANK
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.jdbcStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.jdbcStatement.executeUpdate(Unknown Source)
at dblab.PersonAccessor.läggTillPerson(PersonAccessor.java:82)
at dblab.LäggTill.actionPerformed(LäggTill.java:139)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Hank
A:
I think you need to insert the String value with single quotes, like this:
Statement stmt = anslutning.createStatement();
stmt.executeUpdate("INSERT INTO person (nr, fnamn, snamn, address) VALUES (" + p.getNr() + ",'" + p.getFname()+ "','" + p.getSname()+"', '"+ p.getAddress() + "')");
And i suggest not to use Statement, use PreparedStatement like this:
PreparedStatement stmt = anslutning.prepareStatement("INSERT INTO person (nr, fnamn, snamn, address) VALUES (?, ?, ?, ?)");
stmt.setString(1, p.getNr());
stmt.setString(2, p.getFname());
stmt.setString(3, p.getSname());
stmt.setString(4, p.getAddress());
Ream More About PreparedStatement
|
[
"ru.stackoverflow",
"0001080068.txt"
] | Q:
Как реализованы такие штуки? Не знаю как объяснить, картинка в треде
например вот здесь
http://demo.joomshaper.com/2014/onepage/
там где написано LATEST BLOG
видете, такие линии с кружочками идут вниз от каждого блока
уже не первый раз замечаю подобное но НИКАК не могу нагуглить не зная как это называется.
A:
на коленке, думаю, что идею вы поняли
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.container__inner {
width: 900px;
position: relative;
}
.container__inner::after {
content: '';
position: absolute;
top: 30px;
left: 50%;
width: 2px;
height: calc(100% - 60px); /* 60px = block's padding * 2 */
transform: translateX(-50%);
background-color: green;
}
.container__row {
display: flex;
flex-wrap: wrap;
margin: -30px;
}
.container-block {
width: 50%;
padding: 30px;
height: 100%;
position: relative;
}
.container-block::after {
content: '';
position: absolute;
top: 50%;
right: -7.5px;
width: 15px;
height: 15px;
transform: translateY(-50%);
background-color: red;
border-radius: 50%;
z-index: 2;
}
.container-block:last-of-type {
margin-top: 100px;
}
.container-block:last-of-type::after {
left: -7.5px;
}
.container-block__inner {
border: 1px solid black;
height: 150px;
}
<div class="container">
<div class="container__inner">
<div class="container__row">
<div class="container-block">
<div class="container-block__inner"></div>
</div>
<div class="container-block">
<div class="container-block__inner"></div>
</div>
</div>
<div class="container__row">
<div class="container-block">
<div class="container-block__inner"></div>
</div>
<div class="container-block">
<div class="container-block__inner"></div>
</div>
</div>
<div class="container__row">
<div class="container-block">
<div class="container-block__inner"></div>
</div>
<div class="container-block">
<div class="container-block__inner"></div>
</div>
</div>
</div>
</div>
|
[
"stackoverflow",
"0053628878.txt"
] | Q:
How to make my post api to be able to send data as parameter in python
I have this code:
from flask import (
Flask,
render_template
)
import SocketServer
import SimpleHTTPServer
import re
app = Flask(__name__, template_folder="templates")
@app.route('/index', methods=['GET'])
def index():
return 'Welcome'
@app.route('/write_text_to_file', methods=['POST'])
def write_text_to_file():
f = open("str.txt", "w+")
f.write("hello world")
f.close()
if __name__ == '__main__':
app.run(debug=True)
EDIT:
MY API includes one functionality which is writing a string to local file system by creating this file.
What I want to achieve is to be able to pass a string as part of the api request which could be any string and to write the accepted string into a file, now I'm using hard-coded string which get the job done but I want to achieve the ability to send strings dynamically when using this api to write to file.
A:
Try this:
In postman i posted the string in body as raw. then you can get data using
request.data which will be of byte type so you have to use request.data.decode("utf-8")
@app.route('/write_text_to_file', methods=['POST'])
def write_text_to_file():
if request.method == 'POST':
print(type(request.data))
data = request.data.decode("utf-8")
f = open("str.txt", "w+")
f.write(data)
f.close()
return ''
|
[
"stackoverflow",
"0004985175.txt"
] | Q:
Specifying a list of items for the parameters with WorkItemStore.Query in TFS
I've got the following WIQL query for a TFS project:
string query = "SELECT * FROM Issue WHERE [System.TeamProject] = @Project "+
"AND [Assigned To] IN (@AssignedTo)";
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("Project","test");
parameters.Add("AssignedTo","'chris','tfsuser'");
WorkItemStore.Query(query, parameters);
This is being run via the .NET TFS API.
My problem is with the AssignedTo parameter. How is this meant to be specified? I've tried it as a string[], List<string> as well as with and without quotes as above. Each one doesn't seem to work.
A:
I understand what you're trying to do, but it doesn't look like it's possible. The query that you want is this:
WHERE [System.AssignedTo] in ('John Smith', 'Jane Citizen')
Which is semantically the same as this:
WHERE [System.AssignedTo] = 'John Smith' OR [System.AssignedTo] = 'Jane Citizen'
The only way I can work out how to achieve it in code is by specifying the identities as separate parameters:
TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://localhost:8080/tfs/"));
WorkItemStore wis = tfs.GetService<WorkItemStore>();
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("parameter1", "John Smith");
values.Add("parameter2", "Jane Citizen");
Query query = new Query(wis, "SELECT [System.Id] FROM WorkItems WHERE [System.AssignedTo] IN (@parameter1, @parameter2)", values);
WorkItemCollection workItems = wis.Query(query.QueryString);
WorkItem workItem = workItems[0];
|
[
"stackoverflow",
"0038291516.txt"
] | Q:
I have trouble using reDim in VBA, can't figure out how it works
I would like to write a function, where the input is a string (e.g. ACGTTGCATGTCGCATGATGCATGAGAGCT) and an integer (e.g. 4). The function should be able to identify the sub-string(s) with the length of the integer that are the most commonly repeated in the input string. I think I am supposed to use reDim, and although I have researched how it is supposed to work, I just cannot figure out the proper syntax.
Code Challenge: Solve the Frequent Words Problem. Input: A string
Text and an integer k. Output: All most frequent k-mers in Text.
Function BIOINFO2(txt As String, k As Integer)
Dim FrequentPatterns As String
Dim ptrn As String
Dim n() As Integer
Dim i As Integer
Dim s As Integer
Dim j As Integer
Dim maxCount As Integer
For s = 1 To Len(txt) - k + 1
ptrn = Mid(txt, s, k)
For i = 1 To Len(txt) - Len(ptrn) + 1
If Mid(txt, i, Len(ptrn)) = ptrn Then
ReDim n(i)
n(i) = 0
n(i) = n(i) + 1
End If
Next i
maxCount = Application.Max(n(i))
For j = 1 To Len(txt) - k + 1
If n(i) = maxCount Then
FrequentPatterns = FrequentPatterns + " " + Mid(txt, s, k)
End If
Next j
Next s
BIOINFO2 = FrequentPatterns
End Function
A:
This is just to clarify the ReDim issue, not the logic of your code.
You use ReDim to resize an array (losing the values stored in it), ReDim Preserve to resize an array while keeping the values.
If you know the required size of your array beforehand, you should allocate it with the correct size at the start, as in
Dim arr(1 To m) As Long
If you don't know the required size, you can resize it later on like this
Dim arr() As Long
'Do stuff and find out you need the array to hold m elements
ReDim Preserve arr(1 To m)
Your case is somewhat in between because you know the size right at the start of your function but it is not a constant size. You can Dim an array with a specific size only if it's constant so in this case you need to declare it without bounds first and then ReDim with the correct size.
Dim arr() as Long
ReDim arr(1 To m) As Long
Redim arr(m) is the same as Redim arr(base To m) where base is either 0 or 1. The default value is 0 but you can set it using Option Base 1 at the beginning of your module.
You can find out the highest and lowest array indices using the UBound and LBound functions so a loop that loops over all the values could look like this
For i = LBound(arr) To UBound(arr)
'Do something
Next i
That way you avoid problems with different bases.
It is usually better to do as little resizing of arrays as possible. In the worst case scenario, the system has to copy the whole array to another location in the memory where there is enough free space.
|
[
"stackoverflow",
"0018417515.txt"
] | Q:
Elixir - is there a performance penalty using it instead of plain erlang?
Elixir seems cool but I wonder about the downsides.. if any..
Are there any other potential downsides when choosing it over erlang ?
A:
Elixir reuses most of the compilation stack used by Erlang, so our bytecode is in general very close to the one you would get by compiling Erlang itself. In many cases, it just isn't the same because we include some reflection functions like __info__/1 in the compiled module. Also, there is no conversion cost in between calling Erlang and Elixir and it will never be.
A:
Since elixir compiles directly to Beam bytecode, you don't incure any intermediate costs like a jitter if that's your concern.
|
[
"aviation.stackexchange",
"0000077991.txt"
] | Q:
What do the pilots do if the plane they are operating does not have an anti-ice system?
Anti-icing equipment is designed to prevent the formation of ice, while deicing equipment is designed to remove ice once it has formed. These systems protect the leading edge of wing and tail surfaces, pitot and static port openings, fuel tank vents, stall warning devices, windshields, and propeller blades.
.What if the plane does not not have any anti - ice systems
Here is my research about one type of plane that does not have an anti - ice system and what do the pilots do to deice the plane.
A Cessna 172 has no anti icing system, as long as I remember a electrical pitot heater for preventing freezing over the pitot tube and a carb heater for preventing formation of ice in carburetor are the only two ways to prevent ice from forming; for that the C172 cannot fly in icy conditions.
I have researched about this topic and I am still looking forward to learn from the users who answer my question.
A:
If an aircraft is not equipped with anti-ice or de-icing systems, than the answer is simple: You don't fly into icing conditions. This is usually listed as an operating limitation in the POH/AFM/FCOM of the respective aircraft. For a Cessna 172, you can e.g. find:
KINDS OF OPERATIONS LIMITS
The Cessna 172S Nav III airplane is approved for day and night, VFR
and IFR operations. Flight into known icing conditions is prohibited.
(C172 POH, Section 2 Operating Limitations)
If you are approaching icing conditions, there are usually two options to avoid flying into icing conditions:
Reduce the altitude: The temperature is higher at lower altitudes. If you can reduce your altitude enough to raise the temperature above 10°C, you are out of icing conditions.
Change course: If you see a cloud ahead and the temperature is below 10°C, you cannot enter the cloud because that would mean you enter icing conditions. You can however deviate from your current course and fly around the cloud.
A:
Aircraft such as a Cessna 172 are routinely flown in cold conditions. The regulatory objective is to avoid all known icing conditions. The practical objective is to avoid all likely icing conditions. Aside from that the aircraft has very basic anti-icing tools.
Carburator heat is one, but one must be aware that carburator icing happens under conditions, including warm and humid days and is different from airframe icing.
Pitot heat and in many light aircraft, static port heat, are used to maintain operation of basic flight instruments, namely the barometric altimeter, the airspeed indicator and the vertical speed indicator.
In my experience flying in the northern part of the US and throughout Canada, I have experienced icing which overwhelms pitot heat, as well as other anti-ice systems including prop heat and wing anti-ice system. (Think 1" a minute of clear icing!) Also improper use of boots on the wings can lead to the ability of the expanding boots to shed ice, when the boots have been applied prematurely, causing an expanded shell of thin ice to form which does not shed, and has further accredtion of ice.
There are generally two elements for airframe icing: moisture and temperature.
Moisture is pretty obvious. If one stays out of precipitation and out of clouds, the amount of moisture in the air is locally less, and while a trace of ice may form, in the course of a flight it may also sublimate. Yes, it is possible to pick up very small amounts of ice even in clear air, with no visible moisture or precipitation. But it doesn't happen that often.
Temperature is the other component. Generally an aircraft will shed ice when just slightly above freezing. If flying in conditions with a temperature inversion exists, sometimes climbing 1000 or 2000 feet will be enough to stop accumulation and start shedding ice. Usually higher means colder. And the good news is that colder temperatures may also reduce ice accretiation rates.
For example on one trip between LGA and BOS, at 4000, there was moderate ice. Climbing to 8000, and colder air, reduced the icing, and when dryer conditions were experienced enroute all accumulated ice was sublimated.
When the temperatures are very cold (-30C) there tends to be little ice accumulation. The air contains very little moisture at those temperatures, and while ice can accumulate, it infrequently does, compared to temperatures of -5C.
Propellers are a concern in that they too loose efficiency with ice accumulation. Flexing the prop with power and RPM changes helps shed ice. Some props will have nozzles which sling out alcohol, and some have heated pads which are electrically powered. A asymetrically iced prop can destroy engine mounts and has been the cause of more than a few inflight losses of engines, where they have physically separated from the aircraft.
One additional technique implemented by many pilots who are concerned about icing, is to coat the prop with an ice-shedding substance. A thick silicone spray is used, and it is not slung off by a spinning prop, at least rapidly. Changing RPM or prop pitch flexes the prop and can also aid in keeping the prop clear of ice, and reasonably balanced. Some people have used automotive silicone spray, but it does not work as well.
A more difficult problem operating in icing conditions, is being able to see. Some aircraft have poor or virtually no window de-ice. The Cessna 172 is a good example. More than once I have had to slip on short final to effectively see out the side window to recognize the landing environment. A product called RVR, which works similar to Rainx keeps a hydrophobic state on the windshield and helps enhance ice shedding, as well as liquid water shedding. It is a window treatment and is simply routinely applied, rather than episodically.
Finally, there is no substitute for more power. It can get the aircraft up through a layer where ice is accumulating, and it can also keep up a good climb rate when the aircraft is heavy with accumulated ice. Flying a Cessna 182 vs a Cennsa 172, can reduce the impact and accumulation should unexpected icing conditions be encountered. All the time trying to climb at Vy (where Vy keeps dropping) provides more frontal area to accumulate more ice. So higher power lowers the nose, and also gets one up higher faster, or helps a plane heavy with ice.
Just one anecdotal story...when young and learning weather flying, we would jump at the chance in the fall, when there were brisk mornings, and the freezing level was about 2000, and there was a scattered layer of lake effect clouds. Into the cloud, and we would get a layer of ice, and then out of the cloud, we would watch how it would sumlimbate. Too big of a cloud with ice, and we would climb over the tops and the accumulation would stop. When we were going to land we would drop below the freezing level and the ice would all shed off. I do not recommend this method unless suitably skilled, and you have assured yourself that your operation is regulatorily acceptable.
So winter flights where icing is a possibility should be taken with ice countermeasures, such as silicone on the prop and even on the wings and control surfaces. Not only a through briefing, but more importantly a good understanding of weather specific to winter flight is essential. Changes in altitude either up or down can take the aircraft to better conditions. If clouds are prevalent at lower altitudes, flying at higher altitudes may keep one entirely out of icing conditions. Route deviations, particulary due to orographic and coastal conditions may be in order.
|
[
"stackoverflow",
"0019780394.txt"
] | Q:
XML Serialization structure
Apologies on not being able to phrase the title more specifically but I can only explain by giving an example.
I'm trying to build a class that serializes to the following XML
<Customize>
<Content></Content>
<Content></Content>
<!-- i.e. a list of Content -->
<Command></Command>
<Command></Command>
<Command></Command>
<!-- i.e. a list of Command -->
</Customize>
My C# is:
[XmlRoot]
public Customize Customize { get; set; }
and
public class Customize
{
public List<Content> Content { get; set; }
public List<Command> Command { get; set; }
}
However, this produces (as it should), the following:
<Customize>
<Content>
<Content></Content>
<Content></Content>
</Content>
<Command>
<Command></Command>
<Command></Command>
<Command></Command>
</Command>
</Customize>
Are there some xml serialization attributes that would help achieve my desired xml, or do I have to find another way to write the class?
A:
Use XmlElementAttribute to mark your collection properties.
public class Customize
{
[XmlElement("Content")]
public List<Content> Content { get; set; }
[XmlElement("Command")]
public List<Command> Command { get; set; }
}
Quick test code:
var item = new Customize() { Content = new List<Content> { new Content(), new Content() }, Command = new List<Command> { new Command(), new Command(), new Command() } };
string result;
using (var writer = new StringWriter())
{
var serializer = new XmlSerializer(typeof(Customize));
serializer.Serialize(writer, item);
result = writer.ToString();
}
Prints:
<?xml version="1.0" encoding="utf-16"?>
<Customize xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Content />
<Content />
<Command />
<Command />
<Command />
</Customize>
|
[
"stackoverflow",
"0030200795.txt"
] | Q:
I get the same text my first id in all my tooltips, even though it doesn't belong to that id
I'm trying to learn some Javascript, and combine it with PHP and HTML. For the moment, I'm having the problem that when I mouseover my second or third div, It'll write whatever I'm having in the first div.
$posts = get_posts(((isset($_GET['id'])) ? $_GET['id'] : null));
foreach($posts as $post){
?>
<div onmouseover="fixad()" onmouseout="tabort()" style="background-color:red; width:100px;"><?php echo $post['user'] . " " . $post['contents'] . "<br>";?></div><br>
<div id="popup" style="display:block; background-color:black; width:100px; height:100px; color:white; float:right;"><?php echo $post['date_posted'] . " " . $post['user']; ?></div>
<?php
} ?>
My get_posts function looks like this:
function get_posts($id = null) {
$posts = array();
$query = "select contents, user, date_posted FROM database where id=$'id'";
$query = mysql_query($query);
while($row = mysql_fetch_assoc($query)){
$posts[] = $row;
}
return $posts;
}
My Javascript is simple and looks like this:
function fixad() {
var r = document.GetElementById("popup");
r.style.display = "block";
}
function tabort(){
var r = document.GetElementById("popup");
r.style.display = "none";
}
To summarize it: I want to write out text where id = 5 in 1 div. But I get text from id = 5 when it's supposed to be from another id.
So my
<div id="popup"<?php echo $post['id'];?></div>
Will print out the same id on every popup.
I'm sorry if this was confusing, I'll can elaborate if you want.
A:
All your elements have the same id. So document.GetElementById("popup"); gets the first element every time. Ids should be unique. I'd pass the id of each post back with posts then put that in with the id so each div can be identified correctly.
<div id="popup"
to:
<div id="popup' . $id . '"
|
[
"stackoverflow",
"0045425492.txt"
] | Q:
How can I automatically clear the text in EditText?
final TextView textView = (TextView) findViewById(R.id.textView);
final EditText editText = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String etString = editText.getText().toString();
textView.setText(etString);
}
});
I am new to coding and I don't know how to automatically clear the text in an EditText so the user doesn't have to do it themselves. You can see in all "big" websites that when you enter text into a text box (for example: "What's your name?") you see "first name" in the text box and when you click on it, it disappears. How can I make the text disappear automatically without the user having to delete it manually?
A:
What you're referring to isn't actually text that's being set -- it's a hint (which is why it doesn't show after the EditText is focused or text has already been entered). You can set these placeholder hints in your EditText XML, for example:
android:hint="First Name".
If you're feeling really adventerous, you can also wrap your EditText in a TextInputLayout for a Material Design style floating hint.
If that helps, be sure to accept this answer.
|
[
"stackoverflow",
"0033050989.txt"
] | Q:
How can I query for float/int value or string in a django model using Q Objects?
Django version=1.8 , IDE=pycharm, python 2.7
I have a search form and I want to search and list items("products") in model based on string matching product title or product description or product price.
Below is my "searchitems" part inside views.py . Also im confused what does the line below do in get_queryset function. Cheers
qs = super(ProductListView, self).get_queryset(*args,**kwargs)
#
# Search inside model function
def get_queryset(self, *args, **kwargs):
qs = super(ProductListView, self).get_queryset(*args,**kwargs)
query = self.request.GET.get("q")
if query:
qs = self.model.objects.filter(
Q(title__icontains=query) |
Q(description__icontains=query) |
Q(price=query)
)
return qs
class ProductListView(ListView):
model = Product
queryset=Product.objects.all() #no need to define this as it is a default
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(*args, **kwargs)
return context
Below is models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save
from django.utils.text import slugify
# Create your models here.
class ProductQuerySet(models.query.QuerySet):
def active(self):
return self.filter(active=True)
class ProductManager(models.Manager):
def get_queryset(self):
return ProductQuerySet(self.model, using=self.db)
def all(self, *args, **kwargs):
return self.get_queryset().active()
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=10)
active = models.BooleanField(default=True)
objects = ProductManager()
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk": self.pk})
# OR use this- return "/product/%s"%(self.pk)
class Variation(models.Model):
product = models.ForeignKey(Product) ##this means each Variation is related to single product
title = models.CharField(max_length=120)
price = models.DecimalField(decimal_places=2, max_digits=10)
sale_price = models.DecimalField(decimal_places=2, max_digits=10, null=True, blank=True)
active = models.BooleanField(default=True)
inventory = models.IntegerField(null=True, blank=True) # default=-1 means unlimited
def __unicode__(self):
return self.title
def get_price(self):
if self.sale_price is not None:
return self.sale_price
else:
return self.price
def get_absolute_url(self):
return self.product.get_absolute_url()
# for post save receiver
def product_saved_receiver(sender, instance, created, *args, **kwargs):
# sender=modelclass, instance=actual instance being saved,created=boolean true if record was created
product = instance
variations = product.variation_set.all()
if variations.count() == 0:
new_var = Variation()
new_var.product = product
new_var.title = "Default"
new_var.price = product.price
new_var.save()
post_save.connect(product_saved_receiver, sender=Product)
# product image
# you need to install python pillow library to support.
# it checks if file uploaded is actually an image and checks extension
# class ProductImage(models.Model):
# product = models.ForeignKey(Product)
# image = models.ImageField(upload_to='products/') #image will be uploaded to media/mediaroot/products
#
# def __unicode__(self):
# return self.product.title
#slugify
def image_upload_to(instance, filename):
title = instance.product.title
slug = slugify(title)
file_extension = filename.split(".")[1]
# or basename,file_extension = filename.split(".")
new_filename = "%s.%s" %(instance.id,file_extension)
return "products/%s/%s" %(slug, filename)
# above function changed for slugfying
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to=image_upload_to) #image will be uploaded to media/mediaroot/products
def __unicode__(self):
return self.product.title
With above codes i can search and list according to price eg. 50 or 67.89 but cannot search for strings and get below error
http://127.0.0.1:8000/products/?q=eric clapton riding with the king
ValidationError at /products/
[u"'eric clapton riding with the king' value must be a decimal number."]
Request Method: GET
Request URL: http://127.0.0.1:8000/products/?q=eric%20clapton%20riding%20with%20the%20king
Django Version: 1.8.4
Exception Type: ValidationError
Exception Value:
[u"'eric clapton riding with the king' value must be a decimal number."]
Exception Location: C:\Anaconda\lib\site-packages\django\db\models\fields\__init__.py in to_python, line 1602
Python Executable: C:\Anaconda\python.exe
Python Version: 2.7.10
A:
Since the price requires a decimal value we should supply it a decimal value. Try the following view:
def get_queryset(self, *args, **kwargs):
qs = super(ProductListView, self).get_queryset(*args,**kwargs)
query = self.request.GET.get("q", False) # provide default value or you get a KeyError
if query:
filter_arg = Q(title__icontains=query) | Q(description__icontains=query)
try:
filter_arg |= Q(price=float(query))
except ValueError:
pass
qs = self.model.objects.filter(filter_arg)
return qs
qs = super(ProductListView, self).get_queryset(*args,**kwargs) This is used to obtain the queryset provided by the parent classes of our view class ProductListView. Look in to python classes and inheritance here:
http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/
filter_arg |= Q(price=float(query)) this is used to append to our filter_arg value. It's the same as filter_arg = filter_arg | Q(price=float(query)
float(query) with this we are trying to convert the query variable to a float and we put this in a try statement because it could give us a ValueError in which case the query value is not a float.
|
[
"stackoverflow",
"0040504253.txt"
] | Q:
How can I restrict value of variables in Golang?
I know Go idiomatic don't have setter and getter. But I need to restrict value of variables in Go.
I defined new type
type MyNewStringType string
And variables, that was defined as MyStringType, need to restrict value.
Variables of MyStringType can have only 3 values:
"Yes", "No", "I don't know"
How can I do it in Golang?
In Java, C++ I have setter and getter, but in Golang is not normal.
I know, I can create
type MyNewStringType struct {
Variable string
}
and create
func(m *MyNewStringType) SetVariable(newVar string) error {
if newVar == "Yes" || newVar == "No" || newVar == "I don't know" {
m.Variable = newVar
return nil
} else {
return errors.New("Wrong value")
}
But I think it's wrong way.
A:
Short awnser:
type MyString string
const (
YES MyString = "yes"
NO = "no"
DONTKNOW = "i dont know"
)
func foo(arg MyString){
fmt.Print(arg)
}
foo(YES) //success, prints "yes"
foo("jop") //fails to compile
|
[
"stackoverflow",
"0028857211.txt"
] | Q:
Parallel for loop in R
I have data.frame sent with sentences in sent$words and dictionary with pos/neg words in wordsDF data frame (wordsDF[x,1]). Positive words = 1 and negative = -1 (wordsDF[x,2]). The words in that wordsDF data frame are sorted in decreasing order according to their length (length of string). I used this purpose for my following function.
How this function works:
1) Count occurancies of words stored in wordsDF through each sentences
2) Compute sentiment score: count of occurencies particular word (wordsDF) in particular sentence * sentiment value for that word (positive = 1, negative = -1)
3) Remove that matched word from sentence for another iteration.
Original solution using of stringr package:
scoreSentence_01 <- function(sentence){
score <- 0
for(x in 1:nrow(wordsDF)){
count <- str_count(sentence, wordsDF[x,1])
score <- (score + (count * wordsDF[x,2])) # compute score (count * sentValue)
sentence <- str_replace_all(sentence, wordsDF[x,1], " ")
}
score
}
Faster solution - rows 4 and 5 replace row 4 in original solution.
scoreSentence_02 <- function(sentence){
score <- 0
for(x in 1:nrow(wordsDF)){
sd <- function(text) {stri_count(text, regex=wordsDF[x,1])}
results <- sapply(sentence, sd, USE.NAMES=F)
score <- (score + (results * wordsDF[x,2])) # compute score (count * sentValue)
sentence <- str_replace_all(sentence, wordsDF[x,1], " ")
}
score
}
Calling functions is:
scoreSentence_Score <- scoreSentence_01(sent$words)
In real I'm using data set with 300.000 sentences and dictionary with positive and negative words - overall 7.000 words. This approach is very very slow for that and because my beginer knowledge in R programming I'm in the end of my efforts.
Could you anyone help me, how to rewrite this function into vectorized or parallel solution, please. Any help or advice is very appreciated. Thank you very much in advance.
Dummy data:
sent <- data.frame(words = c("great just great right size and i love this notebook", "benefits great laptop at the top",
"wouldnt bad notebook and very good", "very good quality", "bad orgtop but great",
"great improvement for that great improvement bad product but overall is not good", "notebook is not good but i love batterytop"), user = c(1,2,3,4,5,6,7),
stringsAsFactors=F)
posWords <- c("great","improvement","love","great improvement","very good","good","right","very","benefits",
"extra","benefit","top","extraordinarily","extraordinary","super","benefits super","good","benefits great",
"wouldnt bad")
negWords <- c("hate","bad","not good","horrible")
# Replicate original data.frame - big data simulation (700.000 rows of sentences)
df.expanded <- as.data.frame(replicate(10000,sent$words))
sent <- coredata(sent)[rep(seq(nrow(sent)),10000),]
sent$words <- paste(c(""), sent$words, c(""), collapse = NULL)
rownames(sent) <- NULL
# Ordering words in pos/negWords
wordsDF <- data.frame(words = posWords, value = 1,stringsAsFactors=F)
wordsDF <- rbind(wordsDF,data.frame(words = negWords, value = -1))
wordsDF$lengths <- unlist(lapply(wordsDF$words, nchar))
wordsDF <- wordsDF[order(-wordsDF[,3]),]
wordsDF$words <- paste(c(""), wordsDF$words, c(""), collapse = NULL)
rownames(wordsDF) <- NULL
Desired output is:
words user scoreSentence_Score
great just great right size and i love this notebook 1 4
benefits great laptop at the top 2 2
wouldnt bad notebook and very good 3 2
very good quality 4 1
bad orgtop but great 5 0
great improvement for that great improvement bad product but overall is not good 6 0
notebook is not good but i love batterytop 7 0
A:
Okay, now that I know you have to work around phrases and words... here's another shot at it. Basically, you have to split out your phrases first, score them, remove them from the string, then score your words...
library(stringr)
sent <- data.frame(words = c("great just great right size and i love this notebook", "benefits great laptop at the top",
"wouldnt bad notebook and very good", "very good quality", "bad orgtop but great",
"great improvement for that great improvement bad product but overall is not good", "notebook is not good but i love batterytop"), user = c(1,2,3,4,5,6,7),
stringsAsFactors=F)
posWords <- c("great","improvement","love","great improvement","very good","good","right","very","benefits",
"extra","benefit","top","extraordinarily","extraordinary","super","benefits super","good","benefits great",
"wouldnt bad")
negWords <- c("hate","bad","not good","horrible")
sent$words2 <- sent$words
# split bad into words and phrases...
bad_phrases <- negWords[grepl(" ", negWords)]
bad_words <- negWords[!negWords %in% bad_phrases]
bad_words <- paste0("\\b", bad_words, "\\b")
pos_phrases <- posWords[grepl(" ", posWords)]
pos_words <- posWords[!posWords %in% pos_phrases]
pos_words <- paste0("\\b", pos_words, "\\b")
score <- - str_count(sent$words2, paste(bad_phrases, collapse="|"))
sent$words2 <- gsub(paste(bad_phrases, collapse="|"), "", sent$words2)
score <- score + str_count(sent$words2, paste(pos_phrases, collapse="|"))
sent$words2 <- gsub(paste(pos_phrases, collapse="|"), "", sent$words2)
score <- score + str_count(sent$words2, paste(pos_words, collapse="|")) - str_count(sent$words2, paste(bad_words, collapse="|"))
score
|
[
"stackoverflow",
"0045303515.txt"
] | Q:
Combine data from multiple lists of different length
I have a db query returning three sets of data. It comes in this format.
year = (('Adison', '355', 4), ('windsor windham', '455', 6), ('windham', '655', 2), ('btown', '233', 5))
month = (('Adison', '355', 2), ('windham', '655', 1))
week = (('btown', '233', 8), ('Adison', '355', 9))
The year list is always the longest with the most values. I need to take the last value from each element in the month and week lists and append them to the year list in their proper spot, based on the town.
IF there is not a corresponding value in month or week, I need to append a 0. Ideally making it look like this:
year = (('Adison', '355', 4, 2, 9), ('windsor windham', '455', 6, 0, 0), ('windham', '655', 2, 1, 0), ('btown', '233', 5, 0, 8))
I have tried putting two lists in a for loop and using an if in conditional to check values but I think I am overlooking something and am getting index errors. I tried something like this:
for each in year:
for part in month:
if part in each:
each.append(part[-1])
else:
each.append(0)
I know there has to be a better way, and one that actually works to accomplish this. Is there a tool or module I should be looking into? I have played with zip but because they are not the same length I am having trouble. Thank You!
EDIT
I understand that I have tuples above, In my code a convert them all to list objects before modifying. Also I am on Python 3.6
A:
First, key a dict off of the first two elements, using zeros as default for month and week. Then fill in the month and week, if necessary:
data = {(name, n): [y, 0, 0] for name, n, y in year}
for name, n, m in month:
data[name, n][1] = m
for name, n, w in week:
data[name, n][2] = w
data = tuple(tuple([*k, *v]) for k, v in data.items())
|
[
"stackoverflow",
"0038979791.txt"
] | Q:
Python: Excel to Web to PDF
I'm new to programming and am searching for the best way to pull PDFs of a series of water bills from a city website. I have been able to open the webpage and been able to open an account using an account numbers from an excel list, however, I am having trouble creating a loop to run through all accounts without rewriting code. I have some ideas, but I'm guessing that better suggestions exist. See below for the intro code:
import bs4, requests, openpyxl, os
os.chdir('C:\\Users\\jsmith.ABCINC\\Desktop')
addresses = openpyxl.load_workbook ('WaterBills.xlsx')
type (addresses)
sheet = addresses.get_sheet_by_name ('Sheet1')
cell = sheet ['A1']
cell.value
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://secure.phila.gov/WRB/WaterBill/Account/GetAccount.aspx')
elem = browser.find_element_by_css_selector('#MainContent_AcctNum')
elem.click()
elem.send_keys (cell.value)
elem = browser.find_element_by_css_selector('#MainContent_btnLookup')
elem.click()
Thanks for your assistance!
A:
Couldn't find a nice way to download the PDF but here's everything but:
import openpyxl
from selenium import webdriver
workbook = openpyxl.load_workbook('WaterBills.xlsx')
sheet = workbook.get_sheet_by_name('Sheet1')
column_a = sheet.columns[0]
account_numbers = [row.value for row in column_a if row.value]
browser = webdriver.Firefox()
browser.get('https://secure.phila.gov/WRB/WaterBill/Account/GetAccount.aspx')
for account_number in account_numbers:
search_box = browser.find_element_by_id('MainContent_AcctNum')
search_box.click()
search_box.send_keys(account_number)
search_button = browser.find_element_by_id('MainContent_btnLookup')
search_button.click()
# TODO: download the page as a PDF
browser.back()
browser.quit()
|
[
"stackoverflow",
"0029607080.txt"
] | Q:
TextField/Component Validation with Controls FX
I'm trying to implement a textfield like this one :
TextField Validation http://imageshack.com/a/img537/8329/FSht8P.png
My goal is to identify if the text of the TextField is a Double or something else (then it appears in red).
I want to use ControlsFX to learn the library and to not edit the css, but it doesn't work very well, and I'm lost in the javadoc. Does anyone have an example or can help me improve my code ?
Here what I tried to do :
Validator<Double> checkTextField = new Validator<Double>() {
@Override
public ValidationResult apply(Control t, Double u) {
ValidationResult vd = new ValidationResult();
if(Double.valueOf(t.toString()) != null){
vd.addErrorIf(t, "false", false);
}
return vd;
}
};
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.registerValidator(latitudeTextField, checkTextField/*Validator.createEmptyValidator("Text is required")*/);
ValidationDecoration iconDecorator = new GraphicValidationDecoration();
ValidationDecoration cssDecorator = new StyleClassValidationDecoration();
ValidationDecoration compoundDecorator = new CompoundValidationDecoration(cssDecorator, iconDecorator);
validationSupport.setValidationDecorator(compoundDecorator);
A:
You indeed make several mistakes. First you can have a look at the ControlsFX Showcase. There are always several code examples within their showcase.
Next your example expects the TextField to serve a Double to the Validator, but as you problably know the TextField itself only operates with Strings, so you will need a String Validator.
Then you try whatever control.toString() will print, which is most likely not the text it represents but some information about the control itself. What you want is the Text, which is currently shown in the textfield. For that you will not have to ask the control, since the text-value is already given to you in form of the value parameter 'u' in your case.
So what you want to do now is, you want to check, if the String could be parsed into a double. From the Documention you can find a Regex to check if this is the case (don't know if there are any better regexes for your case).
So all together it could look like this:
ValidationSupport support = new ValidationSupport();
Validator<String> validator = new Validator<String>()
{
@Override
public ValidationResult apply( Control control, String value )
{
boolean condition =
value != null
? !value
.matches(
"[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*" )
: value == null;
System.out.println( condition );
return ValidationResult.fromMessageIf( control, "not a number", Severity.ERROR, condition );
}
};
support.registerValidator( textfield, true, validator );
|
[
"literature.stackexchange",
"0000002402.txt"
] | Q:
In "The Sandman", what are nightmares for?
What purpose do nightmares serve in the world of The Sandman? In the second volume of The Sandman Library (The Doll's House), Dream spends most of his time tracking down and dealing with a number of errant nightmares (Brute, Glob, and the Corinthian). He refers to these as "his creations" many times, unforming some (to be reformed later) and banishing others (for a few thousand years, implying that they will eventually return).
What purpose do these creatures serve? Dream seems to take his "job"1 very seriously; this seems to include caring for the well-being of sentient creatures -- the other main story of The Doll's House, for example, was that of the dream vortex, which posed a great danger to anything that dreamed, and Morpheus did his best to avert the impending disaster.
In this volume, he also disbands and attempts to rehabilitate the Collectors.
One could argue that it's possible that while nightmares are not good for individual humans, they serve a greater purpose for humanity. The basis for that argument would be that the focus of Morpheus' care for sentient creatures appears to undergo some shift from humanity-only to include individual humans, and the nightmares were created long before Dream cared much for lone individuals. The only caveat that accompanies this interpretation is the apparent absence of a benefit for humanity in general. (At least, I don't see one.)
It cannot either be that nightmares are things that humans (or sentient beings) find in their minds, and that Dream does not remove -- in this universe, nightmares are the creations of the King of Dreams. They are things that he expressly created, for some purpose that escapes my understanding at the moment.
Do they serve some purpose in-universe? Are they just a plot device, or a metaphor? (Something else?)
When I searched Google, I was not able to find much about nightmares. The shared Wikia page for dreams and nightmares says (without a source) that "Nightmares are beings created by Dream to populate his realm and to help him with various tasks." This does not, however, explain what the purpose of nightmares is. TV Tropes seems to treat them all as mere "Nightmare Fuel," but I think there should be a greater purpose in them, especially since Neil Gaiman is such a careful writer, and Dream is such a careful guardian.
1 I'm not sure what, exactly, that job is. In three volumes of The Sandman, I have yet to see a job description. Perhaps that will come later.
A:
The Dreaming is supposed to be a reflection of the real world... or maybe vice versa? In any case, The Dreaming (and Dream), in a sense, define the real world - by defining the things that are not real.
Click for full resolution
According to Destiny, Morpheus' realm is a "metaphor" or an "allusion" of the real world; it's then easy to interpret dreams dreamers' reflections on the real world. It's not like dreams are defined as binding scenarios in The Sandman - they're more like stereotypes, or actors, used to convey a message.
What message could a nightmare convey then? Corinthian, according to Morpheus, is supposed to show dreamers the "darkness inside them":
Morpheus described Corinthian in more detail in The Kindly Ones:
Click for full resolution
Clearly, Corinthian was intended to show people that they, of everyone else, are their own antagonists.
How could one convey that message in a nice, happy dream? I imagine this method is the most powerful - how to convey the horrors one carries better than with a horror?
Nightmares, then, are intended for metaphors and allusions that require this, and not some other approach.
In the same way, good and cheerful dreams are supposed to reflect the happiness of the dreamers. If I was a sardonic person, I'd indicate that some people take joy from the suffering of others, but that's another conversation.
I'm saying "reflect" because it's what is implied throughout the whole story - that the Endless do not control but execute the will of the living beings. Hob Gadling's story may be a mockery of that - Death will not take him because he doesn't accept death as a part of life. Morpheus himself says that "[the Endless] are [living beings'] puppets":
Click for full resolution
|
[
"serverfault",
"0000033774.txt"
] | Q:
Read access control with Mercurial and Apache
I've set up Mercurial via Apache (hgwebdir.cgi).
I would like to have the same functionality as when using Subversion and AuthzSVNAccessFile, in which I can restrict which user has read or write permissions for every single repository. The acl extension only controls how changes are brought to the repository, as does the allow_push directive. Any thoughts?
A:
There is an allow_read directive that can be added to a repository hgrc that works the same way as allow_push. If specified, and the user accessing the hgwebdir CGI script is not in the list, the project doesn't even show up at the index page.
|
[
"stackoverflow",
"0024919096.txt"
] | Q:
Unable to retrieve string from EditText
Im trying to figure out why I am unable to get a valid string from two edittexts
The following lines are what I am talking about
String newPin = etNewPassword.getText().toString();
String conPin = etConfirmPassword.getText().toString();
Below is the entire file
public class PasswordDialogPreference extends DialogPreference {
TextView tvOldPassword;
TextView tvNewPassword;
TextView tvConfirmPassword;
EditText etOldPassword;
EditText etNewPassword;
EditText etConfirmPassword;
SharedPreferences sharedPrefs;
SharedPreferences.Editor editor;
public PasswordDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.password_dialog_preference);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel);
setDialogIcon(null);
setPersistent(false);
}
@Override
public void onBindDialogView(View view) {
tvOldPassword = (TextView) view.findViewById(R.id.tvOldPassword);
tvNewPassword = (TextView) view.findViewById(R.id.tvNewPassword);
tvConfirmPassword = (TextView) view.findViewById(R.id.tvConfirmPassword);
etOldPassword = (EditText) view.findViewById(R.id.etOldPassword);
etNewPassword = (EditText) view.findViewById(R.id.etOldPassword);
etConfirmPassword = (EditText) view.findViewById(R.id.etOldPassword);
sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getContext());
if (sharedPrefs.getString("prefPasscode", "").length() < 4) {
tvOldPassword.setVisibility(View.GONE);
etOldPassword.setVisibility(View.GONE);
}
super.onBindDialogView(view);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
persistBoolean(positiveResult);
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
//builder.setNegativeButton(null, null);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getContext());
String oldPin;
String newPin = etNewPassword.getText().toString();
String conPin = etConfirmPassword.getText().toString();
Log.d("pins", etNewPassword.getText().toString() + " " + etConfirmPassword.getText().toString());
if (newPin.equals(conPin)) {
//editor.putString("prefPasscode", etConfirmPassword.getText().toString());
//editor.commit();
Toast.makeText(getContext(), "Pin saved." + conPin,
Toast.LENGTH_SHORT
).show();
} else if (etNewPassword.getText().toString().length() != 4) {
Toast.makeText(getContext(), "Pin must be 4 digits.",
Toast.LENGTH_SHORT
).show();
} else if (!etNewPassword.getText().toString().equals(etConfirmPassword.getText().toString())) {
Toast.makeText(getContext(), "Pin does not match.",
Toast.LENGTH_SHORT
).show();
}
}
});
}
}
Below are the edittext layouts, im not sure if inputtype: numberpassword is causing any issues
<EditText
android:id="@+id/etNewPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:maxLength="4"
android:inputType="numberPassword"
android:width="100dp"
android:key="keyNewPasscode"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/etConfirmPassword"
android:maxLength="4"
android:textSize="15dp"
android:inputType="numberPassword"
android:width="100dp"
android:key="keyConfirmPasscode"/>
A:
You have similar ids of views:
etOldPassword = (EditText) view.findViewById(R.id.etOldPassword);
etNewPassword = (EditText) view.findViewById(R.id.etOldPassword);
etConfirmPassword = (EditText) view.findViewById(R.id.etOldPassword);
|
[
"math.stackexchange",
"0002260693.txt"
] | Q:
Which are the four equivalence classes to the relation R on the integers Z defined by xRy ⇔ x 2 ≡ y 2 (mod 7)?
This is the second part of a question that I don't get.
First part was for proving it is an equivalent relation, which I did, but I have a hard time finding out it's equivalence classes. How should I go about finding them?
A method, or thought process would be highly appreciated because I want to learn.
A:
In principle there could be only up to $7$ equivalence classes, since the group of integers mod $7$ has only seven equivalence classes.
We then can ask ourselves, which numbers (mod $7$), when squared, yield which of the seven potential squares. Well,
$$
0^2 \equiv 0\\1^2\equiv 1\\ 2^2 \equiv 4 \\3^2 \equiv 2
$$
and for the other three values,
$$
(7-k)^2 \equiv (-k)^2 \equiv k^2
$$
So the four equivalence classes are
$$
\{0\}, \{1,6\}, \{2,5\}, \{3,4\}
$$
|
[
"stackoverflow",
"0043114377.txt"
] | Q:
XQuery Count all Nodes
Is there a way to select the sum of all nodes within 1 XML nocument
for $c in doc("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial.xml")
return count($c//country)
That is what i currently have but this only returns the count of all top level nodes.
I would like to count all existing nodes.(recursively?)
A:
To count all nodes in this XML document, the following XPath expression suffices:
count(doc("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial.xml")//node())
|
[
"stackoverflow",
"0048344527.txt"
] | Q:
Mouseover not working when element above target element
I'm learning about mouse events. At the moment, my goal is to have 2 images on top of each other. For example, you move the mouse over an image and see a pop up. When you move the mouse away, the pop up goes. I think this is quite a common thing.
Because I have an image in front of the other, my research suggests I need to use mouseleave
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove_leave_out
The problem I have is that I get a flickering effect as I try to hide or remove the hide class (which makes the image visible or not)
This snippet shows everything
var inst = document.getElementById("instrument");
inst.addEventListener("mouseover", function() {
toggleEdit(true);
})
inst.addEventListener("mouseleave", function() {
toggleEdit(false);
})
var edit = document.getElementById("edit");
var i = 0;
function toggleEdit(isShow) {
console.log(i++);
edit.className = edit.className.replace(" hide", "");
if (!isShow) {
edit.className += " hide";
}
}
.parent {
position: relative;
margin-left: 40%;
background: green;
}
.image1 {
position: absolute;
top: 0;
left: 0;
}
.image2 {
position: absolute;
top: 0px;
}
.image2 img {
max-width: 20px;
}
.hide {
visibility: hidden;
display: block;
}
<div class="parent">
<img class="image1" src="https://placehold.it/100" id="instrument" />
<a id="edit" href="#" class="image2 hide"><img src="https://cdn.pixabay.com/photo/2017/06/06/00/33/edit-icon-2375785_960_720.png" /></a>
</div>
JSFIDDLE
How do I prevent this flickering?
A:
You don't need JS at all for that. It can be achieved just with CSS using :hover
.parent {
position: relative;
margin-left: 40%;
background: green;
}
.parent:hover .image2{
visibility: visible
}
.image1 {
position: absolute;
top: 0;
left: 0;
}
.image2 {
position: absolute;
top: 0px;
visibility: hidden;
}
.image2 img {
max-width: 20px;
}
<div class="parent">
<img class="image1" src="https://placehold.it/100" id="instrument" />
<a id="edit" href="#" class="image2">
<img src="https://cdn.pixabay.com/photo/2017/06/06/00/33/edit-icon-2375785_960_720.png" />
</a>
</div>
|
[
"stackoverflow",
"0018064374.txt"
] | Q:
What do Ctrl+number keys do in a terminal?
I am attempting to fill my keyboard with more bindings for tmux and vim, and I thought about using Ctrl+1, Ctrl+2, etc.
In tmux Ctrl+4 caused it to create a vertical split, which was interesting, then I tried it outside of tmux inside of cat and got this:
% cat
^@^[^\[1] 5730 quit (core dumped) cat
Here I typed Ctrl+1 (produced no output), Ctrl+2 (^@), Ctrl+3 (^[), and Ctrl+4 after which point it promptly died like this.
Now I will say that I have Ctrl+\ bound to vertical split in tmux, so that makes sense, but at this point I'm wondering why these bindings are like this. I fear that it means I can never distinguish e.g. Ctrl+3 from the Esc key.
A:
There's not a real definite answer. It's all based on the operating system you're using. For example, I'm using Ubuntu 12.04 on one computer, and its key bindings are different than what I have another system with an older version that I keep as a server.
|
[
"stackoverflow",
"0004839498.txt"
] | Q:
Using printf to print a COLORREF type variable
I need to print a variable which is a COLORREF.
A:
A COLORREF is just an integer containing an RGB value. You can print a hex representation this way:
printf("%06X", color);
Note that the order of values is bbggrr, so it will look different from the usual rrggbb format.
A:
You might also want to break it up into the individual RGB components:
printf("R: %i, G: %i, B: %i", GetRValue(color), GetGValue(color), GetBValue(color));
this would give you something like:
R: 255, G: 150, B: 75
|
[
"stackoverflow",
"0032464638.txt"
] | Q:
How to invert the colors of a ggmap raster image in R?
I'm assuming the Raster package has what I need... I'm simply wanting to invert the colors in a Raster image.
The actual scenario is this: I want to invert the raster image returned by a ggmap call:
library(ggmap)
ggmap(get_stamenmap(maptype = "toner"))
I want to invert the colors to get a white-on-black version of the Stamen Toner map:
A:
This inverts the raster object returned by get_stamenmap()
library("ggmap")
m <- get_stamenmap(maptype = "toner")
# invert colors in raster
invert <- function(x) rgb(t(255-col2rgb(x))/255)
m_inv <- as.raster(apply(m, 2, invert))
# copy attributes from original object
class(m_inv) <- class(m)
attr(m_inv, "bb") <- attr(m, "bb")
ggmap(m_inv)
|
[
"stackoverflow",
"0005531383.txt"
] | Q:
How do I change a drop placeholder depending on the dragged object in jQuery UI Sortable?
I have modules of different sizes, I want the placeholder to be of the same size of the module being dragged, this is what I have figured out so far...
$( "#col1, #col2, #col3" ).sortable({
connectWith: ".col",
start: function(event, ui) {
var type = ui.item.hasClass("double") ? " double": "";
},
placeholder: "module drop" + type
}).disableSelection();
My problem is that I'm trying to use var "type" outside the scope of start, but I can't figure any other way of doing this.
If anyone wants to play around with the code, I've set up a fiddle here:
http://jsfiddle.net/TfcQq/
A:
According to jquery ui documentation ( http://jqueryui.com/demos/sortable/#placeholder ), there is a setter for placeholder.
Be careful with spaces in the value, looks like it is a css class.
So you can try :
$( "#col1, #col2, #col3" ).sortable({
connectWith: '.col'
}).disableSelection();
$(".module").mouseover(function(){
$( "#col1, #col2, #col3" ).sortable( "option", "placeholder", 'drop-single' );
});
$(".module.double").mouseover(function(){
$( "#col1, #col2, #col3" ).sortable( "option", "placeholder", 'drop-double' );
});
|
[
"stackoverflow",
"0033974509.txt"
] | Q:
CSV to list of ints and count occurrence of integers
This feels like it should be super easy, but i'm struggling to find a solution.
I've got a CSV file full of ints
9,12,9,12,8,6,10,7,7,15,8,8,7,8,8,10,10,3,8
all I am trying to do is read the CSV file to a list of ints and use Counter from Collections to count the occurrence of each int, then save this info to a CSV file.
I've tried
import csv
from collections import Counter
with open('/Users/willturner/Desktop/caloHits.csv', 'rb') as f:
reader = csv.reader(f)
CaloHits = list(reader)
print Counter(10)
to get the number of 10's in the list. But I get
-> TypeError: 'int' object is not iterable
I've tired lots of different things but havn't had success with anything.
A:
You can do this by looping through the csv lines/rows and updating the counter object by each row.
import csv
from collections import Counter
calo_hits = Counter()
with open('/Users/willturner/Desktop/caloHits.csv') as f: # 'rb' is not necessary
reader = csv.reader(f)
for row in reader:
calo_hits.update([int(n.strip()) for n in row if n.strip()])
print calo_hits[10]
|
[
"stackoverflow",
"0013501652.txt"
] | Q:
Regex all uppercase with special characters
I have a regex '^[A0-Z9]+$' that works until it reaches strings with 'special' characters like a period or dash.
List:
UPPER
lower
UPPER lower
lower UPPER
TEST
test
UPPER2.2-1
UPPER2
Gives:
UPPER
TEST
UPPER2
How do I get the regex to ignore non-alphanumeric characters also so it includes UPPER2.2-1 also?
I have a link here to show it 'real-time': http://www.rubular.com/r/ev23M7G1O3
This is for MySQL REGEX
EDIT: I didn't specify I wanted all non-alphanumeric characters (including spaces), but with the help of others here it led me to this: '^[A-Z-0-9[:punct:][:space:]]+$' is there anything wrong with this?
A:
Try
'^[A-Z0-9.-]+$'
You just need to add the special characters to the group, optionally escaping them.
Additionally if you choose not to escape the -, be aware that it should be placed at the start or the end of the grouping expression to avoid the chance that it may be interpreted as delimiting a range.
To your updated question, if you want all non-whitespace, try using a group such as:
^[^ ]+$
which will match everything except for a space.
If instead what you wanted is all non-whitespace and non-lowercase, you likely will want to use:
^[^ a-z]+$
The 'trick' used here is adding a caret symbol after the opening [ in the group expression. This indicates that we want the negation of the match.
Following the pattern, we can also apply this 'trick' to get everything but lowercase letters like this:
^[^a-z]+$
I'm not really sure which of the 3 above you want, but if nothing else, this ought to serve as a good example of what you can do with character classes.
A:
I believe you are looking for (one?) uppercase-word match, where word is pretty much anything.
^[^a-z\s]+$
...or if you want to allow more words with spaces, then probably just
^[^a-z]+$
|
[
"askubuntu",
"0000347531.txt"
] | Q:
How to choose to open with Software Center application from the browser?
I am currently using Ubuntu 12.04. I wanted to install fonts for the Indian languages and searching in Google led me to this site.
When I clicked on the available on the Software Centre button, the Launch Application window opens. I clicked the Choose button to choose the Software Centre application. But I do not know the location to choose from i.e., where the Software Centre application resides on my PC. How do I find it?
A:
This is the location of Ubuntu Software Center:
/usr/bin/software-center
(I've got it very quickly using this answer).
|
[
"meta.stackoverflow",
"0000259987.txt"
] | Q:
Should the public be able to vote on the actions of editing reviewers?
Frankly I find the editor's powers draconian and wish there was a way for the public to easily express their opinion of rulings, such as "closed as primarily opinion-based". It is a matter of opinion as to whether something is a matter of opinion, or duplicate or whatever, and the public should be able to readily override an editor's ruling via a vote.
I've personally experienced having my question shut down because the editor didn't understand a nuance of my question; I found that trying to appeal or change this was not going to be an easy practice so I gave up and had to seek help elsewhere.
I also see discussions that are theoretically asking for objective information but because various answers opine, the entire discussion is closed as being opinion based. I suggest that it would be far better for the editor to flag individual answers as being unsubstantiated rather than closing the discussion. Product-related questions, for instance, are especially plagued by this. There are objective measures to be had for comparing products, and those objective differences are extremely valuable to know, so the forum should be left open for those willing to do the hard research.
Community appeal based voting could also have the side effect of getting users to think more about the appropriateness of various practices and engage them more at the editor level.
A:
Your use of the word "editor" with respect of the rest of your question suggest you might not quite be familiar with the workings of Stack Overflow, despite the fact that you are approaching 500 rep and have been a member for almost 5 years.
"Closed a primarily-opinion based" has absolutely nothing to do with editing. Editing is solely related to editing the body (or title) of the question itself to correct issues with the post. The act of closing questions for various reasons is related to the site's moderation and is performed both by the site's moderators and by regular community members such as yourself.
I find the editor's powers draconian and wish there was a way for the public to easily express their opinion of rulings, such as "closed as primarily opinion-based". It is a matter of opinion as to whether something is a matter of opinion, or duplicate or whatever, and the public should be able to readily override an editor's ruling via a vote.
Your wish is granted. The community can already override any close actions by any users. If a question is incorrectly closed, users with 3K rep can vote to reopen the question. And users with less than 3K rep can flag the post and have a diamond moderator review the question, however, moderators are not likely to override the community unless there is a serious error or misunderstanding.
I've personally experienced having my question shut down because the editor didn't understand a nuance of my question; I found that trying to appeal or change this was not going to be an easy practice so I gave up and had to seek help elsewhere.
If you edited an explanation into your question after it was closed, it would have automatically been put into a review queue so other users can evaluate the edit and decide if the changes merited the question getting reopened. If you left your explanation in the form of a comment, or if your edit did not do enough to convince other users that your question indeed needs to be reopened, then the question would likely have remained closed.
I also see discussions that are theoretically asking for objective information but because various answers opine, the entire discussion is closed as being opinion based. I suggest that it would be far better for the editor to flag individual answers as being unsubstantiated rather than closing the discussion. Product-related questions, for instance, are especially plagued by this. There are objective measures to be had for comparing products, and those objective differences are extremely valuable to know, so the forum should be left open for those willing to do the hard research.
It is impossible to provide any kind of reasonable answer based on the info you have provided. Improperly closed questions happen, but they can be fixed. However, without a specific example (or examples), we can't provide you with any kind of objective feedback. I will say that Stack Overflow is not a site for just any question. There are very strict guidelines on what is on-topic and what is considered acceptable for the site. If you are confused as to what to ask, I suggest you review How to Ask in the help center.
|
[
"stackoverflow",
"0004199370.txt"
] | Q:
How to Create Event for Dynamic Control Array in VB.NET
I'm trying to create an array of checkboxes dynamically and also want to put event to those checkboxes. How can I do this?
For example:
I have a array of checkboxes - Chk1, Chk2.
I want it to work this way: When I check Chk1, I want to disable Chk2, and when Chk1 is unchecked, Chk2 is enable, and vice versa.
Your input is greately appreciated.
Thanks,
P.S.: The code is in VB.NET. Thanks.
Thank you all for the inputs. I really appreciated it. Maybe I wasn't very clear on my explanation earlier.
Let's say, I have an array of 6 checkboxes, and I want them to behave in group like this:
When Chk1 is checked, Chk2 is disabled (grey out), and when we uncheck Chk1, Chk2 is enabled, and Vice Versa.
When Chk3 is checked, Chk4 is disabled, and when we uncheck Chk3, Chk4 is enabled, and Vice Versa.
and so on....
So this is like each pair of checkboxes in the array perform the CheckChanged event upon each other, but not on any other pair. So I think OptionButton is not the case in this situation.
Thanks for any suggestions.
A:
Assuming that it is ASP.Net, have a look at this "strange" example to see how it works(take your array instead of my static creation):
Private Sub WebForm1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For number As Int32 = 1 To 100
Dim chk As New CheckBox
chk.ID = "chk" & number
chk.Text = chk.ID
chk.AutoPostBack = True
AddHandler chk.CheckedChanged, AddressOf onCheckedChanged
Me.MyChkPanel.Controls.Add(chk)
Next
End Sub
Private Sub onCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chk As CheckBox = DirectCast(sender, CheckBox)
Dim number As Int32 = Int32.Parse(chk.ID.Substring("chk".Length))
Dim otherChk As CheckBox
If number Mod 2 = 0 Then
otherChk = DirectCast(Me.MyChkPanel.FindControl("chk" & (number - 1)), CheckBox)
Else
otherChk = DirectCast(Me.MyChkPanel.FindControl("chk" & (number + 1)), CheckBox)
End If
otherChk.Enabled = Not chk.Checked
End Sub
Apart from that i can subscribe Hans' suggestion to use RadioButtons or at least a CheckBoxList.
|
[
"stackoverflow",
"0055502800.txt"
] | Q:
How to add/change names of components to an existing Tensorflow Dataset object?
From the Tensorflow dataset guide it says
It is often convenient to give names to each component of an element,
for example if they represent different features of a training
example. In addition to tuples, you can use collections.namedtuple or
a dictionary mapping strings to tensors to represent a single element
of a Dataset.
dataset = tf.data.Dataset.from_tensor_slices(
{"a": tf.random_uniform([4]),
"b": tf.random_uniform([4, 100], maxval=100, dtype=tf.int32)})
print(dataset.output_types) # ==> "{'a': tf.float32, 'b': tf.int32}"
print(dataset.output_shapes) # ==> "{'a': (), 'b': (100,)}"
https://www.tensorflow.org/guide/datasets
And this is very useful in Keras. If you pass a dataset object to model.fit, the names of the components can be used to match the inputs of your Keras model. Example:
image_input = keras.Input(shape=(32, 32, 3), name='img_input')
timeseries_input = keras.Input(shape=(None, 10), name='ts_input')
x1 = layers.Conv2D(3, 3)(image_input)
x1 = layers.GlobalMaxPooling2D()(x1)
x2 = layers.Conv1D(3, 3)(timeseries_input)
x2 = layers.GlobalMaxPooling1D()(x2)
x = layers.concatenate([x1, x2])
score_output = layers.Dense(1, name='score_output')(x)
class_output = layers.Dense(5, activation='softmax', name='class_output')(x)
model = keras.Model(inputs=[image_input, timeseries_input],
outputs=[score_output, class_output])
train_dataset = tf.data.Dataset.from_tensor_slices(
({'img_input': img_data, 'ts_input': ts_data},
{'score_output': score_targets, 'class_output': class_targets}))
train_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)
model.fit(train_dataset, epochs=3)
So it would be useful for look up, add, and change names to components in tf dataset objects. What is the best way to go about doing these tasks?
A:
You can use map to bring modifications to your dataset, if that is what you are looking for. For example, to transform a plain tuple output to a dict with meaningful names,
import tensorflow as tf
# dummy example
ds_ori = tf.data.Dataset.zip((tf.data.Dataset.range(0, 10), tf.data.Dataset.range(10, 20)))
ds_renamed = ds_ori.map(lambda x, y: {'input': x, 'output': y})
batch_ori = ds_ori.make_one_shot_iterator().get_next()
batch_renamed = ds_renamed.make_one_shot_iterator().get_next()
with tf.Session() as sess:
print(sess.run(batch_ori))
print(sess.run(batch_renamed))
# (0, 10)
# {'input': 0, 'output': 10}
|
[
"stackoverflow",
"0036969353.txt"
] | Q:
Mysql query "reports" with several equal tags
I have a database which stores reports, and every report has several tags. The relationship between tags and reports is stored in a table called report_tags.
As you can see Report 39 and 40 have two equal tags. I want them as a result.
CREATE TABLE IF NOT EXISTS `report_tags` (
`Report_ID` int(5) NOT NULL,
`Tag_ID` int(5) NOT NULL,
PRIMARY KEY (`Report_ID`,`Tag_ID`),
KEY `tagid_fk` (`Tag_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `report_tags` (`Report_ID`, `Tag_ID`) VALUES
(22, 8),(32, 8),(33, 8),(38, 8),(37, 244),(37, 245),(38, 246),(38, 247),(38, 248),(39, 249),(39, 250),(39, 251),(40, 251),(39, 252),(40, 252);
A:
You can do this with joins:
select rt1.report_id, rt2.report_id, count(*) as numtagsincommon
from report_tags rt1 join
report_tags rt2
on rt1.tag_id = rt2.tag_id and rt1.report_id < rt2.report_id
group by rt1.report_id, rt2.report_id
having count(*) > 1;
Here is a SQL Fiddle (albeit using Postgres with one additional value paid).
|
[
"stackoverflow",
"0004445123.txt"
] | Q:
Cannot load Shorturl gem (ruby ErrorLoad)
I'm fairly new to Ruby and keep knocking my head against gems, but this latest puzzle has really got me stumped.
After using the gem install shorturl, I added the following headers to a file in my project:
require "rubygems"
require "shorturl"
class Controller < Autumn::Leaf
When I run the project I get the following error:
myfile.rb:3 in `require': no such file to load -- shorturl (LoadError)
I'm not sure what other information would be useful, except that without the require the script is working. I'm guessing I need to add the rubygems path to some variable, but I have no idea which. Any ideas?
A:
You can run gem environment to see the environment that RubyGems is running in. Under GEM PATHS should be listed the paths that RubyGems will search for gems.
Depending on if you installed the gem as root or not it will either be under somewhere like /usr/local/lib/ruby/gems/1.8 or somewhere within your home directory. You can use gem list -d shorturl to find out where it is installed. If where it is isn't listed in the GEM PATHS you will have to add it to the GEM_PATH environment variable. For example:
export "GEM_PATH=$GEM_PATH:/usr/local/lib/ruby/gems/1.8"
if that works you then need to add it to somewhere like your .bashrc to ensure its always loaded.
|
[
"stackoverflow",
"0030719783.txt"
] | Q:
Creating Stripe transactions without recreating the user each time
I have been working on a Rails shopping cart app and noticed that the example code in Stripe's API creates a new customer every time I put a (test) order through.
This is obviously undesirable, and as a Ruby/Rails newbie, I've been scouring SO and every tutorial I can find to figure out how to have it check to see if the customer exists before creating it. The standard way of doing it seems to be to check for stripe_customer_token and proceed based on whether or not one is present. But no matter how I approach it, I get a NoMethodError for customer_token.
This is my current charges_controller.rb:
class ChargesController < ApplicationController
def new
end
def create
if self.customer_token.present?
@customer = Stripe::Customer.retrieve(current_user.stripe_customer_token)
else
@customer = Stripe::Customer.create(
:email => self.manager.email, card => stripe_token
)
charge = Stripe::Charge.create(
:amount => (params[:amount].to_f * 100).abs.to_i,
currency => "usd",
card => params[:stripeToken],
description => params[:email]
)
@amount = params[:amount]
@payment_id = charge.id
end
end
end
What I get from the server is:
Started POST "/charges" for 50.184.82.198 at 2015-06-08 21:26:57 +0000
Processing by ChargesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"BLAHBLAHBLAH", "stripeToken"=>"BLAHBLAH", "stripeTokenType"=>"card", "stripeEmail"=>"[email protected]"}
Completed 500 Internal Server Error in 7ms
NoMethodError (undefined method `customer_token' for #<ChargesController:0x007fa788783638>):
app/controllers/charges_controller.rb:48:in `create'
Lines 48 and 49 are:
if self.customer_token.present?
@customer = Stripe::Customer.retrieve(current_user.stripe_customer_token)
(the line numbers are so high because there's a fair bit of commented-out code above that with different things I've tried)
What's strange (to my neophyte mind) is that it craps out at stripe_customer_token, but if I change stripe_customer_token to customer_token, it craps out at the line before it -- at self.customer_token. Surely if that were a problem it should be crapping out there regardless of what's on line 49?
More importantly, can anyone shed some light on what I am doing wrong here, or on any solutions that I may have missed on this site? Thank you!!
A:
I think the issue is that you are requesting the customer_tokenfrom the controller, rather than from the current_user. Is stripe_customer_token something that is stored on the user? And are you wanting to check if that is there before you fetch the customer? If so…
Change:
if self.customer_token.present?
to:
if current_user.stripe_customer_token.present?
|
[
"stackoverflow",
"0048828778.txt"
] | Q:
whats the correct way to be back to top view controller in the navigation controller stack?
https://i.stack.imgur.com/ayMVR.png
Sorry, I am a beginner, I am worried that I will make something weird if I do something wrong later.
if I have 3 view controllers like the picture above,and in the 3rd view controller I have an alert that sent me back to the 1st view controller after pressing the alert like the code below :
class ViewController3: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let alert = UIAlertController(title: "Great", message: "lets get back to VC1", preferredStyle: .alert)
let alertAction1 = UIAlertAction(title: "back", style: .default) { (action) in
self.navigationController?.popToRootViewController(animated: true)
}
alert.addAction(alertAction1)
present(alert, animated: true, completion: nil)
}
}
there are 2 ways to be back to first view controller, by using
1. self.navigationController?.popToRootViewController(animated: true)
or by using 2. perform segue with identifier , what is the correct way to be back to the first view controller? the first one or the second? and why?
A:
best way is
1. self.navigationController?.popToRootViewController(animated: true)
also check this out because you will understand why it is better (clear navigation stack)
|
[
"stackoverflow",
"0040759088.txt"
] | Q:
Perl: pair elements in two list
I have two lists:
my @prefixes = ["abc", "def", "ghi", "jklmn"];
my @strings = ["abc123", "def456", "jklmnopqrst"];
I need to find the correct prefix for each string so that "abc123" belongs to "abc" and "def456" belongs to "def" and "jklmnopqrst" belongs to "jklmn".
All strings has a prefix in @prefixes but not all prefix has a matching string (see "ghi").
I have this code:
use List::Util qw(first);
...
foreach my $str (@strings) {
my $prefix = first { $_ eq substr($str, 0, length($_)) } @prefixes;
print "$prefix\n";
# do something with $str and $prefix together
}
But it's not working, I'm getting Use of uninitialized value $prefix in concatenation (.) or string
What's wrong?
UPDATE: So it was an easy fix. I should have initialized my lists using () and not []. To not to close this yet, how would you get rid of the foreach statement?
A:
You can create a regex pattern from the prefixes and use that to construct a hash:
#!/usr/bin/env perl
use strict;
use warnings;
use YAML::XS;
my @prefixes = qw[abc def ghi jklmn];
my @strings = qw[abc123 def456 jklmnopqrst];
my ($prefix_re) = map qr/$_/, sprintf(
'^(?<prefix>%s)',
join '|', sort { length $b <=> length $a } @prefixes
);
print "$prefix_re\n";
my %matches = map { $_ =~ $prefix_re; ($+{prefix}, $_) } @strings;
print Dump \%matches;
Output:
abc: abc123
def: def456
jklmn: jklmnopqrst
If multiple strings can match a prefix, you can map prefixes to lists of matched strings:
#!/usr/bin/env perl
use strict;
use warnings;
use YAML::XS;
my @prefixes = qw[abc def ghi jklmn];
my @strings = qw[abc123 def456 def789 jklmnopqrst];
my ($prefix_re) = map qr/$_/, sprintf(
'^(?<prefix>%s)',
join '|', sort { length $b <=> length $a } @prefixes
);
print "$prefix_re\n";
my %matches;
for my $str ( @strings ) {
next unless $str =~ $prefix_re;
push @{ $matches{ $+{prefix} }}, $str;
}
print Dump \%matches;
Output:
---
abc:
- abc123
def:
- def456
- def789
jklmn:
- jklmnopqrst
|
[
"stackoverflow",
"0043886458.txt"
] | Q:
Unit testing Vue components that rely on a global event bus
I declare an event bus in my global app.js like so:
window.Event = new Vue();
The component looks like
export default {
data() {
return {
hasError: false,
zip: '',
};
},
methods: {
setZip: function() {
this.hasError = false;
this.$emit('setZip', this.zip);
},
},
mounted() {
Event.$on('showErrors', (errors) => {
this.hasError = errors.zip ? true : false;
});
this.zip = this.editZip;
},
props: [
'editZip'
],
}
I unit test my components with ava with the following helpers/setup.js:
const browserEnv = require('browser-env');
const hook = require('vue-node');
const { join } = require('path');
// Setup a fake browser environment
browserEnv();
// Pass an absolute path to your webpack configuration to the hook function.
hook(join(__dirname, './webpack.config.js'));
The webpack.config.js looks like:
module.exports = {
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.js', '.vue'],
},
};
When running the following test
import Vue from 'vue/dist/vue.js';
import test from 'ava';
import Zip from '../../resources/assets/js/components/Company/Zip.vue';
let vm;
test.beforeEach(t => {
let Z = Vue.extend(Zip);
vm = new Z({ propsData: {
editZip: 1220
}}).$mount();
});
test('that it renders a div with class form-group', t => {
t.is(vm.$el.className, 'form-group');
});
it passes, but the following error gets thrown:
[Vue warn]: Error in mounted hook: "TypeError: Event.$on is not a function"
(found in <Root>)
TypeError: Event.$on is not a function
at VueComponent.mounted (/mnt/c/code/leaflets/resources/assets/js/components/Company/City.vue:107:15)
at callHook (/mnt/c/code/leaflets/node_modules/vue/dist/vue.js:2530:21)
at mountComponent (/mnt/c/code/leaflets/node_modules/vue/dist/vue.js:2424:5)
at VueComponent.Vue$3.$mount (/mnt/c/code/leaflets/node_modules/vue/dist/vue.js:7512:10)
at VueComponent.Vue$3.$mount (/mnt/c/code/leaflets/node_modules/vue/dist/vue.js:9592:16)
at Test._ava2.default.beforeEach.t [as fn] (/mnt/c/code/leaflets/tests/js/CompanyCity.js:12:9)
at Test.callFn (/mnt/c/code/leaflets/node_modules/ava/lib/test.js:281:18)
at Test.run (/mnt/c/code/leaflets/node_modules/ava/lib/test.js:294:23)
at runNext (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44)
at Sequence.run (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10)
at Concurrent.run (/mnt/c/code/leaflets/node_modules/ava/lib/concurrent.js:41:37)
at runNext (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44)
at Sequence.run (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10)
at runNext (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44)
at Sequence.run (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10)
at Bluebird.try (/mnt/c/code/leaflets/node_modules/ava/lib/runner.js:214:48)
at tryCatcher (/mnt/c/code/leaflets/node_modules/bluebird/js/release/util.js:16:23)
at Function.Promise.attempt.Promise.try (/mnt/c/code/leaflets/node_modules/bluebird/js/release/method.js:39:29)
at Runner.run (/mnt/c/code/leaflets/node_modules/ava/lib/runner.js:214:22)
at process.on.options (/mnt/c/code/leaflets/node_modules/ava/lib/main.js:82:10)
at emitOne (events.js:96:13)
at process.emit (events.js:191:7)
at process.on.message (/mnt/c/code/leaflets/node_modules/ava/lib/process-adapter.js:14:10)
at emitTwo (events.js:106:13)
at process.emit (events.js:194:7)
at process.nextTick (internal/child_process.js:766:12)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
I can't figure out where to declare the window.Event = new Vue() in my test, so that the tested component can access the Event variable.
A:
First of all, I'd recommend to remove the global EventBus from the window object (if you can), as it's not often ideal to rely on global props that could get overwritten by some other parts of the code leading to undesired effects.
You can just create a event-bus.js file and create the event bus in there:
import Vue from 'vue';
export const EventBus = new Vue();
Then you can just import that file from any other component that needs access to the event bus like
import {EventBus} from '/path/to/event-bus.js'
From there, you can use it exactly as you're currently using it.
However, if you have to keep your EventBus in the window object for some reason, you'll have to also mock it so you can test it.
First, when you call the browserEnv function, you'll need to mock the window object by doing this:
browserEnv(['window']);
Then, window will be available as a global variable, but you will need to change the implementation of your component to explicitly grab the EventBus from the window object, like:
window.EventBus
You can also define it globally in your component like:
const { EventBus } = window
Let me know if this works.
Thanks,
|
[
"stackoverflow",
"0036218551.txt"
] | Q:
How delete many-to-many relation in Entity Framework 6
I have a problem with the removal of items from the database if connects them a many to many relationship
My database look like
| [Project] | <-- | [JobInProject] | --> | [Job] |
============= ================== =========
| ProjectID | | JobInProjectID | | JobID |
| | | ProjectID | | |
| | | JobID | | |
Primary keys from Project and Job table are also set as foreign key in others tables but I think it isn't problem because when I remove item from Job table, it is removed correctly with all related items in others tables
All foreign keys are set by constraint and on delete cascade on update cascade
Code which I use to delete job item
Job job = await db.Jobs.FindAsync(id);
db.Entry(job).State = EntityState.Deleted;
await db.SaveChangesAsync();
and project:
Project project = await db.Projects.FindAsync(id);
db.Entry(project).State = EntityState.Deleted;
await db.SaveChangesAsync();
Code to remove project item remove only data from Project table and JobInProject table do not remove Job and related items.
When I modify code to remove Project like this:
Project project = await db.Projects.FindAsync(id);
foreach (var item in project.JobInProjects)
{
db.Entry(item.Job).State = EntityState.Deleted;
}
db.Entry(project).State = EntityState.Deleted;
await db.SaveChangesAsync();
I get an error on the await db.SaveChangesAsync(); line
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
How can I remove Project item and related Job items ?
I will be grateful for help
A:
It's because you don't mark the JobInProject object as Deleted:
foreach (var item in project.JobInProjects)
{
db.Entry(item.Job).State = EntityState.Deleted;
db.Entry(item).State = EntityState.Deleted; // <= line added
}
If you don't do that, EF will assume you don't want to delete the item and try to set both foreign keys in JobInProject to null, but of course one or more of the foreign-key properties is non-nullable (both aren't).
|
[
"stackoverflow",
"0023064613.txt"
] | Q:
AngularJS ngTable not updated
I am using Angular routing in my application as well as ngTable. One of my pages contains a ngTable, and a search form, where data is coming from database using GET method (MongoDB) every time I search, so every time I search the ngTable (table) should be updated, and my problem is that the Table is updated only one time, after loading the page for the first time.
The contoller used for the partial page :
app.controller('SearchController',function($scope,ngTableParams,$http,$filter, $sce){
$scope.searching=function(){
var str = $scope.search.tags;
var TagsArry = str.split(",");
$http.get('/api/GetDoc',{params:{title:$scope.search.title,tags:$scope.search.tags}})
.success(function(data)
{
if(data.notExist!=-1){
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: data.length, // length of data
getData: function($defer, params) {
$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
}
})
.error(function(err){
});
}
});
A:
I was having the same issue. You need to reload $scope.tableParams every time a new search occurs, so every time the search button is clicked. A simple way to do this is to wrap $scope.tableParams.reload() in a function, and then call that function when your search button is clicked.
controller code:
$scope.doSearch = function () {
$scope.tableParams.reload();
}
html code:
<button ng-click="doSearch()">Search</button>
|
[
"stackoverflow",
"0007246459.txt"
] | Q:
Creating a 2D polygon in XNA
I have some sort of a problem. I'm new to XNA and want to draw a polygon shape that looks something like this (In the end, I want these point to be random):
So I read some articles and this is what I ended up with:
private VertexPositionColor[] vertices;
public TextureClass()
{
setupVertices();
}
public override void Render(SpriteBatch spriteBatch)
{
Texture2D texture = createTexture(spriteBatch);
spriteBatch.Draw(texture, new Rectangle((int)vertices[0].Position.X, (int)vertices[0].Position.Y, 30, 30), Color.Brown);
}
private Texture2D createTexture(SpriteBatch spriteBatch)
{
Texture2D texture = new Texture2D(spriteBatch.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
texture.SetData<Color>(new Color[] { Color.Brown });
return texture;
}
When I call Render it's starts drawing some squares as if it where in a loop. I'm just guessing I'm doing it all wrong. I would love it if someones points me into the right direction. Just creating a polygon and drawing it. It seemed so simple...
A:
Here it what I have right now.
A class that generates a BasicEffect with some desired asignments.
public class StandardBasicEffect : BasicEffect
{
public StandardBasicEffect(GraphicsDevice graphicsDevice)
: base(graphicsDevice)
{
this.VertexColorEnabled = true;
this.Projection = Matrix.CreateOrthographicOffCenter(
0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1);
}
public StandardBasicEffect(BasicEffect effect)
: base(effect) { }
public BasicEffect Clone()
{
return new StandardBasicEffect(this);
}
}
Here is my PolygonShape class
/// <summary>
/// A Polygon object that you will be able to draw.
/// Animations are being implemented as we speak.
/// </summary>
/// <param name="graphicsDevice">The graphicsdevice from a Game object</param>
/// <param name="vertices">The vertices in a clockwise order</param>
public PolygonShape(GraphicsDevice graphicsDevice, VertexPositionColor[] vertices)
{
this.graphicsDevice = graphicsDevice;
this.vertices = vertices;
this.triangulated = false;
triangulatedVertices = new VertexPositionColor[vertices.Length * 3];
indexes = new int[vertices.Length];
}
/// <summary>
/// Triangulate the set of VertexPositionColors so it will be drawn correcrly
/// </summary>
/// <returns>The triangulated vertices array</returns>}
public VertexPositionColor[] Triangulate()
{
calculateCenterPoint();{
setupIndexes();
for (int i = 0; i < indexes.Length; i++)
{
setupDrawableTriangle(indexes[i]);
}
triangulated = true;
return triangulatedVertices;
}
/// <summary>
/// Calculate the center point needed for triangulation.
/// The polygon will be irregular, so this isn't the actual center of the polygon
/// but it will do for now, as we only need an extra point to make the triangles with</summary>
private void calculateCenterPoint()
{
float xCount = 0, yCount = 0;
foreach (VertexPositionColor vertice in vertices)
{
xCount += vertice.Position.X;
yCount += vertice.Position.Y;
}
centerPoint = new Vector3(xCount / vertices.Length, yCount / vertices.Length, 0);
}
private void setupIndexes()
{
for (int i = 1; i < triangulatedVertices.Length; i = i + 3)
{
indexes[i / 3] = i - 1;
}
}
private void setupDrawableTriangle(int index)
{
triangulatedVertices[index] = vertices[index / 3]; //No DividedByZeroException?...
if (index / 3 != vertices.Length - 1)
triangulatedVertices[index + 1] = vertices[(index / 3) + 1];
else
triangulatedVertices[index + 1] = vertices[0];
triangulatedVertices[index + 2].Position = centerPoint;
}
/// <summary>
/// Draw the polygon. If you haven't called Triangulate yet, I wil do it for you.
/// </summary>
/// <param name="effect">The BasicEffect needed for drawing</param>
public void Draw(BasicEffect effect)
{
try
{
if (!triangulated)
Triangulate();
draw(effect);
}
catch (Exception exception)
{
throw exception;
}
}
private void draw(BasicEffect effect)
{
effect.CurrentTechnique.Passes[0].Apply();
graphicsDevice.DrawUserPrimitives<VertexPositionColor>(
PrimitiveType.TriangleList, triangulatedVertices, 0, vertices.Length);
}
Sorry, it's kind of alot. Now for my next quest. Animation my polygon.
Hope it helped fellow people with the same problem.
|
[
"stackoverflow",
"0005238950.txt"
] | Q:
Overlapping images in CSS with divs
I have 2 images I would like to look similar to this photo (sorry about the quality, the PSD for the site is scattered so I whipped an image together in a few mins to show what I meant).
My first image is the logo - which is a png of the guy with glasses, the trail and the title.
The second image is the blue box, which I would like to be a form for users to put their email address on.
My HTML tags are this:
<body id="home">
<div id="main" method="post" action="">
<img id="Smarty" src="images/logo.png" />
</div>
<div id="box" method="post" action="">
<img id="Form" src="images/form.png" />
</div>
And my css follows:
#home #main {
margin-top: 10%;
margin-right: auto;
margin-left: auto; }
#home #main #box {
margin-right: auto;
margin-left: auto; }
The goal is to have the image looking like the attached photo, with it all centered relative to the size of the users screen. I already have the background working to scale accordingly, but cannot for the life of me figure out how to overlap existing PNGs in CSS with % values rather than fixed pixel values.
Thanks for any guidance!
EDIT:
This code puts my logo in the right place (center and 8% down from the top of the page):
#wrapper #main {
margin-top: 8%;
margin-right: auto;
margin-left: auto;
text-align:center;
display:block; }
#wrapper #main #box{
margin-top: 8%;
margin-right: auto;
margin-left: auto;
position: relative;
text-align:center;
display:block; }
But the box is still below the logo, and to the far left.
A:
Why don't You use these images as backgrounds?
Small example.
HTML:
<div id="smarty">
<div id="form">
<!-- The content -->
</div>
</div>
CSS:
#smarty {
background-image: url('images/logo.png');
}
#form {
background-image: url('images/form.png');
}
P.S.
IE6 hate png with alpha.
|
[
"meta.stackexchange",
"0000212944.txt"
] | Q:
Is asking for a citable reference off topic?
Consider a question asking "Is this documented in any citable reference?" (or similar)
It sort of feels like an (off topic) recommendation question, but also not really.
So, can I get a definitive answer as to whether the above, asked as is, is off topic?
Well, not as is 'as is', but 'as is'-ish - "this" obviously needs to be defined.
The question: Average time complexity of finding top-k elements
I realize that, depending on exactly what OP wants, it should be easy enough to modify to avoid asking for a citable reference (thus I figured a comment would be more appropriate than a close vote).
I'd like to reiterate - I don't think the above question necessarily needs to be closed (perhaps just modified a little), I'm just asking about this so I know and have something to reference.
Why this may be off topic:
There could be a tendency to posting answers that consists of little more than a link or reference, and we don't like that. Although one can certainly, in most cases, extract sufficient information from the paper, but the question isn't whether one can, but rather whether most users will (I don't think the typical Stack Overflow user will).
I'd like to point out the "they tend to" in the recommendation reason. As I understand it, we don't disallow them because all of them are unwanted, just because there's a tendency of bad things happening.
Also, it's very much a research-based question, not "a specific programming problem". So perhaps another site, but not really Stack Overflow (perhaps CS Theory, but I really have no idea about that).
Why this may be appropriate:
There shouldn't really be a tendency to "attracted opinionated answers or spam", as the recommendation reason says. But that doesn't mean another reason or a custom reason may not apply.
A:
I think that asking for something specific like that wouldn't really be a recommendation question, though I don't think it should be the whole question either (which your example isn't).
If the question had that as it's main or only part, it could still be answered, though as with link questions, we'd prefer a little excerpt.
|
[
"stackoverflow",
"0015542996.txt"
] | Q:
User Session Management with Spring (Business and Transaction Management)
In my application
The web front end is done using Struts and Spring for Business and transaction Management.
Now, Am implementing logging in the Business Logic side (beans).
The log should happen such that, every method in the Service, should have the logged in User Details
One approach would be sending the User Object to every method in Service, when it is been called from Servlet
But this would really be dirty.
Does spring/ struts2-spring support any other way to do this.??
A:
Use Spring AOP to do your logging for you (Accompanied By a logging framework), Struts2 has nothing to do with Spring AOP. Spring AOP can work on its own regardless if its a Web Application or a Swing application with Minimal Setup.
|
[
"unix.stackexchange",
"0000255924.txt"
] | Q:
scons can't find glib-2.0 >= 2.32 on cygwin
I downloaded the source for rmlint and am trying to compile it on cygwin. When I run scons, it says Checking for glib-2.0 >= 2.32... Error: glib-2.0 >= 2.32 not found.
In the cygwin setup facility, it shows I have the libglib 2.0_0 2.46.2-1 package installed. I re-installed it for good measure, but no luck.
How could I try to find the library on my filesystem, and how do I tell scons where it's located?
A:
Hi I'm one of the rmlint dev's.
Unfortunately I don't think you'll be able to get rmlint running under cygwin (although happy to be proven wrong).
Edit: have been proven wrong. Now have more-or-less working command-line version of rmlint under cygwin. It requires:
gcc-core
pkg-config
libglib2.0-devel
libtool
and optionally:
libjson-glib 1.0-devel
libblkid-devel
libelf-devel
There seems to be no filemap support under cygwin so rmlint can't do its normal optimisation of file order to reduce seek times and thrash.
|
[
"worldbuilding.stackexchange",
"0000126304.txt"
] | Q:
If you could travel back in time by transfering your state of mind/memories to your former self, would you transfer your tiredness to him?
Let's suppose you can travel back in time by passing your state of mind/memories to your former self. You go back to your former self who has slept some hours ago, a day passes without sleeping and you travel back in time again, and you repeat this process dozens of times (presumably to try to change an event you dont want to happen) . Would your former self have the accumulated tiredness of dozens of days (needing to sleep) or since the body of your former self slept a few hours ago would you feel energetic without needing to sleep all the time?
A:
This is a wonderful opportunity to give your science fiction story a bigger science than we currently possess. We have no minds that are independent of the bodies they are currently attached to, so we have no way of testing whether mental weariness is separate and distinct from physical weariness.
I have personally noticed that my mind slows down after 16-18 hours of concentration, but the timing of that slow down is suspiciously close to other symptoms of physical tiredness such as muscle tightening, yawning, and gradually increasing eyelid weight. I cannot empirically determine whether two simultaneous events are occurring (separate physical and mental tiring) or if it is a single event with multiple distinct symptoms.
Your time traveler has an opportunity to learn what we do not know. Does the mind tire separately from the body?
So choose whichever "truth" serves your story best and run with it.
|
[
"stackoverflow",
"0041990279.txt"
] | Q:
PHP outputs a strange french character | é = string(3)
When PHP outputs file names from an FTP folder it produces French characters which are 3 characters long, so when we var_dump:
var_dump("é");
It shows:
string(3)
But the actual character should be
string(2)
The file names are pulled using a Wordpress function
When it's string(3) we can't do a preg_match on it to replace it with a standard ASCII character.
I tried declaring the formatting as UTF-8, but it's already UTF-8. Also tried
header('Content-Type: text/html; charset=iso-8859-1');
But the result is garbled text.
Is there anything else we can try? What kind of a character is it?
A:
Your character é is actually 0x65cc81, rather than the more usual single Unicode codepoint in UTF-8 0xc3a9 (é LATIN SMALL LETTER E WITH ACUTE (U+00E9)). 0x65cc81 is a Unicode "Combining sequence": 0x65 is e "LATIN SMALL LETTER E" (U+0065) and 0xcc81 is ́ "COMBINING ACUTE ACCENT (U+0301)".
You can convert from the combining sequence to the single codepoint using PHP's Normalizer:
function strhex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
$character = "é";
var_dump($character);
var_dump(strhex($character));
$character = Normalizer::normalize($character);
var_dump($character);
var_dump(strhex($character));
gives
string(3) "é"
string(6) "65cc81"
string(2) "é"
string(4) "c3a9"
|
[
"stackoverflow",
"0006146769.txt"
] | Q:
hudson cobertura sonar integration error
I integrate sonar into hudson, but when I build a project using hudson, an error occured
log:
does anyone know how to avoid this error?
thanks in advance~
A:
You have to change the location of you locale maven repository into a different location like c:.m2\ instead c:\Document Settgins etc........This can be done by changing the settings.xml file.
You have reached the limit in Windows...
|
[
"movies.stackexchange",
"0000016997.txt"
] | Q:
What is the source of Truffaut's famous anti-war movie quote?
Francois Truffaut famously said it is impossible to make an anti-war film. This is cited numerous times by Ebert, and there is even the trope "Truffaut was right". But what is the source for this statement?
A:
The earliest reference I could find was referenced in Truffaut: A Biography starting on page 163, 2nd paragraph.
This link starts on page 163 and gives the background. On page 164 there is the trope.
Truffaut never directly says "impossible to make an anti-war film." Rather in describing his desire to make one concerning Algiers, he decides that he cannot because "to show something is to ennoble it."
A:
I found this quote today in a November 11, 1973 Chicago Tribune (pg 3e) interview Gene Siskel did with Francois Truffaut:
"I find that violence is very ambiguous in movies. For example, some films claim to be antiwar, but I don't think I've really seen an antiwar film. Every film about war ends up being pro-war."
|
[
"stackoverflow",
"0017877276.txt"
] | Q:
Mimick photoshop/painter smooth draw on HTML5 canvas?
As many people knew, HTML5 Canvas lineTo() is going to give you a very jaggy line at each corner. At this point, a more preferable solution would be to implement quadraticCurveTo(), which is a very great way to generate smooth drawing. However, I desire to create a smooth, yet accurate, draw on canvas HTML5. Quadratic curve approach works well in smoothing out the draw, but it does not go through all the sample points. In other word, when I try to draw a quick curve using quadratic curve, sometime the curve appears to be "corrected" by the application. Instead of following my drawing path, some of the segment is curved out of its original path to follow a quadratic curve.
My application is intended for a professional drawing on HTML5 canvas, so it is very crucial for the drawing to be both smooth and precise. I am not sure if I am asking for the impossible by trying to put HTML5 canvas on the same level as photoshop or any other painter applications (SAI, painterX, etc.)
Thanks
A:
What you want is a Cardinal spline as cardinal splines goes through the actual points you draw.
Note: to get a professional result you will also need to implement moving average for short thresholds while using cardinal splines for larger thresholds and using knee values to break the lines at sharp corner so you don't smooth the entire line. I won't be addressing the moving average or knee here (nor taper) as these are outside the scope, but show a way to use cardinal spline.
A side note as well - the effect that the app seem to modify the line is in-avoidable as the smoothing happens post. There exists algorithms that smooth while you draw but they do not preserve knee values and the lines seem to "wobble" while you draw. It's a matter of preference I guess.
Here is an fiddle to demonstrate the following:
ONLINE DEMO
First some prerequisites (I am using my easyCanvas library to setup the environment in the demo as it saves me a lot of work, but this is not a requirement for this solution to work):
I recommend you to draw the new stroke to a separate canvas that is on top of the main one.
When stroke is finished (mouse up) pass it through the smoother and store it in the stroke stack.
Then draw the smoothed line to the main.
When you have the points in an array order by X / Y (ie [x1, y1, x2, y2, ... xn, yn]) then you can use this function to smooth it:
The tension value (ts, default 0.5) is what smooths the curve. The higher number the more round the curve becomes. You can go outside the normal interval [0, 1] to make curls.
The segment (nos, or number-of-segments) is the resolution between each point. In most cases you will probably not need higher than 9-10. But on slower computers or where you draw fast higher values is needed.
The function (optimized):
/// cardinal spline by Ken Fyrstenberg, CC-attribute
function smoothCurve(pts, ts, nos) {
// use input value if provided, or use a default value
ts = (typeof ts === 'undefined') ? 0.5 : ts;
nos = (typeof nos === 'undefined') ? 16 : nos;
var _pts = [], res = [], // clone array
x, y, // our x,y coords
t1x, t2x, t1y, t2y, // tension vectors
c1, c2, c3, c4, // cardinal points
st, st2, st3, st23, st32, // steps
t, i, r = 0,
len = pts.length,
pt1, pt2, pt3, pt4;
_pts.push(pts[0]); //copy 1. point and insert at beginning
_pts.push(pts[1]);
_pts = _pts.concat(pts);
_pts.push(pts[len - 2]); //copy last point and append
_pts.push(pts[len - 1]);
for (i = 2; i < len; i+=2) {
pt1 = _pts[i];
pt2 = _pts[i+1];
pt3 = _pts[i+2];
pt4 = _pts[i+3];
t1x = (pt3 - _pts[i-2]) * ts;
t2x = (_pts[i+4] - pt1) * ts;
t1y = (pt4 - _pts[i-1]) * ts;
t2y = (_pts[i+5] - pt2) * ts;
for (t = 0; t <= nos; t++) {
// pre-calc steps
st = t / nos;
st2 = st * st;
st3 = st2 * st;
st23 = st3 * 2;
st32 = st2 * 3;
// calc cardinals
c1 = st23 - st32 + 1;
c2 = st32 - st23;
c3 = st3 - 2 * st2 + st;
c4 = st3 - st2;
res.push(c1 * pt1 + c2 * pt3 + c3 * t1x + c4 * t2x);
res.push(c1 * pt2 + c2 * pt4 + c3 * t1y + c4 * t2y);
} //for t
} //for i
return res;
}
Then simply call it from the mouseup event after the points has been stored:
stroke = smoothCurve(stroke, 0.5, 16);
strokes.push(stroke);
Short comments on knee values:
A knee value in this context is where the angle between points (as part of a line segment) in the line is greater than a certain threshold (typically between 45 - 60 degrees). When a knee occur the lines is broken into a new line so that only the line consisting of points with a lesser angle than threshold between them are used (you see the small curls in the demo as a result of not using knees).
Short comment on moving average:
Moving average is typically used for statistical purposes, but is very useful for drawing applications as well. When you have a cluster of many points with a short distance between them splines doesn't work very well. So here you can use MA to smooth the points.
There is also point reduction algorithms that can be used such as the Ramer/Douglas/Peucker one, but it has more use for storage purposes to reduce amount of data.
|
[
"stackoverflow",
"0037522394.txt"
] | Q:
Python XlsxWriter - Write to many sheets
This writes to the first sheet but all other sheets are blank.
for date in dates:
sheet = wb.add_worksheet(date)
sheet.write(row, 0, 'example')
For each date I want to creat a sheet with the name equal to the date and then write to each sheet. The sheets are created with the correct names but there is nothing in them except for the first sheet.
A:
I supposed that your variable wb is the workbook and is initialized before.
In the instruction
sheet.write(row, 0, 'example')
I don't know how row is enhanced.
So i created a little script:
import xlsxwriter
list_name = ["first sheet", "second sheet", "third sheet"]
workbook = xlsxwriter.Workbook(<Your full path>)
for sheet_name in list_name:
worksheet = workbook.add_worksheet(sheet_name)
worksheet.write('A1', sheet_name)
workbook.close()
Regards
|
[
"stackoverflow",
"0024205552.txt"
] | Q:
Remove values from php variable
How can I remove some values from $sku variable? It returns 2110, 1630, 4565, etc. from DB.
Code:
$products = SProductVariantsQuery::create()->find()->toArray();
foreach ($products as $variant) {
$sku = $variant['Number'];
}
var_dump($sku) return this:
string(4) "2250" string(4) "2251" string(3) "428" string(3) "427" string(4) "2800" string(4) "2804"
A:
Create an array with values you want to exclude before you do the foreach and then check if the value is in there:
// Exclude prod. no 427 and 2800
$exclude = array('427', '2800');
foreach ($products as $variant) {
// Only set $sku if the Number is not in the exclude array
if (!in_array($variant['Number'], $exclude)) {
$sku = $variant['Number'];
}
}
|
[
"stackoverflow",
"0059112415.txt"
] | Q:
Hex in char array
If the following is a one byte array:
char arr[] = "\xFF";
If we do the following:
char arr[] = "\xFFmyrandomstringappendedafterbyte";
printing it would result in this:
byteValueGoesHEREmyrandomstringappendedafterbyte
However, if I try to do the following:
char arr[] = "\xFF98";
It will result in a warning:
warning: hex escape sequence out of range
It treats 98 as part of the hexcode. However, I would it to be treated as a string (as is myrandomstringappendedafterbyte).
I would like to have this as output byteValueGoesHERE98.
How can this be achieved without a whitespace? How can I denote that 98 should be treated as a string?
A:
When string literals have only whitespace (or nothing) between them, the preprocessor combines them into a single string literal, but this does not "merge" escape sequences. So you can just write your desired string using two strings:
char arr[] = "\xFF" "98";
This is four bytes including the terminating '\0'.
|
[
"stackoverflow",
"0007982971.txt"
] | Q:
How to force emacs recolor
Every once and a while Emacs fails at syntax highlighting and the coloring gets all funky in a buffer. Is there any way to force Emacs to "recolor" the syntax? Just try over? I don't mind if it takes a moment.
A:
I think M-x font-lock-fontify-buffer will do what you are looking for. Or select a region and do M-o M-o (or M-x font-lock-fontify-block).
|
[
"stackoverflow",
"0031447868.txt"
] | Q:
Bash/Shell: analyse tab-separated CSV for lines with data in n-th column
I have a tab-separated CSV, to big to download and open locally.
I want to show any lines with data in the n-th column, that is those lines with anything else than a tab right before the n-th tab of that line.
I´d post what I´ve tried so far, but my sed-knowledge is merely enough to assume that it can be done with sed.
edit1:
sample
id num name title
1 1 foo foo
2 2 bar
3 3 baz baz
If n=3 (name), then I want to output the rows 1+3.
If n=4 (title), then I want to output all the lines.
edit 2:
I found this possible solution:
awk -F '","' 'BEGIN {OFS=","} { if (toupper($5) == "STRING 1") print }' file1.csv > file2.csv
source: https://unix.stackexchange.com/questions/97070/filter-a-csv-file-based-on-the-5th-column-values-of-a-file-and-print-those-reco
But trying
awk -F '"\t"' 'BEGIN {OFS="\t"} { if (toupper($72) != "") print }' data.csv > data-tmp.csv
did not work (result file empty), so I propably got the \t wrong? (copy&paste without understanding awk)
A:
I'm not exactly sure I understand your desired behaviour. Is this it?
$ cat file
id num name title
1 1 foo foo
2 2 bar
3 3 baz baz
$ awk -v n=3 -F$'\t' 'NR>1&&$n!=""' file
1 1 foo foo
3 3 baz baz
$ awk -v n=4 -F$'\t' 'NR>1&&$n!=""' file
1 1 foo foo
2 2 bar
3 3 baz baz
|
[
"stackoverflow",
"0053043400.txt"
] | Q:
Configure default document for node on Azure app service
We have an Azure App Service where we deploy a simple web app, a SPA based on React. We have selected the Node.js stack (currently version 10.1) in the Azure Portal for the App Service configuration but at the moment we are only interested in serving the index.html page that drives the rest of the app. There are no serverside js code running.
How can I configure the Node.js stack to "redirect" an incoming request for the root (i.e. https://thesite.azurewebsites.net) to actually serve the index.html content. Right now, when I request the root I'll get a 'Cannot GET /' response back which I suspect is from the generic Node.js hosting (iisnode perhaps?)
Requesting the root works great on my local dev machine when running npm start so I think it is a matter of getting the node.js stack configured wehn hosted on Azure.
I have tried to deploy a simple web.config in the hopes that it'll get picked up and perform a rewrite but it does not affect the root request.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="DynamicContent">
<match url="/*" />
<action type="Rewrite" url="index.html"/>
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Can anybody help me figure out what needs to be done to succeed with this?
A:
Please see https://github.com/projectkudu/kudu/wiki/Using-a-custom-web.config-for-Node-apps
You will need to add a <handlers> section with a proper path to the startup file.
|
[
"stackoverflow",
"0022735105.txt"
] | Q:
Play Framework 2 & AngularJS - Partial Handling
I am starting to develop a business spa application (mobile/desktop web app) with Play Framework 2 and AngularJS. Right now I am tending to go with following solution:
Play behaves as a RESTful application
Play also pre-processes partials
AngularJS handles the rest
My arguments for pre-processing partials are:
Play can remove parts of a partial for a more compact mobile view
Different user roles see more/less content of the partial
Correct language will be loaded into the partial
Are there any disadvantages with this approach? Do you think this would be the best solution for the project's requirements?
A:
Server-side templating is usually what you want to get rid of when building an SPA. In general this should work, but there are a couple of disadvantages:
You are mixing two template languages, Play and AngularJS, so you must be careful not create an unmaintainable mess
Your display logic will also be distributed or duplicated between Angular and Play; in a pure RESTful approach Play would mostly be concerned about access control and JSON (input, output, validation)
You must create a route for every partial instead of just using the assets route
Server side templating slows down compilation speed
Returning different content depending on roles and desktop/mobile might mess with Angular's $template cache
Different user roles see more/less content of the partial
This should be handled by Angular IMHO, Play would just make sure to only serve the appropriate JSON to the right users.
Correct language will be loaded into the partial
How would you reuse Play's Lang in Angular? Build an inline variable? Again, just load it via JSON when the app bootstraps.
|
[
"stackoverflow",
"0029517810.txt"
] | Q:
ruby block that starts with <<-HTML
I'm learning about integrating Devise flash and error messages with Bootstrap (or in my case Materialize). I found an article on the topic within Devise's wiki (https://github.com/plataformatec/devise/wiki/How-To:-Integrate-I18n-Flash-Messages-with-Devise-and-Bootstrap), so I understand how it has to work, but there was a section of the code I'm having problems understanding.
html = <<-HTML
<div class="card-panel red lighten-2">
#{messages}
</div>
HTML
html.html_safe
Can someone explain the <<-HTML syntax? BTW, here is the full function in case you need context
def devise_error_messages!
return '' if resource.errors.empty?
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
html = <<-HTML
<div class="card-panel red lighten-2">
#{messages}
</div>
HTML
html.html_safe
end
A:
This is a ruby common way to declare a string, it is pretty useful in some cases (edit: http://en.wikipedia.org/wiki/Here_document thanks to @Stefan):
sql = <<-SQL
SELECT * FROM users
WHERE users.id > 15
ORDER BY users.username;
SQL
ActiveRecord::Base.connection.execute(sql)
Way better to read this than a simple:
sql = "SELECT * FROM users WHERE users.id > 15 ORDER BY users.username;"
ActiveRecord::Base.connection.execute(sql)
Imagine the pain to read a very complex SQL query without any line-break! (like with a manual join, recursive, union or views of table(s)!
It works with any kind of word:
a_string = <<-WHATEVER
This is a string
with some line-break
to make it more readable
#{and_you_can_use_string_interpolation_too}
WHATEVER
|
[
"stackoverflow",
"0063737857.txt"
] | Q:
What is the read count for realtime listening of cloud_firestore query and can it be done better?
Imagine I have the following pseudo code in flutter/dart :
Stream<List<T>> list() {
Query query = Firestore.instance.collection("items");
return query.snapshots().map((snapshot) {
return snapshot.documents.map((doc) {
return standardSerializers.deserializeWith(serializer, doc.data());
}).toList();
});
}
I am listening to the whole collection of "items" in my database. Let's say for simplicity there are 10 documents in total and I constantly listen for changes.
I listen to this stream somewhere in my code. Let's say this query returns all 10 "items" the first time this is called for example. This counts as 10 reads, ok fine. If I modify one of these documents directly in the firestore web interface (or elsewhere), the listener is fired and I have the impression another 10 reads are counted, even though I only modified one document. I checked in the usage tab of my cloud project and I have this suspicion.
Is this the case that 10 document reads are counted even if just one document is modified for this query?
If the answer is yes, the next question would be "Imagine I wanted to have two calls to list(), one with orderBy "rating", another with orderBy "time" (random attributes), one of these documents changes, this would mean 20 reads for 1 update"?
Either I am missing something or firestore isn't adapted for my use or I should change my architecture or I miscounted.
Is there any way to just retrieve the changed documents? (I can obviously implement a cache, local db, and timestamp system to avoid useless reads if firestore does not do this)
pubspec.yaml =>
firebase_database: ^4.0.0
firebase_auth: ^0.18.0+1
cloud_firestore: ^0.14.0+2
This probably applies to all envs like iOS and Android as it is essentially a more general "firestore" question, but example in flutter/dart as that is what I am using just in case it has something to do with the flutterfire plugin.
Thank you in advance.
A:
Q1: Is this the case that 10 document reads are counted even if just one document is modified for this query?
No, as detailed in the documentation:
When you listen to the results of a query [Note: (or a collection or subcollection)], you are charged for a read
each time a document in the result set is added or updated. You are
also charged for a read when a document is removed from the result set
because the document has changed. (In contrast, when a document is
deleted, you are not charged for a read.)
Also, if the listener is disconnected for more than 30 minutes (for
example, if the user goes offline), you will be charged for reads as
if you had issued a brand-new query. [Note: So 10 reads in your example.]
Q2: If the answer is yes, the next question...
The answer to Q1 is "no" :-)
Q3: Is there any way to just retrieve the changed documents?
Yes, see this part of the doc, which explains how to catch the actual changes to query results between query snapshots, instead of simply using the entire query snapshot. For Flutter you should use the docChanges property.
|
[
"stackoverflow",
"0009461043.txt"
] | Q:
How to UPDATE a new column to be the first word of another column
I downloaded a massive amount of rows (over 98,000) from the USDA about plant classification.
However, upon closer inspection it turns out they did not offer a Genus or Species column.
After some studying it turns out that the Genus is always equal to the first word in the Scientific Name and the Species is the second word.
I used the following query to pull up the correct information I want placed in the Genus column. But, I am stuck at how to UPDATE each and every row based on another column in that same row.
SELECT SUBSTRING_INDEX( `Scientific Name with Author` , ' ', 1 ) AS `Genus`
FROM `plants`
I would really like to be able to execute this query using only MySQL and not have to resort to PHP, which is my knee-jerk reaction.
Any direction would be appreciated, here is an example of the table below.
A:
The UPDATE is almost identical to the SELECT:
UPDATE my_table
SET Genus=SUBSTRING_INDEX( `Scientific Name with Author` , ' ', 1 )
|
[
"stackoverflow",
"0053164632.txt"
] | Q:
Count arrays with values in state in React
I currently have the following state:
this.state = {
selectProduct: [somearrayValues],
quantityProduct: [],
colorsProduct: [somearrayValues],
stockProduct: [somearrayValues],
turnaroundProduct: [],
coatingProduct: [],
attributeProduct: [somearrayValues],
attributeMetaProduct: [somearrayValues],
}
I do a fetch call to fill up the arrays with the needed data.
From here I need to get a count of Arrays that actually contain a value. I'm lost as how to accomplish this.
I first was trying to get to the state with a for each loop but I haven't even got passed this point:
let dropdownArrays = ...this.state;
dropdownArrays.forEach(function(element) {
console.log(element);
});
This gives me an error when babel attempts to compile.
I then tried the below, which returns nothing.
let dropdownArrays = [...this.state];
dropdownArrays.forEach(function(element) {
console.log(element);
});
I know I'm missing it so any help would be greatly appreciated.
A:
Perhaps you could use the Object#values() method to access the array objects (ie the values) of the state, and then count the number of non-empty arrays like so:
// Pre-filled arrays with some values. This solution would work
// regardless of the values you populate the arrays with
const state = {
selectProduct: [1,2,3,4],
quantityProduct: [],
colorsProduct: [4,5,6,7],
stockProduct: [1,2],
turnaroundProduct: [],
coatingProduct: [],
attributeProduct: [6,7,8,9,10],
attributeMetaProduct: [5,4,6],
}
const result = Object.values(state)
.filter((array) => array.length > 0)
.length;
console.log('Number of arrays in state with values (non-empty)', result)
|
[
"ja.stackoverflow",
"0000060609.txt"
] | Q:
RollupJSで、VueJSの単一ファイルコンポーネントを生成したい
内容的には「VueJSを単一ファイルコンポーネントで内包(?)したい」の続きになります。
環境
windows10
yarn 1.12.3
rollup v1.27.0
やりたいこと
VueJSの処理ファイルをhtmlから<script>タグで呼び出せるようにしたい。
要は「単一ファイルコンポーネント」の形にしたい。
やったこと
まず、yarnで必要なモジュールを落としてきました。
package.jsonは以下になります。
{
"dependencies": {
"rollup": "^1.27.0",
"rollup-plugin-css-only": "^1.0.0",
"rollup-plugin-vue": "5.1.0",
"vue-template-compiler": "^2.6.10"
}
}
次に、
rollupjsのVueJSプラグインのサンプルページを見つけたのでここからコードを拝借。
rollup.config.js
import vue from 'rollup-plugin-vue'
export default {
input: 'TestComponent.vue',
output: {
format: 'iife',
file: 'dist/TestComponent.js'
},
plugins: [
vue()
]
}
コンパイル対象の「TestComponent.vue」を作成
TestComponent.vue
<template>
<div class="example">{{ message }}</div>
</template>
<script>
export default {
data () {
return {
message: 'Hello world!'
}
}
}
</script>
<style>
.example {
color: red;
}
</style>
表示させるHTML
index.html
<!doctype html>
<html>
<head>
<script src="./dist/TestComponent.js"></script>
</head>
<body>
<div id="app">
<test-component></test-component>
</div>
</body>
</html>
Rollup Plugin Vueのページには、main.jsなどの情報はなかったので、
一旦この状態でコンパイル(> yarn rollup -c)しました。
ブラウザでHTMLにアクセスしてみると、
SyntaxError: export declarations may only appear at top level of a module
と発生。
なんかHTMLからは呼び出せない?
なので、もともと動いていたサンプルどおり、
main.js経由でコンパイルをさせるように変更しました。
main.js
import TestComponent from './TestComponent.vue';
new Vue({
el: "#app",
components: {
"TestComponent": TestComponent,
},
});
rollup.confing.jsファイルのinput部分も変更
rollup.confing.js
import vue from 'rollup-plugin-vue'
export default {
input: 'main.js',
output: {
format: 'esm',
file: 'dist/TestComponent.js'
},
plugins: [
vue()
]
}
するとエラー内容が変わりました。
ReferenceError: Vue is not defined
Vueがない…。
この辺よくわかっていないのですが、esmやiifeなどoutput.format部分で指定があります。
もともと動いていたサンプルのページではiifeになっていたので、iifeに変更して再度コンパイルします。
rollup.confing.js
import vue from 'rollup-plugin-vue'
export default {
input: 'main.js',
output: {
format: 'iife',
file: 'dist/TestComponent.js'
},
plugins: [
vue()
]
}
変わらずエラー
ReferenceError: Vue is not defined
Vueがない。
私はどうしたらいいのでしょうか。
どうすれば動くのでしょうか。。。(そしていつになったらvueの勉強始められるのでしょうかorz)
お知恵をお貸しただけますと幸いです。
よろしくお願いいたします。
A:
rollupjsのVueJSプラグインのサンプルページを見つけたのでここからコードを拝借。
これはesmを出力していることからも分かるように、他のプロジェクトから参照するコンポーネントの作成する方法で、TestComponentを使うアプリ側でさらにrollupやwebpackを使うことを想定したサンプルです。
ReferenceError: Vue is not defined
Vueがない…。
別途Vueランタイムを読み込まずにバンドルしたいといことでしたら、Vueパッケージをインストールし
yarn add vue
グローバルのVueを使わずに、Vueモジュールをインポートします。
// main.js
import TestComponent from './TestComponent.vue';
import Vue from 'vue/dist/vue.esm.browser.js'
new Vue({
el: "#app",
components: {
"TestComponent": TestComponent,
},
});
さらに、 rollup-plugin-node-resolve プラグインで node_modules 管理の vue をバンドルします。
// rollup.confing.js
import vue from 'rollup-plugin-vue'
import nodeResolve from 'rollup-plugin-node-resolve'
export default {
input: 'src/TestMain.js',
output: {
format: 'iife',
file: 'dist/TestComponent.js'
},
plugins: [
nodeResolve(),
vue()
]
}
最後に、コンパイルしたものを index.html から読み込みます。
<!doctype html>
<html>
<body>
<div id="app">
<test-component></test-component>
</div>
<script src="./dist/TestComponent.js"></script>
</body>
</html>
目的にもよりますがビルド環境の構築は各種しがらみで面倒なので、JS関連が初めてでVueの勉強が目的でしたら、とりあえず細かいこだわりは捨てて @vue/cli でプロジェクトを作ってその流儀に従うのも一つの手です。
|
[
"stackoverflow",
"0024814580.txt"
] | Q:
Program using pointer and dynamic storage to pass around a character string of unknown size at startup
This is my assignment:
Write a program and the following functions using dynamic storage to
manipulate the character strings.
a. A function to input an unknown number of character strings of
unknown length (max 80) and store each string in dynamic storage.
b. A function to output each character string and its corresponding
length in terms of the number of characters.
The program should begin by reading the number of character strings to
be processed and allocating dynamic storage for the pointers.
My code is below. This version compiles fine but breaks when trying to get output.
Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
int funcinput (char **, int *,char *);
void funcoutput (char **, int *);
int main()
{
char c;
int *n;
char *ptr;
char **userinput=calloc(*n,80);
funcinput (userinput,&*n,&*ptr);
funcoutput (userinput,&*n);
}
int funcinput(char **userinput, int *n, char *ptr)
{
char c;
int counter =0;
int max=0;
printf("How many items are in your list\n");
scanf("%d",&*n);
max = *n;
ptr = (char*)calloc(*n,80);
printf("Enter your list, each item can be a max of 80 characters long:\n");
for (counter=0;counter<*n;counter++)
{
scanf("%80s",&userinput[c]);
}
return;
}
void funcoutput (char **userinput,int *n)
{
char c;
int counter1=0;
int max1=0;
max1 = *n;
printf ("You entered %d strings of charectors\n",*n);
printf ("The following is the list you entered \n");
for(counter1=0;counter1<max1;counter1++)
{
printf("\n%-80s \n",*userinput[c]);
}
return;
}
A:
#include <stdio.h>
#include <stdlib.h>
char **funcinput (int *size /* out */);
void funcoutput (char **out_array, int size);
int main(){
//char c;//unused
int n;
//char *ptr;//unused
char **userinput = funcinput(&n);
funcoutput(userinput, n);
//deallocate
int i;
for(i=0;i<n;++i){
free(userinput[i]);
}
free(userinput);
return 0;
}
char **funcinput(int *n){// n : output size
int counter =0;
int max=0;
printf("How many items are in your list\n");
scanf("%d", n);
max = *n;
char **userinput = calloc(max, sizeof(char*));
printf("Enter your list, each item can be a max of 80 characters long:\n");
for (counter=0;counter < max;counter++){
userinput[counter] = calloc(80, sizeof(char));
if(1!=scanf("%79s", userinput[counter])){//spaces not includes
free(userinput[counter]);
break;
}
}
*n = counter;
return userinput;
}
void funcoutput (char **userinput,int n){
int counter=0;
int max=n;
printf ("You entered %d strings\n", n);
printf ("The following is the list you entered \n");
for(counter=0;counter<max;counter++){
printf("%s\n", userinput[counter]);//%-80s : Probably not necessary
}
}
|
[
"stackoverflow",
"0055978371.txt"
] | Q:
How to use the bubble sort and sorting a 2d array with strings
I want to have a main program that reads 10 names using scanf (maximum 100 characters), saves them to a 2D array (char[10][100]) and then calls a function that has the algorithm of the bubblesort and sorts the 2D array. And finally I want the main program to print the sorted 2D array.
The prototype of the function is:
void bubble_sort(str[][100]);
Can anybody show me the code?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 10
void bubble_sort(char str[SIZE][100]);
int main (void) {
char names[SIZE][100];
int i, j;
for (i = 0; i < SIZE; i++) {
printf("Enter names: ");
scanf("%s", names[i]);
}
bubble_sort(names);
for (int i = 0; i < SIZE; i++)
printf ("%s\n", names[i]);
}
void bubble_sort(char str[SIZE][100]) {
int i, j, reorder = 0;
char temp;
for (i = 1; i < SIZE; i++) {
for (j = SIZE - 1; j >= i; j--) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j + 1]);
strcpy(str[j + 1], str[j]);
strcpy(str[j], temp);
reorder = 1;
}
}
if (reorder == 0)
return;
}
}
I expect to type 10 names and then get as an output these 10 names in an ascending alphabetical way.
A:
This is my answer, hope it is useful for you.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 10
void bubble_sort(char str[SIZE][100]);
int main (void)
{
char names[SIZE][100];
printf("The max length of name is 99\n");
int i;
for(i=0;i<SIZE;i++){
printf("Enter names:");
scanf("%99s",names[i]);
}
bubble_sort (names);
for (int i = 0; i < SIZE; i++)
printf ("%s\n", names[i]);
return 0;
}
void bubble_sort (char str[SIZE][100])
{
int i, j;
char temp[100] = {0};
for (i = 0; i < 10 - 1; i++) {
for (j = 0; j < 10 - 1 - i; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
}
The above program output is:
Enter names:ca
Enter names:sd
Enter names:fgg
Enter names:cb
Enter names:dssd
Enter names:hgf
Enter names:jydt
Enter names:jdjy
Enter names:dgr
Enter names:htr
ca
cb
dgr
dssd
fgg
hgf
htr
jdjy
jydt
sd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.