source
list | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0043803441.txt"
] |
Q:
How to get plain text files in Doxygen documentation?
I cannot include any text file in my Doxygen documentation. The only exception is a README.md file that I set as the main page.
In particular, I would like to see the Changelog.txt file in the documentation. I tried to add it explicitly in the INPUT field and in the FILE_PATTERNS field, without success. In the generated HTML documentation, I cannot find anything neither in the file list nor making a search.
The only trace is in Doxygen's log file:
Preprocessing C:/Source/Changelog.txt...
Parsing file C:/Source/Changelog.txt...
...
Parsing code for file Changelog.txt...
If I change the extension of the file from txt to md, the file is added to the documentation.
A:
You need EXTENSION_MAPPING=txt=md otherwise the .txt file is handled as a C / C++ source file and it is missing comment signs, resulting in no output.
From the documentation:
EXTENSION_MAPPING Doxygen selects the parser to use depending on the
extension of the files it parses. With this tag you can assign which
parser to use for a given extension. Doxygen has a built-in mapping,
but you can override or extend it using this tag. The format is
ext=language, where ext is a file extension, and language is one of
the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++,
D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
FortranFixed, free formatted Fortran: FortranFree, unknown formatted
Fortran: Fortran. In the later case the parser tries to guess whether
the code is fixed or free formatted code, this is the default for
Fortran type files), VHDL. For instance to make doxygen treat .inc
files as Fortran files (default is PHP), and .f files as C (default is
Fortran), use: inc=Fortran f=C. Note: For files without extension you
can use no_extension as a placeholder. Note that for custom extensions
you also need to set FILE_PATTERNS otherwise the files are not read by
doxygen.
|
[
"stackoverflow",
"0038486034.txt"
] |
Q:
Escape dot in GString
I have a string like this
def fileName = "$prefix-$currDate.gz"
.gz is an extension of the file and not a property and I get exception that there is no such property.
Is there a way to escape it? I tried \. which didn't work.
I know I could do
def fileName = "$prefix-$currDate" + ".gz"
but that's not too groovy.
A:
"$prefix-${currDate}.gz"
should be good.
|
[
"stackoverflow",
"0048953227.txt"
] |
Q:
Spring Cloud Stream - Concurrency
Using Spring Cloud Stream Version Chelsea.SR2, with RabbitMQ as message broker. To have multiple consumers we are using the property concurrency (The concurrency of the inbound consumer).
If we set concurrency as 50. It is starting with 1 and slowly it is increasing the consumers count. Is there any possible solution to start initial consumer Count with higher number instead of one to increase the consumer performance.
A:
Can you show your configuration? I just tested it and it worked exactly as expected...
spring.cloud.stream.bindings.input.group=foo
spring.cloud.stream.bindings.input.consumer.concurrency=10
with
@SpringBootApplication
@EnableBinding(Sink.class)
public class So48953227Application {
public static void main(String[] args) {
SpringApplication.run(So48953227Application.class, args);
}
@StreamListener(Sink.INPUT)
public void listen(String in) {
}
}
and
immediately, without sending any messages
|
[
"tex.stackexchange",
"0000199576.txt"
] |
Q:
Customizing apacite style using bibtex in SWP
Sorry for the basic question, but I got stuck finishing up my thesis. I'm using Scientific Workplace 5.5 (very basic LaTeX literacy) and I need to customize apacite to meet the faculty requirements.
I need to:
be able to customize the .bbl file and deal with capitalization problems,
create a "numbered" reference list,
modify the spacing between lines.
Even if I edit the .bbl file using Notepad++, nothing changes in my output PDF file.
I am not sure where to add any necessary codes to introduce numbering as I'm using SWP.
Here is a sample of my .bbl file:
\begin{thebibliography}{}
\bibitem[\protect\citeauthoryear{%
C. Capps}{%
C. Capps}{%
2010}]{%
Capp10b}%
\APACinsertmetastar{%
Capp10b}%
Capps, C. \newblock{}\BBOP{}2010, June\BBCP{}. \newblock{}\BBOQ{}Buyer power in health plan mergers.\BBCQ{} \newblock{}\Bem{Journal of Competition Law and Economics}, \Bem{6}(2), 375-391.
\bibitem[\protect\citeauthoryear{%
C. Capps \BBA{} Dranove}{%
C. Capps \BBA{} Dranove}{%
2004}]{%
Capp04}%
\APACinsertmetastar{%
Capp04}%
Capps, C.\BCBT{} \BBA{} Dranove, D. \newblock{}\BBOP{}2004, March\BBCP{}. \newblock{}\BBOQ{}Hospital consolidation and negotiated ppo prices.\BBCQ{} \newblock{}\Bem{Health Affairs}(2), 175-181.
\end{thebibliography}
Here is what my preamble in SWP looks like:
\newtheorem{theorem}{Theorem}
\newtheorem{acknowledgement}[theorem]{Acknowledgement}
\newtheorem{algorithm}[theorem]{Algorithm}
\newtheorem{axiom}[theorem]{Axiom}
\newtheorem{case}[theorem]{Case}
\newtheorem{claim}[theorem]{Claim}
\newtheorem{conclusion}[theorem]{Conclusion}
\newtheorem{condition}[theorem]{Condition}
\newtheorem{conjecture}[theorem]{Conjecture}
\newtheorem{corollary}{Corollary}
\newtheorem{criterion}[theorem]{Criterion}
\newtheorem{definition}{Definition} \newtheorem{assumption}{Assumption}
\newtheorem{example}[theorem]{Example}
\newtheorem{exercise}[theorem]{Exercise}
\newtheorem{lemma}{Lemma}
\newtheorem{notation}[theorem]{Notation}
\newtheorem{problem}[theorem]{Problem}
\newtheorem{proposition}{Proposition}
\newtheorem{remark}{Remark}
\newtheorem{solution}[theorem]{Solution}
\newtheorem{summary}[theorem]{Summary}
\newenvironment{proof}[1][Proof]{\noindent\textbf{#1.} }{\ \rule{0.5em}{0.5em}}
\geometry{left=1.378in,right=0.984in,top=0.984in,bottom=0.984in}
\setlength{\parindent}{0.25in}
\setlength{\parskip}{8pt plus 1pt minus 1pt}
\widowpenalty=50000000
\clubpenalty=50000000
\titleformat*{\section}{\normalsize\bfseries}
\titleformat*{\subsection}{\normalsize\bfseries}
\titleformat*{\subsubsection}{\normalsize\bfseries}
A:
I have learned that working with an online tex editor solves all these problems. I prefer writelatex as it simultaneously provides a preview, hence it's impossible to create a mess with the codes. As it is an online service there is no need to find and download every single additional package, so I can use the alternatives Bernard and mvkorpel adviced above.
|
[
"stackoverflow",
"0031134929.txt"
] |
Q:
How to create elements inside a loop and store them into a variable in JavaScript to be accessed outside the loop
I want to create some elements of a particular number, inside a loop, store them in a variable, then access that variable outside that loop.
The reason I want to access that variable outside the loop is so that I can put them inside an append function.
function range(start, stop, step) {
var a = [start],
b = start;
while (b < stop) {
b += step;
a.push(b);
}
return a;
}
var yAxis = range(1, 100, 10);
$.createAxis = function(axisValues) {
$(axisValues).each(function(index, element) {
yAxisNav = document.createElement('div');
var newValue = document.createTextNode("I have content!");
yAxisNav.appendChild(newValue);
return yAxisNav.className = 'graphBar_yAxis_label';
});
}(yAxis);
console.log(yAxisNav);
//$('body').append('<section>'+yAxisNav+'</section>');
The above only returns one element, how can I store this so that its accessible outside that loop?
A:
As you wants to return a list of div's, I have moved yAxisNav outside function and appending it with every loop.
I think you are looking for this...
var yAxisNav = "";
$.createAxis = function (axisValues) {
$(axisValues).each(function (index, element) {
var elem;
elem = document.createElement('div');
var newValue = document.createTextNode("I have content!");
elem.appendChild(newValue);
elem.className = 'graphBar_yAxis_label';
yAxisNav += elem.outerHTML;
});
return yAxisNav;
}(yAxis);
console.log(yAxisNav);
$('body').append('<section>'+yAxisNav+'</section>');
|
[
"stackoverflow",
"0044757547.txt"
] |
Q:
Not able to delete selected polygon in ui-gmap-google-map
I am able to draw multiple polygon by using Google Draw manager. Now I am not able to select specific polygon from multiple polygon and delete and edit it. Also not able to get new array after edit or delete.
My demo.js code is as follows :
$scope.map = {
center: { latitude: 19.997454, longitude: 73.789803 },
zoom: 10,
//mapTypeId: google.maps.MapTypeId.ROADMAP,
//radius: 15000,
stroke: {
color: '#08B21F',
weight: 2,
opacity: 1
},
fill: {
color: '#08B21F',
opacity: 0.5
},
geodesic: true, // optional: defaults to false
draggable: false, // optional: defaults to false
clickable: false, // optional: defaults to true
editable: false, // optional: defaults to false
visible: true, // optional: defaults to true
control: {},
refresh: "refreshMap",
options: { scrollwheel: true },
Polygon: {
visible: true,
editable: true,
draggable: true,
geodesic: true,
stroke: {
weight: 3,
color: 'red'
}
},
source: {
id: 'source',
coords: {
'latitude': 19.9989551,
'longitude': 73.75095599999997
},
options: {
draggable: false,
icon: 'assets/img/person.png'
}
},
isDrawingModeEnabled: true
};
$scope.drawingManagerOptions = {
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
//google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.POLYGON,
]
},
circleOptions: {
fillColor: '#BCDCF9',
fillOpacity:0.5,
strokeWeight: 2,
clickable: false,
editable: true,
zIndex: 1
},
polygonOptions: {
fillColor: '#BCDCF9',
strokeColor: '#57ACF9',
fillOpacity: 0.5,
strokeWeight: 2,
clickable: false,
editable: true,
zIndex: 1
}
};
var coords = [];
var polygon;
$scope.eventHandler = {
polygoncomplete: function (drawingManager, eventName, scope, args) {
polygon = args[0];
var path = polygon.getPath();
for (var i = 0 ; i < path.length ; i++) {
coords.push({
latitude: path.getAt(i).lat(),
longitude: path.getAt(i).lng()
});
}
},
};
$scope.removeShape = function () {
google.maps.event.clearListeners(polygon, 'click');
google.maps.event.clearListeners(polygon, 'drag_handler_name');
polygon.setMap(null);
}
And My HTML code is as follows :
<ui-gmap-google-map center="map.center" zoom="map.zoom" options="map.options" control="map.control">
<ui-gmap-marker coords="map.source.coords"
options="map.source.options"
idkey="map.source.id">
</ui-gmap-marker>
<ui-gmap-drawing-manager options="drawingManagerOptions" control="drawingManagerControl" events="eventHandler"></ui-gmap-drawing-manager>
</ui-gmap-google-map>
You can find polygon image for reference:
Now I want to select one of polygon from following image and want to delete or update it.
Some help will be really appreciable.
A:
By the ui-google-map plugin's drawing manager doc, you could get the google.maps.drawing.DrawingManager object by the control attributes (putting there an object)
<ui-gmap-drawing-manager control="drawingManagerControl" options="drawingManagerOptions"></ui-gmap-drawing-manager>
and
$scope.drawingManagerControl = {};
//Now get the drawingManager object
var drawingManager = $scope.drawingManagerControl.getDrawingManager();
Having this object is the main work.
Now you can look on everything you need. For your case you need the overlaycomplete events, it will listen for every time you have drawn a shape (=> polygon , circle, polyline)
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
var newShape = e.overlay;
});
newShape is the new shape drawn, polygon in your case, so you can use it like a Polygon object and can use all you need in this reference.
Now I want to select one of polygon from following image and want to
delete or update it.
For it, we'll distinct the polygon selected, by assigning it in a global variable: eg var selectedShape;
And now, Add a click event listener for this drawn polygon and update it as the selectedShape, and now to delete or update, you can use the selectedShape variable.
var selectedShape;
... ...
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
var newShape = e.overlay;
google.maps.event.addListener(newShape, 'click', function() {
selectedShape = newShape;
});
});
Finally you can delete the selected shape by setting his map to null selectedShape.setMap(null); and update the shape by setting it editable to true shape.setEditable(true);
And finally to make these click event possible you need to add clickable options to true for all shape.
PS: Use the IsReady Service to have map ready before working on it
Working plunker: https://embed.plnkr.co/qfjkT2lOu2vkATisGbw7/
Update:
But how to get all co-ordinates of multiple polygon after edit or
draw.
you already have this in your script, in polygonecomplete ($scope.eventHandler). Now you can add it in overlaycomplete events listener, and for everytime you updated the shape (see code bellow)
But challenge is how to identify which polygon is edited on the
map and how to update that specific polygon from my array
You can push in an array for each shape created and could manage it:
...
var allShapes = []; //the array contains all shape, to save in end
....
//get path coords: I use your code there
function getShapeCoords(shape) {
var path = shape.getPath();
var coords = [];
for (var i = 0; i < path.length; i++) {
coords.push({
latitude: path.getAt(i).lat(),
longitude: path.getAt(i).lng()
});
}
return coords;
}
....
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
var newShape = e.overlay;
google.maps.event.addListener(newShape, 'click', function() {
selectedShape = newShape;
});
...
// get coordinate of the polygon
var shapeCoords = getShapeCoords(newShape);
// pushing this shape to allShapes array
allShapes.push(newShape);
});
in the delete function you can delete id by the index of the selectedShape
//delete selected shape
function deleteSelectedShape() {
if (!selectedShape) {
alert("There are no shape selected");
return;
}
var index = allShapes.indexOf(selectedShape);
allShapes.splice(index, 1);
selectedShape.setMap(null);
}
Now you have the allShapes array, and in the end you can loop it then get for each coordinates and save in your db.
I updated the plunker and added some debug log do show you.
|
[
"stackoverflow",
"0063045889.txt"
] |
Q:
Correct syntax to retry SQL connection after connection failed in python?
I have a dash (flask) app that runs on Azure App Services where I ask the user for input, then they click "Submit" and my code runs an SQL query. It works almost all of the time but sometimes the query fails to connect (Communication link failure). When I restart the App Service it starts working again.
Is there a way to utilize a Try & Except clause to try and re-establish the SQL connection or something? How would my code look if I wanted to try and implement that kind of logic? I'm struggling to figure out the right way to write the syntax for it.
@dash_app.callback(
Output('hidden-dataframe', 'children'),
[Input('submit-button', 'n_clicks')],
[State('company-dropdown', 'value')])
def select_company(n_clicks, value):
if value is None:
raise PreventUpdate
else:
x = value
if n_clicks:
from datetime import datetime, timedelta
start_date = (datetime.today() - timedelta(29)).strftime('%Y-%m-%d')
end_date = datetime.today().strftime('%Y-%m-%d')
cnxn = pyodbc.connect(driver='{OBDC Driver 17 for SQL Server}',host,database,trusted_connection,user,password)
query = f"SELECT data FROM table WHERE ..."
df = pd.read_sql_query(query, cnxn)
return df.to_json(date_format='iso', orient='split')
Here's the error code that I get when the connection fails:
A:
For a one-retry shot at re-connecting, replace
df = pd.read_sql_query(query, cnxn)
with
try:
df = pd.read_sql_query(query, cnxn)
except pyodbc.OperationalError:
cnxn.close()
cnxn = pyodbc.connect(driver='{OBDC Driver 17 for SQL Server}',host,database,trusted_connection,user,password)
df = pd.read_sql_query(query, cnxn)
This has worked for me in azure app service/flask. Using the cursor directly though, not pandas so your specific error to handle may be different.
|
[
"stackoverflow",
"0040225692.txt"
] |
Q:
Passing NSNotifications. Good? Bad? NBD?
I'm trying to think through the ramifications of passing an NSNotification object as a var to a method.
It seems like it's difficult to trace what happens to a the flow of logic with a notification anyway (without some great commenting and method/object naming) so passing the notification to another method/class/lib/project would just make it even less fun to debug or respond intelligently to an error.
But it just feels like it's the sort of thing that has a lot of hidden gotchas potentially.
And I know there are still a lot of people out there who love notifications.
So does anyone have some pros/cons/better-practices about passing the actual NSNotification object as a var between methods?
Just for clarity's sake here's some pseudo code:
[[NSNotificationCenter defaultCenter] postNotificationName:kSuperImportantNotification object:self userInfo:soMetaDict];
... Later in the code:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(importantThingHappened:) name:kSuperImportantNotification object:nil];
... Later in the code:
- (void) importantThingHappened:(NSNotification *)notification {
[respondingInterestedClass executeSomethingWith:notification];
}
... In "respondingInterestedClass":
- (void)executeServicesDiscoveredBlock:(NSNotification *)notification {
// ... do something with the NSNotificaiton object.
}
Thanks
A:
It depends in what you are doing, usually this is when to use what:
One-to-One relationship and loose coupling: Delegate
One-to-One relationship and tight coupling: Direct method calls
One-to-Many relationship and loose coupling: Notifications
One-to-Many relationship and tight coupling: KVO
So you should not use Notifications for all kind of communication, lot of developers use them heavily even when its not needed.
Saying this, it is totally fine to pass the notification object to the method handler, but don't pass it anywhere else.
A:
Putting aside how and when notifications should be used and focusing purely on the ephemeral set of uses that are totally the right choice....
Once received, the notification object is a state container that contains some set of state in a format that is convenient to the system. You can shoehorn whatever you want into it by shoving key/value pairs into a dictionary and passing it as the userInfo, if you want, but it is still the system state.
In a well designed body of code, there are hard fought barriers through which the format of the data and the encapsulated messaging are well defined. In a Model-View-Controller system, for example, a Model class won't be a subclass of UIView or handle user events directly.
And Notifications should be treated the same. When the notification is received, unwrap it into whatever internal-and-specific-to-your-architecture representation you want and pass that around.
Or, consider:
- (void) somethingChangedNotification:(NSNotification *)changed
{
[myModelGoop applyChange:...];
}
@implementation MyModelLayer
- (void)applyChange:(....)change
{
}
In the above, you could certainly pass the notification object into the model layer. But that's just pushing a system specific implementation detail into your model.
What happens the moment you have changes that aren't triggered via an NSNotification? Your either left to encapsulate your change into a fake NSNotification instance (because posting a notification may have side effects depending on who is observing) or you have to refactor the above to no longer take a notification in the model layer.
Better to get rid of the dependencies on system encapsulation early.
To that end, the NSNotification instance should never be passed out of the method that handles the notification.
|
[
"stackoverflow",
"0003439511.txt"
] |
Q:
Getting instance of content page within the master page
How can I get the instance of the content page from the maste page?
I need it for that:
All my content pages derive from BasePage class (and BasePage derives from System.Web.UI.Page), the BasePage has a property Index.
The derived page set it's value so that master page can read id and apply special CSS to corresponded menu item that is located on the master page.
A:
Just cast the current page from your MasterPage as your BasePage:
BasePage currentPage = (BasePage)this.Page;
int index = currentPage.Index;
SetMenuIndex(index);
|
[
"stackoverflow",
"0021560404.txt"
] |
Q:
Understanding list comprehension
I'm sort of new to programming. I have created a class that uses list comprehension in its initializer. It is as follows:
class Collection_of_word_counts():
'''this class has one instance variable, called counts which stores a
dictionary where the keys are words and the values are their occurences'''
def __init__(self:'Collection_of_words', file_name: str) -> None:
''' this initializer will read in the words from the file,
and store them in self.counts'''
l_words = open(file_name).read().split()
s_words = set(l_words)
self.counts = dict([ [word, l_words.count(word)]
for word
in s_words])
I think I did alright for a novice. It works! But I don't exactly understand how this would be represented in a for-loop. My guess was terribly wrong:
self.counts =[]
for word in s_words:
self.counts = [word, l_words.count(word)]
dict(self.counts)
A:
This is what your comprehension is as a for loop:
dictlist = []
for word in s_words:
dictlist.append([word, l_words.count(word)])
self.counts = dict(dictlist)
A:
Your guess was not wrong at all; you just forgot to append and assign back to self.counts:
counts = []
for word in s_words:
counts.append([word, l_words.count(word)])
self.counts = dict(counts)
That's what a list comprehension does, essentially; build a list from the loop expression.
You could also translate that to a dictionary comprehension instead:
self.counts = {word: l_words.count(word) for word in s_words}
or better still, use a collections.Counter() object and save yourself all that work:
from collections import Counter
def __init__(self:'Collection_of_words', file_name: str) -> None:
''' this initializer will read in the words from the file,
and store them in self.counts'''
with open(file_name) as infile:
self.counts = Counter(infile.read().split())
The Counter() object goes about counting your words a little more efficiently, and gives you additional helpful functionality such as listing the top N counts and the ability to merge counts.
|
[
"stackoverflow",
"0057134508.txt"
] |
Q:
S3 Select Invalid Path component
I'm trying to figure out how to use AWS S3 Select, everything seems pretty straight forward, but the following query just doesn't want to work:
select r.value from S3Object[*].outputs.private_subnets r
the above returns Invalid Path component.
This is the JSON I'm working with:
{
"outputs": {
"private_subnets": {
"value": [
"subnet-1",
"subnet-2",
"subnet-3"
],
"type": [
"tuple",
[
"string",
"string",
"string"
]
]
},
"public_subnets": {
"value": [
"subnet-1",
"subnet-2",
"subnet-3"
],
"type": [
"tuple",
[
"string",
"string",
"string"
]
]
},
"vpc_id": {
"value": "vpc-123",
"type": "string"
}
}
}
I just don't understand the error, is value a special word in SQL?
Here's what I've tried so far:
select r from S3Object[*].outputs.private_subnets r:
{
"r": {
"value": [
"subnet-1",
"subnet-2",
"subnet-3"
],
"type": [
"tuple",
[
"string",
"string",
"string"
]
]
}
}
select r.type from S3Object[*].outputs.private_subnets r:
{
"type": [
"tuple",
[
"string",
"string",
"string"
]
]
}
So I just don't understand what's the problem with value.
A:
You are unable to select this because "value" is a reserved keyword.
https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference-keyword-list.html . This can be escaped using double quotes around the value.
|
[
"stackoverflow",
"0043376269.txt"
] |
Q:
How do I convert a view method to a Generic List View?
I have this method on the view page. It works fine and shows everything correctly but I want to convert it into a generic list view so that I could apply pagination to it.
Here is the function :`
#views.py
def index(request):
all_artists = Artist.objects.all()
all_songs = Song.objects.all()
all_albums = Album.objects.all()
return render(request, 'index.html', {'all_albums':all_albums,'all_songs':all_songs, 'all_artists':all_artists})
So I followed some tutorials and ended up with this:
#new views.py
class IndexView(ListView):
template_name = 'index.html'
context_object_name = 'home_list'
queryset = Artist.objects.all()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['all_artists']=Artist.objects.all()
context['all_songs']=Song.objects.all()
context['all_albums']=Album.objects.all()
Though it compiles without any error, when I render the page, the context object does not gets rendered.
Your help is very much appreciated!
Thankyou
EDIT(13-APR-17):
Thankyou guys! It finally worked with some little modifications.
class IndexView(generic.ListView):
template_name = 'index.html'
context_object_name = 'home_list'
queryset = Artist.objects.all()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['all_artists']=Artist.objects.all()
context['all_songs']=Song.objects.all()
context['all_albums']=Album.objects.all()
return context
enter code here
enter code here
A:
urls.py
in urls.py from your django app you need to include a url that references to your views and include this urls.py to your django project main urls.py.
#urls.py
from django.conf.urls import url
from .views import IndexView
urlpatterns = [
url(r'^path/$', IndexView.as_view(), name="index"),
]
Then in your views.py override the variable paginate_by
#views.py
class IndexView(ListView):
template_name = 'index.html'
context_object_name = 'home_list'
queryset = Artist.objects.all()
paginate_by = 10 # Number of objects for each page
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['all_artists']=Artist.objects.all()
context['all_songs']=Song.objects.all()
context['all_albums']=Album.objects.all()
return context
Finally in your index.html
add the pagination {% pagination_for page_obj %}
{% block content %}
<!--some content -->
<!--begin paginator -->
{% pagination_for page_obj %}
<!--end paginator-->
{% endblock %}
|
[
"stackoverflow",
"0047575727.txt"
] |
Q:
Visibility in popup menus
I have created an eclipse plugin project. I want this plugin to be available as a popup. Therefore I have created an extension point with "org.eclipse.ui.popupMenus" (I know it is deprecated now, ours is an old project.)
I want this popup option to appear only at the file level with certain extension (say xml). Currently, it is appearing anywhere on right click.
I have looked around the internet and got to know that I can add a "visibility" tag that can set rules where this popup should be visible. However, I do not know the syntax for that.
Can someone please help me out? How to set the visibility of the popup menu so that it is visible only when I right click ON the filename with extension xml?
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
<extension point="org.eclipse.ui.popupMenus">
<objectContribution
adaptable="true"
objectClass="org.eclipse.core.resources.IFile"
nameFilter="*.*"
id="org.eclipse.lyo.tools.codegenerator.ui.popupMenus.contribution.IFile">
<menu id="org.eclipse.acceleo.module.menu" label="Acceleo Model Code Generator" path="additionsAcceleo">
<groupMarker name="acceleo"/>
</menu>
<action
class="org.eclipse.lyo.tools.codegenerator.ui.popupMenus.AcceleoGenerateCodegeneratorAction"
enablesFor="+"
id="org.eclipse.lyo.tools.codegenerator.ui.popupMenus.AcceleoGenerateCodegeneratorAction"
icon="icons/default.gif"
label="Generate Java Code from Model"
menubarPath="org.eclipse.acceleo.module.menu/acceleo"/>
<visibility>
//what should come here?
</visibility>
</objectContribution>
</extension>
</plugin>
(http://help.eclipse.org/kepler/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fextension-points%2Forg_eclipse_ui_popupMenus.html)
Regards,
Yash
A:
visibility can only be a child of objectContribution not action.
In any case you can use the namefilter attribute to restrict the file name matching. You would only use visiblity to do more complex checks.
For example this is one of the JDT items:
<objectContribution
adaptable="true"
objectClass="org.eclipse.core.resources.IFile"
nameFilter="*.xml"
id="org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard">
<visibility>
<objectState name="contentTypeId" value="org.eclipse.ant.core.antBuildFile"/>
</visibility>
In this
adaptable="true"
objectClass="org.eclipse.core.resources.IFile"
restricts the actions to a workspace file
nameFilter="*.xml"
restricts the actions to files ending in .xml
<visibility>
<objectState name="contentTypeId" value="org.eclipse.ant.core.antBuildFile"/>
</visibility>
further restricts the actions to files with a 'content type' of 'Ant build file'
To match multiple name patterns remove the nameFilter and use a visibility like:
<visibility>
<or>
<objectState name="name" value="*.xml"/>
<objectState name="name" value="*.java"/>
</or>
</visibility>
|
[
"stackoverflow",
"0060488172.txt"
] |
Q:
SAM Template for AWS Api Gateway Integration with S3 as AWS Service
I am writing SAM templates and I want to create an API Gateway with the path as follows:-
http:///userFlights/airlines/static/images/{airlineName}.
This should be able to download the file from S3 bucket. The {airlineName} may have value like IndiGo.jpg.
I am able to create this manually. Nevertheless, the problem is I am not able to find the appropriate Documentation for SAM templates. I need to automate my API Gateway with SAM.
The values are as follows:-
Integration type - AWS Service
AWS Region- eu-west-3
AWS Service - Simple Storage Service (S3
Http Method - GET
Path override- airlines/static/images/{airlineName}
A:
You have to make use of an OpenAPI definition using DefinitionBody in your SAM template that defines the API configuration. Check out the S3 proxy example here. I have built an API with the simplest and minimum Swagger definition and deployed via SAM.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS SAM template with a S3 integration
Resources:
ApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod
DefinitionBody: {
"swagger": "2.0",
"info": {
"version": "1.0"
},
"paths": {
"/airlines/static/images/{airlineName}": {
"get": {
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 response"
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200"
}
},
"credentials": "arn:aws:iam::{account-id}:role/{role-name}",
"uri": "arn:aws:apigateway:{aws-region}:s3:path/{bucket-name}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "aws"
}
}
}
}
}
|
[
"expatriates.stackexchange",
"0000009461.txt"
] |
Q:
Can U.S. citizens without a social security number be taxed?
I was born in the U.S, where I lived for the first year of my life only. Have never lived there since. I am a citizen of Canada, where I lived for the first half of my life and now of Israel, where I have lived for the last 24 years. I don't have a social security number. Can the U.S. force me to apply for one and pay taxes on my income earned in Israel? if yes, is there a double taxation agreement between the U.S. and Israel?
A:
As a US citizen, you are subject to US federal taxes no matter where you live. If your income for a particular year was above a certain minimum threshold (something like $10K-20K depending on your filing status and other conditions, see the section in the beginning of the relevant tax year's Form 1040 instructions called "Do You Have To File?"), you are required to file a US federal tax return. Whether you have a Social Security number is irrelevant to this requirement. Since you live permanently abroad, you will likely be able to use the Foreign Earned Income Exclusion to exclude the first about $100K of earned income from US taxes, but to use this you must still file and report the income to make use of this (and you can use Foreign Tax Credit on any income you could not use Foreign Earned Income Exclusion on, but again you have to file and report it).
If you are required to file taxes, then you will be required to apply for a Social Security number and use it on your tax return since you are eligible for one. (Only people not eligible for SSNs are eligible to apply for ITINs.)
There is a US-Israel tax treaty but I am not familiar with the details.
|
[
"pt.meta.stackoverflow",
"0000006038.txt"
] |
Q:
Eu sou dono do meu conteudo?
Estava fazendo uma limpa em minhas perguntas antigas e sem resposta, e que julguei serem específicas demais para serem respondidas.
Eis que recebo esta mensagem :
Após isso refleti um pouco e me surgiu algumas questões.
Questões
Se as Perguntas/Respostas são de minha autoria eu sou "dono" delas?
Porque existe um limite de remoção?
Se existe um limite de remoção para o caso que minha conta ser roubada e alguém estar fazendo mal uso dela. Seria possível restaurar tudo que foi perdido?
Adendo
Lembrando que caso eu queira abrir mão da autoria eu posso alterar para "wiki da comunidade". Isso não seria o mesmo que abrir mão de ser "dono"?
A:
De acordo com os termos de uso você não é dono do seu conteúdo. Você é apenas o autor. São coisas diferentes.
Conforme pode ser visto no rodapé a licença automaticamente usada para o conteúdo postado aqui é Creative Commons (CC by-sa 3.0).
Apagar algo seu pode ser considerado vandalismo em algumas circunstâncias, já que está apagando um conteúdo da comunidade que você foi o autor. Não em todas, claro. O limite existe para evitar o abuso.
Se há algum problema pontual é só arrumar. Se não quer estar vinculado com o conteúdo pode pedir para anonimizá-lo. Mas apagar o que pode ser útil para outras pessoas não pode.
É possível restaurar tudo sim até porque não é apagado de fato, só é escondido. Logo você poderá ver tudo o que fica escondido, não só as suas (10k).
Mudar para Wiki não abre mão da autoria, apenas disfarça um pouco já que só fica visível o último que editou e o histórico de todos autores fica no link que mostra as edições feitas no post. Só a SE pode anonimizar de fato.
A:
Você recebe o crédito pela resposta/pergunta mas o "dono" é o site (SE).
Se existe um limite de remoção para o caso que minha conta ser roubada e alguém estar fazendo mal uso dela. Seria possível restaurar tudo que foi perdido?
Sim é possível restaurar todas as postagem exceto comentários.
Relacionado:
Stack Overflow e o Código-Fonte
|
[
"english.stackexchange",
"0000406779.txt"
] |
Q:
What's the term for a widely accepted cultural idea?
Example sentence: Racism was a ____ in the Elizabethan Era.
I'm looking for a word/phrase that works with "breaking". I was considering "social norms" but it doesn't really mean what I want it to convey.
Even if it doesn't work with "breaking", I'd be happy to hear your suggestions anyway!
A:
Perhaps not fully applicable, but zeitgeist should get a nod:
zeitgeist (noun, often capitalized) | zeit·geist \ˈtsīt-ˌgīst, ˈzīt-\
The general intellectual, moral, and cultural climate of an era
Example:
The Zeitgeist of the Elizabethan Era included an acceptance of racism.
Sources:
https://en.wikipedia.org/wiki/Zeitgeist
https://www.merriam-webster.com/dictionary/zeitgeist
|
[
"ru.stackoverflow",
"0000852157.txt"
] |
Q:
Цикл foreach внутри массива
Пробую перебрать вот такой многомерный массив
вот таким кодом
foreach($array[order] as $dataraw) {
$params = array(
'order' => json_encode(array(
'externalId' => $dataraw[status],
'firstName' => $dataraw[customer][given_name],
'phone' => $dataraw[customer][phone],
'items' => array(
foreach($dataraw[basket] as $raw) {
array(
"initialPrice" => $raw[basket],
"productName" => $raw[basket],
)
)
)
)
);
}
}
Но выбивает такую ошибку, я так понимаю нельзя влаживать цикл foreach таким путем
Parse error: syntax error, unexpected 'foreach' (T_FOREACH), expecting ')' in /home/reklam49/imperial-shop.pro/www/retailcrm/index.php on line 29
Как правильно построить циклы что бы не было такой ошибки ??
вот таким должен быть конечный результат
A:
$params = [];
foreach($array[order] as $dataraw) {
$items = [];
if (isset($dataraw['basket']) && !empty($dataraw['basket'])) {
foreach ($dataraw['basket'] as $raw) {
$items[] = [
'initialPrice' => $raw[basket],
'productName' => $raw[basket]
];
}
}
$params[] = [
'order' => json_encode([
'externalId' => $dataraw['status'],
'firstName' => $dataraw['customer']['given_name'],
'phone' => $dataraw['customer']['phone'],
'items' => $items
])
];
}
|
[
"stackoverflow",
"0054214417.txt"
] |
Q:
How disable button after submit
I develop a form to add users, the form works, but the problem is
when click on the button submit two successive times, the method add two users, I want the button submit (add) disable after click directly ( I work with angular 5)
HTML Code :
<form [formGroup]="addfrm">
...
...
<div style="text-align:center">
<button class="btn btn-primary" (click)="processAdd()" [disabled]="addfrm.invalid">add</button>
<button data-dismiss="modal" class="btn btn-default">cancel</button>
</div>
</form>
A:
You can define a field within your component and set it to true when submitted.
<button class="btn btn-primary" (click)="processAdd()" [disabled]="addfrm.invalid || submitted">add</button>
within component
export class MyComponent {
submitted = false;
...
processAdd() {
this.submitted = true;
this.someService.post(this.addForm).subscribe(result => {
this.submitted = false; // reset it on response from server
});
}
}
|
[
"stackoverflow",
"0025288691.txt"
] |
Q:
How to find href from all tags in Nokogiri?
I want to extract the href from all of the tags in some HTML using Nokogiri.
If I have HTML:
<div>
<a href="/test"></a>
</div>
<link href="/test2"></link>
<map href="/test3"></map>
How should do this?
A:
You can use this XPath: //@href to get all the href attributes.
Example:
html = Nokogiri::HTML(html_source)
links = html.xpath('//@href').map(&:value)
# => ["/test", "/test2", "/test3"]
|
[
"stackoverflow",
"0003046117.txt"
] |
Q:
GNU Makefile: multiple outputs from single rule + preventing intermediate files from being deleted
This is sort of a continuation of question from here. The problem is that there is a rule generating multiple outputs from a single input, and the command is time-consuming so we would prefer to avoid recomputation. Now there is an additional twist, that we want to keep files from being deleted as intermediate files, and rules involve wildcards to allow for parameters.
The solution suggested was that we set up the following rule:
file-a.out: program file.in
./program file.in file-a.out file-b.out file-c.out
file-b.out: file-a.out
@
file-c.out: file-b.out
@
Then, calling make file-c.out creates both and we avoid issues with running make in parallel with -j switch. All fine so far.
The problem is the following. Because the above solution sets up a chain in the DAG, make considers it differently; the files file-a.out and file-b.out are treated as intermediate files, and they by default get deleted as unnecessary as soon as file-c.out is ready.
A way of avoiding that was mentioned somewhere here, and consists of adding file-a.out and file-b.out as dependencies of a target .SECONDARY, which keeps them from being deleted. Unfortunately, this does not solve my case because my rules use wildcard patters; specifically, my rules look more like this:
file-a-%.out: program file.in
./program $* file.in file-a-$*.out file-b-$*.out file-c-$*.out
file-b-%.out: file-a-%.out
@
file-c-%.out: file-b-%.out
@
so that one can pass a parameter that gets included in the file name, for example by running
make file-c-12.out
The solution that make documentation suggests is to add these as implicit rules to the list of dependencies of .PRECIOUS, thus keeping these files from being deleted.
The solution with .PRECIOUS works, but it also prevents these files from being deleted when a rule fails and files are incomplete. Is there any other way to make this work?
A hack to solve this is to define a target .SECONDARY with no prerequisites, i.e.,
.SECONDARY:
which informs make that all files should be treated as secondary and thus not removed, unless when make gets interrupted or a rule fails. Unfortunately, this does not allow for selecting a subset of rules with wildcards to work this way, so I consider this only a hack (even though it's useful).
A:
The Simplest Thing
file-a-%.out file-b-%.out file-c-%.out: program file.in
./program $* file.in file-a-$*.out file-b-$*.out file-c-$*.out
will do exactly what you want.
(Pattern rules with multiple targets are different than the normal rule with multiple targets that you were asking about here. See the bison example in the make manual.)
|
[
"stackoverflow",
"0015212925.txt"
] |
Q:
bad operand types for binary operator "-" first type: int; second type: java.lang.String
I'm having troubles converting a String(birthyear) into an int(age). I want someone to type in their year of birth, and have the program do a simple subtraction calculation to work out their age. I'm new to programming, so I've been searching around, and most places tell me the same thing.
Integer.parseInt(birthyear);
However, having done that, when I try to do the math...
int age = year-birthyear;
I get the error in the title.
public class WordGameScanner
{
public static void main(String[] argus)
{
String name;
String home;
String birthyear;
String course;
String reason;
String feedback;
int year = 2013;
Scanner input = new Scanner(System.in);
System.out.print("What is your name: ");
name = input.nextLine();
System.out.print("Where are you from: ");
home = input.nextLine();
System.out.print("What year were you born: ");
birthyear = input.nextLine();
Integer.parseInt(birthyear);
System.out.print("What are you studying: ");
course = input.nextLine();
System.out.print("Why are you studying " + course + ": ");
reason = input.nextLine();
System.out.print("How is " + course + " coming along so far: ");
feedback = input.nextLine();
int age = year-birthyear;
System.out.println("There once was a person named " + name +
" who came all the way from " + home +
" to study for the " + course +
" degree at --------------.\n\n" + name +
" was born in " + birthyear + " and so will turn " + age +
" this year.");
System.out.println(name + " decided to study the unit ------------, because \"" +
reason + "\". So far, ----------- is turning out to be " +
feedback + ".");
}
}
I'm sorry if this is in the wrong place, this is only my second post here. I just clicked "ask a question" and followed the directions >.<
A:
int age = year-Integer.parseInt(birthyear);
Calling parseInt doesn't redefine the variable String birthYear as an int, it just returns an int value that you can store in another variable (like int birthYearInt = Integer.parseInt(birthYear);) or use in an expression as above.
You may also want to take a minute to think about inputs.
Your users may enter just the last two digits ("83" instead of "1983"), so you could do:
int birthYearInt = Integer.parseInt(birthYear);
if (birthYear.length() == 2) {
// One way to adjust 2-digit year to 1900.
// Problem: There might not be more users born in 1900 than born in 2000.
birthYearInt = birthYearInt + 1900;
}
int age = year = birthYearInt;
Alternatively, you could use java.text.NumberFormat to properly handle commas in inputs. NumberFormat is a good way to deal with numbers that come from humans since it handles the ways people format numbers differently from computers.
Another problem is that this uses the Chinese age numbering system where everyone's age increments by one on the New Year (of the Chinese Lunar calendar, not the Gregorian calendar). This is not they way ages are calculated worldwide though. In the US and most of Europe, for example, your age increments on the anniversary of your birth.
|
[
"stackoverflow",
"0057248622.txt"
] |
Q:
Why template reference variable using ngModel is undefined inside a for-loop?
I'am trying to get a DOM element in HTML template to disable/enable a
form-button based on input value and using ngModel:#Custom_FirstName="ngModel". The input is a custom field in separated component.
My issue is that the element Custom_FirstName is always undefined and I found out that it has to do with the For Loop ngFor. When I remove ngFor, The error is fixed. But this would not solve my issue because I need the for-loop as the user can add more than one input-text and user with firstName dynamically.
Code:
<div *ngFor="let el of users.departments.admins; let i=index; trackBy: trackByFn"
<input-text [name]="'firstanme'"
[(ngModel)]="el.firstName"
[ngModelOptions]="{standalone: true}"
[readonly]="false"
[required]="true"
labelText="First Name"
#Custom_FirstName="ngModel">
</input-text>
</div>
Button:
<button [disabled]="!Custom_FirstName.value || ....>
I have been checking the official Doc, but I was not able to find the fix for that. Any hint how work around this issue?
A:
Official documentation says:
The scope of a reference variable is the entire template. So, don't
define the same variable name more than once in the same template as
the runtime value will be unpredictable.
Since you already have bound input with data just track the data. Add to your component:
hasEmptyValue() {
return users.departments.admins
.some(admin => !admin.firstName || admin.firstName.length===0);
}
And make changes in template:
<button [disabled]="hasEmptyValue() || ....>
|
[
"stackoverflow",
"0013283336.txt"
] |
Q:
Maintaining Session while working with a web server
I am using the simplest way to maintain sessions, which is:
Just create 1 HttpClient and use it for every server call, which will automatically handle cookies etc..,
But the problem here is, when i close the application, the HttpClient object is being destroyed, as expected and hence i cannot login.
So i fixed it, this way:
Store user-email and password in shared preferences, every time the application is launched make a call to the login function(this creates a new session) and use the same HttpClient.
The problem here is, every session in the web server has an expiry duration of 3 years. Where as i am creating a session (Since i am calling login every time user launches the app), every time user launches the app. Which causes session duplication or say unnecessary sessions being created on the server side.
Am i doing it the right way? How can i solve this?
Thank You
A:
Just implement your own CookieStore. It's pretty easy: Extend BasicCookieStore, instantiate it and pass it in the HttpContext. You can store it against a sqlite database, or even just dump it to an xml file (but sqlite is lighter). I have it working here, but I don't time to sanitize the code right now.
|
[
"gaming.stackexchange",
"0000298476.txt"
] |
Q:
Why do Super Mushrooms sometimes appear at the end of Super Mario World levels?
Sometimes, at the end of levels in Super Mario World, a Super Mushroom will emerge from the gate.
Why do these sometimes appear?
A:
Super Mushrooms (and other power-ups) will appear if Mario crosses the Giant Gate with a non-enemy object in his hands. Where as Enemies will turn into coins/1-ups.
There are a few stages though where hidden power-ups will emerge from the ground as you walk/run past a hidden trigger. Yoshi Island 1 has an example of this as you past by a standard bush only to have a Mushroom pop-out from behind it. Likewise, there's some levels where Mushrooms are hidden on the ground to collect as you pass though the Gate. It'll always appear in the same locations in the same stages, so there's no prerequisite for them to appear.
|
[
"stackoverflow",
"0019004351.txt"
] |
Q:
com.sun.imageio.plugins.jpeg.JPEGImageReader leak
We are unsing Adobe CQ5 and have a memory problem.
A dump analysis with Eclipse Memory Analzyer showed that we have
104 instances of "com.sun.imageio.plugins.jpeg.JPEGImageReader", loaded by "<system class loader>" occupy 6,210,086,632 (80.61%) bytes.
Now 104 instances are not much, but 6GB are.
Each class has a sun.awt.image.ByteInterleavedRaster raster of 84 MB.
How can I find out which class references these renderers? If I click on "Path To CG Roots" I get nothing. At first I thought that the memory could be used by some static fields but the big structures (i.e., raster) are not static.
A:
I just ran into this issue myself. It turns out to be a known issue with the Graphics Support Library. Open an Adobe ticket and request cq-5.5.0-hotfix-NPR-3368-1.2.zip, which basically includes the day-commons-gfx-2.1.28.jar. This appears to also work with 5.4, in case that's what you're using. Good luck!
|
[
"hinduism.stackexchange",
"0000018370.txt"
] |
Q:
Is killing infidels allowed in Hindu Scriptures?
Yajur Veda 13.12,
”O king, make progress in thy duty of administration, extend happiness
to the virtuous. O terrible chastiser, burn down the irreligious foes.
O splendid person, humiliate and consume utterly like dried up
stubble, him, who encourages our foe.”
Atharva Veda 12.5.62
Rend, rend to bits, rend through and through, scorch and consume and
burn to dust, the one who rejects the Vedas
Atharva Veda 12.2.23
He who dwells fixed in the atmosphere, smiting the blasphemers of the
god that do not sacrifice to him be reverence with ten
Sakvari-stanzas.
Atharva Veda 10.3.3
This charm shall conquer and cast down thy foemen. Be thou the first
to slay the men who hate thee.
Atharva Veda 20.93.1
May our hymns give you great delight. Display your bounty, Thudered.
Drive off [kill] the enemies of the Vedas.
Everyone must kill Blaspemers:
Rig Veda 6.72.1
ye killed all darkness and the Gods’ blasphemers.
Srimad Bhagvatam 4.4.17
Sati continued: If one hears an irresponsible person blaspheme the
master and controller of religion, one should block his ears and go
away if unable to punish him. But if one is able to kill, then one
should by force cut out the blasphemer’s tongue and kill the offender,
and after that one should give up his own life.
A:
No , killing of Infidels are not fully allowed in Vedas. There are some mantras in Atharva-Veda which asks god agni about destroying evil minds of foes , pardoning / Sheltering then , Welcoming those who came to ask pardon /shelter. Destroying only evil-nature or evil-mind of foes and not the people , even Atharva-Veda prays to god agni for welfare of son's and daughter's of evil-minded people and to motivate them towards good path.
Atharva-Veda , First Kandam , Sukta 7 & 8 , YatudhanNashan Sukta.
Atharva-Veda Samhita , Translated by Pandit ShriRam Sharma Acharya. Published by - Yuga Nirmaan Yojana , Mathura , Uttar-Pradesh , which is a hindi translation.
These are some of the mantras from Atharva-Veda.
पश्याम ते वीर्यम् जातवेदा प्र णो ब्रुहि यतुधानान नृचक्ष: । त्वया
सर्वे परितप्ता: पुरस्तात त आ यन्तु प्रब्रुवाणा उपेदम ॥ 7.5॥
O Agni you are the form of the knowledge , let us see your bright
bravery. You are the guide to whom who have lost the right way. By
your grace lead our foes to the right path. By your order, let wickedness
come here to repentance by identifying themselves.
अयं स्तुवान आगमदिमं स्म प्रति हर्यत । बृहस्पते वशे लब्ध्वाग्निषोमा
वि विध्यतम् ॥ 8.2॥
Welcoming those wicked minded people who came here for
repentance. O guiding star! source of bright knowladge! By your grace
take them in your control. To cure them, O Agni & Soma examine them.
यातुधानस्य सोमप जहि प्रजां नयस्व च । नि स्तुवानस्य पातय
परमक्षुतावरम् ॥8.3॥
O Soma! you let us drink the nectar of knowledge by your grace. Let the
evil-nature gets destroyed by roots, let this reach to the children
of evil-minded once & let them also be made good minded. Let the eyes be
lowered of those, who praise you.
so from above shlokas of Atharva-Veda it is clear that vedas do not at all support/suggest the concept of infidels. It supports a Humanist approach towards enemies, evil-minded people.
|
[
"stackoverflow",
"0029176269.txt"
] |
Q:
Listening to `set_at` event using the ui-gmap-polygon
I'm currently using the DrawingManager to allow users to draw shapes on the map. Once a shape is drawn, I set up a listener on the polygon's path so I can react after the path has been changed:
var polygonPath = event.overlay.getPath();
google.maps.event.addListener(polygonPath, 'set_at', function () {
// my code...
});
This works great when a user adds a new shape using the drawing tool. However, if I already have polygons in my database that I am displaying with the ui-gmap-polygon AngularJS directive (from the angular-google-maps project), how can I listen to the set_at event since this event is not on the polygon, but is instead, on the polygon's path (MVCArray)?
The only place I was able to find a reference to set_at in the source code of the angular-google-maps project was in the array-sync.coffee file, but it doesn't look like it is being exposed.
If I can't listen to the set_at event directly using the directive, I would hope there is an event that gets triggered when the directive creates the polygon so that I can then get the polygon's path and then add a listener to that, just like the code above.
I have put together a JSFiddle with the basic structure, along with the events object. It currently handles the polygon's mouseover and mouseout, but not the set_at event.
A:
Give a try with the below approach.
directive('uiGmapPolygon', function ($timeout) {
return {
restrict: 'E',
link: function (scope, element, attrs) {
// Make sure that the polygon is rendered before accessing it.
// next two lines will do the trick.
$timeout(function () {
// I know that properties with $$ are not good to use, but can't get away without using $$childHead
scope.$$childHead.control.promise.then(function () {
// get the polygons
var polygons = scope.$$childHead.control.polygons;
// iterate over the polygons
polygons.forEach(function (polygon) {
// get google.maps.Polygon instance bound to the polygon
var gObject = polygon.gObject;
// get the Paths of the Polygon
var paths = gObject.getPaths();
// register the events.
paths.forEach(function (path) {
google.maps.event.addListener(path, 'insert_at', function () {
console.log('insert_at event');
});
google.maps.event.addListener(path, 'remove_at', function () {
console.log('remove_at event');
});
google.maps.event.addListener(path, 'set_at', function () {
console.log('set_at event');
});
})
})
})
});
}
}
})
Working Plnkr
|
[
"stackoverflow",
"0062500102.txt"
] |
Q:
Angular PrimeNG menubar: Hide default down arrows next to menu titles
The default PrimeNG menubar includes a little down arrow next to every main menu title. I want to remove the down arrows completely from the top-level menu title. Nested sub-menus may display a right arrow to show there is a sub-menu, and those can stay. Here are some screenshots with default menubar:
https://www.primefaces.org/primeng/showcase/#/menubar
I can change the icons in the menu items easily, but can't find a handle to change/hide the arrows.
I'm using Angular CLI 9.1.8 and PrimeNG 9.1.0.
EDIT -
StackBlitz does not work with PrimeNG due to error: ngcc failed to run on [email protected].
A:
to hide it in style.css change its content like
.pi-caret-down::before{
content: "";
}
check in developer console inspect element font name then make its before css as content: "";
|
[
"stackoverflow",
"0033432303.txt"
] |
Q:
Giving shadow to segmented control
I would like to know if there is any way through .xib or by code, if shadow can be provided to the segmented control, if there is then how can it be done..
Thanks in advance.
A:
You can add UISegmentedControl to a UIView as a subview. And give shadow to the UIView with the help of below code.
self.layer.masksToBounds = NO;
self.layer.shadowOffset = CGSizeMake(-15, 20);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
Don't forget to import QuartzCore Framework.
#import <QuartzCore/QuartzCore.h>
May be it will help you.
|
[
"stackoverflow",
"0003129001.txt"
] |
Q:
How to rename XML attribute that generated after serializing List of objects
I am serializing List of objects List<TestObject>
, and XmlSerializer generates <ArrayOfTestObject> attribute, I want rename it or remove it.
Can it be done with creating new class that encapsulated List as field?
[XmlRoot("Container")]
public class TestObject
{
public TestObject() { }
public string Str { get; set; }
}
List<TestObject> tmpList = new List<TestObject>();
TestObject TestObj = new TestObject();
TestObj.Str = "Test";
TestObject TestObj2 = new TestObject();
TestObj2.Str = "xcvxc";
tmpList.Add(TestObj);
tmpList.Add(TestObj2);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>));
using (XmlWriter writer = XmlWriter.Create(@"C:\test.xml", settings))
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
serializer.Serialize(writer, tmpList, namespaces);
}
<ArrayOfTestObject>
<TestObject>
<Str>Test</Str>
</TestObject>
<TestObject>
<Str>xcvxc</Str>
</TestObject>
</ArrayOfTestObject>
A:
The most reliable way is to declare an outermost DTO class:
[XmlRoot("myOuterElement")]
public class MyOuterMessage {
[XmlElement("item")]
public List<TestObject> Items {get;set;}
}
and serialize that (i.e. put your list into another object).
You can avoid a wrapper class, but I wouldn't:
class Program
{
static void Main()
{
XmlSerializer ser = new XmlSerializer(typeof(List<Foo>),
new XmlRootAttribute("Flibble"));
List<Foo> foos = new List<Foo> {
new Foo {Bar = "abc"},
new Foo {Bar = "def"}
};
ser.Serialize(Console.Out, foos);
}
}
public class Foo
{
public string Bar { get; set; }
}
The problem with this is that when you use custom attributes you need to be very careful to store and re-use the serializer, otherwise you get lots of dynamic assemblies loaded into memory. This is avoided if you just use the XmlSerializer(Type) constructor, as it caches this internally automatically.
A:
Change the following line from:
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>));
To:
XmlRootAttribute root = new XmlRootAttribute("TestObjects");
XmlSerializer serializer = new XmlSerializer(typeof(List<TestObject>), root);
It should work.
A:
You can add an additional parameter to the XmlSerializer constructor to essentially name the root element.
XmlSerializer xsSubmit = new XmlSerializer(typeof(List<DropDownOption>), new XmlRootAttribute("DropDownOptions"));
This would result in the following structure:
<DropDownOptions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DropDownOption>
<ID>1</ID>
<Description>foo</Description>
</DropDownOption>
<DropDownOption>
<ID>2</ID>
<Description>bar</Description>
</DropDownOption>
</DropDownOptions>
|
[
"stackoverflow",
"0058834534.txt"
] |
Q:
How to compare a list with dataframe column headers and substitute the header's name?
There is a df
df_example =
id city street house flat
0 NY street_ny 111 01
1 LA street_la 222 02
2 SF street_sf 333 03
3 Vegas street_vg 444 04
4 Boston street_bs 555 05
And in a database exists a table where every column name matches with column id (withoit id column)
sql_table (as df) =
column_name column_id
city 0
street 1
house 2
flat 3
I need to substitute in df_example column names with column ids from sql_table
Like this
id 0 1 2 3
0 NY street_ny 111 01
1 LA street_la 222 02
2 SF street_sf 333 03
3 Vegas street_vg 444 04
4 Boston street_bs 555 05
So far I got the list of column names without id column name
column_names_list = list(df_example)[1:]
column_names_list = ['city', 'street', 'house', 'flat']
But how to proceed I have no idea
.isin method doesn't really what I need
Appreciate any help
A:
Use rename with dictionary created by zip:
df_example = df_example.rename(columns=dict(zip(df['column_name'], df['column_id'])))
print (df_example)
id 0 1 2 3
0 0 NY street_ny 111 1
1 1 LA street_la 222 2
2 2 SF street_sf 333 3
3 3 Vegas street_vg 444 4
4 4 Boston street_bs 555 5
|
[
"stackoverflow",
"0059495369.txt"
] |
Q:
How to properly use runif and rnorm to make an equation for a variable?
How to properly use runif and rnorm to fit an nls model with a starting value?
Here is a sample code:
set.seed(5000)
x<-seq(0,50,1)
y<-runif(1,5,15)*exp(-runif(1,0.01,0.05)*x)+rnorm(51,0,0.5)
plot(x,y)
I don't have any idea how the equation was formed using runif and rnorm on the variable 'y'.
Thank you for the improvements and responses.
A:
We can split the y formula into four parts:
1) runif(1,5,15) picks a single (1) number from a uniform distribution ranging from 5 to 15. This single number is multiplied by all the 51 output elements of #3 below, so it drives the general height of the curve.
2) runif(1,0.01,0.05) picks a single (1) number from a uniform distribution ranging from 0.01 to 0.05. This number is multiplied by x and put into the exponential function in #3, so it drives the rate of descent of the curve.
3) #2 is put inside a larger term that multiplies the single number from #2 by each of the values of x, which in this case is a vector with 51 elements from 0 to 50, and that in turn is put into the exp exponential function. This is the part that generates the general exponential decay shape of the plot.
4) the last +rnorm(51,0,0.5) sprinkles some normally distributed noise by creating a vector with 51 elements, each of which is from a distribution with a mean of 0 and SD of 0.5.
So this equation simulates an exponential decay with 51 elements. The first term determines the height, the 2nd the slope, and the fourth element adds some noise to that.
|
[
"stackoverflow",
"0001046739.txt"
] |
Q:
jQuery validator plugin without using form
I have multiple section is asp.net that submits data in chunk and i want to use jquery validation plugin, but issue is that asp.net wraps everything in form and child forms not wokring right and technically incorrect.
So only alternative is forget about form and implement validation for divs. But all sames i see are using form. As not being not good at jquery i can't figure out how to use this validator on section of page(On div).
Is it possible? or any other good alternative?
Source:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
A:
Like nightingale2k1 said, you should be able to use that plug-in just fine with a FORM. Here's a quick example that uses a DIV instead:
<div id="pseudoForm">
<input type="text" name="first_name"/>
<input type="text" name="last_name"/>
</div>
<script type="text/javascript">
$("#pseudoForm").validate({
onfocusout:true,
rules:{
first_name:"required",
last_name:"required"
});
</script>
Notice how I used "onfocusout:true", which will make the plug-in validate when the user de-selects either element. You'll need to either use something like that, or else hook up your own event (probably in response to a button press) for the validation to be triggered, as the normal trigger (onSubmit) isn't applicable to DIVs.
|
[
"stackoverflow",
"0020944805.txt"
] |
Q:
Clojure recursion through let binding
From core.clj, the definition of assoc (trimmed of metadata etc)
(def assoc
(fn assoc
([map key val] (. clojure.lang.RT (assoc map key val)))
([map key val & kvs]
(let [ret (assoc map key val)]
(if kvs
(if (next kvs)
(recur ret (first kvs) (second kvs) (nnext kvs))
(throw (IllegalArgumentException. "assoc expects even no of args...")))
ret)))))
what does the let binding of ret achieve? Why is it not just:
(def assoc
(fn assoc
([map key val] (. clojure.lang.RT (assoc map key val)))
([map key val & kvs]
(if kvs
(if (next kvs)
(recur (first kvs) (second kvs) (nnext kvs))
(throw (IllegalArgumentException. "assoc expects even no of args...")))
ret))))
Rudimentary testing (in ClojureCLR) seemed to indicate the latter works ok, and I can't find any documentation indicating the use of the former. Any clues?
Thanks, gary
A:
Your version should fail to compile because not enough arguments are passed to recur (four are needed in this case). The let exists to bind the result of association of the first pair of key/values passed to the first body (3-arity) as ret. In case the second body was invoked by itself earlier using recur with kvs = nil (as a result of calling nnext in the recur form as the fourth argument) (if kvs ..) will fail and ret can simply be returned. If there are more kvs tailrecursion can happen.
|
[
"politics.stackexchange",
"0000013519.txt"
] |
Q:
Is it possible to use blockchain or public ledgers for voting?
As a software developer, I routinely get asked this question and frequently see it being asked online too; it seemed like a great question to pose for the wonderful StackExchange community.
For a quick bit of context, the general idea of public ledgers is everybody can see anonymous information (the votes cast, in this case), and they can also be cryptographically validated so anyone can guarantee it's all correct too.
So, essentially, do you think it's possible to use a digital public ledger system (like, for example, Blockchain) in major democratic elections? Would it meet the requirements we expect a democratic election to satisfy?
On the face of it, it seems like it would be perfect for voting; after all, it should make the process far more transparent , faster, far less prone to corruption and may ultimately turn around those declining voter turnouts because you can vote from anywhere. Or does it?
A:
No, it's not possible.
At least, not without violating multiple fundamental principles of democracy or making it seriously vulnerable. This is primarily because of the authenticity vs. voter anonymity problem. Consider this:
A voter must be a citizen (Authentic)
Their voting choices must not be known, especially not on a public ledger (Anonymous)
The vote they cast isn't tampered with (Valid)
A voter shouldn't be able to prove who they voted for (Bribery)
A public final count so multiple people can validate the system as a whole.
Ledger systems are supposed to guarantee validity - nobody can cook the numbers - but watch what happens when authenticity and anonymity are involved in this example voting system:
I create a cryptographic "key pair" - a private key that only I know and a public key that everybody can see. The Government signs my public key as proof that I'm a citizen using a Government private key.
I place my vote. I sign my choice using my private key and add it along with the Government signature to the public ledger for everybody to see.
It has these properties:
Nobody knows the Government private key so they can't place non-authentic votes.
Nobody should know my private key so they can't tamper with my vote either.
The Government signature provides authenticity and no other information is on the ledger, so it's anonymous too.
The final count is public because anybody can add together the votes.
Nice, right? Nope! It actually scores 1/5:
The Government can use the signature to identify me and my vote. After all, the signature originated from them when they verified me as a citizen and it's also right there on the ledger next to my choices.
The Government can create as many "citizens" as they want, completely undermining both authenticity and validity. Anybody looking at the ledger won't be able to notice anything.
Verifying a signature gives a cryptographic guarantee of exactly who I voted for; it's valid, sure, but it also opens up easy ways for people to bribe me.
So, anonymity is in contention with authenticity and validity is at odds with the ability to be bribed. Yikes.
However, notice that two signatures are involved. This can define a "chain of trust" between the Government and my vote. Maybe adding a few extra 'links' in the chain would at least separate the Government from being able to interfere quite that much? Unfortunately, this too is flawed - you can make the chain infinitely long and some entity along that chain will always be able to identify the voter and their vote. At some point, authenticity has to swap for anonymity. At the swap point, both your vote and identity are available.
Why is a public final count important?
Firstly, a quick side track: As mentioned in Hopelessn00b's answer, it is possible if you have a secret final count. The public ledger contains encrypted data effectively becoming a little useless to anybody but the Government. Estonia's e-Voting system currently has a secret final count - it's not a public ledger but the principle is the same. A public count is particularly important if, as seen in Estonia, the final vote counter is a single server that has been shown to be compromisable remotely. This means their entire democracy depends on a tiny group of people who make a series of rookie mistakes.
What about some kind of hybrid? Surely we can use something?
Don't get me wrong here; I'd love to see a system like this. Maybe someday a breakthrough will happen. A great digital boost to democracy everywhere - democracy so personal that it enters our homes. Let's just entertain the idea with a mixture of physical voting and see what happens.
So, we need to break the link between authenticity and anonymity and we can do that by flipping the voting process around - instead of dropping off your vote into a randomising pile, you pick up something from a randomising pile. Specifically, you pick up a pre-signed citizen ID. Next, in order to make it usable, you build a chain of trust relative to other citizens - for example, your parents could sign your new ID.
We're building trust chains of citizens here. It's still completely flawed however - the Government can still create as many fake citizens as it secretly wants and it'll always be easy to bribe, but at least it requires multiple people (2..) to pull off.
Summary
In order to list out votes in a public ledger, so anyone can count them up to conclude the results and confirm their vote was included, we have to give up the secret ballot. Alternatively we give up the public count but in doing so we make the public ledger useless. We also make ourselves vulnerable to fake citizens being created by the Government with ease, major digital security threats and admin failures due to the layers of complexity. Note that many of these also apply to e-voting in general.
It makes for an interesting concept none the less, but it doesn't come close to beating the simplicity and effectiveness of paper.
A:
Possibly
It all depends on the protocol. Luke Briggs' answer does a great job of stating the requirements for such a protocol and shows a protocol that wouldn't work. The question is whether there is a protocol that could meet the requirements.
I don't believe one has been found but one can get quite close by adding indirection. Below is a protocol that I've just thought up (I doubt it is original) which comes quite close but fails on one stage. Can this failure be closed? I'm not sure but one can do very interesting things with cryptography, such as zero knowledge proofs, so I am hopeful.
Example protocol
Every registered voter has a private/public key pair (only they know the private key) as does the government.
For each vote, the voter generates a private/public key pair and sends the generated public key to the government signed with their personal private key (they send their personal public key too). They encrypt the message using the governments public key.
The government decrypts the message, verifies the signature and checks that the person hasn't previously sent a key for this election. It does this by maintaining a list of registered voter's personal public keys with a boolean flag that it flips when it has received a verified key.
The government then publishes the generated key on a public blockchain ledger signed by the government. The published key may include metdata e.g. state, county, to help with statistics, questionable over/under voting etc. Note, the government does not store or publish the relationship between the personal and generated keys.
Once the generated public key is published, the voter votes by creating an entry on a public ledger with the vote and the generated public key both signed by the generated private key.
The votes can then be checked by anyone by a) confirming that the vote was indeed signed by the respective key and b) that no-one has voted already with that key.
Once validated, the voter then throws away their generated private key.
Advantages of this system:
Only registered voters can vote and only once
The voting portion of the scheme is fully public and publicly verifiable
The voting part cannot be tied back to an individual voter
It's public how many voters will vote
Disadvantages:
An unscrupulous government can know the relationship between the voter and their vote by storing the relationship between the personal and generated public keys.
An unscrupulous government can "create voters" by adding generated keys that aren't tied to voters and votring with them. This can be mitigated with metadata as described or publshing the (voter, flag) list which has other issues.
|
[
"stackoverflow",
"0027656687.txt"
] |
Q:
android studio build suddenly throws a lot of errors
I have been developing this android for some days now, and suddenly the application build has a lot of errors and doesn't run. First few errors are listed below
D:\somepath\someotherpath\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\21.0.3\res\values-v11\values.xml
Error:(50, 21) No resource found that matches the given name: attr 'android:actionModeShareDrawable'.
Error:(50, 21) No resource found that matches the given name: attr 'android:actionModeShareDrawable'.
Error:(50, 21) No resource found that matches the given name: attr 'android:actionModeShareDrawable'.
Error:(50, 21) No resource found that matches the given name: attr 'android:actionModeShareDrawable'.
A couple of things might have caused these errrors are listed below
I was attempting to speed up the Emulator by using Intel HAXM, and also use Genymotion. I can see changes in the dependencies of the build.gradle
build.gradle old
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.nirvanasoftware.donor_app"
minSdkVersion 8
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:20.0.0'
compile 'com.android.support:support-v4:20.0.0'
}
**build.gradle New **
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.nirvanasoftware.donor_app"
minSdkVersion 8
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:support-v4:21.0.3'
}
Is the change in dependency causing build errors or something else.
A:
In the dependencies you have used appcompat-v7:21.0.3 and support-v4:21.0.3
But your compileSdkVersion is 20 buildToolsVersion is "20.0.0"
As I know if you use compileSdkVersion 20 then you should use buildToolsVersion "20.0.0" and the version of support library should also be 20 not 21. If you want to use appcompat-v7:21.0.3' and support-v4:21.0.3' you must use compileSdkVersion 21 and buildToolsVersion 21.x.y (here x and y will be the number according to your build tools that you have installed on your computer)
I am not sure that all of your problems are caused for this. But if there is a problem in your gradle synchronization then suddenly you will have a lot of problems. So if you do not have errors other than your gradle build file then your problems should be removed.
My suggestion is if you want to use latest SDKs and Support libraries install the latest build tools and SDKs from the Android SDK Manager then use
compileSdkVersion 21
buildToolsVersion "21.1.2" // your latest build tools
and dependencies like this
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:support-v4:21.0.3'
}
Hope it will solve your problems. Happy coding :D
In addition: In the latest gradle version that is gradle-1.0.0 runProguard is a deprecated method. So instead of using it you must use minifyEnabled and update your gradle version to 1.0.0.
|
[
"stackoverflow",
"0039057665.txt"
] |
Q:
Java based caching queue having enteries with predefined time to live
I need it in the following scenario:
1.Data are received continuously from network.
2.The data received are added into Queue Buffer.
Data which is add in queue buffer will be having predefined TimeToLive.
If I am adding Data1 in queue it can live upto X seconds.
Guava provides time based cache but it's key based and is not ordered.For me ordering of the data when it's inserted in cache is important as I would want to poll and process the data.
If anyone knows of some existing library/cache api that may have ordered,time based eviction implementation please share.
A:
If I recall correctly I had a similar problem and found guava to be insufficient regarding this point too.
Maybe you could store the data in simple queue and just store references to the items in the cache.
Using handlers on the reference cache you could be notified when they are expired and then manually remove the evicted items from data queue.
|
[
"stackoverflow",
"0031456822.txt"
] |
Q:
Error while saving .less with SublimeText 3
I get this error when i try saving .less file with sublime text. I just started using .less today so
maybe it is my mistake.
EDIT: this is my current piece of code:
//VARIABLES
@color1: blue;
@text_color: black;
@page_background_color: white;
h1 {
color: @color1;
}
#header {
width: 100%;
height: 150px;
}
A:
You are most likely using a version of Sublime Text 3 before Build 3072, or for some other reason you have "atomic_save" enabled in your preferences. It is highly recommended to upgrade to the latest versions when they are released, as they include many bugfixes and new features. Prior to 3072, "atomic_save" was enabled by default, which caused all sorts of problems. It was disabled in 3072 (in the dev builds) and 3080 in the public beta.
If you suspect it has been enabled in your system, follow these steps to disable it:
Open your user preferences (Preferences -> Settings-User)
Check to see if the "atomic_save" option is present. If so, change it to false.
If it is not present, add the following line (adding commas , as necessary to maintain valid JSON):
"atomic_save": false
Save the file, close it, then restart Sublime for good measure.
|
[
"drupal.stackexchange",
"0000255035.txt"
] |
Q:
Change Views Path Programatically
I have a custom form on my site, and on submission, I'd like to update a Views page path.
Within my module, I have a form alter which eventually attaches a custom submit function where I plan to run this Views path change. Within my submit function, so far I have:
function _my_module_custom_submit() {
$view = \Drupal\views\Views::getView('custom_view');
$view->setDisplay('page_1');
// TODO: Change Views path
// Save View
$view->save();
}
This function is running fine, however I cannot find how to change the Views Display path at all. I've tried the setHandler() and setHandlerOption() methods, but these don't appear to be working for this case.
I've found plenty of examples to change the Views path programatically in Drupal 7, but have yet to come across an example for Drupal 8.
A:
In Drupal 8 the configuration of a View is stored in an entity, which you can load, modify and save:
use Drupal\views\Entity\View;
$view = View::load('custom_view');
$display =& $view->getDisplay('page_1');
$display['display_options']['path'] = 'example/path';
$view->save();
|
[
"stackoverflow",
"0006750170.txt"
] |
Q:
run $.ajax() when end typed with format specified. how is it?
i want, when user typed, 0000/00/00(it is format date) after the end of typing run anything(example: AJAX CALL), how is it?
like:
if user typed: 2011/05/04 -> run: $.ajax()...
if user typed: 2011/05 -> not run: $.ajax()...
...
only thing for run $.ajax() is true type this format 0000/00/00.
I hope you understand my purpose.
With respect.
A:
HTML:
<input type="text" name="datefield" onchange="validateField(this)" />
JS:
function validateField() {
var val = this.value;
if (val.length < 10) {
return;
}
if (!val.match(/\d\d\d\d\/\d\d\/\d\d/)) {
return;
}
... do ajax call here
}
|
[
"stackoverflow",
"0059128931.txt"
] |
Q:
Connection with rest-API and SQL server or Azure
I have a problem with the connection to my database located in Azure, I was attempting to do a connection with a rest-API that I create, to a database that I have in Azure, this database I manage directly from SQL Server, and I can't make a connection with this.
I attempt to connect with another test database in SQL Server.
The rest-API ia create is in NodeJS
var sql = require('mssql');
var dbconfig = {
server:"Fernando\EQUIPO",
user: "<user>",
password: "<password>",
database: "<dbname>",
port: 1433,
option: {
encrypt: false
}
};
function getList() {
var record;
var conn = new sql.ConnectionPool(dbconfig);
conn.connect(function(err){
if(err) throw err;
var req = new sql.Request(conn);
req.query("select * from cliente", function(err, recordset) {
if(err) throw err;
else {
console.log(recordset);
record = recordset;
}
conn.close();
});
});
return record;
}
const { Router } = require('express');
const router = Router();
const _ = require('underscore');
const movies = require('../sample.json');
router.get('/', (req, res) => {
res.send(getList());
});
When I make a "get" to my local host http://localhost:3000/api/movies appears the following message in the console:
GET /api/movies 200 126.188 ms - -
(node:11868) UnhandledPromiseRejectionWarning: ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
at Connection.tedious.once.err (C:\Users\luisn\Desktop\rest-API\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Connection.socketError (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1258:12)
at _connector.Connector.execute (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1084:21)
at GetAddrInfoReqWrap._dns.default.lookup [as callback] (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connector.js:152:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:68:17)
(node:11868) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11868) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
A:
Welcome to StackOverflow.
ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
Your error states that it is unable to connect as it could not find a server at the given address.Make sure there is a server runninng and verify connection using some third party app.
Are you sure FernandoEQUIPO gets resolved to a proper hostname ?
|
[
"math.stackexchange",
"0001066745.txt"
] |
Q:
Finding the value of $y=b^2(3a^2+4ab+2b^2)$ if $a^2(2a^2+4ab+3b^2)=3$ and $a$ and $b$ are distinct zeros of $x^3-2x+c$
If $a$ and $b$ are distinct zeroes of the polynomial $x^3-2x+c$ and
$$a^2(2a^2+4ab+3b^2)=3$$
$$b^2(3a^2+4ab+2b^2)=y$$
Evaluate $y$
I tried for many hours but couldn't solve this question. This question is far tougher than it looks!
I made another equation using the fact that $a$ and $b$ are the distinct roots of the given polynomial. I got $a^2+ab+b^2=2$. I tried solving it as a quadratic in $a$ and then putting it in the other given equation, but the expression just got very ugly :(
Please Help!
Thanks!
A:
Since $a$ and $b$ are the solutions of $x^3-2x+c=0$ we have,
$a^3-2a+c=0$
&
$b^3-2b+c=0$
Subtracting the above two equations, we get,
$a^3-b^3-2(a-b)=0$
$\implies (a-b)(a^2+ab+b^2-2)=0$
$\implies a^2+ab+b^2=2$ (Since $a$ and $b$ are distinct)
Now,
$$a^2+ab+b^2=2$$
$$a^2(2a^2+4ab+3b^2)=3$$
$$b^2(3a^2+4ab+2b^2)=y$$
Squaring the first equation, we get,
$a^4+b^4+3a^2b^2+2a^3b+2ab^3=4$
$\implies 2a^4+2b^4+6a^2b^2+4a^3b+4ab^3=8$
Expanding and adding the other two equations, we get,
$y+3=2a^4+2b^4+6a^2b^2+4a^3b+4ab^3$
$\implies y+3=8$
$\implies \boxed{y=5}$
|
[
"stackoverflow",
"0063163687.txt"
] |
Q:
KDB - Referencing functions from a table
I am new to kdb and researching it for a use case to generate time series data using a table of various function inputs. Each row of the table consists of function inputs keyed by an id and segment and will call one function per row. I have figured out how to identify which function albeit using brute force nested conditions.
My question is 2 part
How does one employ kicking off the execution of these functions?
Once the time series data is generated for each id and segment, how best can the the output be compiled into a singular table (sample output noted below - I have thought about one table for each id and then compile in two steps which would work as well but we'll have thousands of ids)
Below is a sample table and some conditions to add meta data including which function to apply
//Create sample table and add columns to identify unknown and desired function
t:([id:`AAA`AAA`AAA`BBB`CCC;seg:1 2 3 1 1];aa: 1500 0n 400 40 900;bb:0n 200 30 40 0n;cc: .40 .25 0n 0n .35)
t: update Uknown:?[0N = aa;`aa;?[0N = bb;`bb;?[0N = cc;`cc;`UNK]]] from t
t: update Call_Function:?[0N = aa;`Solveaa;?[0N = bb;`Solvebb;?[0N = cc;`Solvecc;`NoFunction]]] from t
A sample function below uses the inputs from table t to generate time series data (limited to 5 periods for example here) and test using X
//dummy function to generate output for first 5 time periods
Solvebb:{[aa;cc]
(aa%cc)*(1-exp(neg cc*1+til 5))
}
//test the function as an example for dummy output in result table below
x: flip enlist Solvebb[1500;.40] //sample output for AAA seg1 from t for example
The result would ideally be a sample table similar to below
t2: `id`seg xkey ("SIIIS";enlist",") 0:`:./Data/sampleOutput.csv
id seg| seg_idx tot_idx result
-------| ------------------------
AAA 1 | 1 1 1,236.30
AAA 1 | 2 2 2,065.02
AAA 1 | 3 3 2,620.52
AAA 1 | 4 4 2,992.89
AAA 1 | 5 5 3,242.49
AAA 2 | 1 6
AAA 2 | 2 7
AAA 2 | 3 8
AAA 2 | 4 9
AAA 2 | 5 10
AAA 3 | 1 11
AAA 3 | 2 12
AAA 3 | 3 13
AAA 3 | 4 14
AAA 3 | 5 15
BBB 1 | 1 1
BBB 1 | 2 2
BBB 1 | 3 3
BBB 1 | 4 4
BBB 1 | 5 5
..
A:
It's difficult without more details, but something like the following may help.
First, it may be easier to define Solvebb so that it can take 3 inputs and simple ignores the middle one:
q)Solvebb:{[aa;bb;cc](aa%cc)*(1-exp(neg cc*1+til 5))}
And adding dummy functions for the other two in your table (NB. it's important for the use of ungroup later that the output of these functions are lists):
q)Solveaa:{[aa;bb;cc] (bb+cc;bb*cc)}
q)Solvecc:{[aa;bb;cc] (aa+bb;aa*bb)}
You can apply each call each function on all three vectors of input with:
q)update result:first[Call_Function]'[aa;bb;cc] by Call_Function from t
id seg| aa bb cc Uknown Call_Function result
-------| -------------------------------------------------------------------------------
AAA 1 | 1500 0.4 bb Solvebb 1236.3 2065.016 2620.522 2992.888 3242.493
AAA 2 | 200 0.25 aa Solveaa 200.25 50
AAA 3 | 400 30 cc Solvecc 430 12000f
BBB 1 | 40 40 cc Solvecc 80 1600f
CCC 1 | 900 0.35 bb Solvebb 759.3735 1294.495 1671.589 1937.322 2124.581
and you can unravel this table by applying the ungroup function
q)ungroup update result:first[Call_Function]'[aa;bb;cc] by Call_Function from t
id seg aa bb cc Uknown Call_Function result
---------------------------------------------------
AAA 1 1500 0.4 bb Solvebb 1236.3
AAA 1 1500 0.4 bb Solvebb 2065.016
AAA 1 1500 0.4 bb Solvebb 2620.522
AAA 1 1500 0.4 bb Solvebb 2992.888
AAA 1 1500 0.4 bb Solvebb 3242.493
AAA 2 200 0.25 aa Solveaa 200.25
AAA 2 200 0.25 aa Solveaa 50
AAA 3 400 30 cc Solvecc 430
AAA 3 400 30 cc Solvecc 12000
BBB 1 40 40 cc Solvecc 80
BBB 1 40 40 cc Solvecc 1600
CCC 1 900 0.35 bb Solvebb 759.3735
CCC 1 900 0.35 bb Solvebb 1294.495
CCC 1 900 0.35 bb Solvebb 1671.589
CCC 1 900 0.35 bb Solvebb 1937.322
CCC 1 900 0.35 bb Solvebb 2124.581
|
[
"stackoverflow",
"0005027695.txt"
] |
Q:
Dynmaic checkboxs validation
I want to validate Checkbox in javascript, checkboxes is generating dynamically by PHP and name of checkboxes are like "checkbox1" , "checkbox2" ,"checkbox3" i.e. incrementing i++ and these numbers are coming from database, it might be first time only 2 rows fetched and next time 112 rows.
How i can make sure in javascript that atleast one checkbox must be selected.
A:
If you do not want to use any js framework, then just give the same name attribute to the checkboxes
Assuming your checkboxes are named test
var chkBoxes = document.getElementsByName("test");
var chked=0;
for(var i=0;i<chkBoxes.length;i++)
{
if(chkBoxes[i].checked)
chked++;
}
if(chked===0)
alert("Please select a value");
Added as per the sample code specified in the comment
function isChecked()
{
var i=1;
var chkd=0;
var elem = "";
var chkForMoreChkBoxes=true;
do{
elem=document.getElementById("check_"+i);
try{
if(elem.checked)
{
chkd++;
}
i++;
}
catch(err)
{
chkForMoreChkBoxes=false;
}
}while(chkForMoreChkBoxes)
if(chkd===0)
{
alert("Please select a value");
return false;
}
}
|
[
"stackoverflow",
"0019443740.txt"
] |
Q:
Scale animation on image view not work in >4.0 Os devices
I have modify Cover flow animation to create Gallery animation for images.
I want more zoom centre images, as result I am using following animation on image view in get View method of Item adapter.
Animation grow = AnimationUtils.loadAnimation(getContext(), R.anim.zoom);
ImgView.startAnimation(grow);
Zoom.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/decelerate_interpolator" >
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="100"
android:toXScale="1.18"
android:toYScale="1.18" />
</set>
Item adapter
Here I am scale animation on those image which is come in centre.
int sel_pos;
public class ImageAdapter extends BaseAdapter
{
private Context mContext;
private Integer[] UnselectedImage = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f
};
private Integer[] selectedImage =
{
R.drawable.a_sel,
R.drawable.b_sel,
R.drawable.c_sel,
R.drawable.d_sel,
R.drawable.e_sel,
R.drawable.f_sel,
};
public ImageAdapter(Context c)
{
mContext = c;
}
public int getCount() {
return selectedImage.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressWarnings("deprecation")
public View getView(int position, View convertView, ViewGroup parent)
{
**Animation grow = AnimationUtils.loadAnimation(this, R.anim.zoom);**
final ImageView i = new ImageView(mContext);
i.refreshDrawableState();
i.setDrawingCacheEnabled(false);
i.setAdjustViewBounds(true);
Log.e("position==", ""+position);
if(sel_pos==position)
{
i.setImageResource(selectedImage[position]);
**i.startAnimation(grow);**
}
else
{
i.setImageResource(UnselectedImage[position]);
}
i.setLayoutParams(new CoverFlow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
drawable.setAntiAlias(true);
return i;
}
private class SelectListener implements AdapterView.OnItemSelectedListener
{
public SelectListener(Context c)
{
}
@SuppressWarnings("deprecation")
public void onItemSelected(AdapterView<?> parent, View v, int position,long id)
{
Log.e("Changed----->", "" + position);
// Zoom the new selected view
try
{
sel_pos = position;
coverImageAdapter.notifyDataSetChanged();
} catch (Exception animate)
{
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
This animation is completely work below 4.0 but it is not work those device which have >4.0 OS like S4, Nexus and S3 also.
If any body have idea, Please help.
Thanks in Advance.
A:
If I got you right,then Try below code, it'll work for all version. I am damn sure.
ZoomActivity.java
public class ZoomInActivity extends Activity implements AnimationListener {
ImageView imgPoster;
Button btnStart;
// Animation
Animation animZoomIn;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zoom_in);
imgPoster = (ImageView) findViewById(R.id.imgLogo);
btnStart = (Button) findViewById(R.id.btnStart);
// load the animation
animZoomIn = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.zoom_in);
// set animation listener
animZoomIn.setAnimationListener(this);
// button click event
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// start the animation
imgPoster.startAnimation(animZoomIn);
}
});
}
@Override
public void onAnimationEnd(Animation animation) {
// Take any action after completing the animation
// check for zoom in animation
if (animation == animZoomIn) {
}
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
}
Also made an xml as you already did in your res/anim folder:
res/anim/zoom_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
android:duration="1000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="3"
android:toYScale="3" >
</scale>
</set>
|
[
"stackoverflow",
"0041094727.txt"
] |
Q:
Getting error "Failed to mount component: template or render function not defined." while using js file as Vue component
I'm using Vue in Laravel 5.3. I have already worked with Laravel 5.2. But Laravel 5.3 and Vue.js is new for me. So I'm playing with these pair. I have completed Laravel Passport tutorial successfully. Now what I want to do is put my html template in blade file and js code in Vue component. But I'm getting this error:
[Vue warn]: Failed to mount component: template or render function not defined. (found in component )
So I can't understand reason of this error as I'm new in Vue.js. If any one knows answer, it will be appreciated. Here is my code.
Blade file
<body>
<div id="app">
<tasks></tasks>
</div>
<template id="tasks-template">
<ul class="list-group">
<li class="list-group-item" v-for="task in list">
@{{task.body}}
</li>
</ul>
</template>
<script src="/js/app.js"></script>
</body>
/resources/assets/js/app.js
require('./bootstrap');
Vue.component('tasks', require('./components/Tasks'));
const app = new Vue({
el: '#app'
});
/resources/assets/js/components/Tasks.js
export default {
template: '#tasks-template',
data: function () {
return {
list: ''
};
},
created: function() {
this.$http.get('/api/tasks').then((response) => {
this.list = response.body;
}, (response) => {
alert(0);
});
}
}
UPDATE
Blade file
<body>
<div id="app">
<tasks></tasks>
</div>
</body>
/resources/assets/js/components/Tasks.js
template: require('../components/tasks-template.html'),
instead of
template: '#tasks-template'
/resources/assets/js/components/tasks-template.html
<ul class="list-group">
<li class="list-group-item" v-for="task in list">
{{task.body}}
</li>
</ul>
But now getting this error.
Uncaught Error: Module parse failed: /var/www/html/casesync/resources/assets/js/components/tasks-template.html Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
|
|
| @{{task.body}}
A:
Lets say you have your template file as
/* resources/assets/js/components/tasks.template.html */
<div class="tasks-component component">
<ul class="list-group">
<li class="list-group-item" v-for="task in list">
{{task.body}}
</li>
</ul>
</div>
Then the Tasks.js would be
/* resources/assets/js/components/Tasks.js */
export default {
template: require('./tasks.template.html'),
data: function () {
return {
list: ''
};
},
created: function() {
this.$http.get('/api/tasks').then((response) => {
this.list = response.body;
}, (response) => {
alert(0);
});
}
}
The you can have your app.js as
/* app.js */
require('./bootstrap');
Vue.component('tasks', require('./components/Tasks').default);
const app = new Vue({
//el: '#app'
}).$mount('#app');
//your main index.php or entry point could be
<body>
<div id="app">
<tasks></tasks>
</div>
</body>
UPDATE
For the default/out-of-box webpack configuration to work on Laravel5.3, you will need to pull in html-loader through npm
npm install html-loader --save-dev
Then in the gulpfile.js - specify html-loader to be used for .html files.
const elixir = require('laravel-elixir');
require('laravel-elixir-vue-2');
const config = {
module: {
loaders:[
{
test: /\.html$/,
loader: 'html'
}
]
}
};
elixir((mix) => {
mix.sass('app.scss')
.webpack('app.js', null, null, config);
});
Finally you can register global components in your main/entry file app.js as
Vue.component('test-component', require('./test-component').default);
/* Or using ES2015 import */
import TestComponent from './test-component';
Vue.component('test-component', TestComponent);
I got help from @Alfa here
|
[
"stackoverflow",
"0041768997.txt"
] |
Q:
Prevent multiple ajax calls on enter press
I am using a php chat plugin. Problem with this chat plugin is it works great when message is send through button press but when its set to enter press it invokes too many ajax calls. Sometimes it sends single message and sometimes 4 5 messages are being sent . I have tried all the solutions like defining a variable to have a check on it but i am not sure what i am missing here is the snippet of function used for sending message
$("#text-messages-request").on("focus", "textarea.type-a-message-box", function() {
var ID = $(this).attr("id");
var URL = $.base_url + 'ajax/add_chat_ajax.php';
$('div.message-btn-target').html('<a href="#" id="' + ID + '" class="btn btn-default btn-sm send-message"><i class="glyphicon glyphicon-send"></i> ' + $.sendButton + '</a>');
//$('#type-a-message').remove();
user_is_typing(this, ID);
$(this).on('blur', function() {
stop_type_status();
});
// Input Handler
if ($.enterIsSend == true) {
var running = false;
$(document).bind("keypress", function(e) {
if (e.which == 13) {
if (running === false) {
running = true;
send_message(ID, URL);
}
return false;
}
});
$("a.send-message").on("click", function() {
if (running === false) {
running = true;
send_message(ID, URL);
$(".type-a-message-box").focus();
}
});
} else {
$("a.send-message").on("click", function() {
send_message(ID, URL);
$(".type-a-message-box").focus();
});
}
return false;
});
Please help i am stuck on this for days .
There is this real time chat function which initiates when both users are online and it keeps calling itself after every 7 secs
setInterval("realtime_chat()", 7000);
function realtime_chat()
{
last_msg_id = $(".msg-div").last().attr("id");
var ID = $("#text-messages").attr("rel");
var R_URL = $.base_url + 'ajax/refresh_unreadMessages_ajax.php';
var URL = $.base_url + 'ajax/chat_realtime_ajax.php';
var I_URL = $.base_url + 'ajax/chat_last_id.php';
var dataString = 'id='+encodeURIComponent(ID);
$.post(URL, dataString, function(html) {
var html_response = $(html);
var new_msg_id = html_response.attr("id");
if(new_msg_id !== last_msg_id)
{
$("#text-messages").append(html);
}
})
// deal with update counter and typing status
$('ul#messages-stack-list li').each(function() {
cID = $(this).attr('id');
cString = 'id='+cID;
type_status(cID);
update_unMsg_counter(R_URL, cString, cID, 'realtime');
});
title_unread_counter();
return false; }
Its just to append what if there is some new message stored in database.
and here is my html of textbox
<div id="type" class="collapse border-top">
<textarea type="text" class="form-control border-none" id="type-a-message- box" placeholder="Write the message"></textarea>
</div>
function for getting textarea content is at top and the send message function is as follows
function send_message(ID, URL)
{
var textarea = $('textarea.type-a-message-box').val();
if ($.trim(textarea).length == 0)
{
alert($.emptyBox);
} else {
$.ajax({
type: "POST",
url: URL,
data: {id: ID, message: textarea},
cache: false,
beforeSend: function() { $('#loadingDiv').show(); },
error: function() { $('#loadingDiv').hide(); $('#errorDiv').html('<p>'+$.ajaxError+'</p>'); },
success: function(html) {
$('#loadingDiv').hide();
$("p.no-messages").remove();
$("#text-messages-request").html(html);
$("#text-messages").attr("rel", ID);
stop_type_status();
$(".type-a-message-box").focus();
}
});
}
}
Hope it will help in formulating the solution
A:
Rather than keypress use Keyup event.
|
[
"stackoverflow",
"0058017584.txt"
] |
Q:
Difference between $TRAVIS_EVENT_TYPE != 'pull_request' and $TRAVIS_PULL_REQUEST_SLUG != $TRAVIS_REPO_SLUG
I am trying to set up Chromatic in Travis.
I saw Chromatic document recommends using this script in Travis
if [[ $TRAVIS_EVENT_TYPE != 'pull_request' || $TRAVIS_PULL_REQUEST_SLUG != $TRAVIS_REPO_SLUG ]];
then
npm run chromatic
fi
with explanation
Travis offers two type of builds for commits on pull requests: so
called pr and push builds. It only makes sense to run Chromatic once
per PR, so we suggest disabling Chromatic on pr builds for internal
PRs (i.e. PRs that aren’t from forks). You should make sure that you
have push builds turned on, and add the following code: [[THE CODE ABOVE]]
For external PRs (PRs from forks of your repo), the above code will
ensure Chromatic does run on the pr build, because Travis does not
trigger push builds in such cases.
Note: We recommend running Chromatic on push builds as pr builds can't
always run and fall out of the normal git ancestry. For instance, if
you change the base branch of a PR, you may find that you need to
re-approve changes as some history may be lost.
Chromatic does work with Travis pr builds however!
Then I read the Travis document about TRAVIS_PULL_REQUEST_SLUG and TRAVIS_REPO_SLUG.
TRAVIS_PULL_REQUEST_SLUG:
if the current job is a pull request, the slug (in the form
owner_name/repo_name) of the repository from which the PR originated.
if the current job is a push build, this variable is empty ("").
TRAVIS_REPO_SLUG:
The slug (in form: owner_name/repo_name) of the repository currently being built.
So my understanding is when $TRAVIS_PULL_REQUEST_SLUG != $TRAVIS_REPO_SLUG, it is a push build, then why it still needs $TRAVIS_EVENT_TYPE != 'pull_request'?
Is there any difference between them?
A:
Gert from Chroma here.
We recommend to run chromatic only when a build does not originate from a pull request (i.e. a push build), OR when it is a pull request build originating from a fork, in which case the PR slug differs from the repo slug.
Based on the quoted Travis docs, in case of a push build, TRAVIS_PULL_REQUEST_SLUG is empty, in case of a PR build from a fork, it will reference the fork's repo owner. In either case it will be different from TRAVIS_REPO_SLUG. So you're correct that the left-hand side of this condition is superfluous. Feel free to omit it.
|
[
"stackoverflow",
"0036705293.txt"
] |
Q:
jQuery selector for varying HTML structure
I'm working with a page which displays a product's price. Normally it looks like this:
<span id="priceText">
$26.94
</span>
When the item is on sale, it looks like this:
<span id="priceText">
<strike>$26.94</strike>
<span class="salePrice">$25.00</span>
</span>
I have a generic function which extracts the price from any page like so:
var getPrice = function(price_id) {
return jQuery(price_id).text();
};
Where price_id is the id of the element which contains the price.
As is plainly obvious, this will not work with the above structure since the "sale" version will return both $26.94 and $25.00 if I set price_id to priceText
I do not have control over the html on the product's page, so I can't change the structure. I need to use the getPrice function on other pages which do not have this HTML structure, so I also want to avoid changing it.
What I am looking for is some sort of jQuery selector which will return $25.00 if the item is on sale, or $26.94 if it isn't. Something like "return all text inside of priceText NOT in a strike tag"
I currently have a custom snippet which does the following:
jQuery('#priceText .salePrice').length ? jQuery('#priceText .salePrice').text() : jQuery('#priceText strike').text()
However I want to avoid custom lines of code like this. I think this may not be possible using only jQuery selectors but I'm hoping someone proves me wrong!
A:
You can use a multiple selector.
jQuery('#priceText .salePrice, #priceText:not(:has(.salePrice))').text()
DEMO
|
[
"stackoverflow",
"0017624624.txt"
] |
Q:
Get type of data stored in a string in python
Is there any way to understand what data type that a string holds... The question is of little logic but see below cases
varname = '444'
somefunc(varname) => int
varname = 'somestring'
somefunc(varname) => String
varname = '1.2323'
somefunc(varname) => float
My Case:
I get a mixed data in a list but they're in string format.
myList = ['1', '2', '1.2', 'string']
I'm looking for a generic way to understand whats their data so that i can add respective comparison. Since they're already converted to string format, I cant really call the list (myList) as mixed data... but still is there a way?
A:
from ast import literal_eval
def str_to_type(s):
try:
k=literal_eval(s)
return type(k)
except:
return type(s)
l = ['444', '1.2', 'foo', '[1,2]', '[1']
for v in l:
print str_to_type(v)
Output
<type 'int'>
<type 'float'>
<type 'str'>
<type 'list'>
<type 'str'>
A:
You can use ast.literal_eval() and type():
import ast
stringy_value = '333'
try:
the_type = type(ast.literal_eval(stringy_value))
except:
the_type = type('string')
|
[
"stackoverflow",
"0042842668.txt"
] |
Q:
how to set objeck hashmap on java
i have a model "sentence" like this :
String kalimat;
HashMap<String, Double> bobotChiSquare = new HashMap<>();
HashMap<String, Double> bobotTFIDF = new HashMap<>();
HashMap<String, Integer> countTandaBaca = new HashMap<>();
public HashMap<String, Double> getBobotChiSquare() {
return bobotChiSquare;
}
public void setBobotChiSquare(HashMap<String, Double> bobotChiSquare) {
this.bobotChiSquare = bobotChiSquare;
}
and i want to set value hashmap on object "sentence" like this :
ArrayList <Sentence> listToken = new ArrayList<>();
Sentence sentence = null;
for (int i = 0; i < input.size(); i++) {
sentence.setKalimat(input.get(i));
String[] token = input.get(i).split(" ");
for (int j = 0; j < token.length; j++) {
sentence.setBobotChiSquare(token[j] , new Double(0,0));
}
}
but i have an error in line
sentence.setBobotChiSquare(token[j] , new Double(0,0));
Can anyone help?
A:
Your method expects a HashMap as parameter but your passing a String and a double. You first have to put them into a HashMap.
|
[
"ethereum.stackexchange",
"0000069312.txt"
] |
Q:
Is mining specific to unpermissioned blockchain?
I was studying the differences between permissioned vs. unpermissioned blockchain and came across this: https://www.youtube.com/watch?v=llCjL1up65M
Here it mentions that mining is not required for validating and verifying transactions in permissioned blockchain.
I am curious to know - what is the alternative of mining in permissioned blockchain?
A:
Since initial work by Satoshi, who suggested proof of work consensus schema, that implies mining, many other distributed consensus schemas were invented. Some of these schemas are applicable to public trustless blockchain, while the other may only be used in private trustful ones. Here trustful means that all participants trust small group of validators who responsible for establishing transaction ordering and decide which one of several conflicting transactions will be finally included into blockchain.
For example, J.P.Morgan Quorum private blockchain uses Istanbul BFT consensus that requires modifications in geth. Out of the box, geth supports proof of authority consensus, currently used by Rinkeby test network.
In general, mining is needed to make all nodes agree on who is eligible to construct next block. So, for permissioned blockchains, there are usually small number of validators knowing each other in real life, who may negotiate and agree on the contents of next block without necessity to spend lots of resource on mining. The other nodes will trust blocks as long as they have enough validator signatures.
|
[
"superuser",
"0000439486.txt"
] |
Q:
Share ADSL Internet connection between two computers 40 meters away (straight) from each other
I have a box with a working ADSL Internet connection. About 40 meters away (straight), in another house, there is another, older box. There are two houses in between.
Would there be some practical way to supply an Internet connection to the older box? The neighbors are ok with us installing cables and stuff. I'd say wifi would not be practical, since the houses in between would weaken the signal too much. And using Ethernet cables might require a switch or router in between, due to Ethernet distance limitations.
Advice?
A:
Even though your neighbours may be fine with you running cables through their houses, they're probably less keen on people walking in every now and then for maintenance. Adding switches is a solid way of extending the range of your wired network, but not having physical access to them can be a real pain.
Luckily, 40 meters is well under the maximum distance for up to Gigabit Ethernet connections with any decent (as in: holds up to specifications) Cat 5, Cat 5e or Cat 6 cable, that can run up to 100 meters. Cables meant to be used outdoors are available, but obviously cost more. A simple and cheap way to protect them from the elements is to run the wiring through a plastic pipe.
Wifi might also be suitable for 40 meters, but will either be slower, less reliable or more expensive and unless you're into building directional antennas from kitchen supplies, probably be slower, less reliable and more expensive.
|
[
"stackoverflow",
"0049889589.txt"
] |
Q:
How to inline form control input with label
Using Bootstrap 4, how do you get a form control input to inline with the label. I couldn't find any examples of how to inline form controls while maintaining responsive rows and columns per form group.
The problem I'm having is that the labels take up a whole block, I want a more compact controls where the label is on the same block as the control while still having each group of labels and inputs be in a responsive grid.
<form action="#" autocomplete="nope">
<div class="form-row">
<div class="form-group col-md-4">
<label for="companyName" class="mr-2 col-form-label-sm">Name: </label>
<input type="text" class="form-control form-control-sm" autocomplete="off" name="companyName" id="companyName" placeholder="Company Name" required="" pattern="^.+$" value="">
</div>
<div class="form-group col-md-4">
<label for="version" class="mr-2 col-form-label-sm">Version: </label>
<input type="text" class="form-control form-control-sm" autocomplete="off" name="version" id="version" placeholder="Version" required="" pattern="^.+$" value="">
</div>
<div class="form-group col-md-4">
<label for="notes" class="mr-2 col-form-label-sm">Notes: </label>
<input type="text" class="form-control form-control-sm" autocomplete="off" name="notes" id="notes" placeholder="Notes" pattern="^.+$" value="">
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-12">
<button type="submit" class="btn btn-primary btn-sm">Add</button>
<button type="button" class="btn btn-light btn-sm ml-1">Cancel</button>
</div>
</div>
</form>
A:
You can add below code to achieve this.
.form-group.col-md-4 {
display: flex;
align-items: center;
}
.form-group.col-md-4 {
display: flex;
align-items: center;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<form action="#" autocomplete="nope">
<div class="form-row">
<div class="form-group col-md-4">
<label for="companyName" class="mr-2 col-form-label-sm">Name: </label>
<input type="text" class="form-control form-control-sm" autocomplete="off" name="companyName" id="companyName" placeholder="Company Name" required="" pattern="^.+$" value="">
</div>
<div class="form-group col-md-4">
<label for="version" class="mr-2 col-form-label-sm">Version: </label>
<input type="text" class="form-control form-control-sm" autocomplete="off" name="version" id="version" placeholder="Version" required="" pattern="^.+$" value="">
</div>
<div class="form-group col-md-4">
<label for="notes" class="mr-2 col-form-label-sm">Notes: </label>
<input type="text" class="form-control form-control-sm" autocomplete="off" name="notes" id="notes" placeholder="Notes" pattern="^.+$" value="">
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-12">
<button type="submit" class="btn btn-primary btn-sm">Add</button>
<button type="button" class="btn btn-light btn-sm ml-1">Cancel</button>
</div>
</div>
</form>
</div>
|
[
"stackoverflow",
"0053344965.txt"
] |
Q:
how to remove 0's from a string without impacting other cells in pandas data frame?
I have a data frame which has "0's" and looks as below:
df = pd.DataFrame({
'WARNING':['4402,43527,0,7628,54337',4402,0,0,'0,1234,56437,76252',0,3602],
'FAILED':[0,0,'5555,6753,0','4572,0,8764,8753',9876,0,'0,4579,7514']
})
I want to remove the zeroes from the strings where there are multiple values such that the results df looks like this:
df = pd.DataFrame({
'WARNING':['4402,43527,7628,54337',4402,0,0,'1234,56437,76252',0,3602],
'FAILED':[0,0,'5555,6753','4572,8764,8753',9876,0,'4579,7514']
})
However the ones which have individual 0's in a cell should remain intact. How do I achieve this?
A:
df = pd.DataFrame({
'WARNING':['0,0786,1230,01234,0',4402,0,0,'0,1234,56437,76252',0,3602],
'FAILED':[0,0,'5555,6753,0','4572,0,8764,8753',9876,0,'0,4579,7514']
})
df.apply(lambda x: x.str.strip('0,|,0')).replace(",0,", ",")
Output:
WARNING FAILED
0 786,1230,01234 NaN
1 NaN NaN
2 NaN 5555,6753
3 NaN 4572,0,8764,8753
4 1234,56437,76252 NaN
5 NaN NaN
6 NaN 4579,7514
|
[
"stackoverflow",
"0033291499.txt"
] |
Q:
Jenkins shows error after successful project build creating
Jenkins shows error after build successfull. I have integrated sonarQube for code analysis.
I searched a lot but i not found any solution. waiting for help :)
RROR: Error during Sonar runner execution
org.sonar.runner.impl.RunnerException: Unable to execute Sonar
at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91)
at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
at java.security.AccessController.doPrivileged(Native Method)
at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
at org.sonar.runner.api.Runner.execute(Runner.java:100)
at org.sonar.runner.Main.executeTask(Main.java:70)
at org.sonar.runner.Main.execute(Main.java:59)
at org.sonar.runner.Main.main(Main.java:53)
Caused by: java.lang.IllegalStateException: java.io.IOException: Cannot run program "svn" (in directory "C:\.jenkins\jobs\Hello\workspace"): CreateProcess error=2, The system cannot find the file specified
at org.sonar.plugins.scm.svn.SvnBlameCommand.blame(SvnBlameCommand.java:107)
at org.sonar.plugins.scm.svn.SvnBlameCommand.access$000(SvnBlameCommand.java:45)
at org.sonar.plugins.scm.svn.SvnBlameCommand$1.call(SvnBlameCommand.java:91)
at org.sonar.plugins.scm.svn.SvnBlameCommand$1.call(SvnBlameCommand.java:88)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.io.IOException: Cannot run program "svn" (in directory "C:\.jenkins\jobs\Hello\workspace"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
at org.sonar.api.utils.command.CommandExecutor.execute(CommandExecutor.java:76)
at org.sonar.plugins.scm.svn.SvnBlameCommand.execute(SvnBlameCommand.java:125)
at org.sonar.plugins.scm.svn.SvnBlameCommand.blame(SvnBlameCommand.java:104)
... 8 more
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:189)
at java.lang.ProcessImpl.start(ProcessImpl.java:133)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
... 11 more
ERROR:
ERROR: Re-run SonarQube Runner using the -X switch to enable full debug logging.
Build step 'Invoke Standalone SonarQube Analysis' marked build as failure
Finished: FAILURE
A:
Here's the key bit:
Cannot run program "svn"
The analysis is trying to query your SCM (apparently Subversion) for commit data on the files. It's not finding svn in $PATH to run, and that's causing analysis to fail.
Your options are to make svn available (preferable), or to configure the project on the server side to skip this part of the analysis.
If the project hasn't yet been created, you'll need to provision it. Then use the project-level Administration menu: Administration > General Settings > SCM and set Disable the SCM Sensor to true.
|
[
"stackoverflow",
"0009556943.txt"
] |
Q:
Pass an array of strings from VB6 to a COM object
I'm using ATL do create a COM wrapper around a DLL. For some functions, I need to pass an array of strings. How would I set up the IDL so that intellisense in VB6 will show the parameter as 'String()' instead of just 'String' or 'Variant()'?
A:
You need:
[in, out] SAFEARRAY(BSTR)* inout_asParam
|
[
"unix.stackexchange",
"0000175381.txt"
] |
Q:
Is btrfs suitable as backup filesystem?
Right now I have a pretty traditional backup filesystem structure on top of ext4. Every time a backup is made, a new folder backup-DATE is created to which files are rsync'ed (with hardlinks made using rsync's --link-dest option).
Since I have read about bitrot, I would like to have a checksum for all files, transparently. Apparently ext4 cannot do that, but btrfs does offer support for data checksums (and even a built-in RAID1 mode). For a start, I would like to use btrfs as a "dumb" filesystem which supports data checksums without using its advanced features such as RAID, subvolume snapshots, send/receive, etc.
However, their wiki do not really inspire confidence in the filesystem for backups purposes:
"While many people use it reliably, there are still problems being
found. You should keep and test backups of your data, and be prepared
to use them." - Getting Started
"Is btrfs stable? Long answer: [..] Whatever you do, we recommend
keeping good, tested, off-system (and off-site) backups." - FAQ.
My use case is to have an offline backup. For that reason the disk will see very little use (as in hours) and will be frequently plugged/unplugged (eSATA or USB 3.0). Having a reliable filesystem is a must. It must not be worse than ext4 wrt. power failures, unclean shutdowns, etc.
Is it actually recommended to use btrfs as filesystem for backup purposes? Are there other properties of btrfs which may make it less (or more) suitable?
A:
I will just provide a short answer because I think this is being overthought.
If you read the main kernel wiki about the btrfs (sub-)commands, you will find that there are two commands for:
making a "backup": btrfs-send
and restore: btrfs-restore
Just in case, this means that it is not (designed to be) a backup, but to be an snapshot filesystem, with the idea of rolling back if needed, not as a backup but as "flexible".
Therefore — no, do not use it as backup — use it as a versioned filesystem where you can test things and go back. Don't rely on it.
A:
I recently had problems with a btrfs file system on an up-to-date kernel 4.10.0. The file system got destroyed in a virtualbox VM because TRIM doesn't seem to be correctly implemented somewhere, and AFAIK it had something to do with index numbers of sub volumes. After switching to VMware, the file system was still corrupt and surprisingly btrfs check wasn't able to find and fix the error. Finally I switched back to ext4.
The good thing: I didn't lose data. btrfs seems to be always consistent at least for reading, but it showed me it's still far away from production readiness.
Anyway, on a server I'm still using it as backup volume because there I need the feature of cow-copying for deduplication (exactly your use case). The data is just too much in size for a traditional file system.
Update
I still have the filesystem on my server (see above), but it broke right after I posted this here. Now, I have a big read-only backup volume of 700G which would expand to ~7TB on ext4 if I try to copy away everything using tar|tar. Due to lack of time, I didn't yet check if newer kernel versions can handle it. The actual problem is a "transaction abort" which occours ~2 seconds after mounting writeable and which remounts the volume read-only. The original cause is probably a broken version of btrfs-convert, which I used years ago when I created this volume, and still a limited feature set of the current btrfs check which at least should be able to find all damages on a volume which reproducibly lead to a transaction abort or any other problems, instead of just saying that my filesystem is healthy.
Update 2
I was finally able to solve this by copying over everything to a new volume using a python script (based on an oss deduplication tool). It works with a file pool on the target filesystem based on checksums and makes cow-links from there. This semi-efficient process took 2 days, but then I had a new clean btrfs-based filesystem with all my data recovered. Could publish that code if wanted, but don't expect a perfect, easy-to-use and error-proof tool.
|
[
"stackoverflow",
"0060499209.txt"
] |
Q:
Is there a way to delete a user from FirebaseAuth by their UID?
I was wondering if there was a way to delete a user from FirebaseAuth by their UID. Upon my research online, it seems like you can only delete the current logged in user.
Please advise if this is a possibility.
A:
A user signed in can only delete their own account. No user has ability or permission to delete another account from your client web or mobile app, not matter what platform. That would actually be a huge security hole.
What you can do instead is delete the user from a backend you control using the Firebase Admin SDK, which has the ability to manage users. Privileged backend code can delete any user by UID. If you intend for your end users to invoke some function on your backend that deletes another user, you should verify in your backend code that the user should have this privilege.
|
[
"stackoverflow",
"0011915306.txt"
] |
Q:
How to implement a turnoff switch when using composition (java)?
I have a very simple Player class in java that uses some strategies object all inheriting from the interface PlayerStrategy.
Some implementations of PlayerStrategy are simple but a few others are so resource intensive that I need to make sure I free resources properly when the strategy stops being used. Those strategies have an additional method: turnOff() that takes care of that.
Now if Player leaves the game I'd like it to call turnOff() in all the strategies it has that need it.
The problem is that only a few strategies need turnOff() so I don't feel comfortable adding that method to the PlayerStrategy interface.
Right now when a Player stops playing it checks through reflection if the method turnOff() exists in its strategy. But it's clunky and ugly. Is there a better way?
A:
Avoid Reflection: Reflection is a bad idea. Wherever you can (and it seems you can), avoid it.
It's Good to have turnOff() in the Interface: If you have to use interface... believe me adding turnOff() or cleanup() method is a good idea; even if most of the subclasses will have just empty curly brackets. You wouldn't need to do extra work if they get updated in future to use some resource that requires a clean up.
You can get What You Want but the Cost is Higher: If you are really rigid and sure that subclasses wouldn't extend any other class. You may make the PlayerStrategy a abstract class with turnOff() as empty method. This will solve both your issue, but will limit the subclasses ability to extend other class.
|
[
"stackoverflow",
"0021167823.txt"
] |
Q:
TortoiseGit filter for 2 user names
I have tried to make a TortoiseGit report for the commit history,
i made it to exclude 2 users from the logs, i did so for one with:
^(.(?!username))*$
But i need to exclude an additional user to. How do i filter for 2 strings?
I have already tried with following:
^(.(?!username|username1))*$
and
^(.(?!username))*$|^(.(?!username1))*$
ps. Only this filter format works for TortoiseGit
A:
^(?!(?:username1|username2)$).*$ is correct.
Furthermore, please untick other search criteria than Author, and remember to tick Use Regular Expression
Note:
Since TortoiseGit 1.8.7.1, you have Toggle checked filters
|
[
"stackoverflow",
"0063237039.txt"
] |
Q:
Is there an equivalent to `overflow:scroll` in Flutter web?
I'm trying to access the native scrollbar of the browser (check out the thing on the right side here). Normally, if the content of a widget exceeds the viewport, Flutter throws an error like: A RenderFlex overflowed by 445 pixels on the bottom. Is there a setting or something that can tell Flutter web to just make that particular widget scrollable? If we use the Scrollbar widget than it's not draggable, and the DraggableScrollbar widget looks very weird and the implementation code is way over my pay grade. I just want the normal scrollbar that my grandparents are used to.
A:
I write the full steps because maybe someone is going to use the DraggableScrollbar widget for the first time.
1. Add this to the pubspec.yaml dependencies:
draggable_scrollbar: ^0.0.4
2. Import the package:
import 'package:draggable_scrollbar/draggable_scrollbar.dart';
3. Define a ScrollController:
final ScrollController _scrollController = ScrollController();
4. Usage:
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DraggableScrollbar.rrect(
controller: _scrollController,
heightScrollThumb: 100,
backgroundColor: Colors.yellow,
child: ListView.builder(
controller: _scrollController,
itemExtent: 150.0,
itemCount: 50,
itemBuilder: (context, index) {
return Container(
child: Card(
child: Center(
child: Text(index.toString()),
),
),
);
},
),
),
),
);
}
|
[
"math.stackexchange",
"0001483379.txt"
] |
Q:
Error, (in sum) summation variable previously assigned
Assume that I have a function like this
func1 := proc (a)
return sum(i, i=1..a);
end proc;
This function works as long as I don't define a global variable $i$. If I do that, every subsequent call to func1 returns this error:
Error, (in sum) summation variable previously assigned, second argument evaluates to ...
I understand that Maple doesn't like the $i$ in the summation, as it thinks it needs to use the global $i$. Can I somehow tell Maple that the $i$ in the summation is a temporary variable and not to be confused with the global $i$?
P.S. In the real package, I have dozens of methods using summation and multiplication with indexes like $i$, $j$, etc. Renaming them all to something weird is not a solution, since you never know which variables the user has defined in his files.
P.P.S. If you do the same in Mathematica:
i = 4;
Sum[i, {i,1,k}];
this works without a hitch, as Mathematica recognizes the $i$ in the curly brackets as a temporary parameter. I can't imagine Maple can't do the same.
Thanks!
A:
You simply need to make the summation index a local variable:
func1:= proc(a)
local i;
sum(i, i= 1..a)
end proc;
|
[
"stackoverflow",
"0029356803.txt"
] |
Q:
Center Tab Bar Icons Without Text in Swift
we're trying to center the tab bar icons to the tab bar center because we don't want to have the text below. So the icons should be alone and centered in the tab bar. This is how they look now. The tab bar controller is not the root viewcontroller, so we can't access it directly using rootviewcontroller as many responses we've found out there. Any ideas? We're turning crazy...
A:
To remove titletext, you can use code:
let tabBarItems = tabBar.items! as [UITabBarItem]
tabBarItems[0].title = nil
To get center of icon tabs, use this code
let tabBarItems = tabBar.items! as [UITabBarItem]
tabBarItems[0].imageInsets = UIEdgeInsetsMake(6,0,-6,0)
for complete code remove titletext and get center icon
let tabBarItems = tabBar.items! as [UITabBarItem]
tabBarItems[0].title = nil
tabBarItems[0].imageInsets = UIEdgeInsetsMake(6,0,-6,0)
|
[
"ell.stackexchange",
"0000101740.txt"
] |
Q:
What's correct between "To turn it on is forbidden" and "Turning it on is forbidden"?
to turn it on is forbidden
turning it on is forbidden
I always have troubles when I have to use infinite forms of verbs. In particular like in this example, where a verb describes something more in the next sentence.
I mean when a verb is the subject of a sentence, i.e.: "Walking is healthy" vs "To walk is healthy". I seem to hear more the first version, but some times I wonder if the -ing form is always the correct way.
A:
Active things (walking, running, climbing) have a very strong association between the gerund and the activity itself.
Smoking is (for some reason) regarded as an activity, so "Smoking is forbidden" is the idiomatic way of expressing it.
With turning something on or off, we are more interested in the state on or off, rather than the activity turn on, turn off, so an instruction would more likely be written like this:
This X must be turned off [at all times].
Using an infinitive in this kind of sentence lends it a rather formal air, as in this quote:
to err is human, to forgive is divine Alexander Pope
|
[
"stackoverflow",
"0000948074.txt"
] |
Q:
Dynamic Business Rules in a web application
Greetings!
Working on a web based project were business rules and logic need to be customized by client. I want to do this without having to recompile the application every time we sign up a new client on the system. The architectures I have outlined so far are:
Windows Workflow: Creating dynamic workflows and saving them to the database.
Reflection: Creating a business rules interface and use reflection to load the custom client assembly.
A true business rules engine
Implementing an IOC Container like structure map. [zaff: added 6/4]
Have you ever implemented anything similar to this? If so, what is your experience? And finally is there another solution that I should be exploring?
Thanks for your help!!
A:
I have implemented most of the approaches you mention. The answer may depend on a variety of factors.
What client role(s) will be making the changes to the business rules (e.g. business analyst, developer, power user, etc.)? Meaningful support for business analysts may require a rules engine with externalized rules in a db and a useable UI. Meaningful support for developers might be as simple as leveraging something like MEF (http://www.codeplex.com/MEF).
You might also factor in how often will the business rules need to be changed and what sorts of associated operational requirements may apply (e.g. host process must remain running, app domain unloading ok, etc.). A good selection may require some careful thought about likely vs. unlikely future needs.
|
[
"stackoverflow",
"0062641116.txt"
] |
Q:
Swift: [NSNib _initWithNibNamed:bundle:options:] could not load the nibName
I am building a Cocoa app for production and when I create an NSViewController for routing without NSStoryboard instantiate, I got the error like below.
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: ContentFully.AnotherController in bundle (null).
Actually I solved my problem via using an NSViewController to adding NSStoryboard but I would like to learn what is going on when I call it programmatically and why did crash?
Working scenario
let storyboard = NSStoryboard(name: "Dashboard", bundle: nil)
let vc = storyboard.instantiateInitialController() as! AnotherController
Crashed scenario
let vc = AnotherController()
self.view.window?.contentViewController = vc
Even if I create a class fully programmatically and non-relational with NSStoryboard I could not use it when I change the contentViewController. Is it necessary to search every controller in NSBundle for Swift?
Thanks in advance
A:
A very simple working version would be:
import Cocoa
class AnotherController: NSViewController {
override func loadView() {
view = NSView(frame: NSMakeRect(0.0, 0.0, 400.0, 270.0))
let label = NSTextField(labelWithString: "Another Controller")
view.addSubview(label)
}
}
I can call that from my first controller using the code you say crashes and get the expected result.
@IBAction func replaceMe(_ sender: Any) {
let vc = AnotherController()
self.view.window?.contentViewController = vc
}
|
[
"cstheory.stackexchange",
"0000008640.txt"
] |
Q:
What limits the performance of evolutionary computing techniques?
What limits the current performance of genetic algorithms and neural networks?
The principles underlying these techniques, at least the popular science presentation of these principles, suggests that with enough training they could be improved
as much as desired. It seems that this is not the case though.
What are the causes for this? Why can't better results be achieved simply with
more computing power? Are there fundamental theoretical reasons for this?
I realize this is a very broad question, but I'm sure some of the people here
push against these bounds in their work, and I'd like to hear what they have to say.
A:
To bring this to something resembling theoretical computer science: In his PNAS 2008 paper A Mixability Theory of Sex in Evolution, Christos Papadimitriou has theorized that one limit on the power of genetic algorithms is that they do not optimize what you think they should be optimizing (the objective function you're using in the selection part of the algorithm) but rather they optimize "mixability" (a measure of robustness, the ability of genomes to be combined and still have a high objective function value).
So, if the space of solutions that you're trying to optimize has moderately-high plateaus of pretty good but not great solutions that combine well with each other, and a few steep spikes of high quality solutions that do not combine well, you'll be stuck on the plateaus.
Papadimitriou then uses this observation to make inferences about sexual reproduction in nature, but that's getting off-topic again.
A:
I can't speak for neural networks, but the performance of a genetic algorithm is primarily limited by the difficulty of the problem and how long you're willing to run your algorithm.
What frequently happens with standard genetic algorithms is that after a certain amount of time, the solutions tend to converge to a local optimum. Genetic algorithms work by initially creating a set amount of random solutions and then combining and mutating those solutions. The best solutions are kept and the worst are thrown away. The set of solutions is referred to as the population and one iteration of the recombination, mutation, and replacing solutions is called a generation. The user will set a limit of generations to take place before the algorithm ends.
In a standard genetic algorithm, the solutions in the population tend to become very similar to each other after a number of generations (depending on the problem type and how hard the problem is). The more difficult the problem, the sooner the population tends to converge on a single or a very small number of different solutions. There are MANY different proposed solutions for this, none of which are perfect. Researchers have developed new operators for recombination, mutation, replacing solutions, as well as entire new representations for the solutions. I think it is generally accepted that the better you tune your operators and representation to maintain good diversity within the population, your algorithm will be more successful. However, this is a VERY hard problem and there is no single solution.
The most popular conferences in this area are GECCO, WCCI/CEC, and Evo*. They'd have papers on the state of the art in the field for these things.
TL;DR - The population converges to a very small number of solutions and has a hard time breaking away from these.
I'm not sure if I answered your question sufficiently, but I hope this helps!
|
[
"stackoverflow",
"0062169117.txt"
] |
Q:
angular adding a tag hyperlink dinamically with additional parameters
I have some string variable in angular to which I assign html and then put it to the template
varString = "<a [routerLink]="[]" class="some class" >test</a>"
and then assign template div with this variable.
This creates hyperlink tag with class "some class"
But now I want to add some additional parameteres to it, for example id.
varString = "<a [routerLink]="[]" class="some class" id="123">test</a>"
like this.But unfortunately it generates the same hyperlink without additional parameters.
I've tried different ways but no additional parameters are added to a tag. Is this because of angular ? if I write it directly in template html page everything is fine.
This is stackblitz link
https://stackblitz.com/edit/angular-ivy-xhpoxe
Please inspect element after creation and you can see it takes only class parameter
A:
It's happed because angular sanitize your string by itself for content security reasons. You need to use DomSanitizer and say angular your content is safe.
Stackblitz
|
[
"stackoverflow",
"0044182463.txt"
] |
Q:
How to get IPAddress using InetAddress in Android
I'm having difficulty using InetAddress in Java for my Android project. I included the InetAddress library, however it never works.
The code is the follow:
InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
However all time show me:
Description Resource Path Location Type
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor LauncherActivity.java /src/my/app/client line 25 Java Problem
I included the library:
import java.net.InetAddress;
What must I do to use InetAddress in my Android Project?
The class of my project is:
public class LauncherActivity extends Activity
{
/** Called when the activity is first created. */
Intent Client, ClientAlt;
// Button btnStart, btnStop;
// EditText ipfield, portfield;
//InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
//private InetAddress giriAddress;
private InetAddress giriAddress;
public LauncherActivity()
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
private String myIp = "MYIP"; // Put your IP in these quotes.
private int myPort = PORT; // Put your port there, notice that there are no quotes here.
@Override
public void onStart()
{
super.onStart();
onResume();
}
@Override
public void onResume()
{
super.onResume();
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
moveTaskToBack(true);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
//moveTaskToBack(true);
}
/**
* get Config
*/
private void getConfig()
{
Properties pro = new Properties();
InputStream is = getResources().openRawResource(R.raw.config);
try
{
pro.load(is);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myIp = pro.getProperty("host");
myPort = Integer.valueOf(pro.getProperty("prot"));
System.out.println(myIp);
System.out.println(myPort);
}
}
The error's i get.
Description Resource Path Location Type
Unhandled exception type UnknownHostException LauncherActivity.java /Androrat/src/my/app/client line 31 Java Problem
Picture:
MY VERSION OF JAVA IS JAVA SE 1.6
A:
I propose two alternatives:
If the IP of the given host is mandatory for your application to work properly, you could get it into the constructor and re-throw the exception as a configuration error:
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
{
try {
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
catch (UnknownHostException e)
{
throw new ServiceConfigurationError(e.toString(),e);
}
}
}
But if it is not that mandatory, and this error might be recovered somehow, simply declare UnknownHostException in the constructor's throws clause (which will force you to capture/rethrow that exception in all the call hierarchy of your class' constructor):
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
throws UnknownHostException
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
}
|
[
"stackoverflow",
"0051585897.txt"
] |
Q:
Map Dictionary Keys to add values - Swift
I have two dictionaries: a data dict and a results dict
var data = ["flushes": 0.0, "times": 0.0, "glasses": 0.0, "showers": 0.0, "brushings": 0.0, "loads": 0.0, "washings": 0.0, "baths": 252.0, "dishes": 0.0]
let results = ["flushes": 21.0, "times": 0.0, "glasses": 0.0, "showers": 150.0, "brushings": 4.0, "loads": 0.0, "washings": 5.0, "baths": 0.0, "dishes": 9.0]
I am wondering how to add like values based on key and have only one dictionary.
A:
Assuming data is mutable, this should do it:
data.merge(results, uniquingKeysWith: { $0 + $1 })
|
[
"stackoverflow",
"0055365309.txt"
] |
Q:
SQL - SELECT rows NOT EXISTS in another table
I'm trying to select the rows not present in table B, based on table A.
Unlike table B, table A has "_00" at the end of the titleid, and the column is called title instead of titleid.
Table A:
id | titleid
---+----------
1 | TEST1_00
2 | TEST2_00
3 | TEST3_00
4 | TEST4_00
Table B:
id | title
---+-------
1 | TEST1
2 | TEST2
I currently have:
SELECT `t1.titleid`
FROM `tableb t1`
LEFT JOIN `tablea t2` ON `t2.title + '_00' = t1.titleid`
WHERE `t2.title` IS NULL
How can I select the values which are present in A but not in B?
Desired output
id | title
---+----------
3 | TEST3_00
4 | TEST4_00
A:
SELECT t1.titleid
FROM tablea t1
LEFT JOIN tableb t2 ON t2.title + '_00' = t1.titleid
WHERE t2.title IS NULL
You want to pull Data from Table A , do a left join on Table B and pull data where TableB.Title is null.
Your Query was trying to pull data where TableA.Title is NULL.
|
[
"stackoverflow",
"0036538574.txt"
] |
Q:
How do I access observables that belong to a component from a form in the parent viewmodel?
If I have a knockout view that contain a form made up of several components, how I should I access the values of the component observables when I submit the form? I've been doing something like this:
component foo:
function component_vm(params) {
this.item = params.item || ko.observable();
}
in the parent viewmodel:
function parent_vm() {
this.item = ko.observable();
}
in the parent view:
<form>
<foo params="item: item"></foo>
</form>
This seems kludgy to me. Is there a better way?
A:
A first note...
The mechanism you're using (passing something through params) is AFAIK the main built-in mechanism to do this.
The first thing you'll have to do is ask yourself why this is needed. You haven't shown a real case but an abstract repro; chances are that in your real scenario there's a design issue to be solved. I can't quite imagine any specific instance of the abstract scenario you demo (i.e. that a component view model re-uses exactly the observable from its parent), are you sure you're not breaking encapsulation?
One typical thing where I do think a link between components and its parent makes sense is when the parent's (computed) observables differ based on its children. You could consider using ko-postbox for this, or manually do pub-sub like so:
function component_vm(params) {
this.item = ko.observable();
if (!!params.itemChangedHandler) {
this.item.subscribe(params.itemChangedHandler);
}
}
function parent_vm() {
this.someHandler = function() {
alert('Parent knows something is up!');
}
}
<form>
<foo params="itemChangedHandler: someHandler "></foo>
</form>
A second note...
I typically like components to be self-contained (as you might have gathered from my earlier suggestion to use something like ko-postbox for inter-component comms). My components typically have their own "tasks" for the user and their own unit of work associated with it.
Don't forget that KnockoutJS also supports the template binding, because it sounds to me (at least from your comment to this answer) that the child "components" actually are required for the parent to work properly, and in that case I recommend using templates instead for modularizing your app and making your code more reuseable.
// Mock ajax calls:
var $ = { post: function(url, dto) { console.log(dto); } };
function Address() {
this.addressLine1 = ko.observable();
this.addressLine2 = ko.observable();
this.addressLine3 = ko.observable();
}
function Person() {
this.firstName = ko.observable();
this.lastName = ko.observable();
this.mainAddress = new Address();
this.secondaryAddress = new Address();
}
function RootVm() {
var self = this;
self.person = new Person();
self.submit = function() {
$.post("my_url", ko.toJSON(self.person));
}
}
ko.applyBindings(new RootVm());
div { margin: 10px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<script type="text/html" id="addressTmpl">
<input data-bind="textInput: addressLine1" placeholder="address line 1"><br>
<input data-bind="textInput: addressLine2" placeholder="address line 2"><br>
<input data-bind="textInput: addressLine3" placeholder="address line 3">
</script>
<script type="text/html" id="personTmpl">
Name:
<div>
<input data-bind="textInput: firstName" placeholder="firstname">
<input data-bind="textInput: lastName" placeholder="surname">
</div>
Main address: <div data-bind="template: { name: 'addressTmpl', data: mainAddress }"></div>
Secondary address: <div data-bind="template: { name: 'addressTmpl', data: secondaryAddress }"></div>
</script>
<div data-bind="template: { name: 'personTmpl', data: person }"></div>
<button data-bind="click: submit">submit</button>
A final note...
If you really want to have a hard link between the two view models, and dislike the above two options / insist on using components, then I second the suggestion in @Andrew's answer and use a createViewModel factory function.
The details would be specific to your actual situation / app, but you can give that function access to the parent either through a means in your own app, or the contextFor suggestion in the other answer.
|
[
"stackoverflow",
"0032705627.txt"
] |
Q:
didSet called when getting a property declared as a protocol
Here's some code:
import UIKit
protocol ViewModelProtocol {
var price: String { get }
}
class ViewModel: ViewModelProtocol {
var price: String {
return "$420"
}
}
class ViewController: UIViewController {
// If you change the type to ViewModel directly, no infinite loop
var viewModel: ViewModelProtocol? = nil {
didSet {
print("viewModel didSet called")
updateDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
viewModel = ViewModel()
super.init(coder: aDecoder)
updateDisplay()
}
func updateDisplay() {
print("In updateDisplay()")
print("\(viewModel?.price)")
// if you access the viewModel like this, no infinite loop
// if let v = viewModel {
// print("\(v.price)")
// }
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This code will run in an infinite loop. Specifically, it bounces between print("\(viewModel?.price)") in updateDisplay() and the didSet for viewModel.
If you change viewModel's type to ViewModel directly (skipping the protocol), the infinite loop disappears. Alternatively, if you unwrap viewModel in updateDisplay() before using it the infinite loop also disappears.
This is in Swift 2, although I haven't verified if it has the same behavior in earlier Swift. One other data point, calling methods on the protocol doesn't cause a call to didSet.
Does this look like a Swift bug to you?
A:
It seems that not only I have this problem with didSet{}.
There is open radar for this issue: https://openradar.appspot.com/22574299
|
[
"stackoverflow",
"0009170827.txt"
] |
Q:
Why is my custom layout file not recognized?
I created a file in \res\layout named contactlist.xml
But it is not recognized in my code:
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
//android.R.layout.simple_list_item_1, mContacts, //if cre8 own layout, replace "simple_[etc]"
//android.R.layout.simple_list_item_checked, mContacts, // or simple_list_item_multiple_choice
//android.R.layout.simple_list_item_multiple_choice, mContacts,
android.R.layout.contactlist, mContacts, // <- contact list ist xml-non-grata
new String[] { ContactsContract.Contacts.DISPLAY_NAME },
new int[] { android.R.id.text1 });
I want to create a custom layout that for each Contact has three checkboxes.
Why is my custom layout not accepted as valid?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Updated 2/9/2012:
Finally!
With the help of stackOverflowers and this article: http://www.vogella.de/articles/AndroidListView/article.html
I finally got it working; as usual, it's not that tough once you grok a couple of concepts. It boils down to using this sort of code, which I begged/borrowed/stole and adapted:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Return all contacts, ordered by name
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
projection, null, null, ContactsContract.Contacts.DISPLAY_NAME);
// Display all contacts in a ListView
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.ondemandandautomatic_authorize, mContacts,
new String[] { ContactsContract.Contacts.DISPLAY_NAME },
new int[] { R.id.contactLabel });
setListAdapter(mAdapter);
}
...and making sure "ondemandandautomatic_authorize" (or whatever you name your layout file) is something like this (unfinished, but you get the idea):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3" />
<TextView
android:id="@+id/contactLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(replace this)"
android:textSize="20px" >
</TextView>
</LinearLayout>
...and that "R.id.contactLabel" is replaced with "R.id."
There's more to be done, obviously, but a big obstacle has been hurdled.
A:
It should be
R.layout.contactlist
and not
android.R.layout.contactlist
android is used when you are using the system resources.
|
[
"stackoverflow",
"0012082249.txt"
] |
Q:
maven skip packaging phase
I'm mavenizing an ANT project and building the POM file. The current ANT build file has a target that generates 2 EAR files using weblogic's JwscTask. Now I just have to deploy only these 2 EAR files to a remote repo's weblogic server. I do not want Maven to generate any package, but take the generated 2 EAR files and deploy it. Essentially, the clean, compile and deploy phases have to be taken care of by Maven; packaging is done by ANT. I use the maven-antrun-plugin in the pom file to call the target in the build.xml file.
If I choose the packaging as 'POM', then Maven will not generate any packaging, but it won't compile the src files as well.
Is there any way in which I can skip the package phase in the Maven lifecycle? Say I specify the packaging as WAR in the POM, is there a way to skip the generation of the WAR file, and deploy the 2 EAR files?
Here is a section of the POM file:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
<executions>
<execution>
<phase>package</phase>
<configuration>
<tasks>
<ant antfile="${basedir}/build.xml" target="build-service"/>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
A:
Use the mvn deploy:deploy-file goal. This allows you to deploy a file into a repository without having to do the rest of the project in Maven. You can give it either a pom.xml to deploy with it, or specify the various parameters:
$ mvn deploy:deploy-file -Dfile=app.ear \
-DpomFile=pom.xml \
-DrepositoryId=VeggieCorp \
-Durl=http://mvn.veggiecorp.com/releases
Or
$ mvn deploy:deploy-file -Dfile=app.ear \
-DgroupId=com.veggicorp \
-DartifactId=app \
-Dversion=3.2.1 \
-DrepositoryId=VeggieCorp \
-Durl=http://mvn.veggiecorp.com/releases
In fact, you don't even need the -DrepositoryId parameter unless you've created a settings.xml because the repository requires a username and password or need a proxy.
|
[
"stackoverflow",
"0004537045.txt"
] |
Q:
Best practice for dual-use iFrame + External authentication for Facebook enabled app
Okay, if cookies are a no-no, then I need a little guidance as to the best way to implement the application(s) that I'm creating.
The scenario is that I'm trying to create a single Asp.Net MVC application that can authenticate a user regardless of whether the user visits a site directly or via an iFrame in Facebook. There are separate actions (in separate controllers, actually) for getting INTO the app depending on whether the user enters via Facebook or not, but there are also places in the Facebook app where I'm opening up a new window to "extended" functionality in other areas of the application that can't really work well within the iFrame. It is supposed to transition seamlessly. It's currently working quite well using cookies, but I've from multiple sources that this is not a good thing for iFrame apps. However, I'm not sure exactly what this means.
Without cookies, can you still somehow get server-side access to the authentication token? If not, then what is the "right" way to handle this. Do I need to resort to manually parsing the token using the JS API and sending an AJAX notification to the server of the fact that the user is authenticated and create a forms auth token? Will the CanvasAuthorize attribute work without cookies? Right now I have added code to the FormsAuthentication_OnAuthenticate event in Global.asax to create the forms auth token if the user is logged in via Facebook (and properly associated with a valid user in the external app) as follows:
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs args)
{
if (FormsAuthentication.CookiesSupported)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
{
// Attempt to authenticate using Facebook
try
{
FacebookApp fbApp = new FacebookApp();
if (fbApp.Session != null)
{
dynamic me = fbApp.Get("me");
String fbID = "" + me.id;
MembershipUser mUser = AppMembershipProvider.GetUserByFacebookID(fbID);
if (mUser != null)
{
FormsAuthentication.SetAuthCookie(mUser.UserName, false);
AppMembershipProvider.UpdateLastLogin(mUser.UserName);
Session["FacebookLogin"] = true;
}
}
}
catch (Exception e)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
}
}
}
else
{
throw new HttpException("Cookieless Forms Authentication is not " +
"supported for this application.");
}
}
Will I need to change this?
Sorry if this is basic knowledge, but I'm confused as to how best to implement this. Thanks!
A:
First, let me address the issue with the cookies. So, when I say to not use cookies in iFrames I am saying that for a couple reasons. First in IE, there are some security issues. You need to add the following header to your app to make cookies work correctly inside iframes:
P3P: CP="CAO PSA OUR"
The second big issue with cookies in iframe apps is Safari. Due to security settings in Safari, cookies cannot be created by iframes. As such, you will not be able to rely on cookies for authentication inside of iframes.
Give that you are using the app inside and outside of the iframe, you should have cookie support turned on. However, your app must be designed in a way that will work around the iframe issues. That is going to be the hard part.
The most reliable authentication inside iframe apps is the signed request method. What happens is facebook will append a query parameter to your url when the url is rendered inside the iframe. This query parameter contains the user's session. The Facebook C# SDK handles reading this for you, so you dont need to parse it etc. But you need to be aware that it is there. If you view the incoming request url of your iframe app in facebook you will see something like http://www.mysite.com/page/?signed_request={blahblahblah}.
So the key is that you need to make sure that if you are in the iframe you keep that ?signed_request value on the url.
You can do this several ways. First, you can use the CanvasRedirect methods. These are extension methods on System.Web.Mvc.Controller in the Facebook.Web.Mvc namespace. The canvas redirect uses javascript to redirect your page in the top url. This way Facebook is actually handling the redirects and will always add the signed_request to your iframe url. The problem for you is that this method of redirecting will only work in the iframe, not outside.
The second way would be to manually add the ?signed_request to the url when you redirect. You would do something like:
public ActionResult Something() {
return RedirectToAction("something", new { signed_request = Request.Querystring["signed_requets"]);
}
There are other ways also, like storing data in the session or something, but I wouldn't recommend going down that path.
What you are doing is definitely an advanced senario, but hopefully the above will help you get going in the right direction. Feel free to contact me directly if you have any questions. [email protected] or @ntotten on twitter.
|
[
"stackoverflow",
"0010466469.txt"
] |
Q:
How to do delete in DataGridView in winforms application
From this MSDN Forum's answer by the moderator. To delete a row, user can select the whole row, and then just use a "Delete" key to delete this row. I am confused by this sentence.
Does it mean when I click the row I selected by mouse and hit "DEL" key on the keyboard?
If it is, it just deleted the row from the grid but not saved it in the database at all.
I doubt that the answer is wrong. How to delete the row in datagridview? I am using C# 4.0.
A:
It will not delete the row from the database. You have to implement your own logic.
Please follow this article Insert, Update, Delete with DataGridView Control in C# (Windows Application)
|
[
"stackoverflow",
"0062976730.txt"
] |
Q:
Lograthmic yaxsis setting not working in chartjs
I have previous experience in plotly , now I am trying similar graphs with Chart.js. In plotly I can set yaxis_type="log" , which will automatically scale the values of Y axis. I am tryin gto do a similar thing in chart.js , but unable to achieve desired output.
My chart.js output looks like
The Y axis starts from 0 and jumps directly to 20000 , so it is quite difficult to visualize the first three lines. I would like it to be scaled accordingly based on the values.
My JS code :
<script type="text/javascript">
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: {{xaxis|safe}},
datasets: {{data_Categoryline|safe}}
},
options: {
title: {
display: true,
text: 'Category wise Trend'
},
scales: {
xAxes: [{
display : true,
scaleLabel :{
display : true,
labelString : 'Across the days/weeks/months'
}
}],
yAxes: [{
ticks: {
beginAtZero: false,
type: 'logarithmic'
},
scaleLabel :{
display : true,
labelString : 'Total Amount'
}
}]
},
legend: {
position : 'right'
}
}
});
</script>
A:
The axis type must not be defined inside the ticks option but directly on the axis as follows:
yAxes: [{
type: 'logarithmic',
ticks: {
beginAtZero: false
},
Please consult Cartesian Axes Common Configuration from Chart.js documentation.
|
[
"math.stackexchange",
"0000579772.txt"
] |
Q:
Aren't two infinite asymmetric graphs always identical?
Suppose you have an infinite graph $G$. I assume $G$ to be cubic and planar. No further conditions, so it will be asymmetric, maybe in the sense of cubic planar version of Rado's graph: Every possible combination of faces exists somewhere in this graph (like in normal numbers).
Now you are given a second one of such a graph $G'$. They might look different at first glance, but aren't they actually identical?
A:
These are not isomorphic: the second has bridges, and the first has none.
--o----o----o----o--
| | | |
--o----o----o----o--
o o o
/|\ /|\ /|\
/ | \ / | \ / | \
--o | o----o | o----o | o--
\ | / \ | / \ | /
\|/ \|/ \|/
0 o o
|
[
"stackoverflow",
"0003471253.txt"
] |
Q:
Why isn't this form updating the database?
I'm learning php through head first's php and mysql and I'm toying with the simplest of php scripts: data from a form is inserted into a mysql database. I have modified the example from chapter two to use it on my own form and db, but I haven't been able to make the db accept anything I write into the form.
Where's the error?
Here's the php script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Evaluaciones</title>
</head>
<body>
<h2>Evaluaciones</h2>
<?php
$nombre_apellido = $_POST['nombreYapellido'];
$dbc = mysqli_connect('localhost', 'root', 'password', 'evaluaciones')
or die('Error connecting to MySQL server.');
$query = "INSERT INTO `evaluaciones_cursos` (nombre_apellido) " .
"VALUES ('$nombre_apellido')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
echo 'Gracias por llenar el formulario .<br />'.$nombre_apellido;
?>
</body>
</html>
And here's the html form
formbeta2.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1" />
<title>Evaluación de Curso</title>
<style type="text/css">
body {
background-color: #CC7722;
margin-left:20%;
margin-right:20%;
border:3px dotted gray;
padding: 10px 10px 10px 10px;
font-family:sans-serif;
}
.tabla img {
width:100%;
}
</style>
</head>
<body>
<form>
<img src='http://img690.imageshack.us/img690/4338/softrain2.jpg' width="408" height="123"border='0'/>
<h1>Evaluación</h1>
<p>Por favor, tome unos minutos para llenar esta evaluación. </p>
<p> </p>
<form action="script2.php" method="POST">
<p>
<!--h3>Info Personal</h3-->
<table>
<tr><td>Nombre y Apellido:</td> <td> <input type="text" name="nombreYapellido" value="" /> </td></tr>
</table>
<input type="submit" value="Enviar Evaluación"/>
</body>
</form>
</html>
On mysql I ran:
CREATE TABLE `evaluaciones_cursos` (
`nombre_apellido` VARCHAR(60)
)
Yet the info isn't showing on phpmyadmin. Why?
A:
You have a form nested inside of another form. I'd start there.
Edit: What's probably happening is that the first (empty) form is what is being submitted. Since it submits to the same page formbeta2.html, your PHP and SQL are never even being run. Please answer the question in my comment and we can help further from there.
A:
Looking at the HTML, the </form> is outside the </body> tag. Change this to:
</form>
</body>
Then, you need to remove the <form> that is right under the <body> tag since you already have it later.
Once you make those changes, everything else looks like it should work just fine.
Buena Suerte!
|
[
"cs.stackexchange",
"0000001124.txt"
] |
Q:
How to devise an algorithm that suggests feasible cooking recipes?
I once had a veteran in my course that created an algorithm that would suggest cooking recipes. At first, all sort of crazy recipes would come out. Then, she would train the cooking algorithm with real recipes and eventually it would suggest very good ones.
I believe she used something related to Bayes Theorem or Clustering, but she is long gone and so is the algorithm. I have searched the internet but looking for cooking recipes will yield any sort of results but not the one I am looking for. So, my question is:
What techniques can be used to devise an algorithm that (randomly) suggests feasible recipes (without using a database of fixed recipes)?
Why would I bother looking for a cooking algorithm? Well, it was a very good example of a real world application of the underlying concepts, and such algorithm could be useful in different settings that are closer to the real world.
A:
Hmm, using Bayes Theorem to make new recipes out of old recipes. I imagine you first would want the algorithm to pull apart the ingredients into a form it understands (not sure if we are using NLP for that, or if you manually enter the data in yourself, that's neither here nor there.) From there...
I envision something like this.
Test Data analyzed. Now we have a list of recipes and the probabilities that each ingredient will take place alongside another ingredient, and in what quantities. After we have this data then you would have the program randomly make the new recipes. First it cycles through a list of all the known ingredients, then randomly selects a main ingredient, from there it uses the probabilities of an ingredient given another ingredient to start throwing in more random ingredients, all the while matching appropriate trained data for quantities and compatible ingredients.
Might I suggest that when creating a new recipe the program be given information like, I want something sweet, or something sour, or for instance something mostly made up of wheat.
Hopefully this helps a bit.
A:
For a broad US-centric dataset of nearly 2000 recipes you could look at the Armed Forces Recipe Service. This does not answer your question, but would provide you with real-world training data.
The requirements for the problem are probably difficult to articulate for most people and the selected approach will likely end up implicitly adjusting fitness in the way you have suggested. Foods in geenral are very culture-specific and the approach would probably travel very poorly without extensive tuning.
This also needs substantial sematic, and domain, knowledge to prepare more than just a list of ingredients. After all, coffee-flavoured ice-cream with wafer, cafe au lait and a croissant and tira misu would otherwise be indistinguishable.
A:
Recipe generation is commonly used as an example application for Case Based Reasoning systems. It is even used as an example on the Wikipedia Page. A google search for "case based reasoning recipes" yields numerous results.
|
[
"stackoverflow",
"0002276805.txt"
] |
Q:
boost::lock_guard vs boost::mutex::scoped_lock
Which is preferred boost::lock_guard or boost::mutex::scoped_lock?
I'm using Boost.Thread with the hope to move to C++11 threading when it becomes available.
Is scoped_lock part of the next c++ standard?
Are the any advantages to prefer one over the other?
NOTE: I'm aware that scoped_lock is just a typedef of lock_guard.
edit: I was wrong scoped_lock is not a typedef of lock_guard. It's a typedef of unique_lock.
A:
Amit is right: boost::mutex::scoped_lock is a typedef for boost::unique_lock<boost::mutex>, not lock_guard. scoped_lock is not available in C++0x.
Unless you need the flexibility of unique_lock, I would use lock_guard. It is simpler, and more clearly expresses the intent to limit the lock to a defined scope.
A:
Not much difference between the two. As per Boost, scoped_lock is a typedef for unique_lock<mutex>. Both of unique_lock and lock_guard implement RAII-style locking. The difference between is simply that unique_lock has a more complex interface -- it allows to defer lock and call unlock.
|
[
"stackoverflow",
"0019662956.txt"
] |
Q:
How to pass value from javascript function to django view
my question is, what´s the better way to pass a value from a javascript function to django view.
I have a template where I get a value through a javascript function, and I want to pass that value to a django view.
A:
The question is pretty general, but here's one way of doing it. You could use jQuery to make your AJAX call like this:
$.ajax({type: 'POST',
url: '/fetch_data/', // some data url
data: {param: 'hello', another_param: 5}, // some params
success: function (response) { // callback
if (response.result === 'OK') {
if (response.data && typeof(response.data) === 'object') {
// do something with the successful response.data
// e.g. response.data can be a JSON object
}
} else {
// handle an unsuccessful response
}
}
});
And your Django view would be something like this:
def fetch_data(request):
if request.is_ajax():
# extract your params (also, remember to validate them)
param = request.POST.get('param', None)
another_param = request.POST.get('another param', None)
# construct your JSON response by calling a data method from elsewhere
items, summary = build_my_response(param, another_param)
return JsonResponse({'result': 'OK', 'data': {'items': items, 'summary': summary}})
return HttpResponseBadRequest()
Many details are obviously omitted here, but you can use this as a guideline.
|
[
"stackoverflow",
"0028571244.txt"
] |
Q:
Will Intents started by AlarmManager retain its objects between runs?
I have an app that uses an AlarmManager to do a task regularly. From the Intent that is called by the AlarmManager I access the application to get access to shared data.
Application foo = getApplication();
I then use the foo object both for reading and writing data. Most of the lifecycle of this app is in a resting state with occasional wake ups.
According to the developer documentation:
When an alarm goes off, the Intent that had been registered for it is
broadcast by the system, automatically starting the target application
if it is not already running.
But what happens to the instatiated foo object? (And all other objects in that is created by the Intent) Will that be the same as during the previous iteration or will it be a new one?
A:
The foo object, being an instance of the Application class, will remain in existence as long as
the process in which this is app is running remains alive.
the garbage collector does not mark & sweep through objects on your app heap.
When the process is killed, memory is reclaimed by the kernel and your foo object would vanish. If your app recedes into the background for a long time, then the foo object is no longer in scope and will be disposed of in the normal way by the garbage collector.
Every time the AlarmManager creates a new instance of your Service, a new process running your app is spawned (if the app is not already running) and the Service is run from within this process. The foo object remains in scope as long as the containing process is alive and it has a valid reference on the heap.
As a developer, you should always assume that between separate runs of your Service, either the process containing your app will be killed, OR the GC will mark & sweep through your app's heap. This is the most likely scenario and you have no control over it. So the answer to your question is that the foo object will probably be a new instance every time your Service runs.
For more, see here and here.
|
[
"mathematica.stackexchange",
"0000036875.txt"
] |
Q:
Caching data in Mathematica package
Consider the following:
m=Quantity[1,"meter"]
If I run the package, it will return 1m
But when I load the package, the package is re-evaluated meaning, that internet i required.
Is it possible to use cached results in a Mathematica package?
A:
For this specific case (units in Quantity) a solution is relatively simple: if you use the "standard" unit name Mathematica won't need to use the internet to try to interpret ist. Here that means using "Meters" should avoid the slow evaluation in the first place (I think that is documented and was already discussed once on this site)>
m = Quantity[1,"Meters"]
if in doubt you can get the "standard" unit notation with something like this:
Quantity[1,"meter"]//InputForm
|
[
"stackoverflow",
"0003681841.txt"
] |
Q:
Code Golf: recognize ascii art boxes
Came up with this a while ago while doing some data structure work, though it'd make a good code golf: Given a two dimensional array of characters containing ascii art rectangles, produce a list of coordinates and sizes for the rectangles.
Any trivially convertable input or output format is fine (eg: char**, list of strings, lines on standard input; list of four ints, struct, fixed amount +/- for the size; etc).
Similarly, output need not be in any particular order.
You dont have to anything useful for invalid input or malformed rectangles, but you shouldnt to produce valid-looking coordinates for a rectangle that isnt in the input.
No two valid rectangles share a + (though + may appear not only as part of rectangle)
You can assume that all rectangles are at least 3x3: each side has a - or | in it.
Examples:
" "
" +-+ | "
" | | \-"
" +-+ "
(2,1;3,3)
"+--+ +--+"
"| | | |"
"+--+ +--+"
(0,0;4,3), (6,0;4,3)
" +---+ "
"->|...| "
" +---+ "
(2,0;5,3)
"+-+ +--+ +--+"
"| | | | | |"
"+-+ | | + -+"
" | | "
" +--+ +-+ "
" +--+ | "
" +--+ +-+ "
(0,0;3,3), (4,0;4,5) # (2,5;4,2) is fine, but not needed
A:
Perl, 167 165 159 chars
(156 chars if you don't count slurping stdin to @a, just remove the last 3 chars and assign a list of strings representing your input to @a)
Gets input from stdin. Newlines not significant, added for readability. Notice the use of the +++ operator ;P
map{$l=$i++;while($c=/\+-+\+/g){$w=$+[0]-2-($x=$-[0]);
$c++while$a[$l+$c]=~/^.{$x}\|.{$w}\|/;
print"($x,$l;",$w+2,",$c)\n"if$a[$c+++$l]=~/^.{$x}\+-{$w}\+/}}@a=<>
Be liberal in what you accept version, 170 chars
map{$l=$i++;while($c=/\+-*\+/g){pos=-1+pos;$w=$+[0]-2-($x=$-[0]);
$c++while$a[$l+$c]=~/^.{$x}\|.{$w}\|/;
print"($x,$l;",$w+2,",$c)\n"if$a[$c+++$l]=~/^.{$x}\+-{$w}\+/}}@a=<>
Be conservative in what you accept version, 177 chars
map{$l=$i++;while($c=/\+-+\+/g){$w=$+[0]-2-($x=$-[0]);
$c++while$a[$l+$c]=~/^.{$x}\|.{$w}\|/;print
"($x,$l;",$w+2,",$c)\n"if$c>1&&$a[$c+++$l]=~s/^(.{$x})\+(-{$w})\+/$1v$2v/}}@a=<>
Commented version:
@a=<>; # slurp stdin into an array of lines
$l=0; # start counting lines from zero
map{ # for each line
while(/\+-+\+/g){ # match all box tops
$c=1; # initialize height
# x coordinate, width of box - sides
$w=$+[0]-2-($x=$-[0]);
# increment height while there are inner parts
# of a box with x and w coinciding with last top
# (look into next lines of array)
$c++ while $a[$l+$c]=~/^.{$x}\|.{$w}\|/;
# if there is a box bottom on line + height
# with coinciding x and w, print coords
# (after incrementing height)
print "($x,$l;",$w+2,",$c)\n"
if $a[$c+++$l]=~/^.{$x}\+-{$w}\+/
}
$l++ # line++
}@a
Mega test case:
+--+ +-+ +-+ +++ +---+ +-+ +-+-+ +-++-+
|SO| | | | | +++ |+-+| | | | | | | || |
+--+ +-+-+-+ +++ ||+|| +-+ +-+-+ +-++-+
| | |+-+| | |
+-+-+-+ +---+ +-+
| | | |
+-+ +-+
++ +-+ ++ +-+ +- + +--+ +--+ +--+
|| +-+ ++ +-+-+ | | | | | | |
++ | | | | | | | | |
+-+ +--+ + -+ +--+ +--+
A:
Ruby — 306 260 245 228 168
# 228 chars
g=->(s,u='-'){o=[];s.scan(/\+#{u}+\+/){o<<[$`,$`+$&].map(&:size)};o}
b=t.map{|i|i.split''}.transpose.map{|s|g[s*'','\|']}
(1...t.size).map{|i|i.times{|j|(g[t[i]]&g[t[j]]).map{|x,y|p [x,j,y-x,i-j+1]if(b[x]&b[y-1]&[[j,i+1]])[0]}}}
produces
[0, 0, 3, 3]
[4, 1, 4, 3]
[10, 3, 3, 3]
for t=
["+-+ +--+",
"| | +--+ | |",
"+-+ | | + -+",
" +--+ +-+ ",
" +--+ | | ",
" +--+ +-+ "]
Explanation:
# function returns info about all inclusions of "+---+" in string
# " +--+ +-+" -> [[2,5],[7,9]]
g=->(s,u='-'){o=[];s.scan(/\+#{u}+\+/){o<<[$`,$`+$&].map(&:size)};o}
# mapping transposed input with this function
b=t.map{|i|i.split''}.transpose.map{|s|g[s*'','\|']}
# earlier here was also mapping original input, but later was merged with "analyse"
# "analyse"
# take each pair of lines
(1...t.size).map{|i|i.times{|j|
# find horizontal sides of the same length on the same positions
(g[t[i]]&g[t[j]]).map{|x,y|
# make output if there are correct vertical sides
p [x,j,y-x,i-j+1]if(b[x]&b[y-1]&[[j,i+1]])[0]
}
}}
# yeah, some strange +/-1 magick included ,.)
And more straight-forward 168-chars solution!
t.size.times{|i|t[0].size.times{|j|i.times{|k|j.times{|l|p [l,k,j-l+1,i-k+1]if
t[k..i].map{|m|m[j]+m[l]}*''=~/^\+\+\|+\+\+$/&&t[i][l..j]+t[k][l..j]=~/^(\+-+\+){2}$/}}}}
A:
Perl - 223 222 216
Golfed version (newlines not significant):
$y=0;sub k{$s=$-[0];"($s,%i;".($+[0]-$s).",%i)"}while(<>){while(/\+-+\+/g){
if(exists$h{&k}){push@o,sprintf k,@{$h{&k}};delete$h{&k}}else{$h{&k}=[$y,2]}}
while(/\|.+?\|/g){++${$h{&k}}[1]if exists$h{&k}}++$y}print"@o\n"
Older de-golfed version:
# y starts at line zero.
$y = 0;
# Abuse Perl's dynamic scoping rules
# to get a key for the hash of current rectangles,
# which indexes rectangles by x and width,
# and is also used as a format string.
sub k {
# The start of the current match.
$s = $-[0];
# $+[0] is the end of the current match,
# so subtract the beginning to get the width.
"($s,%i;" . ($+[0] - $s) . ",%i)"
}
# Read lines from STDIN.
while (<>) {
# Get all rectangle tops and bottoms in this line.
while (/\+-+\+/g) {
# If line is a bottom:
if (exists $h{&k}) {
# Add to output list and remove from current.
push @o, sprintf k, @{$h{&k}};
delete $h{&k}
# If line is a top:
} else {
# Add rectangle to current.
$h{&k} = [$y, 2]
}
}
# Get all rectangle sides in this line.
while (/\|.+?\|/g) {
# Increment the height of the corresponding
# rectangle, if one exists.
++${$h{&k}}[1] if exists $h{&k}
}
# Keep track of the current line.
++$y
}
# Print output.
print join", ",@o
Note that this does not handle junk vertical bars to the left of the rectangles, that is:
+--+ +--+
| | | | |
+--+ +--+
Will incorrectly yield a height of 2 for both. This is because the /\|.+?\|/g pattern starts searching from the beginning of the line. Anyone have a suggestion for how to fix this?
|
[
"tex.stackexchange",
"0000194885.txt"
] |
Q:
multiple colormaps
I would like to define multiple colormaps. But when I try this
\pgfplotsset{
colormap={something}{
color(0cm)=(blue);
color(1cm)=(orange!75!red)
}
colormap={somethingelse}{
color(0cm)=(white);
color(1cm)=(orange!75!red)
}
}
I get an error.
(This works):
\pgfplotsset{
colormap={something}{
color(0cm)=(blue);
color(1cm)=(orange!75!red)
}
}
Any ideas?
A:
It's a typo since options in the key value syntax needs a separating comma. This would work;
\pgfplotsset{
colormap={something}{
color(0cm)=(blue);
color(1cm)=(orange!75!red)
},%<---- comma here
colormap={somethingelse}{
color(0cm)=(white);
color(1cm)=(orange!75!red)
}
}
|
[
"stackoverflow",
"0037403579.txt"
] |
Q:
Text in CheckedTextView can't be centered
<CheckedTextView
android:id="@+id/charge_industry_textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableTop="@drawable/charge3"
android:gravity="center"
android:text="@string/ChargeIndustry"
android:background="@drawable/checkedtextview_checked"/>
The text in the CheckedTextView can't be centered, when I make android:gravity="center"
A:
try android:layout_centerHorizontal="true"
or android:textAlignment="center"
|
[
"stackoverflow",
"0021534930.txt"
] |
Q:
htaccess request as 'folder'
i ran into a problem, im trying to map url to folder(virtual one),
so, im trying instead of http://site.eu/controlpanel.php?username=Username&do=services
map it as http://site.eu/cp/user/services
Im using the following code
RewriteRule ^cp/([^/]+)/([^/]+) /controlpanel.php?username=$1&do=$2 [L,QSA,NC]
All fine, except two things, if im trying to access
http://site.eu/cp/user/
it gives me 404 Error (why?)
Also, if im trying to access anything further than
http://site.eu/cp/user/services/
Like
http://site.eu/cp/user/services/ServiceID/
or
http://site.eu/cp/user/services/ServiceID/Action
It gives me same error.
In php file, im using this construction
<?php
switch($_REQUEST['do'])
{
case 'services':
some code to display page;
break;
}
?>
I dont know how to make this pages, after /cp/user/services/.../... available to users.
Help me please
A:
You could use the following structure instead:
RewriteRule ^cp/([^/]+)/?(.*)$ /controlpanel.php?username=$1&path=$2 [L,QSA,NC]
So, if you use the URL:
http://site.eu/cp/user/services/ServiceID/Action
...you'll be sent to:
http://site.eu/controlpanel.php?username=user&path=services/ServiceID/Action
Then, in your PHP file:
<?php
$path = ($_REQUEST['path']) ? explode('/', strtolower($_REQUEST['path'])) : array();
if (!empty($path)) { // A path is established; find the page.
if ($path[0] === 'services') {
if (!empty($path[1])) { // Visitor is at '/cp/user/services'.
// ...
}
else if (ctype_digit($path[1])) { // Visitor is at '/cp/user/services/[ServiceId]'.
// ...
}
// ...
}
}
else { // No path exists. Visitor is at '/cp/user'.
// ...
}
?>
|
[
"stackoverflow",
"0037595980.txt"
] |
Q:
Angular 2, Http and Not setting Content-Type "application/json"
I am trying to do a simple Check Login method using Angular 2(2.0.0-rc.1) in a service. When I attempt to set the content-type to application/json it never sets the headers when sending to my web api backend.
import { Injectable } from '@angular/core';
import { HTTP_PROVIDERS, Http, Response, Headers, RequestOptionsArgs, RequestMethod, Request, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Other Modules Left out for Security } from 'Hidden';
@Injectable()
export class LoginService {
private _http: Http;
constructor(http: Http) {
this._http = http;
}
CheckLogin(model: CredentialModel) {
let url = 'http://localhost:51671/api/Login';
let data = JSON.stringify(model);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let requestOptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: headers,
body: data
});
console.log(requestOptions);
console.log(data);
return this._http.post(url, data, requestOptions);
}
}
Request from Web Api
OPTIONS /api/Login HTTP/1.1
Host: localhost:51671
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:5616
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2754.0 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
DNT: 1
Referer: http://localhost:5616/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Using the exact same data using PostMan works fine! Looks like there is an issue with Angular 2 sending application/json using the POST method.
Any help resolving this issue would be helpful. Open to trying any suggestions.
A:
The post method of the Http class accepts an object of type RequestOptionsArgs and not RequestOptions.
class RequestOptionsArgs {
url : string
method : string | RequestMethod
search : string | URLSearchParams
headers : Headers
body : any
withCredentials : boolean
}
You can specify it literally this way within the third parameter:
return this._http.post(url, data, { headers: headers });
|
[
"stackoverflow",
"0049524193.txt"
] |
Q:
Eigen Range Initialization
I'm trying to use Eigen3 to generate a 2d float matrix (num_samples, num_ranges) such that each column is a continuously spaced range from [0, num_samples) like [0, 1, 2 ... num_samples - 1].
I'm currently achieving this by creating a similar 2d std::vector with std::iota and then converting that to an Eigen 2d matrix.
Is there a faster and simpler way to do this in Eigen?
A:
If I understood correctly, you want the matrix to be like
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
for a 4x4 matrix. For that, you can use a combination of LinSpaced (for a single column) and replicate (to duplicate that column):
int rows = 5;
int cols = 4;
Eigen::MatrixXd m = Eigen::VectorXd::LinSpaced(rows, 0.0, rows - 1).replicate(1, cols);
std::cout << m;
|
[
"stackoverflow",
"0062526087.txt"
] |
Q:
What would be a good way to get a full locale date and hour string with allowed filename characters, in Java?
I want to build a string with the locale date and hour, concatenated, that must be human readable and compatible with the most common OS file allowed characters as well. Something like:
6-23-20_03-06-50
I am using this as an automated filename suggestion for the user.
To achieve this, I have written the following code:
public class CustomDateProvider {
private static final String TWO_DIGIT_PATTERN = "%02d";
public static String getDashedDateAndHourFromDate(Date date) {
ZonedDateTime dateTime = date.toInstant().atZone(ZoneId.systemDefault());
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
String localeDate = dateFormat.format(date);
String dashedDate = localeDate.replace("/", "-");
return dashedDate
+ "_"
+ String.format(TWO_DIGIT_PATTERN, hour)
+ "-"
+ String.format(TWO_DIGIT_PATTERN, minute)
+ "-"
+ String.format(TWO_DIGIT_PATTERN, second);
}
}
Thus, I am assuming the date separator char will always be "/", and I am not sure if this is always correct.
Either way, there are probably better ways to achieve my goal, and I would appreciate any improvement.
A:
java.time
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.
Avoid localized formats
You asked for text representing the date-time value in various localized formats. That approach is unwise in a file name.
Localized formats may well contain characters that would be problematic on various file systems. Your example MM/dd/yyyy format using slash characters might cause problems on some Unix/POSIX-oriented file systems.
Localized formats may be misinterpreted by humans who assume a different custom.
Localized formats may make difficult or impossible parsing that string back to a date-time value.
Instead, I strongly recommend using only standard ISO 8601 formats.
“Basic” variant of ISO 8601
You asked for:
must be human readable and compatible
I suggest sticking with the "basic" variant of ISO 8601 format that makes minimal use of delimiters. For compatibility with various filesystems you want to avoid slash, backslash, colon, and space characters.
The ISO 8601 format is in order of significance: year, month, day, hour, minute, second, fractional second. An uppercase T separates the date portion from the time-of-day portion. Such strings sort alphabetically as chronological.
UTC
I also suggest you stick with UTC (an offset of zero hours-minutes-seconds). For this, use Instant (or OffsetDateTime set to UTC).
Instant instant = Instant.now() ; // Capture current moment as seen in UTC.
Truncate if you do not want fractional seconds or minutes.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES ) ;
You would do string manipulation to remove the hyphens between the year-month-day and the colons between the hour-minute-second.
String output = instant.replace( "-" , "" ).replace( ":" , "" ) ;
For 2021-01-23T12:30:35Z that would be:
20210123T123035Z
The trailing Z means UTC, and is pronounced “Zulu”.
Zoned moment
If you insist on using the date-time as seen in a particular time zone, use ZonedDateTime.
ZoneId z = ZoneId.systemDefault() ; // Or ZoneId.of( "Africa/Tunis" ) and such.
ZonedDateTime zdt = ZonedDateTime.now().truncatedTo( ChronoUnit.MINUTES ) ;
Specify a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" ) ;
String output = zdt.format( f ) ;
Example:
20210123T123035
I do not recommend omitting the zone or offset, but there you go if you insist.
If you insist your example format of 6-23-20_03-06-50, define a DateTimeFormatter to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M-d-uu'_'HH-mm-ss" ) ;
Allowing single-digit month or day is yet another thing I recommend against. As is the use of a two-digit year.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
|
[
"stackoverflow",
"0004614306.txt"
] |
Q:
How to create two independent columns in a webpage?
I want to have two columns in webpage and each one with their own scrollbars instead of the common one that both uses. For example, what I'm thinking is along the lines of new twitter ui.. where one column shows the list with its scrollbar if the list is longer than the height and similarly the other column shows the details with its own scrollbar.
I am simply lost which way to proceed, do I need to use frames to achieve this. Can the global scrollbar be suppressed and each column use their own scrollbar with css?
A:
HTML:
<html>
<body>
<div class='right'>
<!-- data -->
</div>
<div class='left'>
<!-- data -->
</div>
</body>
</html>
CSS:
body{
overflow:hidden; /* This will remove the default scroll, not really needed, safer nonetheless */
}
.right, .left{
overflow:auto; /* This will add a scroll when required */
width:50%;
float:left;
height: 100%
}
|
[
"stackoverflow",
"0006122138.txt"
] |
Q:
ASP.NET - Current name of page from web user control?
I need to find out name of location where web user control is. Somethnig like HttpContext.Current.Request.Url.ToString(), but I get only page for this web user control.
A:
Request.Url.Segments will give you a string array. The last item is the page
A:
You should try the Request.Url.LocalPath property
string fileNameFromLocalPath = Path.GetFileName(Request.Url.LocalPath);
|
[
"stackoverflow",
"0002616104.txt"
] |
Q:
Load In and Animate content
I have a little issue concerning an animation-effect which loads a certain div into the body of the site.
Let me be more precise: I have a div with the id 'contact':
<div id="contact">content</div> The jquery code loads the contents within that div, when I press the link with the id 'ajax_contact': <a href="#" id="ajax_contact">link</a>.
The code is working perfectly. However, I want #contact to be HIDDEN when the site loads, i.e. the default state must be non-visible. Only when the user clicks the link #ajax_contact, the div must appear.
Please have a look at the jquery code:
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('#ajax_contact').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #contact';
$('#contact').load(toLoad)
}
});
$('#ajax_contact').click(function(){
var toLoad = $(this).attr('href')+' #contact';
$('#contact').hide('fast',loadContent);
$('#load').remove();
$('body').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#contact').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#contact').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
I am not sure whether I must change something inside the HTML, but I believe the key is inside the jquery-code. I also tried giving the #contact a CSS style of visible:none, yet this loops and makes the jquery impossible to load the #contact in.
I hope I've explained myself well; thank you very much in advance.
Chris
A:
CSS:
#contact { display: none; }
jQuery:
$("#contact").hide();
What I'd suggest is:
<a id="contact" class="load">Load contacts</a>
<div id="content_contact" class="load"></div>
with CSS:
div.load { display: none; }
and:
$("a.load").click(function() {
$("#load_" + this.id).load("...", function() {
$(this).show();
});
return false;
});
Edit: your main problem is the way you're passing callbacks. Instead of:
$("#contact").load(toLoad, '', showNewContent());
do:
$("#contact").load(toLoad, '', showNewContent);
The first version passes the return value to load(). The second passes the function itself.
Edit 2: to toggle to display:
$("a.load").click(function() {
var dest = $("#load_" + this.id);
if (dest.hasClass("loading")) {
// do nothing if already loading
} else if (dest.is(":visible")) {
dest.hide();
} else if (dest.is(":empty")) {
dest.addClass("loading").load("...", function() {
$(this).removeClass("loading").show();
});
} else {
dest.show();
}
return false;
});
A class of "loading" is added to stop multiple load() calls. The class is removed once loaded. The content is only loaded once by checking if the destination div is empty. You can change this if you wish so it's loaded each time its hidden. It depends on what you're loading.
|
[
"stackoverflow",
"0038977271.txt"
] |
Q:
C - Limit the string length
(Sorry for my bad english !)
I wrote a program that asks you to type a password no longer than a certain number, eight characters in this case. The characters that pass the limit will be cut out from the array:
#include <stdio.h>
#define MAXCHAR 8
main()
{
char password[MAXCHAR];
int i;
char c;
printf("Insert password: MAX 8 CHARS!\n\n");
for(i = 0; i <= MAXCHAR; i++){
c = getchar();
if(i == MAXCHAR){
break;
}
else{
password[i] = c;
}
}
printf("%s\n", password);
}
So the program works BUT there is a "strange" problem. If the limit IS EIGHT and I type a password longer than eight characters
(Example: P455w0rds98)
the output will be like this:
P455w0rd☺
So it puts a smiley at the end and I don't know why. It happens only if a the limit is established at eight.
A:
You must specify the length to print or terminate the string. Otherwise, you will invoke undefined behavior. Try this, in which the latter method is implemented.
#include <stdio.h>
#define MAXCHAR 8
int main(void)
{
char password[MAXCHAR + 1]; /* allocate one more element for terminating null-character */
int i;
char c;
printf("Insert password: MAX 8 CHARS!\n\n");
for(i = 0; i <= MAXCHAR; i++){
c = getchar();
if(i == MAXCHAR){
break;
}
else{
password[i] = c;
}
}
password[MAXCHAR] = '\0'; /* terminate the string */
printf("%s\n", password);
}
Some people say that the if(i == MAXCHAR){ break; } part doesn't look good, so here is another code example:
#include <stdio.h>
#define MAXCHAR 8
int main(void)
{
char password[MAXCHAR + 1]; /* allocate one more element for terminating null-character */
int i;
printf("Insert password: MAX 8 CHARS!\n\n");
/* read exactly 8 characters. To improve, breaking on seeing newline or EOF may be good */
for(i = 0; i < MAXCHAR; i++){
password[i] = getchar();
}
password[MAXCHAR] = '\0'; /* terminate the string */
getchar(); /* to match number of call of getchar() to the original: maybe for consuming newline character after 8-digit password */
printf("%s\n", password);
}
|
[
"stackoverflow",
"0006999010.txt"
] |
Q:
What is the difference between these two vector statements?
[!!Correction made to the second code!!]
vector<int> a;
vector<int>*p = &a;
and
vector<int>*b = new vector<int>();
I know that in first scenario, a is on stack and in second b is on heap. But, are there any other differences? Like memory consumed etc.
A:
Yes vector b is allocated on the heap and vector a is on the stack (assuming the code is in the scope of a method) along with a 4 byte pointer also on the stack. Other differences in memory consumed would depend on the memory manager and how it allocates blocks and any internal bookkeeping required for the heap.
A:
I know that in first scenario, a is on stack and in second b is on heap.
Both parts of that statement are wrong.
Mostly because the terms stack/heap are useless in describing C++ objects.
vector<int> a;
This is an automatic storage duration object. More commonly referred to as an automatic object.
It is created on first use and destroyed when it goes out of scope. The definition of scope depends on context. If you are in a function it is placed on the stack and destroyed when the function exists. If it is a member of an object then it is created with the object and destroyed with the object (in this case the object could be on the heap or stack).
Conversely:
vector<int>* p = &a;
This is a pointer to an object. What it points to depends. In this case you are making it point at an automatic object (which as described above could be on the stack or heap).
Finally:
vector<int>* q = new vector<int>();
This is a pointer to an object of dynamic storage duration. This means it is created with new and must be manually destroyed (Which is also why you never create RAW pointers, they are always wrapped in smart pointers (please read a book)). If this object is on the stack or heap depends on a lot of things as the language allows you override the default behavior (in a simple naive way you can think of it as being on the heap (but it is best to just forget the concept of heap and stack as they don't apply to C++).
It is best to think of object belonging to one of four categories:
Static storage duration objects
Global variables (and a few other things)
You can think of these (until you know more) as created before main destroyed after main
Thread Storage duration objects
Globals associated with a thread.
You can think of these as created with the thread destroyed after the thread
Automatic Storage duration objects
Nearly all other objects
These are created when first encountered.
Destroyed when they go out of scope.
Scope depends on context.
Dynamic storage duration objects
Objects allocated with new and de-allocated with delete.
Objects that should be contained in smart pointers or containers
|
[
"stackoverflow",
"0038028525.txt"
] |
Q:
How to read NFC type A card pages?
I have an Android app that is reading Mifare Ultralight card content. Previously all cards had Ultralight in android.nfc.tech and I was using readPages() to get the data with no problems.
Now I encountered new types of card that do not have Ultralight in android.nfc.tech and I can't use readPages() anymore. However I encounter that TagInfo app by NXP does read pages. How can I achieve same result? Should I use tranceive() command? What command should I generate?
A:
You could have a look at MifareUltralight source and try to reproduce code for your tag:
public byte[] readPages(int pageOffset) throws IOException {
validatePageIndex(pageOffset);
checkConnected();
byte[] cmd = { 0x30, (byte) pageOffset};
return transceive(cmd, false);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.